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
|
|
|
|