Completed
Pull Request — 1.x (#637)
by Daniel
14:10 queued 04:01
created

AdapterChainServiceFactory::setOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
namespace ZfcUser\Authentication\Adapter;
3
4
use Zend\ServiceManager\FactoryInterface;
5
use Zend\ServiceManager\ServiceLocatorInterface;
6
use ZfcUser\Authentication\Adapter\AdapterChain;
7
use ZfcUser\Options\ModuleOptions;
8
use ZfcUser\Authentication\Adapter\Exception\OptionsNotFoundException;
9
10
class AdapterChainServiceFactory implements FactoryInterface
11
{
12
13
    /**
14
     * @var ModuleOptions
15
     */
16
    protected $options;
17
18
    public function createService(ServiceLocatorInterface $serviceLocator)
19
    {
20
        $chain = new AdapterChain();
21
22
        $options = $this->getOptions($serviceLocator);
23
24
        //iterate and attach multiple adapters and events if offered
25
        foreach ($options->getAuthAdapters() as $priority => $adapterName) {
26
            $adapter = $serviceLocator->get($adapterName);
27
28
            if (is_callable(array($adapter, 'authenticate'))) {
29
                $chain->getEventManager()->attach('authenticate', array($adapter, 'authenticate'), $priority);
30
            }
31
32
            if (is_callable(array($adapter, 'logout'))) {
33
                $chain->getEventManager()->attach('logout', array($adapter, 'logout'), $priority);
34
            }
35
        }
36
37
        return $chain;
38
    }
39
40
41
    /**
42
     * set options
43
     *
44
     * @param ModuleOptions $options
45
     * @return AdapterChainServiceFactory
46
     */
47
    public function setOptions(ModuleOptions $options)
48
    {
49
        $this->options = $options;
50
        return $this;
51
    }
52
53
    /**
54
     * get options
55
     *
56
     * @param ServiceLocatorInterface $serviceLocator (optional) Service Locator
57
     * @return ModuleOptions $options
58
     * @throws OptionsNotFoundException If options tried to retrieve without being set but no SL was provided
59
     */
60
    public function getOptions(ServiceLocatorInterface $serviceLocator = null)
61
    {
62
        if (!$this->options) {
63
            if (!$serviceLocator) {
64
                throw new OptionsNotFoundException(
65
                    'Options were tried to retrieve but not set ' .
66
                    'and no service locator was provided'
67
                );
68
            }
69
70
            $this->setOptions($serviceLocator->get('zfcuser_module_options'));
71
        }
72
73
        return $this->options;
74
    }
75
}
76