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 simple methods like red() or blue() to print readable, attention-grabbing console output for scripts and command-line tools.

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:

    $climate = new \League\CLImate\CLImate;
    $climate->success('Migration completed!')->bold();
    
  3. Key Entry Points:

    • Output: $climate->text(), $climate->error(), $climate->warning().
    • Interactive: $climate->input(), $climate->confirm(), $climate->checkboxes().
    • Structured: $climate->table(), $climate->progress().
    • Debugging: $climate->debug() (logs to STDERR).
  4. Where to Look First:

    • Official Docs (method reference, examples).
    • src/League/CLImate/ for core classes (e.g., CLImate.php, TerminalObject/).
    • Laravel integration: Use Artisan::output() with CLImate’s Logger for consistency.

Implementation Patterns

1. Unified CLI Output in Laravel

Pattern: Replace echo/Artisan::line() with CLImate in commands. Example:

use League\CLImate\CLImate;
use Symfony\Component\Console\Command\Command;

class DeployCommand extends Command {
    protected function execute(InputInterface $input, OutputInterface $output) {
        $climate = new CLImate();
        $climate->info('Starting deployment...')->bold();

        // Progress bar for steps
        $progress = $climate->progress()->start('Deploying...');
        foreach ($steps as $step) {
            $progress->advance();
            $climate->text("  - $step");
        }
        $progress->finish();

        $climate->success('Deployment complete!')->newline(2);
    }
}

2. Interactive User Prompts

Pattern: Replace readline() or custom input with CLImate’s prompts. Example:

$climate = new CLImate;

// Confirmation
if ($climate->confirm('Overwrite existing files?', false)) {
    $climate->text('Proceeding...')->bold();
}

// Multi-select
$options = ['Option 1', 'Option 2', 'Option 3'];
$selected = $climate->checkboxes('Choose options:', $options, 1);
$climate->text('Selected: ' . implode(', ', $selected));

// Password input (secure)
$password = $climate->password('Enter password:');

3. Structured Data Output

Pattern: Use tables for CLI reports or logs. Example:

$data = [
    ['ID', 'Name', 'Status'],
    [1, 'User 1', 'Active'],
    [2, 'User 2', 'Inactive'],
];

$climate->table($data)
    ->setHeaders(['ID', 'Name', 'Status'])
    ->setPadding(2)
    ->render();

4. Progress Tracking

Pattern: Wrap long-running tasks with progress bars/spinners. Example:

$climate = new CLImate;
$progress = $climate->progress()->start('Processing 100 items...');

// Simulate work
foreach (range(1, 100) as $i) {
    usleep(50000);
    $progress->advance("Item $i/100");
}
$progress->finish();

5. Extending CLImate

Pattern: Create custom decorators or extend core functionality. Example:

$climate = new CLImate;
$climate->extend('git', function ($message) {
    return $this->yellow("GIT: $message");
});

// Usage:
$climate->git('Commit pushed!');

6. Logging Integration

Pattern: Use CLImate as a PSR-3 logger for CLI tools. Example:

use League\CLImate\Logger;

$logger = new Logger(new CLImate());
$logger->debug('Debug message');
$logger->error('Error occurred!', ['trace' => $e->getTraceAsString()]);

7. Cross-Platform Compatibility

Pattern: Handle Windows/Linux/macOS inconsistencies gracefully. Example:

$climate = new CLImate;
if (!$climate->isWindows()) {
    $climate->text('This runs only on Unix-like systems.')->warning();
}

Gotchas and Tips

Pitfalls

  1. ANSI Color Issues:

    • Gotcha: Colors may not render on Windows or non-ANSI terminals.
    • Fix: Use $climate->forceAnsiOn() or check $climate->supportsAnsi() before coloring.
    • Tip: Test with $climate->isWindows() and adjust output accordingly.
  2. Progress Bar Precision:

    • Gotcha: Floating-point precision can cause progress bars to stall at 100%.
    • Fix: Use $progress->setPrecision(2) or cast values to integers.
  3. Input Validation:

    • Gotcha: $climate->input() may not validate types (e.g., expects int but gets string).
    • Fix: Use filter_var() or custom validation after input:
      $age = (int) $climate->input('Enter age:', 0);
      
  4. Terminal Width Detection:

    • Gotcha: $climate->width() may return 0 on some Windows setups.
    • Fix: Fallback to a default width (e.g., 80):
      $width = max($climate->width(), 80);
      
  5. Multibyte Strings:

    • Gotcha: Text truncation or misalignment with UTF-8 characters.
    • Fix: Ensure mbstring extension is enabled or use the symfony/polyfill-mbstring package.
  6. Spinner Indeterminacy:

    • Gotcha: Indeterminate spinners may flicker or freeze.
    • Fix: Use $spinner->setInterval(100) to control refresh rate.
  7. Argument Parsing:

    • Gotcha: $climate->arguments may not handle nested options (e.g., --option=value).
    • Fix: Use $climate->arguments->getArray('option') for complex cases.
  8. Output Buffering:

    • Gotcha: Buffered output may not flush immediately, causing delays.
    • Fix: Explicitly flush with $climate->output()->flush().

Debugging Tips

  1. Check ANSI Support:

    $climate->text('ANSI Supported: ' . ($climate->supportsAnsi() ? 'Yes' : 'No'));
    
  2. Inspect Terminal Width:

    $climate->text("Terminal Width: {$climate->width()} chars");
    
  3. Log Raw Output:

    $climate->debug('Raw output:', ['output' => $climate->output()->getContent()]);
    
  4. Disable Colors for Testing:

    $climate->forceAnsiOff();
    
  5. Validate Input:

    $input = $climate->input('Enter a number:', 0);
    if (!is_numeric($input)) {
        $climate->error('Invalid input!')->newline();
        exit(1);
    }
    

Extension Points

  1. Custom Output Writers:

    • Override $climate->output() to redirect output to files, APIs, or databases.
    • Example:
      $climate->output(new \League\CLImate\Output\FileWriter('log.txt'));
      
  2. Decorators:

    • Extend \League\CLImate\Decorator\DecoratorInterface to add custom formatting (e.g., emojis, icons).
    • Example:
      $climate->extend('emoji', function ($text) {
          return $this->green("🚀 $text");
      });
      
  3. Argument Parsers:

    • Extend \League\CLImate\Argument\ArgumentParser for custom CLI argument handling.
  4. Interactive Prompts:

    • Subclass \League\CLImate\Prompt\Prompt to create custom prompts (e.g., select(), slider()).
  5. Progress Bar Styling:

    • Override \League\CLImate\ProgressBar\ProgressBar to change bar characters or colors.

Laravel-Specific Tips

  1. Artisan Integration:
    • Use Artisan::output() with CLImate’s Logger for consistent output:
      $logger = new Logger(new CLImate());
      Artisan
      
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony