Skip to content

[Yaml] Add Yaml::parseFile() #23537

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Symfony/Component/Yaml/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----

Expand Down
15 changes: 15 additions & 0 deletions src/Symfony/Component/Yaml/Tests/YamlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
17 changes: 17 additions & 0 deletions src/Symfony/Component/Yaml/Yaml.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down