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

Console Laravel Package

draw/console

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require draw/console
    

    Add the bundle to config/bundles.php (Symfony) or AppKernel.php (legacy Laravel <5.5):

    Draw\Component\Console\DrawConsoleBundle::class => ['all' => true],
    
  2. Configuration: Add the minimal config to config/packages/draw_command.yaml (Symfony) or config/draw_command.php (Laravel):

    draw_command:
        sonata:
            commands:
                clearCache:
                    commandName: "cache:clear"
                    label: "Clear Cache"
                    icon: "fa-ban"
    
  3. First Use Case:

    • Sonata Admin Integration: After configuring, the command appears in Sonata Admin under a custom tab (e.g., "System Tools").
    • Manual Execution: Run via CLI with logging:
      php artisan your:command --output=buffered
      
      (Note: Laravel doesn’t natively support Symfony bundles, so this assumes a Laravel-Symfony hybrid setup or a custom CLI wrapper.)

Implementation Patterns

Workflows

  1. Sonata Admin Integration:

    • Configure commands in draw_command.yaml with commandName, label, and icon.
    • Access via Sonata Admin’s custom tab (requires sonata-admin bundle).
    • Example workflow:
      1. Admin clicks "Clear Cache" in Sonata.
      2. Bundle triggers cache:clear and logs execution (output, exit code, duration).
  2. CLI Logging:

    • Wrap CLI output with BufferedConsoleOutput to capture logs:
      $output = new \Draw\Component\Console\Output\BufferedConsoleOutput();
      $application->run($input, $output);
      
    • Logs are stored in the database (schema: command_execution table).
  3. Laravel-Specific Adaptation:

    • Artisan Commands: Extend Laravel’s Artisan::call() to log executions:
      use Draw\Component\Console\Output\BufferedConsoleOutput;
      $output = new BufferedConsoleOutput();
      $exitCode = Artisan::call('command:name', [], $output);
      // Save $output->getContent() to DB.
      
    • Service Provider: Register a listener for Illuminate\Console\Events\ArtisanStarting to auto-log commands.
  4. Dynamic Command Arguments:

    • Predefined Args: Extend config to include arguments:
      reIndexSearch:
          commandName: "fos:elastica:populate"
          arguments: ["--env=prod"]
      
    • Runtime Input: Use Sonata’s form builder to collect args dynamically (requires custom form type).

Gotchas and Tips

Pitfalls

  1. Database Schema:

    • The bundle assumes a command_execution table. If missing, create it manually or extend the bundle to auto-migrate (e.g., via Doctrine migrations).
    • Schema example:
      CREATE TABLE command_execution (
          id INT AUTO_INCREMENT PRIMARY KEY,
          command_name VARCHAR(255),
          output TEXT,
          exit_code INT,
          duration INT,
          created_at TIMESTAMP
      );
      
  2. Ignored Commands:

    • Hardcoded ignored commands (help, doctrine:database:drop, etc.) cannot be customized without patching the bundle. Override via a custom logger:
      // config/draw_command.php
      'logger' => [
          'ignored_commands' => ['custom:ignored-command'],
      ],
      
  3. Laravel Compatibility:

    • Artisan vs. Symfony Console: The bundle is Symfony-centric. For Laravel:
      • Use BufferedConsoleOutput with Artisan commands.
      • Mock the Command class to integrate with Laravel’s Artisan facade.
    • Event Listeners: Laravel’s Artisan::call() doesn’t natively support Symfony’s Application. Use a wrapper:
      class ConsoleLogger
      {
          public function log(string $command, array $args = []): string
          {
              $output = new BufferedConsoleOutput();
              Artisan::call($command, $args, $output);
              return $output->getContent();
          }
      }
      
  4. Output Buffering:

    • BufferedConsoleOutput captures only the output passed to it. Ensure all CLI output (e.g., echo, dd()) uses the buffered output:
      // Wrong: Uses default output
      echo "Debug: " . $var;
      
      // Right: Uses buffered output
      $output->writeln("Debug: " . $var);
      

Tips

  1. Debugging Failed Commands:

    • Query the command_execution table for failed runs (exit_code != 0) and inspect output for errors.
    • Example query:
      SELECT * FROM command_execution WHERE exit_code != 0 ORDER BY created_at DESC LIMIT 10;
      
  2. Extending Ignored Commands:

    • Override the logger service in Symfony:
      # config/services.yaml
      Draw\Component\Console\Logger\CommandLogger:
          arguments:
              $ignoredCommands: ['%kernel.environment%:debug', 'custom:command']
      
  3. Performance:

    • Log large outputs (e.g., cache:clear) asynchronously to avoid blocking the admin UI. Use Laravel’s queues or Symfony’s Messenger component.
  4. Security:

    • Restrict Sonata Admin access to command execution via ACLs (e.g., sonata_admin roles).
    • Sanitize command arguments to prevent injection (e.g., rm -rf).
  5. Testing:

    • Mock BufferedConsoleOutput in PHPUnit:
      $output = $this->createMock(BufferedConsoleOutput::class);
      $output->method('getContent')->willReturn('Mocked output');
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware