Passed
Push — master ( 77b471...6dcba4 )
by Pedro
49s
created

AbstractElasticsearchServiceFactory::getFactory()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 21
ccs 15
cts 15
cp 1
rs 9.0534
c 1
b 0
f 0
cc 4
eloc 14
nc 3
nop 2
crap 4
1
<?php
2
3
namespace ElasticsearchModule\ServiceFactory;
4
5
use Interop\Container\ContainerInterface;
6
use Zend\ServiceManager\Factory\AbstractFactoryInterface;
7
use Zend\ServiceManager\Factory\FactoryInterface;
8
use Zend\ServiceManager\ServiceLocatorInterface;
9
10
/**
11
 * @author Pedro Alves <[email protected]>
12
 */
13
class AbstractElasticsearchServiceFactory implements AbstractFactoryInterface
14
{
15
16
    /**
17
     * {@inheritDoc}
18
     */
19 1
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
20
    {
21 1
        $factory = $this->getFactory($container, $requestedName);
22 1
        return $factory($container, $requestedName);
23
    }
24
25
    /**
26
     * {@inheritDoc}
27
     */
28 8
    public function canCreate(ContainerInterface $container, $requestedName)
29
    {
30 8
        return $this->getFactory($container, $requestedName) !== null;
31
    }
32
33
    /**
34
     * @param ContainerInterface $container
35
     * @param string $requestedName
36
     * @return FactoryInterface
37
     */
38 8
    private function getFactory(ContainerInterface $container, $requestedName)
39
    {
40 8
        $pattern = "/^elasticsearch\.(?P<serviceType>[a-z0-9_-]+)\.(?P<serviceName>[a-z0-9_-]+)$/";
41 8
        $matches = [];
42
        
43 8
        if (!preg_match($pattern, $requestedName, $matches)) {
44 1
            return null;
45
        }
46 8
        $serviceType = $matches['serviceType'];
47 8
        $serviceName = $matches['serviceName'];
48 8
        $config = $container->get('Config');
49 8
        $elasticsearchModuleConfig = $config['elasticsearch'];
50
        
51 8
        if (!isset($elasticsearchModuleConfig[$serviceType]) ||
52 1
            !isset($config['elasticsearch_factories'][$serviceType])
53 8
        ) {
54 7
            return null;
55
        }
56 1
        $factoryClass = $config['elasticsearch_factories'][$serviceType];
57 1
        return new $factoryClass($serviceName);
58
    }
59
}
60