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
    

    Add to composer.json under require:

    "internal/toml": "^1.1"
    
  2. First Use Case: Parse a TOML config file into a PHP array:

    use Internal\Toml\Toml;
    
    $tomlContent = file_get_contents('config/app.toml');
    $config = Toml::parseToArray($tomlContent);
    

    Access values like a standard array:

    $databaseHost = $config['database']['host'];
    
  3. Where to Look First:

    • API Reference: Focus on Toml::parseToArray() (decoding) and Toml::encode() (encoding).
    • Examples: The README’s Quick Start covers 90% of use cases.
    • AST Documentation: Use Toml::parse() for advanced manipulation (e.g., preserving comments or format).

Implementation Patterns

Core Workflows

1. Configuration Management

  • Pattern: Replace Laravel’s config/ arrays with TOML files.
  • Implementation:
    // config/app.toml
    [database]
    connection = "mysql"
    host = "127.0.0.1"
    port = 3306
    
    // In a Service Provider
    $config = Toml::parseToArray(file_get_contents(base_path('config/app.toml')));
    $this->app->singleton('config', fn() => $config);
    
  • Integration Tip: Use Laravel’s config() helper by binding the parsed TOML to the container:
    $this->app->bind('config', fn() => Toml::parseToArray(file_get_contents(config_path('app.toml'))));
    

2. Dynamic TOML Generation

  • Pattern: Generate TOML for external tools (e.g., Kubernetes, Terraform) from PHP data.
  • Implementation:
    $k8sConfig = [
        'apiVersion' => 'v1',
        'kind' => 'Pod',
        'metadata' => ['name' => 'my-pod'],
        'spec' => ['containers' => [['name' => 'nginx', 'image' => 'nginx:latest']]],
    ];
    file_put_contents('pod.toml', (string) Toml::encode($k8sConfig));
    
  • Integration Tip: Use Stringable return type to chain with file_put_contents() or HTTP responses.

3. Validation and Round-Trip Editing

  • Pattern: Parse TOML, modify, and re-encode while preserving format (e.g., hex numbers, comments).
  • Implementation:
    $document = Toml::parse(file_get_contents('config.toml'));
    $data = $document->toArray();
    $data['new_key'] = 'value';
    file_put_contents('config.toml', (string) Toml::encode($data));
    
  • Integration Tip: Use the AST (Document object) to inspect/manipulate nodes before encoding.

4. CLI Tools and Artisans

  • Pattern: Accept TOML input in Laravel Artisans or CLI scripts.
  • Implementation:
    // In a custom Artisan command
    protected $tomlContent;
    protected function handle(): void
    {
        $this->tomlContent = $this->argument('config');
        $config = Toml::parseToArray($this->tomlContent);
        // Process config...
    }
    
  • Integration Tip: Use --toml argument with getArgument() and validate with Toml::parse().

Laravel-Specific Patterns

1. Config Caching

  • Pattern: Cache parsed TOML configs to avoid repeated parsing.
  • Implementation:
    $configCache = cache()->remember('toml_config', now()->addHours(1), fn() =>
        Toml::parseToArray(file_get_contents(config_path('app.toml')))
    );
    

2. Environment-Specific Configs

  • Pattern: Load TOML configs based on environment (e.g., config/local.toml, config/prod.toml).
  • Implementation:
    $env = app()->environment();
    $config = Toml::parseToArray(file_get_contents("config/{$env}.toml"));
    

3. TOML-Based Feature Flags

  • Pattern: Store feature flags in TOML for easy toggling.
  • Implementation:
    // config/features.toml
    [flags]
    new_dashboard = true
    experimental_api = false
    
    // In a service
    $flags = Toml::parseToArray(file_get_contents(config_path('features.toml')))['flags'];
    if ($flags['new_dashboard']) { ... }
    

4. Migration from JSON/YAML

  • Pattern: Convert existing JSON/YAML configs to TOML incrementally.
  • Implementation:
    $jsonData = json_decode(file_get_contents('config.json'), true);
    file_put_contents('config.toml', (string) Toml::encode($jsonData));
    

Advanced Patterns

1. Custom Decoders for Complex Types

  • Pattern: Extend the encoder to handle custom PHP objects (e.g., Carbon instances).
  • Implementation:
    Toml::encode([
        'date' => Carbon::now(),
        'user' => new UserModel(),
    ]);
    
  • Integration Tip: Implement JsonSerializable on your objects or use a post-encode callback:
    $data = ['date' => Carbon::now()];
    $toml = Toml::encode(array_map(fn($value) => $value instanceof Carbon ? $value->toIso8601String() : $value, $data));
    

2. TOML Schema Validation

  • Pattern: Validate TOML against a schema (e.g., using respect/validation).
  • Implementation:
    use Respect\Validation\Validator as v;
    
    $config = Toml::parseToArray(file_get_contents('config.toml'));
    $validator = v::key('database.host', v::stringType())
        ->key('database.port', v::numeric()->between(1, 65535));
    $validator->assert($config['database']);
    

3. TOML Templates

  • Pattern: Use TOML templates with placeholders for dynamic values.
  • Implementation:
    $template = <<<'TOML'
    [database]
    host = "{{HOST}}"
    port = {{PORT}}
    TOML;
    $data = [
        'HOST' => 'db.example.com',
        'PORT' => 5432,
    ];
    $toml = str_replace(
        array_keys($data),
        array_map(fn($v) => is_numeric($v) ? $v : "'{$v}'", $data),
        $template
    );
    $config = Toml::parseToArray($toml);
    
  • Integration Tip: Combine with strtr() or a templating engine like php-league/plates.

Gotchas and Tips

Pitfalls

  1. PHP 8.1+ Requirement:

    • Gotcha: The package drops support for PHP < 8.1. Check your environment with:
      php -r "echo PHP_VERSION_ID >= 80100 || 'Upgrade PHP!';"
      
    • Workaround: Use a Docker image or local PHP version manager (e.g., phpbrew).
  2. TOML 1.1 Quirks:

    • Gotcha: TOML 1.1 introduces stricter parsing rules (e.g., no trailing commas in arrays). Test with:
      # Valid TOML 1.1 (no trailing comma)
      items = [1, 2, 3]
      
    • Tip: Use Toml::parse() to catch syntax errors early:
      try {
          $document = Toml::parse($tomlString);
      } catch (\Internal\Toml\Exception\ParseError $e) {
          report($e);
      }
      
  3. DateTime Handling:

    • Gotcha: The encoder converts DateTime objects to ISO 8601 strings, but parsing expects specific formats (e.g., 1979-05-27T07:32:00Z).
    • Tip: Normalize dates before encoding:
      $data = ['created' => (new DateTime())->format(DateTime::ATOM)];
      
  4. Comments and Whitespace:

    • Gotcha: The encoder strips comments and normalizes whitespace. To preserve formatting:
      $document = Toml::parse($tomlString);
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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