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

Toml Laravel Package

internal/toml

PHP 8.1+ TOML 1.0/1.1 parser and encoder. Parse TOML into PHP arrays or an AST, modify and round-trip back to TOML. Simple static API (Toml::parse/parseToArray/encode) for config files and tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require internal/toml
    

    Requires PHP 8.1+.

  2. First Use Case - Parsing:

    use Internal\Toml\Toml;
    
    $tomlString = file_get_contents('config.toml');
    $configArray = Toml::parseToArray($tomlString);
    

    Use this for loading configuration files (e.g., config/toml/) into PHP arrays.

  3. First Use Case - Encoding:

    $phpData = ['database' => ['host' => 'localhost']];
    $tomlString = (string) Toml::encode($phpData);
    

    Use this for generating TOML output (e.g., for API responses or config exports).

  4. First Use Case - AST Access:

    $document = Toml::parse($tomlString);
    $array = $document->toArray(); // Convert to array
    $modifiedToml = (string) $document; // Re-encode with original formatting
    

    Use this for advanced workflows like validation or schema enforcement.

Where to Look First

  • API Reference: Focus on Toml::parseToArray(), Toml::encode(), and Toml::parse().
  • Examples: The README provides clear examples for parsing, encoding, and AST manipulation.
  • Changelog: Check for TOML 1.1 fixes (e.g., #5) if you encounter edge cases.

Implementation Patterns

Common Workflows

1. Configuration Loading

// config/toml/database.toml
[mysql]
host = "localhost"
port = 3306

// In Laravel service provider
public function register()
{
    $config = Toml::parseToArray(file_get_contents(base_path('config/toml/database.toml')));
    $this->app->singleton('db.config', fn() => $config);
}
  • Tip: Cache parsed TOML files in memory or use Laravel’s config system with a custom loader.

2. Dynamic TOML Generation

// Generate TOML for a feature flag
$featureFlags = [
    'new_ui' => ['enabled' => true, 'environments' => ['production', 'staging']],
];
$toml = (string) Toml::encode($featureFlags);
file_put_contents(storage_path('toml/feature-flags.toml'), $toml);
  • Use Case: Runtime-generated TOML for feature flags, environment-specific configs, or API responses.

3. Round-Trip Editing

// Parse → Modify → Encode
$document = Toml::parse(file_get_contents('config.toml'));
$data = $document->toArray();
$data['new_key'] = 'new_value';

// Preserve original formatting (e.g., hex numbers, comments)
$document->nodes = ...; // Manipulate AST if needed
file_put_contents('config.toml', (string) $document);
  • Use Case: Edit TOML files programmatically while preserving structure (e.g., for CI/CD pipelines or config management tools).

4. AST-Based Validation

$document = Toml::parse($tomlString);
foreach ($document->nodes as $node) {
    if ($node instanceof \Internal\Toml\Node\Table) {
        // Validate table structure
        if (!array_key_exists('required_key', $node->entries)) {
            throw new \InvalidArgumentException("Missing required key in table");
        }
    }
}
  • Use Case: Enforce schema rules or validate TOML files before processing.

5. Integration with Laravel Config

// In a custom config loader (e.g., app/Providers/ConfigServiceProvider)
public function boot()
{
    $tomlFiles = glob(app_path('config/toml/*.toml'));
    foreach ($tomlFiles as $file) {
        $configKey = str_replace('.toml', '', basename($file));
        config([$configKey => Toml::parseToArray(file_get_contents($file))]);
    }
}
  • Tip: Use this to load TOML configs alongside Laravel’s native config files.

Integration Tips

  • File Watching: Use Laravel’s files helper or a package like spatie/laravel-file-watcher to reload TOML configs when files change (e.g., for development).
  • Caching: Cache parsed TOML files in memory or use Laravel’s cache system to avoid repeated parsing.
  • Error Handling: Wrap Toml::parse() in a try-catch to handle malformed TOML gracefully:
    try {
        $data = Toml::parseToArray($tomlString);
    } catch (\Internal\Toml\Exception\ParseException $e) {
        report($e);
        $data = []; // Fallback
    }
    
  • Testing: Use Toml::encode() to generate test TOML files or validate round-trip conversions:
    $originalToml = 'key = "value"';
    $data = Toml::parseToArray($originalToml);
    $roundTripToml = (string) Toml::encode($data);
    $this->assertEquals($originalToml, $roundTripToml);
    

Gotchas and Tips

Pitfalls

  1. TOML 1.1 vs. 1.0:

    • The package supports TOML 1.1, but some tools (e.g., older versions of Terraform) may still use TOML 1.0. If you encounter parsing issues, check if the input TOML is strictly 1.0-compliant.
    • Fix: Use Toml::encode() to generate TOML 1.0-compatible output if needed (it defaults to 1.0 for maximum interoperability).
  2. Bare Keys and Dotted Keys:

    • TOML 1.1 introduces bare keys (e.g., key = "value") and dotted keys (e.g., [table.key]). If your TOML uses these, ensure you’re on 1.1.2+.
    • Gotcha: Older TOML parsers may fail on these syntaxes.
    • Fix: Upgrade to the latest version and validate your TOML files with the TOML spec validator.
  3. AST Manipulation:

    • Modifying the AST directly (e.g., $document->nodes) can break formatting or validation.
    • Tip: Use toArray() and encode() for safer round-trip edits:
      $data = $document->toArray();
      $data['new_key'] = 'new_value';
      $document = Toml::parse((string) Toml::encode($data));
      
  4. DateTime Handling:

    • The encoder supports DateTimeImmutable objects, but parsing relies on the input TOML’s format.
    • Gotcha: If you parse a TOML with created = 1979-05-27, the output array will use a DateTime object, but re-encoding may not preserve the exact string format.
    • Fix: Use DateTimeImmutable objects for consistent encoding:
      $data = ['created' => new DateTimeImmutable('1979-05-27')];
      $toml = (string) Toml::encode($data); // Output: created = 1979-05-27T00:00:00Z
      
  5. Comments Preservation:

    • The package preserves comments during round-trip encoding, but only if you work with the AST (Document object).
    • Gotcha: Using parseToArray() + encode() may strip comments.
    • Fix: Use the AST for comment-preserving edits:
      $document = Toml::parse($tomlString);
      // Modify AST (e.g., add comments)
      $document->addComment('New comment');
      file_put_contents('output.toml', (string) $document);
      
  6. Hex/Octal/Binary Numbers:

    • The encoder preserves the original format (e.g., 0xDEADBEEF stays as hex), but parsing may convert these to integers.
    • Gotcha: If you re-encode a parsed TOML with hex numbers, they may become decimal unless you use the AST.
    • Fix: Use the AST for format-preserving round-trips:
      $document = Toml::parse('magic = 0xDEADBEEF');
      $toml = (string) $document; // Output: magic = 0xDEADBEEF
      
  7. JsonSerializable Support:

    • The encoder works with JsonSerializable objects, but nested structures may not serialize
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