1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Rinvex\Support\Traits; |
6
|
|
|
|
7
|
|
|
trait UniqueInjector |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Prepare a unique rule, adding the table name, column and model indetifier |
11
|
|
|
* if required. |
12
|
|
|
* |
13
|
|
|
* @param array $parameters |
14
|
|
|
* @param string $field |
15
|
|
|
* |
16
|
|
|
* @return string |
17
|
|
|
*/ |
18
|
|
|
protected function prepareUniqueRule($parameters, $field) |
19
|
|
|
{ |
20
|
|
|
// If the table name isn't set, infer it. |
21
|
|
|
if (empty($parameters[0])) { |
22
|
|
|
$parameters[0] = $this->getModel()->getTable(); |
|
|
|
|
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
// If the connection name isn't set but exists, infer it. |
26
|
|
|
if ((mb_strpos($parameters[0], '.') === false) && (($connectionName = $this->getModel()->getConnectionName()) !== null)) { |
|
|
|
|
27
|
|
|
$parameters[0] = $connectionName.'.'.$parameters[0]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
// If the field name isn't get, infer it. |
31
|
|
|
if (! isset($parameters[1])) { |
32
|
|
|
$parameters[1] = $field; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if ($this->exists) { |
|
|
|
|
36
|
|
|
// If the identifier isn't set, infer it. |
37
|
|
|
if (! isset($parameters[2]) || mb_strtolower($parameters[2]) === 'null') { |
38
|
|
|
$parameters[2] = $this->getModel()->getKey(); |
|
|
|
|
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// If the primary key isn't set, infer it. |
42
|
|
|
if (! isset($parameters[3])) { |
43
|
|
|
$parameters[3] = $this->getModel()->getKeyName(); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// If the additional where clause isn't set, infer it. |
47
|
|
|
// Example: unique:abilities,resource,123,id,action,NULL |
|
|
|
|
48
|
|
|
foreach ($parameters as $key => $parameter) { |
49
|
|
|
if (mb_strtolower((string) $parameter) === 'null') { |
50
|
|
|
$parameters[$key] = $this->getModel()->{$parameters[$key - 1]}; |
|
|
|
|
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return 'unique:'.implode(',', $parameters); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.