Passed
Push — feature/initial-implementation ( 0c2c6c...79751f )
by Fike
01:54
created

TargetClassListener::accept()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 5
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AmaTeam\ElasticSearch\Mapping\Annotation\Property\Listener;
6
7
use AmaTeam\ElasticSearch\API\Annotation\Mapping\TargetClass;
8
use AmaTeam\ElasticSearch\Mapping\Annotation\Property\AnnotationListenerInterface;
9
use AmaTeam\ElasticSearch\Mapping\PropertyMapping;
10
use phpDocumentor\Reflection\TypeResolver;
11
use phpDocumentor\Reflection\Types\ContextFactory;
12
use ReflectionProperty;
13
14
class TargetClassListener implements AnnotationListenerInterface
15
{
16
    /**
17
     * @var TypeResolver
18
     */
19
    private $resolver;
20
    /**
21
     * @var ContextFactory
22
     */
23
    private $contextFactory;
24
25
    public function __construct()
26
    {
27
        $this->resolver = new TypeResolver();
28
        $this->contextFactory = new ContextFactory();
29
    }
30
31
    public function accept(ReflectionProperty $reflection, PropertyMapping $descriptor, $annotation): void
32
    {
33
        if (!($annotation instanceof TargetClass)) {
34
            return;
35
        }
36
        $views = $descriptor->getDefaultView();
37
        if (!empty($annotation->views)) {
38
            $views = $descriptor->requestViews(...$annotation->views);
39
        }
40
        $context = $this->contextFactory->createFromReflector($reflection);
41
        $className = $this->resolver->resolve($annotation->value, $context);
42
        foreach ($views as $view) {
43
            $view->setTargetClass((string) $className);
44
        }
45
    }
46
}
47