Passed
Push — master ( 743cc2...6ffec3 )
by Oleg
02:50
created

UniqueProviderDecorator::prepareUnique()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 8
cp 0
crap 12
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DFCodeGeneration\Generator\Controllers;
5
6
use Doctrine\Common\Annotations\AnnotationReader;
7
use Zend\Code\Reflection\ClassReflection;
8
9
class UniqueProviderDecorator implements DataProviderDecoratorInterface
10
{
11
    /**
12
     * @var bool
13
     */
14
    private $hasUnique = false;
15
    /**
16
     * @var string[]
17
     */
18
    private $uniqueFields = [];
19
    /**
20
     * @var string
21
     */
22
    private $entityClassName;
23
24
    public function __construct(string $entityClassName)
25
    {
26
        $this->entityClassName = $entityClassName;
27
    }
28
29
    /**
30
     * @throws \Doctrine\Common\Annotations\AnnotationException
31
     * @throws \ReflectionException
32
     */
33
    private function prepareUnique(): void
34
    {
35
        $reflectionClassName = new ClassReflection($this->entityClassName);
36
        foreach ($reflectionClassName->getProperties() as $property) {
37
            /** @var \Doctrine\ORM\Mapping\Column $annotation */
38
            $annotation = (new AnnotationReader())
39
                ->getPropertyAnnotation($property, \Doctrine\ORM\Mapping\Column::class);
40
            if ($annotation->unique) {
41
                $this->uniqueFields[] = $property->getName();
42
                $this->hasUnique = true;
43
            }
44
        }
45
    }
46
47
    /**
48
     * @param array $data
49
     * @return array
50
     * @throws \Doctrine\Common\Annotations\AnnotationException
51
     * @throws \ReflectionException
52
     */
53
    public function decorate(array $data): array
54
    {
55
        $this->prepareUnique();
56
57
        $message = '';
58
        if ($this->hasUnique) {
59
            $message = sprintf(
60
                'Provided %s already exist%s.',
61
                implode(' or ', $this->uniqueFields),
62
                count($this->uniqueFields) > 1 ? '' : 's'
63
            );
64
        }
65
66
        $data['hasUnique'] = $this->hasUnique;
67
        $data['uniqueIdxMessage'] = $message;
68
69
        return $data;
70
    }
71
}
72