1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace iamsaint\yml; |
4
|
|
|
|
5
|
|
|
use iamsaint\yml\exceptions\IncorrectRuleException; |
6
|
|
|
use iamsaint\yml\helpers\RuleHelper; |
7
|
|
|
use iamsaint\yml\interfaces\Base; |
8
|
|
|
use XMLWriter; |
9
|
|
|
use function array_key_exists; |
10
|
|
|
use function count; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class BaseObject |
14
|
|
|
* @package iamsaint\yml |
15
|
|
|
* |
16
|
|
|
* @property array $errors |
17
|
|
|
*/ |
18
|
|
|
class BaseObject implements Base |
19
|
|
|
{ |
20
|
|
|
public $errors = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string $groupTag |
24
|
|
|
* @param array|BaseObject[] $elements |
25
|
|
|
* @param XMLWriter $writer |
26
|
|
|
*/ |
27
|
|
|
public function writeElements(XMLWriter $writer, string $groupTag, array $elements): void |
28
|
|
|
{ |
29
|
|
|
$writer->startElement($groupTag); |
30
|
|
|
|
31
|
|
|
foreach ($elements as $element) { |
32
|
|
|
if ($element instanceof Base) { |
33
|
|
|
$element->write($writer); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$writer->endElement(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return bool |
42
|
|
|
* @throws IncorrectRuleException |
43
|
|
|
*/ |
44
|
|
|
public function validate(): bool |
45
|
|
|
{ |
46
|
|
|
$this->errors = []; |
47
|
|
|
$rules = $this->rules(); |
48
|
|
|
foreach ($rules as $rule) { |
49
|
|
|
RuleHelper::validate($this, $rule); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return count($this->errors) === 0; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
|
|
public function rules(): array |
59
|
|
|
{ |
60
|
|
|
return []; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $attribute |
65
|
|
|
* @param string $text |
66
|
|
|
*/ |
67
|
|
|
public function addError($attribute, $text): void |
68
|
|
|
{ |
69
|
|
|
if (!array_key_exists($attribute, $this->errors)) { |
70
|
|
|
$this->errors[$attribute] = []; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$this->errors[$attribute][] = $text; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param XMLWriter $writer |
78
|
|
|
*/ |
79
|
|
|
public function write($writer): void |
80
|
|
|
{ |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param string $tagName |
85
|
|
|
* @param mixed $value |
86
|
|
|
* @param XMLWriter $writer |
87
|
|
|
* @param null|bool $notWriteCondition |
88
|
|
|
*/ |
89
|
|
|
public function writeTag($tagName, $value, $writer, $notWriteCondition = null): void |
90
|
|
|
{ |
91
|
|
|
if ($notWriteCondition !== $value) { |
92
|
|
|
$writer->writeElement($tagName, $value); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|