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

TargetClassListener   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 30
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A accept() 0 13 4
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