Completed
Push — master ( 111bcd...99ca87 )
by Andrey
26:30
created

DriverChainFactory::createService()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
rs 6.7272
cc 7
eloc 20
nc 5
nop 1
1
<?php
2
/**
3
 * @link    https://github.com/nnx-framework/jms-serializer-module
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\JmsSerializerModule\MetadataDriver;
7
8
use Zend\ServiceManager\FactoryInterface;
9
use Zend\ServiceManager\MutableCreationOptionsInterface;
10
use Zend\ServiceManager\MutableCreationOptionsTrait;
11
use Zend\ServiceManager\ServiceLocatorInterface;
12
use Metadata\Driver\DriverChain;
13
use Metadata\Driver\DriverInterface;
14
15
/**
16
 * Class DriverChainFactory
17
 *
18
 * @package Nnx\JmsSerializerModule\MetadataDriver
19
 */
20
class DriverChainFactory implements FactoryInterface, MutableCreationOptionsInterface
21
{
22
    use MutableCreationOptionsTrait;
23
24
    /**
25
     * @param ServiceLocatorInterface $serviceLocator
26
     *
27
     * @return LazyLoadingDriver
28
     * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
29
     * @throws \Nnx\JmsSerializerModule\MetadataDriver\Exception\RuntimeException
30
     */
31
    public function createService(ServiceLocatorInterface $serviceLocator)
32
    {
33
        $creationOptions = $this->getCreationOptions();
34
35
        $targetDrivers = [];
36
        if (array_key_exists('drivers', $creationOptions)) {
37
            $drivers = $creationOptions['drivers'];
38
39
            if (!is_array($drivers)) {
40
                $errMsg = 'Drivers config is not array';
41
                throw new Exception\RuntimeException($errMsg);
42
            }
43
44
            foreach ($drivers as $driver) {
45
                $targetDriver = $driver;
46
                if (is_string($driver)) {
47
                    $targetDriver = $serviceLocator->get($driver);
48
                }
49
50
                if (!$targetDriver instanceof DriverInterface) {
51
                    $errMsg = sprintf(
52
                        'Driver of type %s is invalid; must implement %s',
53
                        (is_object($targetDriver) ? get_class($targetDriver) : gettype($targetDriver)),
54
                        DriverInterface::class
55
                    );
56
                    throw new Exception\RuntimeException($errMsg);
57
                }
58
59
                $targetDrivers[] = $targetDriver;
60
            }
61
        }
62
63
        return new DriverChain($targetDrivers);
64
    }
65
}
66