Passed
Push — master ( a169e2...1d919a )
by Paweł
02:02
created

LazyServiceTrait::getAllServices()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
c 2
b 0
f 0
nc 8
nop 0
dl 0
loc 22
rs 8.8333
1
<?php
2
3
namespace pjpawel\LightApi\Container;
4
5
use Psr\Container\ContainerInterface;
6
use ReflectionClass;
7
use ReflectionNamedType;
8
9
trait LazyServiceTrait
10
{
11
12
    public ?ContainerInterface $container;
13
14
    /**
15
     * @inheritDoc
16
     */
17
    public function setContainer(?ContainerInterface $container): void
18
    {
19
        if (isset($this->container)) {
20
            $this->container = $container;
21
        }
22
    }
23
24
    /**
25
     * @inheritDoc
26
     */
27
    public static function getAllServices(): array
28
    {
29
        /** @var array<string,string> $services */
30
        $services = [];
31
        if (get_parent_class(self::class) &&
32
            method_exists(get_parent_class(self::class), __FUNCTION__)) {
33
            $services = parent::getLazyServices();
34
        }
35
        $reflectionClass = new ReflectionClass(self::class);
36
        foreach ($reflectionClass->getMethods() as $method) {
37
            $reflectionAttributes = $method->getAttributes(AsLazyService::class);
38
            if (!isset($reflectionAttributes[0])) {
39
                continue;
40
            }
41
            // Allow to set in AsLazyService is of service
42
            $returnType = $method->getReturnType();
43
            if (!$returnType instanceof ReflectionNamedType || $returnType->isBuiltin()) {
44
                throw new \Exception(sprintf('%s must return class', $method->getName()));
45
            }
46
            $services[self::class . '::' . $method->getName()] = $returnType->getName();
47
        }
48
        return $services;
49
    }
50
51
}