1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Selami\Entity\Parser; |
5
|
|
|
|
6
|
|
|
use Selami\Entity\Interfaces\ParserInterface; |
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use SimpleXMLElement; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* XML Parser |
12
|
|
|
* |
13
|
|
|
* @package Selami\Entity\Parser |
14
|
|
|
*/ |
15
|
|
|
class Xml implements ParserInterface |
16
|
|
|
{ |
17
|
|
|
use ParserTrait; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Config constructor. |
21
|
|
|
* |
22
|
|
|
* @param string $schemaConfig |
23
|
|
|
* @throws InvalidArgumentException |
24
|
|
|
* |
25
|
|
|
*/ |
26
|
|
|
public function __construct(string $schemaConfig = null) |
27
|
|
|
{ |
28
|
|
|
if ($schemaConfig !== null) { |
29
|
|
|
$this->setConfig($schemaConfig); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritDoc} |
35
|
|
|
*/ |
36
|
|
|
public function parse() |
37
|
|
|
{ |
38
|
|
|
$this->isConfigEmpty($this->schemaConfig); |
39
|
|
|
try { |
40
|
|
|
$schemaData = new SimpleXMLElement($this->schemaConfig); |
41
|
|
|
} catch (\Exception $e) { |
42
|
|
|
throw new InvalidArgumentException($e->getMessage()); |
43
|
|
|
} |
44
|
|
|
$schema = $this->checkSchemaData($schemaData); |
45
|
|
|
return ['schema' => $schema]; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* {@inheritDoc} |
50
|
|
|
*/ |
51
|
|
|
public function checkFormat() |
52
|
|
|
{ |
53
|
|
|
try { |
54
|
|
|
new SimpleXMLElement($this->schemaConfig); |
55
|
|
|
} catch (\Exception $e) { |
56
|
|
|
return false; |
57
|
|
|
} |
58
|
|
|
return true; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function checkSchemaData($schemaData) |
62
|
|
|
{ |
63
|
|
|
if ($schemaData instanceof SimpleXMLElement) { |
64
|
|
|
return $this->arrayWalkRecursively((array) $schemaData); |
65
|
|
|
} |
66
|
|
|
return []; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private function arrayWalkRecursively(array $schemaData) |
70
|
|
|
{ |
71
|
|
|
foreach ($schemaData as $key => $value) { |
72
|
|
|
$newValue = null; |
73
|
|
|
if ($value instanceof SimpleXMLElement) { |
74
|
|
|
$newValue = (array) $value; |
75
|
|
|
$newValue = $this->arrayWalkRecursively($newValue); |
76
|
|
|
} |
77
|
|
|
$schemaData[$key] = $newValue===null ? $value: $newValue; |
78
|
|
|
} |
79
|
|
|
return $schemaData; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|