1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
5
|
|
|
* @license https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE |
6
|
|
|
* @link https://github.com/flipboxfactory/craft-ember |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace flipbox\ember\services\traits\records; |
10
|
|
|
|
11
|
|
|
use flipbox\ember\exceptions\RecordNotFoundException; |
12
|
|
|
use yii\db\ActiveRecord as Record; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @author Flipbox Factory <[email protected]> |
16
|
|
|
* @since 1.0.0 |
17
|
|
|
* |
18
|
|
|
* @method Record parentFind($identifier) |
19
|
|
|
*/ |
20
|
|
|
trait AccessorByString |
21
|
|
|
{ |
22
|
|
|
use Accessor { |
23
|
|
|
find as parentFind; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @return string |
28
|
|
|
*/ |
29
|
|
|
abstract protected static function stringProperty(): string; |
30
|
|
|
|
31
|
|
|
/******************************************* |
32
|
|
|
* OVERRIDE |
33
|
|
|
*******************************************/ |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param $identifier |
37
|
|
|
* @return Record|null |
38
|
|
|
*/ |
39
|
|
|
public function find($identifier) |
40
|
|
|
{ |
41
|
|
|
if (!is_numeric($identifier) && is_string($identifier)) { |
42
|
|
|
return $this->findByString($identifier); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $this->parentFind($identifier); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/******************************************* |
49
|
|
|
* FIND STRING |
50
|
|
|
*******************************************/ |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param string $string |
54
|
|
|
* @return Record|null |
55
|
|
|
*/ |
56
|
|
|
public function findByString(string $string) |
57
|
|
|
{ |
58
|
|
|
return $this->findByCondition( |
59
|
|
|
[self::stringProperty() => $string] |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $string |
65
|
|
|
* @throws RecordNotFoundException |
66
|
|
|
* @return Record|null |
67
|
|
|
*/ |
68
|
|
|
public function getByString(string $string) |
69
|
|
|
{ |
70
|
|
|
if (null === ($record = $this->findByString($string))) { |
71
|
|
|
$this->notFoundByStringException($string); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $record; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param string|null $string |
79
|
|
|
* @throws RecordNotFoundException |
80
|
|
|
*/ |
81
|
|
|
protected function notFoundByStringException(string $string = null) |
82
|
|
|
{ |
83
|
|
|
throw new RecordNotFoundException( |
84
|
|
|
sprintf( |
85
|
|
|
'Record does not exist with the string "%s".', |
86
|
|
|
(string)$string |
87
|
|
|
) |
88
|
|
|
); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|