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
|
|
|
* @throws ParseException |
23
|
|
|
* |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
2 |
|
public function parseFile($path) |
27
|
|
|
{ |
28
|
2 |
|
return Yaml::fileDelegate($path, array($this, 'parseBuffer')); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $path |
33
|
|
|
* |
34
|
|
|
* @return null|array |
35
|
|
|
*/ |
36
|
3 |
|
public function tryParseFile($path) |
37
|
|
|
{ |
38
|
3 |
|
return Yaml::fileDelegate($path, array($this, 'tryParseBuffer')); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $buffer |
43
|
|
|
* |
44
|
|
|
* @throws ParseException |
45
|
|
|
* |
46
|
|
|
* @return array |
47
|
|
|
*/ |
48
|
4 |
|
public function parseBuffer($buffer) |
49
|
|
|
{ |
50
|
4 |
|
if (!function_exists('yaml_parse')) { |
51
|
|
|
// @codeCoverageIgnoreStart |
52
|
|
|
throw new \BadMethodCallException('LibYaml based parsing n/a, is the PHP extension loaded?'); |
53
|
|
|
// @codeCoverageIgnoreEnd |
54
|
|
|
} |
55
|
|
|
|
56
|
4 |
|
$error = ErrorCatcher::create(); |
57
|
4 |
|
$result = yaml_parse($buffer, 0); |
58
|
4 |
|
$result = $error->end() ? null : $result; |
59
|
4 |
|
if (null === $result && null !== $message = $error->getLastErrorMessage()) { |
60
|
1 |
|
throw new ParseException($message); |
61
|
|
|
} |
62
|
3 |
|
if (!is_array($result)) { |
63
|
1 |
|
throw new ParseException('LibYaml invalid YAML parsing'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
# ext-yaml parser does aliases, remove any potential ones |
67
|
2 |
|
return json_decode(json_encode($result), true); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param string $buffer |
72
|
|
|
* |
73
|
|
|
* @return null|array |
74
|
|
|
*/ |
75
|
4 |
|
public function tryParseBuffer($buffer) |
76
|
|
|
{ |
77
|
|
|
try { |
78
|
4 |
|
$result = $this->parseBuffer($buffer); |
79
|
2 |
|
} catch (ParseException $ex) { |
80
|
2 |
|
return null; |
81
|
|
|
} |
82
|
|
|
|
83
|
2 |
|
return $result; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|