1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nip\Records\Traits\Unique; |
4
|
|
|
|
5
|
|
|
use Nip\Database\Query\Condition\Condition; |
6
|
|
|
use Nip\Records\AbstractModels\Record; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class RecordsTrait |
10
|
|
|
* @package Nip\Records\Traits\Unique |
11
|
|
|
*/ |
12
|
|
|
trait RecordsTrait |
13
|
|
|
{ |
14
|
|
|
protected $uniqueFields = null; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param Record $item |
18
|
|
|
* @return bool|false|Record |
19
|
|
|
*/ |
20
|
|
|
public function exists(Record $item) |
21
|
|
|
{ |
22
|
|
|
$params = $this->generateExistsParams($item); |
23
|
|
|
|
24
|
|
|
if (!$params) { |
25
|
|
|
return false; |
26
|
|
|
} |
27
|
|
|
return $this->findOneByParams($params); |
|
|
|
|
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param Record $item |
32
|
|
|
* @return array|bool |
33
|
|
|
*/ |
34
|
1 |
|
public function generateExistsParams(Record $item) |
35
|
|
|
{ |
36
|
1 |
|
$params = []; |
37
|
1 |
|
$params['where'] = []; |
38
|
|
|
|
39
|
1 |
|
$uniqueFields = $this->getUniqueFields(); |
|
|
|
|
40
|
|
|
|
41
|
1 |
|
if (!$uniqueFields) { |
42
|
|
|
return false; |
43
|
|
|
} |
44
|
|
|
|
45
|
1 |
|
foreach ($uniqueFields as $uniqueName => $fields) { |
46
|
1 |
|
$conditions = []; |
47
|
1 |
|
foreach ($fields as $field) { |
48
|
1 |
|
$conditions[] = "`$field` = '{$item->{$field}}'"; |
49
|
|
|
} |
50
|
1 |
|
$params['where'][$uniqueName . '-UNQ'] = implode(' AND ', $conditions); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
$pk = $this->getPrimaryKey(); |
|
|
|
|
54
|
1 |
|
if ($item->getPrimaryKey()) { |
55
|
|
|
$params['where'][] = ["$pk != ?", $item->getPrimaryKey()]; |
56
|
|
|
} |
57
|
1 |
|
return $params; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @return null |
62
|
|
|
*/ |
63
|
2 |
|
public function getUniqueFields() |
64
|
|
|
{ |
65
|
2 |
|
if ($this->uniqueFields === null) { |
66
|
2 |
|
$this->initUniqueFields(); |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
return $this->uniqueFields; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return array|null |
74
|
|
|
*/ |
75
|
2 |
|
public function initUniqueFields() |
76
|
|
|
{ |
77
|
2 |
|
$this->uniqueFields = []; |
78
|
2 |
|
$structure = $this->getTableStructure(); |
|
|
|
|
79
|
2 |
|
foreach ($structure['indexes'] as $name => $index) { |
80
|
2 |
|
if ($index['unique'] && $name != 'PRIMARY') { |
81
|
2 |
|
$this->uniqueFields[$name] = $index['fields']; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
2 |
|
return $this->uniqueFields; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
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.