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 dumping YAML. Load YAML files or strings into PHP arrays and objects, and generate clean YAML output with configurable dumping options. Well-tested, documented, and maintained as part of the Symfony ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/yaml
    

    Laravel’s Composer autoloader will handle the rest.

  2. First Use Case: Parse a YAML file into a PHP array:

    use Symfony\Component\Yaml\Yaml;
    
    $yaml = Yaml::parseFile(__DIR__.'/config.yaml');
    // $yaml is now a PHP array
    

    Dump a PHP array back to YAML:

    $yamlString = Yaml::dump($phpArray, 10, 2); // Indent: 10, inline: 2
    file_put_contents(__DIR__.'/output.yaml', $yamlString);
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

1. Configuration Loading

Load Laravel’s config/ YAML files dynamically (e.g., for multi-environment overrides):

$envConfig = Yaml::parseFile(config_path("environments/{$env}.yaml"));
config()->set($envConfig); // Merge into Laravel's config

2. Kubernetes/Helm Integration

Parse Kubernetes manifests or Helm values:

$manifest = Yaml::parseFile(storage_path('k8s/deployment.yaml'));
$container = $manifest['spec']['template']['spec']['containers'][0];

3. Dynamic Form/Validation Rules

Load YAML-defined validation rules at runtime:

$rules = Yaml::parseFile(config_path('validation/rules.yaml'));
Validator::extend($rules['custom']['regex']);

4. Caching YAML Data

Cache parsed YAML to avoid repeated I/O:

$cacheKey = 'yaml_config_' . md5($filePath);
$yaml = Cache::remember($cacheKey, now()->addHours(1), function () use ($filePath) {
    return Yaml::parseFile($filePath);
});

5. Dumping Structured Data

Generate YAML for APIs, logs, or external systems:

$logEntry = [
    'timestamp' => now()->toIso8601String(),
    'level' => 'error',
    'message' => 'Database connection failed',
    'context' => ['query' => 'SELECT * FROM users']
];
Yaml::dumpFile(storage_path('logs/error.yaml'), [$logEntry], 10, 2);

Workflows

1. Schema Validation Workflow

Combine with Respect/Validation or Laravel’s Validator:

$yamlData = Yaml::parseFile($file);
$validator = Validator::make($yamlData, [
    'database.host' => 'required|string',
    'database.port' => 'required|integer|between:1,65535',
]);

2. Merge YAML Configs

Override default configs with environment-specific YAML:

$defaults = Yaml::parseFile(config_path('default.yaml'));
$overrides = Yaml::parseFile(config_path("environments/{$env}.yaml"));
$config = array_merge_recursive($defaults, $overrides);

3. YAML-to-PHP Object Conversion

Use Symfony\Component\Yaml\Inline for inline YAML in PHP strings:

$inlineYaml = <<<YAML
services:
  - { name: "app", class: "App\\Services\\AppService" }
YAML;
$services = Yaml::parse($inlineYaml);

4. Error Handling

Catch parsing errors gracefully:

try {
    $data = Yaml::parse($yamlString);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
    Log::error("Invalid YAML: " . $e->getMessage());
    throw new \RuntimeException("Configuration error", 0, $e);
}

Integration Tips

Laravel-Specific

  • Service Provider Binding:

    $this->app->singleton('yaml', function () {
        return new Yaml();
    });
    

    Then inject via constructor:

    public function __construct(private Yaml $yaml) {}
    
  • Artisan Commands: Use YAML for CLI config:

    $config = Yaml::parseFile(base_path('artisan-config.yaml'));
    $this->option('timeout', $config['default_timeout']);
    
  • Laravel Mix/Webpack: Parse YAML for asset configurations:

    $mixConfig = Yaml::parseFile(base_path('webpack.mix.yaml'));
    mix()->setPublicPath($mixConfig['public_path']);
    

Performance

  • Stream Large Files: For files >10MB, use SplFileObject with a custom parser (Symfony/YAML loads entire file into memory). Example:

    $file = new SplFileObject(__DIR__.'/large.yaml');
    $parser = new \Symfony\Component\Yaml\Parser();
    $data = $parser->parse($file); // Still loads all, but demonstrates API
    
  • Cache Parsed YAML: Use Laravel’s cache or Symfony\Component\Cache:

    $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
    $yaml = $cache->get($filePath, function () use ($filePath) {
        return Yaml::parseFile($filePath);
    });
    

Testing

  • Unit Test Parsing:

    public function testYamlParsing()
    {
        $yaml = <<<YAML
        name: "John Doe"
        age: 30
        YAML;
        $expected = ['name' => 'John Doe', 'age' => 30];
        $this->assertEquals($expected, Yaml::parse($yaml));
    }
    
  • Mock YAML Files: Use Yaml::parse() with hardcoded strings in tests:

    $this->app->instance('yaml', fn() => Yaml::parse($mockYaml));
    

Gotchas and Tips

Pitfalls

  1. Duplicate Keys in YAML:

    • Symfony/YAML raises an exception for duplicate keys (fixed in v8.0+).
    • Workaround: Use Yaml::parse($yaml, Yaml::PARSE_CONSTANT) to keep the last value.
    • Example:
      # Invalid YAML (duplicate key)
      key: value1
      key: value2
      
      Fix: Merge keys manually or restructure YAML.
  2. Unquoted Multiline Scalars:

    • Blank lines or comments in unquoted multiline strings may break parsing (fixed in v7.3.8+).
    • Example of problematic YAML:
      unquoted: |
        line 1
        line 2
      
        line 3  # comment
      
    • Fix: Use quoted scalars ("...") or ensure no blank lines between content.
  3. Flow Style vs. Block Style:

    • Flow style (e.g., {key: value}) may not render as expected in nested structures.
    • Use Yaml::DUMP_OBJECT_AS_ARRAY flag for consistent output:
      Yaml::dump($array, null, 10, Yaml::DUMP_OBJECT_AS_ARRAY);
      
  4. Null Handling:

    • By default, null values are dumped as null. Use Yaml::DUMP_NULL_AS_EMPTY to output empty strings:
      Yaml::dump($array, null, 10, Yaml::DUMP_NULL_AS_EMPTY);
      
  5. PHP 8.4+ Requirements for v8.x:

    • Symfony/YAML v8.x requires PHP 8.4+. Downgrade to v7.x for older PHP versions:
      composer require symfony/yaml:^7.4
      
  6. Memory Limits:

    • Large YAML files (>50MB) may hit PHP’s memory_limit. Use streaming libraries like spatie/yaml-front-matter for edge cases.

Debugging

  1. Parse Errors:
    • Symfony/YAML provides detailed error messages with line numbers:
      try {
          Yaml::parse($yaml);
      } catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
          echo "Error at line {$e->getLine()}: {$e->getMessage()}\n";
      }
      

2

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport