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

YamlParser::fixHashMaps()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 8.8571
cc 5
eloc 12
nc 3
nop 1
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