Passed
Push — master ( 503f62...3f0369 )
by Tom
13:13 queued 10:28
created

Yaml::fileDelegate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
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\LibFsStream;
8
9
class Yaml
10
{
11
    /**
12
     * @var array of Yaml parser classes
13
     *
14
     * @see ParserInterface
15
     * @see Yaml::parser()
16
     */
17
    public static $classes = array();
18
19
    /**
20
     * @param string $file
21
     *
22
     * @throws \InvalidArgumentException
23
     *
24
     * @return null|array on error
25
     */
26 3
    public static function file($file)
27
    {
28 3
        $path = '-' === $file ? 'php://stdin' : $file;
29
30 3
        $path = LibFsStream::fdToPhp($path);
31
32 3
        if (!LibFsStream::isReadable($path)) {
33 1
            throw new \InvalidArgumentException(
34 1
                sprintf("not a readable file: '%s'", $file)
35
            );
36
        }
37
38 2
        return self::parser()->parseFile($path);
39
    }
40
41
    /**
42
     * error-free (suppressed) file_get_contents()
43
     *
44
     * available for implementations aligned with {@see Yaml::file()}
45
     * that already checks readability before getting the contents.
46
     *
47
     * fall-back on file-reading error is null.
48
     *
49
     * @param string $path
50
     * @param callable $parseBuffer function(string $buffer): array|null
51
     *
52
     * @return null|array
53
     */
54 4
    public static function fileDelegate($path, $parseBuffer)
55
    {
56 4
        $buffer = @file_get_contents($path);
57
58 4
        return false === $buffer ? null : call_user_func($parseBuffer, $buffer);
59
    }
60
61
    /**
62
     * @param string $buffer
63
     *
64
     * @return null|array
65
     */
66 2
    public static function buffer($buffer)
67
    {
68 2
        return self::parser()->parseBuffer($buffer);
69
    }
70
71
    /**
72
     * @return ParserInterface
73
     */
74 4
    private static function parser()
75
    {
76 4
        $classes = self::$classes ?: array(
77 3
            'Ktomk\Pipelines\Yaml\LibYaml',
78
            'Ktomk\Pipelines\Yaml\Sf2Yaml',
79
        );
80
81 4
        foreach ($classes as $class) {
82
            if (
83 4
                class_exists($class)
84 4
                && is_subclass_of($class, 'Ktomk\Pipelines\Yaml\ParserInterface')
85 4
                && $class::isAvailable()
86
            ) {
87 3
                return new $class();
88
            }
89
        }
90
91 1
        throw new \BadMethodCallException(sprintf('No YAML parser available'));
92
    }
93
}
94