|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Nip\Records\Traits\HasManager; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Nip\Records\AbstractModels\RecordManager; |
|
7
|
|
|
use Nip\Records\Locator\ModelLocator; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Trait HasManagerRecordTrait |
|
11
|
|
|
* @package Nip\Records\Traits\HasManager |
|
12
|
|
|
*/ |
|
13
|
|
|
trait HasManagerRecordTrait |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var string |
|
17
|
|
|
*/ |
|
18
|
|
|
protected $managerName = null; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @return RecordManager |
|
22
|
|
|
*/ |
|
23
|
9 |
|
public function getManager() |
|
24
|
|
|
{ |
|
25
|
9 |
|
return ModelLocator::get($this->getManagerName()); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param RecordManager $manager |
|
30
|
|
|
*/ |
|
31
|
11 |
|
public function setManager($manager) |
|
32
|
|
|
{ |
|
33
|
11 |
|
$class = get_class($manager); |
|
34
|
11 |
|
ModelLocator::set($class, $manager); |
|
35
|
11 |
|
$this->setManagerName($class); |
|
36
|
11 |
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @return string |
|
40
|
|
|
*/ |
|
41
|
12 |
|
public function getManagerName() |
|
42
|
|
|
{ |
|
43
|
12 |
|
if ($this->managerName === null) { |
|
44
|
5 |
|
$this->initManagerName(); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
12 |
|
return $this->managerName; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param string $managerName |
|
52
|
|
|
*/ |
|
53
|
14 |
|
public function setManagerName($managerName) |
|
54
|
|
|
{ |
|
55
|
14 |
|
$this->managerName = $managerName; |
|
56
|
14 |
|
} |
|
57
|
|
|
|
|
58
|
5 |
|
protected function initManagerName() |
|
59
|
|
|
{ |
|
60
|
5 |
|
$this->setManagerName($this->inflectManagerName()); |
|
61
|
5 |
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @return string |
|
65
|
|
|
*/ |
|
66
|
5 |
|
protected function inflectManagerName() |
|
67
|
|
|
{ |
|
68
|
5 |
|
return ucfirst(inflector()->pluralize($this->getClassName())); |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param string $class |
|
73
|
|
|
* @return RecordManager |
|
74
|
|
|
* @throws Exception |
|
75
|
|
|
*/ |
|
76
|
|
|
protected function getManagerInstance($class) |
|
77
|
|
|
{ |
|
78
|
|
|
if (class_exists($class)) { |
|
79
|
|
|
return call_user_func([$class, 'instance']); |
|
80
|
|
|
} |
|
81
|
|
|
throw new Exception('invalid manager name [' . $class . ']'); |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
} |
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
Idableprovides a methodequalsIdthat 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.