Created
January 3, 2019 11:04
-
-
Save tobiasfabian/bfe521f1654f3fe9b2ec324c7afea3e7 to your computer and use it in GitHub Desktop.
Kirby Yaml Class with Symfony’s Yaml Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Kirby\Data; | |
use Exception; | |
use Spyc; | |
use \Symfony\Component\Yaml\Yaml as SymfonyYaml; | |
function array_map_recursive(callable $func, array $array) { | |
return filter_var($array, \FILTER_CALLBACK, ['options' => $func]); | |
} | |
/** | |
* Simple Wrapper around Symfony's Yaml Component | |
* | |
* @package Kirby Data | |
* @author Bastian Allgeier <bastian@getkirby.com> | |
* @link http://getkirby.com | |
* @copyright Bastian Allgeier | |
* @license MIT | |
*/ | |
class Yaml extends Handler | |
{ | |
/** | |
* Converts an array to an encoded YAML string | |
* | |
* @param array $data | |
* @return string | |
*/ | |
public static function encode(array $data): string | |
{ | |
// $data, $indent, $wordwrap, $no_opening_dashes | |
// return Spyc::YAMLDump($data, false, false, true); | |
$flag = SymfonyYaml::DUMP_MULTI_LINE_LITERAL_BLOCK; | |
return SymfonyYaml::dump($data, 4, 2, $flag); | |
} | |
/** | |
* Parses an encoded YAML string and returns a multi-dimensional array | |
* | |
* @param string $string | |
* @return array | |
*/ | |
public static function decode($yaml): array | |
{ | |
if (empty($yaml)) { | |
return []; | |
} | |
if (is_array($yaml) === true) { | |
return $yaml; | |
} | |
// $result = Spyc::YAMLLoadString($yaml); | |
$result = SymfonyYaml::parse($yaml); | |
// dump($result); | |
$result = array_map_recursive(function($item) { | |
if (is_string($item)) { | |
return trim($item); | |
} | |
return $item; | |
}, $result); | |
if (is_array($result)) { | |
return $result; | |
} else { | |
throw new Exception('YAML string is invalid'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment