AbstractServiceFactory::canCreate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\JWTModule\DIFactory;
6
7
use Interop\Container\ContainerInterface;
8
use TMV\JWTModule\Exception\InvalidArgumentException;
9
use Zend\ServiceManager\Factory\AbstractFactoryInterface;
10
11
abstract class AbstractServiceFactory implements AbstractFactoryInterface
12
{
13
    protected const MODULE_KEY = 'jwt_module';
14
15
    abstract protected function getServiceTypeName(): string;
16
17
    /**
18
     * @param ContainerInterface $container
19
     * @param string $requestedName
20
     *
21
     * @throws InvalidArgumentException
22
     *
23
     * @return array
24
     */
25 32
    protected function getServiceConfig(ContainerInterface $container, string $requestedName): array
26
    {
27 32
        if (0 !== \strpos($requestedName, \implode('.', [static::MODULE_KEY, $this->getServiceTypeName(), '']))) {
28 13
            throw new InvalidArgumentException('Invalid service name');
29
        }
30
31
        /** @var string[] $exploded */
32 32
        $exploded = \explode('.', $requestedName);
33 32
        $serviceName = $exploded[2] ?? null;
34
35 32
        if (! $serviceName) {
36
            throw new InvalidArgumentException('Invalid service name');
37
        }
38
39 32
        $keyConfig = $container->get('config')[static::MODULE_KEY][$this->getServiceTypeName()][$serviceName] ?? null;
40
41 32
        if (! \is_array($keyConfig)) {
42
            throw new InvalidArgumentException('Invalid service name');
43
        }
44
45 32
        return $keyConfig;
46
    }
47
48
    /**
49
     * Can the factory create an instance for the service?
50
     *
51
     * @param ContainerInterface $container
52
     * @param string $requestedName
53
     *
54
     * @return bool
55
     */
56 26
    public function canCreate(ContainerInterface $container, $requestedName): bool
57
    {
58
        try {
59 26
            $this->getServiceConfig($container, $requestedName);
60
61 26
            return true;
62 13
        } catch (InvalidArgumentException $e) {
63 13
            return false;
64
        }
65
    }
66
}
67