-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYaml.php
More file actions
55 lines (44 loc) · 1.4 KB
/
Yaml.php
File metadata and controls
55 lines (44 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace Vection\Component\Common;
use Vection\Component\Common\Exception\RuntimeException;
/**
* @author BloodhunterD <bloodhunterd@bloodhunterd.com>
*/
class Yaml
{
public static function parse(string $yaml, bool $immutable = false): VArray
{
if (!function_exists('yaml_parse')) {
throw new RuntimeException('Yaml::parse(yaml) requires php-yaml extension to be enabled.');
}
$data = yaml_parse($yaml);
if ($data === false) {
throw new RuntimeException('Malformed YAML');
}
return new VArray($data ?? [], $immutable);
}
public static function read(string $filePath): VArray
{
return VArray::parseFile($filePath);
}
/**
* @param VArray|array<mixed> $data
*/
public static function encode(VArray|array $data): string
{
if (!function_exists('yaml_emit')) {
throw new RuntimeException('Yaml::encode(yaml) requires php-yaml extension to be enabled.');
}
return yaml_emit(!$data instanceof VArray ?: $data->jsonSerialize());
}
/**
* @param VArray|array<mixed> $data
*/
public static function toFile(string $filePath, VArray|array $data): void
{
if (!file_put_contents($filePath, self::encode($data))) {
throw new RuntimeException('Failed to save YAML data in file.');
}
}
}