Passed
Push — test ( 33612f...4075b0 )
by Tom
12:36
created

LibYaml::tryParseFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Yaml;
6
7
use Ktomk\Pipelines\ErrorCatcher;
8
9
class LibYaml implements ParserInterface
10
{
11
    /**
12
     * @return bool
13
     */
14 1
    public static function isAvailable()
15
    {
16 1
        return extension_loaded('yaml') && function_exists('yaml_parse');
17
    }
18
19
    /**
20
     * @param string $path
21
     *
22
     * @return array
23
     * @throws ParseException
24
     */
25 2
    public function parseFile($path)
26
    {
27 2
        return Yaml::fileDelegate($path, array($this, 'parseBuffer'));
28
    }
29
30
    /**
31
     * @param string $path
32
     *
33
     * @return null|array
34
     */
35 3
    public function tryParseFile($path)
36
    {
37 3
        return Yaml::fileDelegate($path, array($this, 'tryParseBuffer'));
38
    }
39
40
    /**
41
     * @param string $buffer
42
     *
43
     * @return array
44
     * @throws ParseException
45
     */
46 4
    public function parseBuffer($buffer)
47
    {
48 4
        if (!function_exists('yaml_parse')) {
49
            // @codeCoverageIgnoreStart
50
            throw new \BadMethodCallException('LibYaml based parsing n/a, is the PHP extension loaded?');
51
            // @codeCoverageIgnoreEnd
52
        }
53
54 4
        $error = ErrorCatcher::create();
55 4
        $result = yaml_parse($buffer, 0);
56 4
        $result = $error->end() ? null : $result;
57 4
        if (null === $result && null !== $message = $error->getLastErrorMessage()) {
58 1
            throw new ParseException($message);
59
        }
60 3
        if (!is_array($result)) {
61 1
            throw new ParseException('LibYaml invalid YAML parsing');
62
        }
63
64
        # ext-yaml parser does aliases, remove any potential ones
65 2
        return json_decode(json_encode($result), true);
66
    }
67
68
    /**
69
     * @param string $buffer
70
     *
71
     * @return null|array
72
     */
73 4
    public function tryParseBuffer($buffer)
74
    {
75
        try {
76 4
            $result = $this->parseBuffer($buffer);
77 2
        } catch (ParseException $ex) {
78 2
            return null;
79
        }
80
81 2
        return $result;
82
    }
83
}
84