diff --git a/src/Symfony/Component/Yaml/CHANGELOG.md b/src/Symfony/Component/Yaml/CHANGELOG.md index 89c1a83ae238a..98dd68d7e68c2 100644 --- a/src/Symfony/Component/Yaml/CHANGELOG.md +++ b/src/Symfony/Component/Yaml/CHANGELOG.md @@ -9,6 +9,20 @@ CHANGELOG * Deprecated using the non-specific tag `!` as its behavior will change in 4.0. It will force non-evaluating your values in 4.0. Use plain integers or `!!float` instead. + * Added `Yaml::parseFile`: + + Before: + + ```php + Yaml::parse(file_get_contents($path)); + ``` + + After: + + ```php + Yaml::parseFile($path); + ``` + 3.3.0 ----- diff --git a/src/Symfony/Component/Yaml/Tests/YamlTest.php b/src/Symfony/Component/Yaml/Tests/YamlTest.php index 3f6c2525f755c..8f705fc372f9c 100644 --- a/src/Symfony/Component/Yaml/Tests/YamlTest.php +++ b/src/Symfony/Component/Yaml/Tests/YamlTest.php @@ -41,4 +41,19 @@ public function testNegativeIndentationThrowsException() { Yaml::dump(array('lorem' => 'ipsum', 'dolor' => 'sit'), 2, -4); } + + public function testParseFile() + { + $path = __DIR__.'/Fixtures/booleanMappingKeys.yml'; + $this->assertEquals(Yaml::parse(file_get_contents($path)), Yaml::parseFile($path)); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage file is not readable. + */ + public function testParseFileException() + { + Yaml::parseFile('file/which/does/not/exist.yml'); + } } diff --git a/src/Symfony/Component/Yaml/Yaml.php b/src/Symfony/Component/Yaml/Yaml.php index 84f749b560dbf..cda7c8a833995 100644 --- a/src/Symfony/Component/Yaml/Yaml.php +++ b/src/Symfony/Component/Yaml/Yaml.php @@ -82,6 +82,23 @@ public static function parse($input, $flags = 0) return $yaml->parse($input, $flags); } + /** + * Parses YAML file into a PHP value. + * + * @param string $filePath A path to a file containing YAML + * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior + * + * @return mixed The YAML converted to a PHP value + */ + public static function parseFile($filePath, $flags = 0) + { + if (is_file($filePath) && is_readable($filePath)) { + return static::parse(file_get_contents($filePath), $flags); + } + + throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $filePath)); + } + /** * Dumps a PHP value to a YAML string. *