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

Climate Laravel Package

league/climate

League CLImate makes PHP CLI output nicer with easy colored text, formatting, and styled messages. Install via Composer and use a simple API to print red, blue, and more, helping your command-line scripts look clean and readable.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/climate
    

    Add to composer.json under require-dev if only for local scripts.

  2. First Use Case: Replace raw echo statements in CLI scripts with CLImate for colored output:

    use League\CLImate\CLImate;
    
    $climate = new CLImate();
    $climate->blue('Task completed!')->bold();
    

    Where to look first: CLImate Docs → "Basic Usage" section.


Implementation Patterns

Core Workflows

  1. Colored Output & Styling

    • Chain methods for readability:
      $climate->yellow('Warning: ')->bold()->underline('Disk space low!');
      
    • Use contextual colors (e.g., $climate->error('Failed') for red).
  2. Interactive Prompts

    • Replace fgets() with structured prompts:
      $name = $climate->input('Enter your name:')->defaultTo('Guest');
      $confirm = $climate->confirm('Proceed?', false);
      $choice = $climate->radio('Select:', ['Option 1', 'Option 2']);
      
  3. Progress & Feedback

    • Progress Bars:
      $progress = $climate->progress()->start(100);
      foreach ($items as $item) {
          $progress->advance();
      }
      
    • Spinners for async tasks:
      $spinner = $climate->spinner('Processing...');
      $spinner->start();
      // Simulate work
      $spinner->finish();
      
  4. Tables & Data Display

    • Format tabular data dynamically:
      $climate->table(['Name', 'Status'], [
          ['Task 1', 'Completed'],
          ['Task 2', 'Pending'],
      ]);
      
  5. Argument Parsing

    • Parse CLI args in Laravel Artisan commands:
      $args = $climate->arguments->getArray('d'); // Parse `--d=value` flags
      

Laravel Integration Tips

  • Artisan Commands: Inject CLImate into commands via constructor:

    use League\CLImate\CLImate;
    
    class MyCommand extends Command {
        protected $climate;
    
        public function __construct(CLImate $climate) {
            $this->climate = $climate;
            parent::__construct();
        }
    
        public function handle() {
            $this->climate->info('Command executed!');
        }
    }
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        League\CLImate\CLImateServiceProvider::class,
    ],
    
  • Console Kernel: Use CLImate globally in app/Console/Kernel.php:

    protected $climate;
    
    public function __construct(CLImate $climate) {
        $this->climate = $climate;
    }
    
    public function handle() {
        $this->climate->comment('Starting console tasks...');
    }
    
  • Views & Blade: Extend CLImate for Blade templates (e.g., resources/views/console.blade.php):

    @inject('climate', 'League\CLImate\CLImate')
    {{ $climate->table(['Key', 'Value'], $data) }}
    

Gotchas and Tips

Pitfalls

  1. ANSI Escape Sequences

    • Issue: Colors/spinners may not render on Windows or non-ANSI terminals.
    • Fix: Force ANSI mode or use forceAnsiOn():
      $climate->forceAnsiOn();
      
    • Debug: Check $climate->supportsAnsi() before rendering.
  2. Progress Bar Precision

    • Issue: Floating-point precision errors in progress bars (e.g., 99.999%).
    • Fix: Use precision() method:
      $progress->precision(0); // Show whole numbers only
      
  3. Input Validation

    • Issue: accept() method may not work as expected with multiline input.
    • Fix: Use defaultTo() with validation:
      $input = $climate->input('Enter value:')->defaultTo('default')->accept(fn($val) => strlen($val) > 3);
      
  4. Terminal Width Detection

    • Issue: Incorrect column widths on Windows or SSH.
    • Fix: Manually set width or use $climate->width().
  5. Phar/Non-CLI Contexts

    • Issue: STDOUT errors in non-CLI environments (e.g., web servers).
    • Fix: Wrap usage in if (php_sapi_name() === 'cli').

Debugging Tips

  • Disable ANSI Temporarily:
    $climate->forceAnsiOff();
    
  • Log Raw Output: Use buffer() to capture output for debugging:
    $buffer = $climate->buffer();
    $buffer->write($climate->red('Test'));
    $output = $buffer->output();
    
  • Check for Deprecations: Run php -l or use phpstan to catch deprecated methods (e.g., valueArray()values()).

Extension Points

  1. Custom Output Writers

    • Override default output (e.g., log to file):
      $climate->output = new \League\CLImate\Util\Writer\FileWriter('log.txt');
      
  2. Extend CLImate

    • Add methods via extend():
      $climate->extend(function ($climate) {
          $climate->success('Custom method!', fn() => $climate->green('Success!'));
      });
      
  3. PSR-3 Logger Integration

    • Use CLImate as a logger:
      $logger = new \League\CLImate\Logger\Logger($climate);
      $logger->info('Log message');
      
  4. Art & Animations

    • Load custom ASCII art:
      $climate->art(__DIR__.'/assets/art.txt');
      
    • Animate GIFs:
      $climate->animate('http://example.com/loading.gif');
      

Configuration Quirks

  • PHP 8.1+ Type Safety: CLImate uses string return types; ensure IDE autocompletion is enabled (e.g., PHPStorm’s "Strict Generics").
  • Multibyte Strings: Requires ext-mbstring or symfony/polyfill-mbstring for Unicode support.
  • Windows-Specific Fixes: Use seld/cli-prompt polyfill if password input fails (included in v3.1.1+).

Performance Notes

  • Progress Bars: Avoid forceRedraw() in tight loops; use each() for batch updates.
  • Tables: Pre-calculate column widths for large datasets to avoid runtime delays.

```markdown
### Laravel-Specific Gotchas
1. **Service Container Binding**
   - Bind CLImate as a singleton in `AppServiceProvider`:
     ```php
     $this->app->singleton(CLImate::class, function () {
         return new CLImate();
     });
     ```
   - *Why*: Prevents recreation of CLImate instances (e.g., in loops).

2. **Artisan Command Output**
   - Use `$this->climate` instead of `$this->output` in commands to avoid Artisan’s default styling conflicts.

3. **Testing CLI Output**
   - Mock CLImate in tests:
     ```php
     $mock = Mockery::mock(CLImate::class);
     $mock->shouldReceive('info')->once()->with('Test');
     $this->app->instance(CLImate::class, $mock);
     ```

4. **Queue Workers**
   - Avoid CLImate in queue workers (non-CLI context). Use logging instead:
     ```php
     if (app()->runningInConsole()) {
         $climate->info('Processed job!');
     } else {
         Log::info('Processed job!');
     }
     ```
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport