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 Cli Tools Laravel Package

wp-cli/php-cli-tools

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wp-cli/php-cli-tools
    

    Add to composer.json under require-dev if only needed for testing/scaffolding.

  2. First Use Case: Display a formatted table in a Laravel Artisan command:

    use cli\Table;
    
    $table = new Table(['ID', 'Name', 'Status']);
    $table->addRow([1, 'User 1', 'Active']);
    $table->addRow([2, 'User 2', 'Inactive']);
    $table->display();
    
  3. Where to Look First:

    • Examples: vendor/wp-cli/php-cli-tools/examples/ for ready-to-use snippets.
    • API Docs: Focus on cli\Table, cli\progress\Bar, and cli\out() for daily use.
    • TTY Detection: Check cli\is_tty() for conditional CLI output logic.

Implementation Patterns

Core Workflows

1. Artisan Command Output

Replace echo/var_dump with structured output:

use cli\out;

out('Processing...', 'green');
out('Done!', 'bold green');

2. Progress Feedback

Use progress bars for long-running tasks (e.g., migrations, imports):

use cli\progress\Bar;

$bar = new Bar('Migrating data', 100);
for ($i = 0; $i < 100; $i++) {
    $bar->tick();
    // Simulate work
    sleep(0.1);
}

3. Interactive Prompts

Collect user input in CLI tools:

use cli\prompt;

$confirm = prompt('Overwrite existing file?', 'n');
if ($confirm === 'y') {
    // Proceed
}

4. Tabular Data

Display query results or logs:

use cli\Table;

$table = new Table(['User ID', 'Email', 'Role']);
foreach ($users as $user) {
    $table->addRow([$user->id, $user->email, $user->role]);
}
$table->display();

5. Tree Structures

Visualize directory/file hierarchies:

use cli\Tree;

$tree = new Tree();
$tree->setData(['folder' => ['file1.txt', 'subfolder' => ['file2.txt']]]);
$tree->display();

Laravel-Specific Patterns

1. Artisan Command Integration

Extend Laravel’s Command class with CLI tools:

use Illuminate\Console\Command;
use cli\out;

class MyCommand extends Command {
    protected $signature = 'my:command {--force}';

    public function handle() {
        out('Command executed!', 'yellow');
        // ...
    }
}

2. Testing CLI Output

Use cli\Table/cli\progress\Bar in PHPUnit tests:

use cli\Table;
use Tests\TestCase;

class TableTest extends TestCase {
    public function testTableOutput() {
        $table = new Table(['ID', 'Name']);
        $table->addRow([1, 'Test']);
        $this->expectOutputRegex('/\|\s*1\s*\|\s*Test\s*\|\s*/');
        $table->display();
    }
}

3. Dynamic Menus

Build interactive CLI menus (e.g., for admin tools):

use cli\menu;

$choices = ['Option 1', 'Option 2', 'Quit'];
$choice = menu('Select an option:', $choices, 'Option 1');

4. Cross-Platform Compatibility

Handle Windows/Linux differences:

if (cli\is_windows()) {
    // Windows-specific logic
}

Integration Tips

1. Composer Scripts

Add to composer.json for reusable CLI tasks:

"scripts": {
    "test": "phpunit && php-cs-fixer fix --dry-run",
    "lint": "php-cs-fixer fix"
}

2. Custom Renderers

Extend cli\table\Renderer for custom table styles:

class MyRenderer extends \cli\table\Renderer {
    public function renderCell($value) {
        return '<span style="color: red;">' . parent::renderCell($value) . '</span>';
    }
}

3. TTY-Aware Output

Detect piped vs. interactive output:

if (cli\is_tty()) {
    out('Interactive mode: ', 'green');
} else {
    out('Piped output: ', 'yellow');
}

4. Process Execution

Run shell commands with error handling:

use cli\run_command;

$result = run_command('git status');
if ($result['success']) {
    out($result['output']);
} else {
    err('Git error: ' . $result['error']);
}

Gotchas and Tips

Pitfalls

1. TTY Detection Issues

  • Problem: cli\is_tty() may return false in CI/CD pipelines even when output is to a terminal.
  • Fix: Use environment variables or manual checks:
    $isTty = !defined('CI') && posix_isatty(STDERR);
    

2. Windows Line Endings

  • Problem: Progress bars or tables may render incorrectly on Windows.
  • Fix: Use cli\is_windows() and adjust rendering logic:
    if (cli\is_windows()) {
        $bar->setInterval(200); // Slower updates for Windows
    }
    

3. Color Output in Pipes

  • Problem: ANSI colors may break when piped to files/tools.
  • Fix: Disable colors in non-TTY contexts:
    if (!cli\is_tty()) {
        cli\Colors::disable();
    }
    

4. Table Column Wrapping

  • Problem: Long text in tables may overflow or wrap unpredictably.
  • Fix: Configure column width and wrapping:
    $table->setColumnWidths([10, 30, 'auto']); // Fixed, fixed, auto
    $table->setWrap(true);
    

5. PHP Version Quirks

  • Problem: Some functions (e.g., grapheme_strlen) may not work on older PHP versions.
  • Fix: Use fallbacks:
    if (!function_exists('grapheme_strlen')) {
        require 'vendor/wp-cli/php-cli-tools/src/cli/fallbacks.php';
    }
    

Debugging Tips

1. Enable Debug Output

cli\out('Debug: ' . print_r($variable, true), 'red');

2. Check TTY State

out('TTY: ' . (cli\is_tty() ? 'Yes' : 'No'), 'blue');

3. Validate Table Data

$table->setHeaders(['ID', 'Name']);
$table->setRows([['1', 'Test']]);
$table->display();

4. Progress Bar Debugging

$bar = new Bar('Test', 5);
$bar->setInterval(50); // Faster updates for debugging

Extension Points

1. Custom Table Renderers

Override cli\table\Renderer for custom styles (e.g., Markdown, HTML):

class MarkdownRenderer extends \cli\table\Renderer {
    public function renderHeader() { /* ... */ }
    public function renderRow() { /* ... */ }
}

2. Extend Argument Parser

Customize cli\ArgumentParser for project-specific CLI flags:

$parser = new \cli\ArgumentParser();
$parser->addOption('verbose', 'v', 'Enable verbose output');
$args = $parser->parse($_SERVER['argv']);

3. Add Custom Notifiers

Extend cli\notify\Notifier for new progress indicators (e.g., ASCII art):

class HeartbeatNotifier extends \cli\notify\Notifier {
    public function render($msg) { /* ... */ }
}

4. Hook into Output

Override cli\out() globally via autoloading:

// In a service provider
cli\out::setHandler(function ($msg, $color) {
    // Custom logic (e.g., log to file)
    echo $msg . PHP_EOL;
});

Configuration Quirks

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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views