diff --git a/src/Actions/ConvertsArrayToFrontMatter.php b/src/Actions/ConvertsArrayToFrontMatter.php index 567ca3d6..71e36652 100644 --- a/src/Actions/ConvertsArrayToFrontMatter.php +++ b/src/Actions/ConvertsArrayToFrontMatter.php @@ -2,10 +2,12 @@ namespace Hyde\Framework\Actions; +use Symfony\Component\Yaml\Yaml; + /** * Convert an array into YAML Front Matter. * - * Currently, does not support nested arrays. + * @see \Hyde\Framework\Testing\Feature\ConvertsArrayToFrontMatterTest */ class ConvertsArrayToFrontMatter { @@ -17,26 +19,10 @@ class ConvertsArrayToFrontMatter */ public function execute(array $array): string { - // Initialize the array - $yaml = []; - - // Set the first line to the opening starting block - $yaml[] = '---'; - - // For each line, add the key-value pair as YAML - foreach ($array as $key => $value) { - if (trim($value) !== '' && $value !== null) { - $yaml[] = "$key: $value"; - } + if (empty($array)) { + return ''; } - // Set the closing block - $yaml[] = '---'; - - // Add an extra line - $yaml[] = ''; - - // Return the array imploded into a string with newline characters - return implode("\n", $yaml); + return "---\n".Yaml::dump($array)."---\n"; } } diff --git a/tests/Feature/Commands/MakePostCommandTest.php b/tests/Feature/Commands/MakePostCommandTest.php index 2093b223..f03ee93e 100644 --- a/tests/Feature/Commands/MakePostCommandTest.php +++ b/tests/Feature/Commands/MakePostCommandTest.php @@ -46,7 +46,7 @@ public function test_command_has_expected_output_and_creates_valid_file() $this->assertFileExists($this->getPath()); $this->assertStringContainsString( - 'title: Test Post', + "title: 'Test Post'", file_get_contents($this->getPath()) ); } @@ -90,7 +90,7 @@ public function test_that_files_are_overwritten_when_force_flag_is_set() file_get_contents($this->getPath()) ); $this->assertStringContainsString( - 'title: Test Post', + "title: 'Test Post'", file_get_contents($this->getPath()) ); } diff --git a/tests/Feature/ConvertsArrayToFrontMatterTest.php b/tests/Feature/ConvertsArrayToFrontMatterTest.php new file mode 100644 index 00000000..aa2655ca --- /dev/null +++ b/tests/Feature/ConvertsArrayToFrontMatterTest.php @@ -0,0 +1,44 @@ + 'value', + 'string' => 'quoted string', + 'boolean' => true, + 'integer' => 100, + 'array' => ['key' => 'value'], + 'list' => ['foo', 'bar'], + ]; + $expected = <<<'YAML' +--- +key: value +string: 'quoted string' +boolean: true +integer: 100 +array: + key: value +list: + - foo + - bar +--- + +YAML; + $this->assertEquals(str_replace("\r", '', $expected), (new ConvertsArrayToFrontMatter)->execute($array)); + } + + public function test_action_returns_empty_string_if_array_is_empty() + { + $this->assertEquals('', (new ConvertsArrayToFrontMatter)->execute([])); + } +}