Passed
Pull Request — master (#25)
by Jakub
12:34
created

AnnotationLoggableContextCollectionFactory   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 4
Bugs 3 Features 0
Metric Value
eloc 15
c 4
b 3
f 0
dl 0
loc 42
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 21 6
A __construct() 0 4 1
A getLoggableAttribute() 0 9 3
1
<?php
2
3
namespace Locastic\Loggastic\Metadata\LoggableContext\Factory;
4
5
use Locastic\Loggastic\Annotation\Loggable;
6
use Locastic\Loggastic\Metadata\LoggableContext\LoggableContextCollection;
7
use Locastic\Loggastic\Util\RecursiveClassIterator;
8
9
final class AnnotationLoggableContextCollectionFactory implements LoggableContextCollectionFactoryInterface
10
{
11
    /**
12
     * @param string[] $loggablePaths
13
     */
14
    public function __construct(
15
        private readonly LoggableContextCollectionFactoryInterface $decorated,
16
        private readonly array $loggablePaths
17
    ) {}
18
19
    public function create(): LoggableContextCollection
20
    {
21
        if (count($this->loggablePaths) === 0) {
22
            return new LoggableContextCollection([]);
23
        }
24
25
        $classes = [];
26
27
        if ($this->decorated) {
28
            foreach ($this->decorated->create() as $loggableClass => $config) {
29
                $classes[$loggableClass] = $config;
30
            }
31
        }
32
33
        foreach (RecursiveClassIterator::getReflectionClasses($this->loggablePaths) as $className => $reflectionClass) {
34
            if ($loggable = $this->getLoggableAttribute($reflectionClass)) {
35
                $classes[$className] = ['groups' => $loggable->getGroups()];
36
            }
37
        }
38
39
        return new LoggableContextCollection($classes);
40
    }
41
42
    private function getLoggableAttribute(\ReflectionClass $reflectionClass): ?Loggable
43
    {
44
        foreach ($reflectionClass->getAttributes() as $attribute) {
45
            if (is_a($attribute->getName(), Loggable::class, true)) {
46
                return $attribute->newInstance();
47
            }
48
        }
49
50
        return null;
51
    }
52
}