ChainServiceFactory.php 2.51 KB
Newer Older
1
<?php
2

3
4
namespace UnicaenAuth\Provider\Identity;

5
6
7
use BjyAuthorize\Service\Authorize;
use Interop\Container\ContainerInterface;
use UnicaenAuth\Service\UserContext;
8
use Zend\EventManager\EventManager;
9
10
11
12
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
13
 * Intsancie une chaîne de fournisseurs d'identité.
14
15
16
17
18
19
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
class ChainServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
20
21
22
23
24
    {
        return $this->__invoke($serviceLocator, '?');
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
25
26
    {
        $chain = new Chain();
27

28
        /** @var UserContext $userContextService */
29
        $userContextService = $container->get('AuthUserContext');
30
31
32
33

        /* @var $authorizeService Authorize */
        $authorizeService = $container->get('BjyAuthorize\Service\Authorize');

34
35
36
        /** @var EventManager $eventManager */
        $eventManager = $container->get('EventManager');

37
38
        $chain->setUserContextService($userContextService);
        $chain->setAuthorizeService($authorizeService);
39
        $chain->setEventManager($eventManager);
40
41

        $providers = $this->computeProviders($container);
42

43
        foreach ($providers as $priority => $name) {
44
            $provider = $container->get($name);
45
            $chain->getEventManager()->attach('getIdentityRoles', [$provider, 'injectIdentityRoles'], $priority);
46
        }
47

48
49
        return $chain;
    }
50
51

    /**
52
     * @param ContainerInterface $serviceLocator
53
54
     * @return array
     */
55
    private function computeProviders(ContainerInterface $serviceLocator)
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    {
        $config = $serviceLocator->get('Config'); //'unicaen-auth_module_options'
        if (! isset($config['unicaen-auth']['identity_providers']) || ! $config['unicaen-auth']['identity_providers']) {
            throw new \UnicaenApp\Exception\RuntimeException("Aucun fournisseur d'identité spécifié dans la config.");
        }

        $providers = (array) $config['unicaen-auth']['identity_providers'];

        // retrait du fournisseur 'Ldap' si l'auth Ldap est désactivée
        if (isset($config['unicaen-auth']['ldap']['enabled']) && ! $config['unicaen-auth']['ldap']['enabled']) {
            $key = array_search('UnicaenAuth\Provider\Identity\Ldap', $providers, true);
            if ($key !== false) {
                unset($providers[$key]);
            }
        }

        return $providers;
    }
74
}