1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vvval\Spiral\Validation\Checkers; |
4
|
|
|
|
5
|
|
|
use Spiral\ORM\Entities\RecordSource; |
6
|
|
|
use Spiral\ORM\RecordInterface; |
7
|
|
|
use Spiral\Validation\Prototypes\AbstractChecker; |
8
|
|
|
|
9
|
|
|
class EntityChecker extends AbstractChecker |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Default error messages associated with checker method by name. |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
|
|
const MESSAGES = [ |
16
|
|
|
'isUnique' => '[[Must be unique value.]]', |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Check if current value is unique. |
21
|
|
|
* |
22
|
|
|
* @param mixed $value |
23
|
|
|
* @param string $sourceClass |
24
|
|
|
* @param string $field |
25
|
|
|
* |
26
|
|
|
* @return bool |
27
|
|
|
* @throws \Psr\Container\ContainerExceptionInterface |
28
|
|
|
* @throws \Psr\Container\NotFoundExceptionInterface |
29
|
|
|
* @throws \Spiral\Models\Exceptions\EntityExceptionInterface |
30
|
|
|
*/ |
31
|
|
|
public function isUnique($value, string $sourceClass, string $field): bool |
32
|
|
|
{ |
33
|
|
|
$entity = $this->getEntity(); |
34
|
|
|
|
35
|
|
|
//Entity is passed and its value hasn't changed. |
36
|
|
|
if (!empty($entity) && $entity->getField($field) === $value) { |
37
|
|
|
return true; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$source = $this->getSource($sourceClass); |
41
|
|
|
|
42
|
|
|
//Another entity in database with same field value will cause error. |
43
|
|
|
return !$this->hasAnotherEntity($source, $field, $value); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Fetch entity from validation context. |
48
|
|
|
* |
49
|
|
|
* @return RecordInterface|null |
50
|
|
|
*/ |
51
|
|
|
private function getEntity(): ?RecordInterface |
52
|
|
|
{ |
53
|
|
|
return $this->getValidator()->getContext(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Cast record source by its class name. |
58
|
|
|
* |
59
|
|
|
* @param string $sourceClass |
60
|
|
|
* |
61
|
|
|
* @return \Spiral\ORM\Entities\RecordSource |
62
|
|
|
* @throws \Psr\Container\ContainerExceptionInterface |
63
|
|
|
* @throws \Psr\Container\NotFoundExceptionInterface |
64
|
|
|
*/ |
65
|
|
|
private function getSource(string $sourceClass): RecordSource |
66
|
|
|
{ |
67
|
|
|
return $this->container->get($sourceClass); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param RecordSource $source |
72
|
|
|
* @param string $field |
73
|
|
|
* @param mixed $value |
74
|
|
|
* |
75
|
|
|
* @return bool |
76
|
|
|
*/ |
77
|
|
|
private function hasAnotherEntity(RecordSource $source, string $field, $value): bool |
78
|
|
|
{ |
79
|
|
|
return (bool)$source->findOne([$field => $value]); |
80
|
|
|
} |
81
|
|
|
} |