1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SleepingOwl\Admin\Form\Related; |
4
|
|
|
|
5
|
|
|
use Validator; |
6
|
|
|
|
7
|
|
|
trait HasUniqueValidation |
8
|
|
|
{ |
9
|
|
|
protected $unique; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Columns, that should be unique. |
13
|
|
|
* |
14
|
|
|
* @param array $columns |
15
|
|
|
* @param string|null $message |
16
|
|
|
* |
17
|
|
|
* @return static |
18
|
|
|
*/ |
19
|
|
|
public function unique(array $columns, $message = null) |
20
|
|
|
{ |
21
|
|
|
$this->initializeUniqueValidator($message); |
22
|
|
|
$this->unique = $columns; |
23
|
|
|
|
24
|
|
|
return $this; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
protected function initializeUniqueValidator($message = null) |
28
|
|
|
{ |
29
|
|
|
Validator::extendImplicit('unique_related', function () { |
30
|
|
|
return false; |
31
|
|
|
}, $message); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getValidationRules() |
35
|
|
|
{ |
36
|
|
|
$this->addUniqueValidation(); |
37
|
|
|
|
38
|
|
|
return parent::getValidationRules(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
protected function addUniqueValidation() |
42
|
|
|
{ |
43
|
|
|
if (count((array) $this->unique) > 0) { |
44
|
|
|
$pairs = []; |
45
|
|
|
$parameters = array_unique(array_merge([ |
46
|
|
|
$mainKey = $this->getModel()->getForeignKey(), |
|
|
|
|
47
|
|
|
], $this->unique)); |
48
|
|
|
|
49
|
|
|
$errorColumns = array_filter($parameters, function ($param) use ($mainKey) { |
50
|
|
|
return $param !== $mainKey; |
51
|
|
|
}); |
52
|
|
|
|
53
|
|
|
$relations = (array) request($this->relationName); |
54
|
|
|
|
55
|
|
|
foreach ($relations as $index => $relation) { |
56
|
|
|
$relation[$mainKey] = $this->getModel()->getKey(); |
57
|
|
|
$key = $this->getCompositeKey($relation, (array) $parameters); |
|
|
|
|
58
|
|
|
|
59
|
|
|
if (array_key_exists($key, $pairs)) { |
60
|
|
|
foreach ($errorColumns as $column) { |
61
|
|
|
$this->validationRules[$this->relationName.'.'.$index.'.'.$column] = 'unique_related'; |
|
|
|
|
62
|
|
|
} |
63
|
|
|
} else { |
64
|
|
|
$pairs[$key] = true; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|