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.0/1.1.0 parser and encoder. Parse TOML strings/files into PHP arrays or an AST, modify documents, and serialize back to TOML with round-trip support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require internal/toml
    

    Requires PHP 8.1+.

  2. First Use Case: Parse a TOML config file into a PHP array for immediate use:

    use Internal\Toml\Toml;
    
    $config = Toml::parseToArray(file_get_contents('config.toml'));
    // Access config values like $config['database']['host']
    
  3. Where to Look First:

    • API Reference: Focus on Toml::parseToArray() (for reading) and Toml::encode() (for writing).
    • Examples: The README’s "Quick Start" section covers 90% of daily use cases (parsing, encoding, and round-trips).
    • AST (Advanced): Use Toml::parse() for programmatic TOML manipulation (e.g., modifying nodes before encoding).

Implementation Patterns

Core Workflows

1. Configuration Management

  • Pattern: Replace Laravel’s config/ arrays or JSON/YAML configs with TOML files.
  • Workflow:
    // config/database.toml
    [mysql]
    host = "localhost"
    port = 3306
    
    // In PHP:
    $dbConfig = Toml::parseToArray(file_get_contents(config_path('database.toml')));
    DB::connection($dbConfig['mysql']);
    
  • Integration Tip: Use Laravel’s config() helper with a custom loader:
    Config::addLoader('toml', function ($path) {
        return Toml::parseToArray(file_get_contents($path));
    }, 10); // High priority
    

2. Dynamic TOML Generation

  • Pattern: Generate TOML files from PHP data (e.g., for CI/CD, Kubernetes, or feature flags).
  • Workflow:
    $featureFlags = [
        'new_dashboard' => ['enabled' => true, 'environments' => ['prod', 'staging']],
    ];
    $toml = (string) Toml::encode($featureFlags);
    file_put_contents('feature-flags.toml', $toml);
    
  • Integration Tip: Combine with Str::of() for pretty-printing:
    $toml = Str::of(Toml::encode($data))->indent(4);
    

3. Round-Trip Editing

  • Pattern: Parse → Modify → Encode TOML while preserving formatting (e.g., hex numbers, comments).
  • Workflow:
    $document = Toml::parse(file_get_contents('config.toml'));
    $data = $document->toArray();
    $data['version'] = '2.0.0'; // Modify
    $updatedToml = (string) Toml::encode($data);
    file_put_contents('config.toml', $updatedToml);
    
  • Integration Tip: Use the AST ($document->nodes) to add comments or metadata before encoding.

4. Schema Validation

  • Pattern: Validate TOML against a schema (e.g., using toml-validator).
  • Workflow:
    use BetterU\TomlValidator\Validator;
    
    $validator = new Validator();
    $isValid = $validator->validate(file_get_contents('config.toml'), $schema);
    if (!$isValid) {
        throw new \RuntimeException('Invalid TOML config');
    }
    

Laravel-Specific Patterns

1. Service Provider Bootstrapping

  • Load TOML configs in a service provider:
    public function boot()
    {
        $config = Toml::parseToArray(config_path('app.toml'));
        $this->app->singleton('config.cache', function () use ($config) {
            return new ConfigCache($config);
        });
    }
    

2. Artisan Commands

  • Generate TOML configs from CLI input:
    $toml = (string) Toml::encode([
        'command' => $this->argument('name'),
        'description' => $this->option('description'),
    ]);
    $this->info($toml);
    

3. Migration Helpers

  • Convert legacy JSON/YAML configs to TOML during migrations:
    $legacyJson = json_decode(file_get_contents('old-config.json'), true);
    $toml = (string) Toml::encode($legacyJson);
    file_put_contents('config.toml', $toml);
    

4. Environment-Specific Configs

  • Use TOML for environment overrides (e.g., .env.toml):
    $envConfig = Toml::parseToArray(file_get_contents('.env.toml'));
    config(['app.debug' => $envConfig['debug'] ?? false]);
    

Gotchas and Tips

Pitfalls

  1. PHP 8.1+ Requirement:

    • Gotcha: The package will not work on PHP < 8.1 (e.g., PHP 8.0 or 7.x). Check your composer.json constraints.
    • Fix: Use a polyfill or upgrade PHP if needed.
  2. TOML 1.1 vs. 1.0 Quirks:

    • Gotcha: Some TOML 1.1 features (e.g., bare keys, true/false booleans) may behave unexpectedly in older parsers. This package fully supports 1.1, but legacy tools might not.
    • Tip: Use Toml::encode() to generate 1.0-compatible output if interoperability is critical:
      $toml = (string) Toml::encode($data, Toml::ENCODE_TOML_1_0);
      
  3. Floating-Point Precision:

    • Gotcha: TOML floats are parsed as PHP float, which may lose precision. For exact decimals, use strings:
      # config.toml
      precision_value = "123.456789"  # Stored as string
      
    • Fix: Post-process the parsed array to convert critical floats to strings.
  4. Comments and Whitespace:

    • Gotcha: Toml::encode() does not preserve comments by default. Use the AST for comment retention:
      $document = Toml::parse($tomlWithComments);
      $document->addComment('New comment', $someNode);
      $toml = (string) $document;
      
  5. DateTime Handling:

    • Gotcha: The encoder converts DateTime objects to ISO 8601 strings, but parsing expects strict TOML datetime formats (e.g., 1979-05-27T07:32:00Z).
    • Tip: Normalize dates before encoding:
      $date = (new DateTime('now'))->format(DateTime::ATOM);
      $data = ['event_date' => $date];
      
  6. Arrays of Tables:

    • Gotcha: Arrays of tables (e.g., [[servers]]) are encoded as nested arrays, but parsing may flatten them unexpectedly.
    • Fix: Use Toml::parse() to inspect the AST structure:
      $document = Toml::parse($toml);
      foreach ($document->nodes as $node) {
          if ($node instanceof TableArray) {
              // Handle array of tables
          }
      }
      
  7. File Encoding:

    • Gotcha: TOML files must be UTF-8 encoded. Non-UTF-8 files may cause parsing errors.
    • Fix: Use file_get_contents() with FILE_UTF8 flag or mb_convert_encoding():
      $toml = mb_convert_encoding(file_get_contents('config.toml'), 'UTF-8');
      

Debugging Tips

  1. Validate TOML Syntax: Use the AST to debug parsing issues:

    try {
        $document = Toml::parse($toml);
    } catch (\Internal\Toml\Exception\ParseError $e) {
        echo "Error at line {$e->getLine()}: {$e->getMessage()}";
    }
    
  2. Inspect AST Structure: Dump the AST to understand node types:

    $document = Toml::parse($toml);
    dump(get_class($document->nodes[0])); // e.g., Entry, Table, TableArray
    
  3. Round-Trip Debugging: Verify format preservation:

    $originalToml = 'key = 0xDEADBEEF';
    $document = Toml::parse($originalToml);
    $roundTripToml = (string) $document;
    assert($originalToml === $roundTripToml, 'Format not preserved!');
    
  4. Performance:

    • Parsing large TOML files (e.g., >1MB) may hit memory limits
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky