1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace floor12\DalliApi\Models; |
4
|
|
|
|
5
|
|
|
use floor12\DalliApi\Exceptions\EmptyApiMethodException; |
6
|
|
|
use ReflectionClass; |
7
|
|
|
use ReflectionException; |
8
|
|
|
use SimpleXMLElement; |
9
|
|
|
|
10
|
|
|
class DalliApiBody extends BaseXmlObject |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
protected $authToken; |
14
|
|
|
/** @var string */ |
15
|
|
|
protected $apiMethodName; |
16
|
|
|
/** @var SimpleXMLElement */ |
17
|
|
|
public $mainElement; |
18
|
|
|
/** @var array|null */ |
19
|
|
|
private $params; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* DalliApiBody constructor. |
23
|
|
|
* @param string|null $apiMethodName |
24
|
|
|
* @param array|null $params |
25
|
|
|
* @throws EmptyApiMethodException |
26
|
|
|
*/ |
27
|
6 |
|
public function __construct(?string $apiMethodName, ?array $params = []) |
28
|
|
|
{ |
29
|
6 |
|
if (empty($apiMethodName)) |
30
|
1 |
|
throw new EmptyApiMethodException(); |
31
|
|
|
|
32
|
5 |
|
$this->apiMethodName = $apiMethodName; |
33
|
5 |
|
$this->mainElement = new SimpleXMLElement("<$this->apiMethodName></$this->apiMethodName>"); |
34
|
5 |
|
$this->params = $params; |
35
|
5 |
|
$this->parseParamsToXml(); |
36
|
5 |
|
} |
37
|
|
|
|
38
|
|
|
|
39
|
5 |
|
private function parseParamsToXml(): void |
40
|
|
|
{ |
41
|
5 |
|
if (empty($this->params)) |
42
|
4 |
|
return; |
43
|
1 |
|
$this->addParamArrayToElement($this->mainElement, $this->params); |
44
|
1 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param SimpleXMLElement $element |
48
|
|
|
* @param array $paramsArray |
49
|
|
|
*/ |
50
|
1 |
|
private function addParamArrayToElement(SimpleXMLElement $element, array $paramsArray): void |
51
|
|
|
{ |
52
|
1 |
|
foreach ($paramsArray as $paramName => $paramValue) { |
53
|
1 |
|
$child = $element->addChild($paramName); |
54
|
1 |
|
if (is_array($paramValue)) { |
55
|
1 |
|
$this->addParamArrayToElement($child, $paramValue); |
56
|
|
|
} else { |
57
|
1 |
|
$child[0] = $paramValue; |
58
|
|
|
} |
59
|
|
|
} |
60
|
1 |
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param BaseXmlObject $object |
64
|
|
|
* @return $this |
65
|
|
|
* @throws ReflectionException |
66
|
|
|
*/ |
67
|
1 |
|
public function add(BaseXmlObject $object): self |
68
|
|
|
{ |
69
|
1 |
|
$className = mb_strtolower((new ReflectionClass($object))->getShortName()); |
70
|
1 |
|
$mainElement = $this->mainElement->addChild($className); |
71
|
1 |
|
foreach ($object as $attributeName => $attributeValue) { |
72
|
1 |
|
$this->processAttributeNameAndValue($mainElement, $attributeName, $attributeValue); |
73
|
|
|
} |
74
|
1 |
|
return $this; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param BaseXmlObject|null $object |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
5 |
|
public function getAsXmlString(BaseXmlObject $object = null): string |
82
|
|
|
{ |
83
|
5 |
|
return $this->mainElement->asXML(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|