Passed
Push — feature/initial-implementation ( 79751f...3b7c72 )
by Fike
01:53
created

PropertyTargetClassAnnotationListener::accept()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 5
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AmaTeam\ElasticSearch\Entity\Annotation\Listener\Mapping\Property;
6
7
use AmaTeam\ElasticSearch\API\Annotation\Mapping\TargetClass;
8
use AmaTeam\ElasticSearch\Entity\Annotation\PropertyAnnotationListenerInterface;
9
use AmaTeam\ElasticSearch\Entity\Entity;
10
use phpDocumentor\Reflection\TypeResolver;
11
use phpDocumentor\Reflection\Types\ContextFactory;
12
use ReflectionProperty;
13
14
class PropertyTargetClassAnnotationListener implements PropertyAnnotationListenerInterface
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 $property, Entity $entity, $annotation): void
32
    {
33
        if (!($annotation instanceof TargetClass)) {
34
            return;
35
        }
36
        $context = $this->contextFactory->createFromReflector($property);
37
        $className = $this->resolver->resolve($annotation->value, $context);
38
        $mapping = $entity->getMapping()->requestProperty($property->getName());
39
        $views = [$mapping->getDefaultView()];
40
        if (!empty($annotation->views)) {
41
            $views = $mapping->requestViews(...$annotation->views);
42
        }
43
        foreach ($views as $view) {
44
            $view->setTargetClass((string) $className);
45
        }
46
    }
47
}
48