Completed
Push — master ( eea540...1a3db9 )
by Mehmet
02:24
created

Xml   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 10
c 0
b 0
f 0
wmc 11
lcom 1
cbo 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A parse() 0 11 2
A checkFormat() 0 9 2
A getSchema() 0 4 1
A arrayWalkRecursively() 0 12 4
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->getSchema($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 getSchema($schemaData)
62
    {
63
        return $this->arrayWalkRecursively((array) $schemaData);
64
    }
65
66
    private function arrayWalkRecursively(array $schemaData)
67
    {
68
        foreach ($schemaData as $key => $value) {
69
            $newValue = null;
70
            if ($value instanceof SimpleXMLElement) {
71
                $newValue = (array) $value;
72
                $newValue = $this->arrayWalkRecursively($newValue);
73
            }
74
            $schemaData[$key] = $newValue===null ? $value: $newValue;
75
        }
76
        return $schemaData;
77
    }
78
}
79