-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuilderAbstract.php
96 lines (83 loc) · 2.19 KB
/
BuilderAbstract.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace ABC\Builder;
use \ABC\Builder\BuilderAction;
use \Exception;
abstract class BuilderAbstract
{
/** @var array(\ABC\Builder\BuilderAction) */
public $builderActions = array();
/** @var bool */
public $executed = false;
/** @var array(callable) */
public $validations = array();
/**
* @return null
*/
public function execute()
{
foreach ($this->builderActions as $action) {
call_user_func_array($action->action, $action->arguments);
}
$this->validate();
$this->executed = true;
return $this;
}
/**
* @return \ABC\Builder\BaseAbstract
*/
public function addAction($action)
{
$this->builderActions[] = $action;
return $this;
}
/**
* @throws \Exception
*/
public function checkStatus()
{
if (!$this->executed) {
throw new Exception('Builder actions not executed');
}
}
/**
* @throws \Exception
*/
protected function validate()
{
$actions = $this->compileActionCounts();
foreach ($this->validations as $validation) {
$result = call_user_func_array($validation['callback'], array($actions));
if (!$result) {
$class = $validation['exceptionType'];
throw new $class($validation['exceptionMessage']);
}
}
}
/**
* @return array
*/
protected function compileActionCounts()
{
$counts = array();
foreach ($this->builderActions as $action) {
$counts[$action->name] = isset($counts[$action->name]) ? $counts[$action->name]+1 : 1;
}
return $counts;
}
/**
* @param callable $callback
* @param string $exceptionType
* @param string $exceptionMessage
*
* @return \ABC\Builder\BuilderAbstract
*/
protected function addValidation($callback, $exceptionType, $exceptionMessage = '')
{
$this->validations[] = array(
'callback' => $callback,
'exceptionType' => $exceptionType,
'exceptionMessage' => $exceptionMessage,
);
return $this;
}
}