Skip to content

Instantly share code, notes, and snippets.

@tobiasfabian
Created January 3, 2019 11:04
Show Gist options
  • Save tobiasfabian/bfe521f1654f3fe9b2ec324c7afea3e7 to your computer and use it in GitHub Desktop.
Save tobiasfabian/bfe521f1654f3fe9b2ec324c7afea3e7 to your computer and use it in GitHub Desktop.
Kirby Yaml Class with Symfony’s Yaml Component
<?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