Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Yaml Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/yaml:^8.1
    

    Requires PHP 8.1+. No additional configuration is needed—it remains a standalone component.

  2. 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']]`).
    
  3. Where to Look First:

    • Official Documentation (updated for v8.1).
    • Yaml::class (main class with static methods for parsing/dumping).
    • Critical: Check Release Notes for security hardening (regexes, recursion depth, and collection-alias resolution bounds).
    • Security: Review CVE Fixes for catastrophic backtracking and recursion depth limits.

Implementation Patterns

Core Workflows

  1. Parsing YAML (unchanged):

    • Files: Use Yaml::parseFile() for direct file loading.
      $config = Yaml::parseFile('path/to/config.yaml');
      
    • Strings: Use Yaml::parse() for inline YAML strings.
  2. Dumping PHP to YAML (unchanged):

    • Arrays/Objects: Use Yaml::dump() with optional indent/inline parameters.
      $yamlString = Yaml::dump(['key' => 'value'], 10, 2);
      
  3. Binary Data Handling (updated):

    • Strict !!binary Validation: The parser now rejects non-stringable objects when encountering !!binary tags.
    • Workaround: Ensure binary data is a string or implement __toString():
      $binaryData = file_get_contents('image.png'); // string
      $yaml = Yaml::dump(['image' => $binaryData]);
      
    • Error Handling: Wrap in a try-catch for ParseException:
      try {
          Yaml::parse("data: !!binary $binaryData");
      } catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
          Log::error("Binary data must be stringable: {$e->getMessage()}");
      }
      
  4. Configuration Management (unchanged):

    • Load YAML configs in Laravel’s config/ and merge with the config system.
  5. Validation & Sanitization (updated):

    • Strict Parsing: Use Yaml::parse($string, Yaml::PARSE_CONSTANT) for type safety.
    • Binary Data: Validate binary strings before parsing:
      if (!is_string($binaryString)) {
          throw new \InvalidArgumentException("Binary data must be a string.");
      }
      
    • Security: Sanitize YAML input to avoid catastrophic backtracking (e.g., maliciously crafted YAML with excessive nesting or recursion).
  6. Testing (updated):

    • Security Tests: Validate YAML parsing with edge cases (e.g., deeply nested structures, recursive aliases).
    • Binary Data: Test binary string handling and error cases.

Gotchas and Tips

Pitfalls

  1. Whitespace Sensitivity (unchanged):

    • YAML remains indentation-sensitive. Use tools like yaml-lint to validate.
  2. Boolean/Null Handling (unchanged):

    • Lowercase true/false are booleans; False (capitalized) may cause issues.
  3. Binary Data Errors (updated):

    • Gotcha: !!binary tags now fail explicitly if the value isn’t stringable.
    • Fix: Convert binary data to a string before parsing/dumping:
      $binaryString = (string) $resource; // Cast to string
      $yaml = Yaml::dump(['data' => $binaryString]);
      
  4. Security Vulnerabilities (new):

    • Catastrophic Backtracking: Malicious YAML input (e.g., regex-heavy strings) could cause performance issues. Mitigation: Validate YAML structure or use a whitelist for trusted sources.
    • Recursion Depth: Deeply nested YAML or recursive aliases may trigger stack overflows. Mitigation: Limit nesting depth or use Yaml::parse($string, Yaml::PARSE_CONSTANT).
    • Collection-Alias Resolution: Unbounded aliases could lead to memory exhaustion. Mitigation: Pre-validate YAML or use a bounded parser.
  5. Object Serialization (unchanged):

    • Objects default to arrays in YAML. Use Yaml::DUMP_OBJECT for custom serialization.
  6. File Permissions (unchanged):

    • Always handle ParseException for unreadable files or invalid YAML.

Debugging Tips

  1. Pretty-Print Dumped YAML (unchanged): Use Yaml::dump($data, 10, 2) for readable output.

  2. Validate YAML Online (unchanged): Use yaml-online-parser for pre-validation.

  3. Binary Data Debugging (updated):

    • Check for Non-Stringable Data:
      if (!is_string($binaryData)) {
          dd("Binary data must be a string. Got: ", gettype($binaryData));
      }
      
    • Test !!binary Handling:
      try {
          $parsed = Yaml::parse("data: !!binary $binaryString");
          dd($parsed);
      } catch (\Exception $e) {
          dd($e->getMessage());
      }
      
  4. Security Debugging (new):

    • Test for Catastrophic Backtracking:
      $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()}");
      }
      
    • Monitor Recursion Depth:
      set_error_handler(function ($errno, $errstr) {
          if (strpos($errstr, 'Allowed memory exhausted') !== false) {
              dd("Recursion depth exceeded. Limit YAML nesting.");
          }
      });
      

Extension Points

  1. Custom Tags (updated):

    • Binary Tag Handling: Extend with a custom tag handler for binary data:
      Yaml::addTagHandler('!binary', function ($node) {
          if (!is_string($node->getValue())) {
              throw new \RuntimeException("Binary data must be a string.");
          }
          return $node->getValue();
      });
      
  2. Pre/Post-Processing (unchanged):

    • Transform data with array_walk_recursive() or custom logic.
  3. Laravel Service Provider (unchanged):

    • Bind the parser to the container for DI.
  4. Artisan Commands (updated):

    • Binary-Safe Export: Modify commands to handle binary data and validate security:
      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!');
      });
      
  5. PHP 8.1 Features (updated):

    • Leverage PHP 8.1’s readonly properties or union types in custom YAML handlers:
      class BinaryData {
          public function __toString(): string { /* ... */ }
      }
      Yaml::addTagHandler('!binary', fn($node) => new BinaryData($node->getValue()));
      
    • Attribute-Based Validation: Use PHP 8.1 attributes to validate YAML input:
      #[Attribute]
      class SecureYaml {
          public function __construct(private int $maxDepth) {}
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope