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, loading, and dumping YAML documents in PHP. Supports reading YAML files/strings and exporting arrays/objects to YAML with configurable formatting, inline levels, and error handling. Includes comprehensive docs and Symfony integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

Install via Composer:

composer require symfony/yaml

First Use Case: Loading YAML

use Symfony\Component\Yaml\Yaml;

// Load a YAML file into a PHP array
$config = Yaml::parseFile(__DIR__.'/config.yaml');

// Or parse a YAML string directly
$yamlString = "name: John\nage: 30";
$data = Yaml::parse($yamlString);

First Use Case: Dumping PHP to YAML

$data = [
    'name' => 'John',
    'age' => 30,
    'skills' => ['PHP', 'Laravel']
];

// Dump to a YAML string
$yamlString = Yaml::dump($data);

// Save to a file
Yaml::dumpFile(__DIR__.'/output.yaml', $data);

Where to Look First

  • Documentation: Symfony YAML Component
  • Key Classes: Symfony\Component\Yaml\Yaml (main facade), Parser, Dumper
  • Common Flags: Yaml::DUMP_OBJECT_AS_ARRAY, Yaml::DUMP_NULL_AS_EMPTY, etc.

Implementation Patterns

Common Workflows

1. Configuration Management

// config/app.yaml
database:
    default: mysql
    connections:
        mysql:
            driver: pdo_mysql
            host: localhost
            database: app_db

// In Laravel service provider
public function boot()
{
    $config = Yaml::parseFile(config_path('app.yaml'));
    $this->app->singleton('config', fn() => $config);
}

2. Dynamic YAML Generation

// Generate YAML for API responses
$responseData = [
    'status' => 'success',
    'data' => [
        'user' => [
            'id' => 1,
            'name' => 'Jane Doe',
            'roles' => ['admin', 'user']
        ]
    ]
];

$yamlResponse = Yaml::dump($responseData, 10, 2); // Indent 10, inline arrays after 2 items

3. Merging YAML Configs

// Merge base and environment-specific configs
$baseConfig = Yaml::parseFile(config_path('base.yaml'));
$envConfig = Yaml::parseFile(config_path('local.yaml'));

$mergedConfig = array_merge_recursive($baseConfig, $envConfig);

4. Validation with YAML Schemas

// Validate against a schema (using Symfony's Validator)
$validator = $this->container->get('validator');
$constraints = Yaml::parseFile(config_path('validation_schema.yaml'));
$errors = $validator->validate($data, $constraints);

5. Integration with Laravel's Filesystem

use Illuminate\Support\Facades\Storage;

// Load YAML from storage
$yamlContent = Storage::disk('config')->get('services.yaml');
$services = Yaml::parse($yamlContent);

// Save YAML to storage
Storage::disk('logs')->put('error_log.yaml', Yaml::dump($errors));

Integration Tips

Laravel Service Providers

// Register YAML-based configuration
public function register()
{
    $this->mergeConfigFrom(
        Yaml::parseFile(__DIR__.'/configs/database.yaml'),
        'database.connections'
    );
}

Artisan Commands

// Use YAML for command configuration
protected function getConfig()
{
    return Yaml::parseFile(__DIR__.'/config.yaml');
}

Package Development

// Publish YAML templates
public function boot()
{
    $this->publishes([
        __DIR__.'/configs/default.yaml' => config_path('vendor/packages/default.yaml'),
    ], 'package-config');
}

Testing

// Test YAML parsing in PHPUnit
public function testYamlParsing()
{
    $yaml = <<<'YAML'
    name: Test User
    roles:
        - admin
        - editor
    YAML;

    $data = Yaml::parse($yaml);
    $this->assertEquals('Test User', $data['name']);
    $this->assertContains('admin', $data['roles']);
}

Gotchas and Tips

Common Pitfalls

1. Duplicate Keys

  • Issue: YAML allows duplicate keys, but Symfony's parser will raise an error by default in newer versions.
  • Fix: Use Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED) to enforce strict parsing or handle duplicates in your code:
    $data = Yaml::parse($yaml);
    $data = array_unique($data, SORT_REGULAR); // Simple deduplication
    

2. Binary Data Handling

  • Issue: Binary data (e.g., !!binary) must be stringable. Non-stringables will throw an error.
  • Fix: Ensure binary data is converted to strings before dumping:
    $binaryData = file_get_contents('image.png');
    $data['image'] = base64_encode($binaryData); // Store as base64 string
    

3. Recursion Depth

  • Issue: Deeply nested YAML can cause stack overflows due to recursion limits.
  • Fix: Use Yaml::DUMP_EMPTY_ARRAY_AS_EMPTY or increase PHP's xdebug.max_nesting_level if needed.

4. Multiline Strings

  • Issue: Unquoted multiline strings may behave unexpectedly with blank lines or comments.
  • Fix: Use quoted strings ("...") or literal blocks (|) for multiline content:
    # Correct
    description: |
      This is a
      multiline string.
    

5. Date/Time Parsing

  • Issue: YAML dates may not parse correctly into DateTime objects.
  • Fix: Use custom tags or post-process the parsed data:
    $data['created_at'] = new DateTime($data['created_at']);
    

Debugging Tips

1. Enable Strict Parsing

Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED);

This will throw exceptions for invalid YAML, making debugging easier.

2. Inspect Parsed Data

$data = Yaml::parse($yaml);
dump($data); // Use Laravel's dump() or Symfony's VarDumper

3. Check for Hidden Characters

  • YAML is sensitive to whitespace and special characters. Use:
    $cleanYaml = preg_replace('/[\x00-\x1F]/', '', $yaml);
    

4. Validate YAML Online

  • Use tools like YAML Lint to pre-validate YAML before parsing.

Configuration Quirks

1. Dumping Flags

  • Yaml::DUMP_OBJECT_AS_ARRAY: Converts objects to arrays during dumping.
  • Yaml::DUMP_NULL_AS_EMPTY: Omits null values entirely.
  • Yaml::DUMP_EMPTY_ARRAY_AS_EMPTY: Omits empty arrays.
  • Yaml::DUMP_FORCE_DOUBLE_QUOTES_ON_VALUES: Ensures all strings are double-quoted.

Example:

$yaml = Yaml::dump($data, 10, 2, Yaml::DUMP_OBJECT_AS_ARRAY | Yaml::DUMP_NULL_AS_EMPTY);

2. Custom Tags

  • Register custom tags for complex data types:
    Yaml::addTagHandler('!my_tag', function ($value) {
        return new MyCustomClass($value);
    });
    

3. Performance

  • For large YAML files, consider streaming parsers or chunked processing:
    $parser = new Parser();
    $data = $parser->parse(new StringStream($yaml));
    

Extension Points

1. Custom Dumper

Extend Symfony\Component\Yaml\Dumper to add custom formatting:

class CustomDumper extends Dumper
{
    protected function serializeScalar($value, $inline, $depth)
    {
        if ($value instanceof MyCustomClass) {
            return $this->representScalar('!my_tag', $value->getId());
        }
        return parent::serializeScalar($value, $inline, $depth);
    }
}

2. Pre/Post-Processing

Wrap Yaml::parse() and Yaml::dump() for consistency:

function parseYaml($yaml, array $options = [])
{
    $data = Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED);
    return postProcessData($data);
}

function dumpYaml($data, array $options = [])
{
    return Yaml::dump(preProcessData($data), 10, 2, $options);
}

3. Integration with Laravel's Config

Create a

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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle