1
|
|
|
<?php namespace Pz\Doctrine\Rest\BuilderChain; |
2
|
|
|
|
3
|
|
|
use Pz\Doctrine\Rest\BuilderChain\Exceptions\InvalidChainMember; |
4
|
|
|
use Pz\Doctrine\Rest\BuilderChain\Exceptions\InvalidChainMemberResponse; |
5
|
|
|
|
6
|
|
|
class Chain |
7
|
|
|
{ |
8
|
|
|
/** |
9
|
|
|
* @var array |
10
|
|
|
*/ |
11
|
|
|
protected $members = []; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Provide class or interface for verification member return. |
15
|
|
|
* |
16
|
|
|
* @return string|bool |
17
|
|
|
*/ |
18
|
1 |
|
public function buildClass() |
19
|
|
|
{ |
20
|
1 |
|
return false; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param array $members |
25
|
|
|
* |
26
|
|
|
* @return static |
27
|
|
|
*/ |
28
|
13 |
|
public static function create(array $members = []) |
29
|
|
|
{ |
30
|
13 |
|
return new static($members); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* QueryBuilderChain constructor. |
35
|
|
|
* |
36
|
|
|
* @param array|MemberInterface $members |
37
|
|
|
*/ |
38
|
15 |
|
public function __construct(array $members = []) |
39
|
|
|
{ |
40
|
15 |
|
$this->add($members); |
41
|
14 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param array|MemberInterface|callable $member |
45
|
|
|
* |
46
|
|
|
* @return $this |
47
|
|
|
* @throws InvalidChainMember |
48
|
|
|
*/ |
49
|
16 |
|
public function add($member) |
50
|
|
|
{ |
51
|
16 |
|
if (is_array($member)) { |
52
|
15 |
|
foreach ($member as $item) { |
53
|
14 |
|
$this->add($item); |
54
|
|
|
} |
55
|
|
|
|
56
|
14 |
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
15 |
|
if (!is_callable($member)) { |
60
|
1 |
|
throw new InvalidChainMember(); |
61
|
|
|
} |
62
|
|
|
|
63
|
14 |
|
$this->members[] = $member; |
64
|
|
|
|
65
|
14 |
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param object $object |
70
|
|
|
* |
71
|
|
|
* @return object |
72
|
|
|
* |
73
|
|
|
* @throws InvalidChainMember |
74
|
|
|
* @throws InvalidChainMemberResponse |
75
|
|
|
*/ |
76
|
15 |
|
public function process($object) |
77
|
|
|
{ |
78
|
|
|
/** @var callable|MemberInterface $member */ |
79
|
15 |
|
foreach ($this->members as $member) { |
80
|
15 |
|
if (!is_callable($member)) { |
81
|
1 |
|
throw new InvalidChainMember(); |
82
|
|
|
} |
83
|
|
|
|
84
|
14 |
|
$qb = call_user_func($member, $object); |
85
|
|
|
|
86
|
14 |
|
if (($class = $this->buildClass()) && !($qb instanceof $class)) { |
87
|
1 |
|
throw new InvalidChainMemberResponse($class); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|
91
|
13 |
|
return $object; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|