ChainServiceFactory.php 2.35 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
9
10
11
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

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

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

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

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

        $chain->setUserContextService($userContextService);
        $chain->setAuthorizeService($authorizeService);

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

38
        foreach ($providers as $priority => $name) {
39
            $provider = $container->get($name);
40
            $chain->getEventManager()->attach('getIdentityRoles', [$provider, 'injectIdentityRoles'], $priority);
41
        }
42

43
44
        return $chain;
    }
45
46

    /**
47
     * @param ContainerInterface $serviceLocator
48
49
     * @return array
     */
50
    private function computeProviders(ContainerInterface $serviceLocator)
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    {
        $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;
    }
69
}