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

Php Composer Reader Laravel Package

nadar/php-composer-reader

Small PHP library to read and manipulate composer.json. Load and validate readability/writability, dump full content, and work with typed section readers (e.g., require, autoload PSR-4) to iterate packages/namespaces, inspect constraints, and add sections.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require nadar/php-composer-reader
    
    • No additional setup required; the package is dependency-free and now supports PHP 8.3+ (including 8.4).
  2. First Use Case: Reading composer.json

    use Nadar\ComposerReader\ComposerReader;
    
    $reader = new ComposerReader();
    $composerData = $reader->read(__DIR__ . '/../composer.json');
    
    // Access data like a PHP array
    echo $composerData['name']; // e.g., "vendor/package"
    

    New Feature: Input from Array

    $arrayInput = ['name' => 'test/package', 'version' => '1.0.0'];
    $composerData = $reader->read($arrayInput); // Accepts array input directly
    
  3. Where to Look First

    • Class Reference: ComposerReader now includes new methods for command output and array input handling.
      • read(string|array $path): Accepts either a file path or a PHP array.
      • write(string $path, array $data): Saves modified data back to disk.
      • merge(array $data): Merges new data into existing config.
      • New: getCommandOutput(array $composerData): Generates CLI-compatible output (e.g., for composer show).
    • Exceptions: Still throws Nadar\ComposerReader\Exception\InvalidComposerFileException for malformed files.

Implementation Patterns

Usage Patterns

  1. Dynamic Dependency Management

    $reader = new ComposerReader();
    $composer = $reader->read('composer.json');
    
    // Add a new dev dependency
    $composer['require-dev']['phpunit/phpunit'] = '^9.0';
    $reader->write('composer.json', $composer);
    
    • Use Case: Automate dependency updates in CI/CD or scaffolding tools.
  2. Array Input for Testing/Validation

    $mockComposer = [
        'name' => 'test/package',
        'require' => ['laravel/framework' => '^10.0'],
    ];
    $reader->read($mockComposer); // No file I/O needed
    
    • Use Case: Unit testing, validation, or generating composer.json snippets without disk access.
  3. Generating CLI Output

    $composer = $reader->read('composer.json');
    $output = $reader->getCommandOutput($composer);
    // Outputs formatted data like `composer show`:
    // name     : test/package
    // version  : 1.0.0
    
    • Use Case: Build custom CLI tools or integrate with Laravel Artisan commands.
  4. Configuration Overrides

    $reader->merge([
        'config' => [
            'autoload' => ['psr-4' => ['App\\' => 'src/']],
        ],
    ]);
    
    • Use Case: Extend or override composer.json settings programmatically (e.g., in plugins).

Workflow Integration

  • Pre-Commit Hooks: Validate composer.json structure or generate CLI reports using getCommandOutput().
  • Custom Composer Plugins: Use read() with array input to manipulate composer.json in-memory before writing.
  • Laravel Service Providers: Cache composer.json data and generate CLI output dynamically:
    public function register()
    {
        $this->app->singleton('composer', function () {
            $reader = new ComposerReader();
            return [
                'data' => $reader->read(base_path('composer.json')),
                'output' => $reader->getCommandOutput($reader->read(base_path('composer.json'))),
            ];
        });
    }
    

Integration Tips

  • Leverage getCommandOutput(): Format composer.json data for human-readable output in logs or notifications.
  • Combine with spatie/fork: Use array input to modify composer.json before forking packages.
  • Environment-Specific Configs: Load base configs as arrays and merge with environment-specific data:
    $base = $reader->read('composer.json');
    $envOverrides = ['require-dev' => ['laravel/pint' => '^1.0']];
    $merged = $reader->merge($envOverrides);
    

Gotchas and Tips

Pitfalls

  1. File Path vs. Array Input

    • Gotcha: read() now accepts both file paths and arrays. Passing an invalid array (e.g., missing "name") may not throw an exception unless explicitly validated.
    • Fix: Validate input structure:
      if (is_array($input) && !isset($input['name'])) {
          throw new \InvalidArgumentException('Array input must include a "name" key.');
      }
      
  2. Data Merging Quirks

    • Gotcha: merge() still uses array_merge_recursive, which may overwrite arrays (e.g., require keys). Array input does not bypass this.
    • Fix: Use array_replace_recursive for critical sections or manually merge:
      $reader->merge(array_replace_recursive($composer, $newData));
      
  3. JSON Validation

    • Gotcha: The package does not validate JSON schema (e.g., required fields like "version"). Array input skips file parsing but still requires manual validation.
    • Fix: Use webmozart/assert or a schema validator:
      assert(array_key_exists('version', $composer), 'Composer data must include a "version" field.');
      
  4. Command Output Formatting

    • Gotcha: getCommandOutput() generates plain-text output. Custom formatting (e.g., ANSI colors) requires post-processing.
    • Fix: Extend the method or use a templating library:
      $output = str_replace(':', ': ', $reader->getCommandOutput($composer));
      

Debugging

  • Inspect Raw Data: Dump array input or file data to debug:
    var_dump($reader->read($arrayInput)); // For array input
    var_dump($reader->read('composer.json')); // For file input
    
  • Check for Hidden Characters: If parsing fails, ensure UTF-8 encoding (applies to both file and array input).

Extension Points

  1. Custom Command Output

    • Extend getCommandOutput() to support Markdown, JSON, or HTML:
      class CustomComposerReader extends ComposerReader {
          public function getJsonOutput(array $composerData): string {
              return json_encode($composerData, JSON_PRETTY_PRINT);
          }
      }
      
  2. Schema Validation for Arrays

    • Validate array input against composer.json schema using justinrainbow/json-schema:
      $schema = json_decode(file_get_contents(__DIR__ . '/composer-schema.json'), true);
      $validator = new \Justinrainbow\JsonSchema\Validator();
      $validator->validate($arrayInput, $schema);
      
  3. Event Dispatching for Array Input

    • Trigger events when using array input (e.g., for logging or side effects):
      if (is_array($input)) {
          event(new ComposerArrayLoaded($input));
      }
      
  4. PHP 8.3+ Features

    • Use named arguments or readonly properties in custom extensions:
      $reader->read(path: 'composer.json'); // Named argument (PHP 8.1+)
      

Config Quirks

  • No Global Config: Behavior is runtime-driven. Array input bypasses file I/O but requires manual validation.
  • Default Behavior: write() still overwrites files entirely. Use merge() for partial updates.
  • PHP 8.4 Support: No breaking changes, but leverage new features like array unpacking for cleaner merges:
    $reader->merge([...$newData, 'config' => ['autoload' => [...]]]);
    
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.
aimeos/prisma
besmartand-pro/php-quality-config
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views