Passed
Push — master ( 5dce54...909d6e )
by Paweł
12:04 queued 12s
created

LazyServiceTrait::setContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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