symfony/yaml
Symfony Yaml Component for parsing and generating YAML. Load YAML files into PHP arrays/objects and dump PHP data back to YAML, with robust support for common YAML features and integration with the Symfony ecosystem.
Installation:
composer require symfony/yaml:^8.1
Requires PHP 8.1+. No additional configuration is needed—it remains a standalone component.
First Use Case: Parse a YAML file into a PHP array (unchanged):
use Symfony\Component\Yaml\Yaml;
$yaml = Yaml::parseFile(__DIR__.'/config.yaml');
// Returns an associative array (e.g., `['database' => ['host' => 'localhost']]`).
Where to Look First:
Yaml::class (main class with static methods for parsing/dumping).Parsing YAML (unchanged):
Yaml::parseFile() for direct file loading.
$config = Yaml::parseFile('path/to/config.yaml');
Yaml::parse() for inline YAML strings.Dumping PHP to YAML (unchanged):
Yaml::dump() with optional indent/inline parameters.
$yamlString = Yaml::dump(['key' => 'value'], 10, 2);
Binary Data Handling (updated):
!!binary Validation: The parser now rejects non-stringable objects when encountering !!binary tags.__toString():
$binaryData = file_get_contents('image.png'); // string
$yaml = Yaml::dump(['image' => $binaryData]);
ParseException:
try {
Yaml::parse("data: !!binary $binaryData");
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
Log::error("Binary data must be stringable: {$e->getMessage()}");
}
Configuration Management (unchanged):
config/ and merge with the config system.Validation & Sanitization (updated):
Yaml::parse($string, Yaml::PARSE_CONSTANT) for type safety.if (!is_string($binaryString)) {
throw new \InvalidArgumentException("Binary data must be a string.");
}
Testing (updated):
Whitespace Sensitivity (unchanged):
yaml-lint to validate.Boolean/Null Handling (unchanged):
true/false are booleans; False (capitalized) may cause issues.Binary Data Errors (updated):
!!binary tags now fail explicitly if the value isn’t stringable.$binaryString = (string) $resource; // Cast to string
$yaml = Yaml::dump(['data' => $binaryString]);
Security Vulnerabilities (new):
Yaml::parse($string, Yaml::PARSE_CONSTANT).Object Serialization (unchanged):
Yaml::DUMP_OBJECT for custom serialization.File Permissions (unchanged):
ParseException for unreadable files or invalid YAML.Pretty-Print Dumped YAML (unchanged):
Use Yaml::dump($data, 10, 2) for readable output.
Validate YAML Online (unchanged): Use yaml-online-parser for pre-validation.
Binary Data Debugging (updated):
if (!is_string($binaryData)) {
dd("Binary data must be a string. Got: ", gettype($binaryData));
}
!!binary Handling:
try {
$parsed = Yaml::parse("data: !!binary $binaryString");
dd($parsed);
} catch (\Exception $e) {
dd($e->getMessage());
}
Security Debugging (new):
$maliciousYaml = str_repeat("key: ", 1000) . "value: test";
try {
$parsed = Yaml::parse($maliciousYaml);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
dd("Malicious YAML detected: {$e->getMessage()}");
}
set_error_handler(function ($errno, $errstr) {
if (strpos($errstr, 'Allowed memory exhausted') !== false) {
dd("Recursion depth exceeded. Limit YAML nesting.");
}
});
Custom Tags (updated):
Yaml::addTagHandler('!binary', function ($node) {
if (!is_string($node->getValue())) {
throw new \RuntimeException("Binary data must be a string.");
}
return $node->getValue();
});
Pre/Post-Processing (unchanged):
array_walk_recursive() or custom logic.Laravel Service Provider (unchanged):
Artisan Commands (updated):
Artisan::command('config:export', function () {
$config = config()->all();
// Ensure all binary data is stringable
array_walk_recursive($config, function (&$value) {
if (is_resource($value)) {
$value = (string) $value;
}
});
// Validate YAML structure to prevent security issues
if (strlen(Yaml::dump($config)) > 1000000) { // Example size limit
$this->error("YAML output too large. Risk of catastrophic backtracking.");
return;
}
file_put_contents(public_path('config_export.yaml'), Yaml::dump($config));
$this->info('Config exported!');
});
PHP 8.1 Features (updated):
class BinaryData {
public function __toString(): string { /* ... */ }
}
Yaml::addTagHandler('!binary', fn($node) => new BinaryData($node->getValue()));
#[Attribute]
class SecureYaml {
public function __construct(private int $maxDepth) {}
}
How can I help you explore Laravel packages today?