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

PropertyTargetClassAnnotationListener   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

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

2 Methods

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