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

Laravel Toon Laravel Package

knackline/laravel-toon

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require knackline/laravel-toon
    

    No additional configuration is required—the package auto-registers its service provider and facade.

  2. First Use Case: Convert a simple JSON array to Toon format:

    use Knackline\LaravelToon\Facades\Toon;
    
    $json = ['name' => 'John', 'age' => 30];
    $toon = Toon::fromJson($json);
    echo $toon; // Outputs compact Toon string
    
  3. Where to Look First:

    • Facade: Knackline\LaravelToon\Facades\Toon (preferred for readability).
    • Helper Methods: fromJson(), toJson(), and parse() for direct conversions.
    • README Examples: Focus on the JSON-to-Toon and Toon-to-JSON workflows.

Implementation Patterns

Core Workflows

  1. JSON-to-Toon Conversion:

    • Use Toon::fromJson($array) for arrays or Toon::fromJsonFile($path) for files.
    • Example: Transform nested Eloquent collections or API responses into Toon for logging/debugging.
      $users = User::with('posts')->get();
      $toon = Toon::fromJson($users->toArray());
      
  2. Toon-to-JSON Parsing:

    • Use Toon::parse($toonString) to reconstruct JSON.
    • Example: Parse user-uploaded Toon-formatted data (e.g., config snippets).
      $toonData = "users[2]{id,name}: 1,John, 2,Jane";
      $json = Toon::parse($toonData);
      
  3. Integration with Laravel Features:

    • Logging: Store Toon-formatted debug logs (reduces verbosity).
      \Log::info('User data', ['data' => Toon::fromJson($user->toArray())]);
      
    • API Responses: Return Toon for mobile clients with limited bandwidth.
      return response()->json(Toon::fromJson($data)->toJson());
      
    • Configuration: Load Toon-formatted configs (e.g., config/toon.php).
      $config = Toon::parse(file_get_contents(config_path('toon.php')));
      
  4. Batch Processing:

    • Process large datasets (e.g., CSV imports) by converting chunks to Toon for intermediate storage.
      foreach ($chunk as $item) {
          $toonChunk[] = Toon::fromJson($item);
      }
      

Advanced Patterns

  • Custom Field Mapping: Use Toon::fromJson($array, ['custom_field' => 'toon_key']) to alias fields.

    $toon = Toon::fromJson($data, ['user_id' => 'uid']);
    
  • Conditional Conversion: Dynamically convert based on request headers or user roles.

    if ($request->wantsToon()) {
        return Toon::fromJson($data);
    }
    return $data;
    
  • Validation: Validate Toon strings before parsing (e.g., check for syntax errors).

    try {
        $json = Toon::parse($toonString);
    } catch (\InvalidArgumentException $e) {
        abort(400, 'Invalid Toon format');
    }
    

Gotchas and Tips

Pitfalls

  1. Nested Arrays/Objects:

    • Toon flattens nested structures by default. Use explicit keys (e.g., users[3]{id,name}) to preserve hierarchy.
    • Fix: Ensure arrays are indexed or use custom field mappings.
      // Fails: Loses nested structure
      $toon = Toon::fromJson(['user' => ['posts' => [...]]]);
      
      // Works: Explicitly define structure
      $toon = Toon::fromJson(['users[1]{id,posts[2]{title}}' => [...]]);
      
  2. Special Characters:

    • Toon escapes colons (:) and newlines in values. Use backslashes (\) for literal colons.
      // Input: "price: $10"
      // Output: "price: \$10" (escaped)
      
    • Fix: Escape manually or use addcslashes() pre-conversion.
  3. Boolean/Null Handling:

    • Toon omits null values and converts booleans to true/false strings.
    • Tip: Use Toon::fromJson($array, ['preserve_nulls' => true]) to retain null values.
  4. Performance:

    • Parsing large Toon strings (>1MB) may hit memory limits.
    • Tip: Stream parse with file_get_contents() in chunks or use Toon::parse(file($path)).
  5. Facade vs. Class:

    • The facade (Toon::...) is stateless but slower for repeated calls. Use the class directly (new \Knackline\LaravelToon\Toon) in loops.
      $converter = new \Knackline\LaravelToon\Toon();
      foreach ($data as $item) {
          $converter->fromJson($item); // Reuses instance
      }
      

Debugging Tips

  • Validate Toon Syntax: Use Toon::parse($toonString, true) to throw exceptions on invalid syntax.
  • Inspect Intermediate Output: Log the Toon string before parsing to verify structure:
    \Log::debug('Toon output:', ['toon' => $toonString]);
    
  • Check for Hidden Characters: Use trim($toonString) or preg_replace('/\s+/', ' ', $toonString) to clean input.

Extension Points

  1. Custom Parsers: Extend the Knackline\LaravelToon\Parsers\ParserInterface to handle domain-specific Toon dialects.

    class CustomParser implements ParserInterface {
        public function parse(string $toon): array { ... }
    }
    

    Register via the service provider:

    $this->app->bind(
        ParserInterface::class,
        CustomParser::class
    );
    
  2. Toon Directives: Add custom directives (e.g., @include) using the Toon::directive() method.

    Toon::directive('include', function ($path) {
        return file_get_contents($path);
    });
    

    Usage:

    @include('config/toon.php')
    
  3. Event Hooks: Listen for toon.converted events to post-process output:

    Toon::fromJson($data)->then(function ($toon) {
        // Modify $toon before use
    });
    

Configuration Quirks

  • Default Options: The package uses sensible defaults (e.g., preserve_keys = false, indent = 2). Override via:
    Toon::fromJson($data, [
        'preserve_keys' => true,
        'indent' => 4,
    ]);
    
  • Environment-Specific Settings: Publish the config with php artisan vendor:publish --provider="Knackline\LaravelToon\ToonServiceProvider" to customize globally.

Pro Tips

  • API Documentation: Generate Toon-formatted API docs for mobile clients:
    $docs = Toon::fromJson($apiSchema);
    return response($docs, 200, ['Content-Type' => 'text/toon']);
    
  • Localization: Use Toon for multilingual configs (e.g., translations[3]{locale,key,value}).
  • Testing: Mock Toon responses in tests:
    $this->app->instance(
        Toon::class,
        Mockery::mock(Toon::class)->shouldReceive('parse')->andReturn(['test' => 'data'])
    );
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui