Completed
Push — master ( 9c5fdf...27a5d2 )
by John
7s
created

YamlParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 55
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parse() 0 7 1
B fixHashMaps() 0 19 5
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\SwaggerBundle\Document\Parser;
10
11
use Symfony\Component\Yaml\Parser;
12
13
/**
14
 * Facade/Adapter for Symfony\Yaml
15
 *
16
 * @author John Kleijn <[email protected]>
17
 */
18
class YamlParser
19
{
20
    /**
21
     * @var Parser
22
     */
23
    private $parser;
24
25
    /**
26
     * Construct the wrapper
27
     */
28
    public function __construct()
29
    {
30
        $this->parser = new Parser();
31
    }
32
33
    /**
34
     * @param string $string
35
     *
36
     * @return mixed
37
     */
38
    public function parse(string $string)
39
    {
40
        // Hashmap support is broken, so disable it and attempt fix afterwards
41
        $data = $this->parser->parse($string, true, false, false);
42
43
        return $this->fixHashMaps($data);
44
    }
45
46
    /**
47
     * @see https://github.com/symfony/symfony/pull/17711
48
     *
49
     * @param mixed $data
50
     *
51
     * @return mixed
52
     */
53
    private function fixHashMaps(&$data)
54
    {
55
        if (is_array($data)) {
56
            $shouldBeObject = false;
57
            $object         = new \stdClass();
58
            $index          = 0;
59
            foreach ($data as $key => &$value) {
60
                $object->$key = $this->fixHashMaps($value);
61
                if ($index++ !== $key) {
62
                    $shouldBeObject = true;
63
                }
64
            }
65
            if ($shouldBeObject) {
66
                $data = $object;
67
            }
68
        }
69
70
        return $data;
71
    }
72
}
73