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

Kit Phpencoder Laravel Package

riimu/kit-phpencoder

Export PHP variables as customizable, readable or compact PHP code. A flexible alternative to var_export() with control over whitespace, array syntax, and useful object conversion—ideal for generated config files and optimized cache output.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require riimu/kit-phpencoder
    

    Add to composer.json if using strict mode:

    "require": {
        "riimu/kit-phpencoder": "^2.0"
    }
    
  2. Basic Usage Import the encoder and use it like var_export but with more control:

    use Riimu\Kit\PhpEncoder\Encoder;
    
    $encoder = new Encoder();
    $output = $encoder->encode([1, 2, 3]);
    echo $output; // Outputs: array ( 0 => 1, 1 => 2, 2 => 3, )
    
  3. First Use Case Generate PHP code for database seeds or fixtures:

    $data = ['user_id' => 1, 'name' => 'John Doe'];
    $encoder = new Encoder();
    $seedCode = $encoder->encode($data);
    file_put_contents('database/seeds/UsersTableSeeder.php', "<?php\n\$users = {$seedCode};");
    

Implementation Patterns

Core Workflows

  1. Customizing Output Format Use EncoderOptions to tweak formatting:

    use Riimu\Kit\PhpEncoder\EncoderOptions;
    
    $options = new EncoderOptions();
    $options->setArrayFormat(EncoderOptions::ARRAY_FORMAT_SHORT); // array(1, 2, 3)
    $encoder = new Encoder($options);
    
  2. Handling Complex Data

    • Objects: Implement __toArray() or use Encoder::encodeObject().
      • PHP 8.2+ Note: Objects with export type now ensure consistent index order when encoded. For custom objects, explicitly define __toArray() or use Encoder::encodeObject() with a callback.
    • Resources: Convert to arrays first or use custom handlers.
    • Circular References: Disable with $options->setAllowCircularReferences(false).
  3. Integration with Laravel

    • Service Provider Binding:
      $this->app->singleton(Encoder::class, function ($app) {
          $options = new EncoderOptions();
          $options->setArrayFormat(EncoderOptions::ARRAY_FORMAT_SHORT);
          return new Encoder($options);
      });
      
    • Blade Directives (for debugging):
      Blade::directive('dump', function ($expr) {
          return "<?php echo Riimu\\Kit\\PhpEncoder\\Encoder::encode({$expr}); ?>";
      });
      
  4. Batch Processing Encode arrays of data (e.g., for API responses or exports):

    $encoder = new Encoder();
    $batch = [
        ['id' => 1, 'name' => 'Foo'],
        ['id' => 2, 'name' => 'Bar'],
    ];
    $encodedBatch = array_map([$encoder, 'encode'], $batch);
    

Integration Tips

  • Laravel Eloquent: Use toArray() or toJson() + json_decode() to flatten models before encoding.

    $user = User::find(1);
    $encoder->encode($user->toArray());
    
  • API Responses: Replace json_encode() for human-readable debug outputs:

    $response = $encoder->encode($apiData);
    Log::debug("API Response: {$response}");
    
  • Testing: Assert encoded output matches expected PHP syntax:

    $this->assertEquals(
        "array ( 'key' => 'value', )",
        $encoder->encode(['key' => 'value'])
    );
    
  • PHP 8.2+ Objects: Ensure consistent index order for objects with export type by implementing __toArray() or using Encoder::encodeObject() with a callback:

    $encoder->encodeObject($obj, fn($o) => $o->toArray());
    

Gotchas and Tips

Pitfalls

  1. Circular References

    • Default behavior throws CircularReferenceException. Disable with:
      $options->setAllowCircularReferences(true);
      
    • Or use Encoder::encodeObject() with a custom callback to break cycles.
  2. Type Handling

    • Resources: Not auto-converted; pre-process with get() or toArray().
    • Closures/Callables: Encoded as strings (e.g., "function() { ... }"). Use Encoder::encodeCallable() for custom logic.
    • PHP 8.2+ Objects:
      • Objects with export type now have consistent index order by default.
      • Custom objects may require explicit __toArray() or a callback in encodeObject() for predictable behavior.
  3. Whitespace Sensitivity

    • Output may vary across PHP versions. Use $options->setPrettyPrint(true) for consistency.
  4. Performance

    • Avoid encoding large datasets in loops. Cache results or batch-process.

Debugging

  • Unexpected Output: Check EncoderOptions settings (e.g., setArrayFormat, setUseShortArraySyntax).

    var_dump($encoder->getOptions()->toArray());
    
  • Custom Objects: Implement __toString() or __debugInfo() for fallback encoding. For PHP 8.2+ objects, ensure __toArray() is defined or use Encoder::encodeObject() with a callback.

  • Edge Cases: Test with:

    • null, false, true
    • Nested arrays/objects
    • Special characters (e.g., ' in strings)
    • PHP 8.2+ objects with export type behavior.

Extension Points

  1. Custom Encoders Extend Encoder or implement Riimu\Kit\PhpEncoder\EncoderInterface:

    class CustomEncoder extends Encoder {
        protected function encodeString($value) {
            return "/* Custom: */ '{$value}'";
        }
    }
    
  2. Filters Use EncoderOptions::addFilter() to transform values before encoding:

    $options->addFilter(function ($value) {
        return strtoupper($value);
    });
    
  3. Hooks Override protected methods like:

    • encodeArray()
    • encodeObject()
    • encodeScalar()

Config Quirks

  • Short Array Syntax: Enabled by default in PHP 5.4+. Disable with:

    $options->setUseShortArraySyntax(false);
    
  • Pretty Printing: Adds newlines/indentation but may break minification:

    $options->setPrettyPrint(true);
    $options->setIndentString('    ');
    
  • PHP 8.2+ Compatibility:

    • Objects with export type now ensure consistent index order during encoding.
    • Test custom objects to ensure compatibility with PHP 8.2's new features, especially if relying on __toArray() or encodeObject() callbacks.
  • Namespace Handling: Objects without __toArray() are encoded as stdClass by default. Use Encoder::encodeObject($obj, fn($o) => $o->toArray()) for custom logic.

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