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

Ansi Php Laravel Package

bramus/ansi-php

bramus/ansi-php is a lightweight PHP library for working with ANSI escape codes in the terminal. Easily colorize and style CLI output, move the cursor, clear sections of the screen, and build richer command-line interfaces with minimal setup.

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require bramus/ansi-php
    

    No additional configuration is required—it’s a drop-in library.

  2. First Use Case Output colored text in a CLI script:

    use Bramus\Ansi\Ansi;
    
    echo Ansi::colorize('Hello, Laravel!', 'green');
    

    Or use ANSI escape sequences directly:

    echo Ansi::ansi('Hello, Laravel!')->fg('green')->render();
    
  3. Where to Look First

    • Class Documentation (if available) for methods like colorize(), ansi(), and modifiers (fg(), bg(), bold(), etc.).
    • Examples in the repo for practical use cases (e.g., tables, progress bars).

Implementation Patterns

Usage Patterns

  1. Basic Text Styling Use Ansi::colorize() for one-off colored text:

    Ansi::colorize('Warning!', 'yellow', 'bold');
    
  2. Fluent Chaining Build complex styles with method chaining:

    echo Ansi::ansi('Error: File not found')
        ->fg('red')
        ->bg('white')
        ->bold()
        ->render();
    
  3. CLI Artifacts

    • Tables: Use Ansi::table() for formatted output:
      Ansi::table(['User', 'Email'], [
          ['John', 'john@example.com'],
          ['Jane', 'jane@example.com'],
      ]);
      
    • Progress Bars: Combine with Ansi::ansi() for dynamic updates:
      $progress = Ansi::ansi('[' . str_repeat(' ', 50) . ']')->fg('gray');
      // Update later: $progress->fg('green')->render();
      
  4. Integration with Laravel Artisan Enhance command output:

    $this->info(Ansi::colorize('Task completed!', 'green'));
    
  5. Conditional Styling Dynamically apply styles based on logic:

    $status = $job->status;
    $color = $status === 'failed' ? 'red' : 'green';
    $this->line(Ansi::colorize($status, $color));
    

Workflows

  • Logging: Style log messages in Monolog handlers:
    $handler = new \Monolog\Handler\StreamHandler(storage_path('logs/app.log'));
    $handler->pushProcessor(function ($record) {
        $record['formatted'] = Ansi::colorize($record['message'], 'cyan');
        return $record;
    });
    
  • Testing: Use ANSI colors in PHPUnit output for better readability:
    $this->assertTrue(true, Ansi::colorize('Test passed!', 'green'));
    

Integration Tips

  • Terminal Detection: Check if ANSI is supported (e.g., Ansi::isSupported()) before rendering.
  • Cross-Platform: Works on Windows (with ANSI enabled) and Unix-like systems.
  • Laravel Mix: Use in build logs for frontend tasks:
    mix->then(function () {
        echo Ansi::colorize('Build complete!', 'green') . PHP_EOL;
    });
    

Gotchas and Tips

Pitfalls

  1. Windows Compatibility

    • ANSI escape sequences may not work on older Windows terminals (pre-Windows 10).
    • Fix: Enable ANSI support in your terminal or use a library like symfony/console for cross-platform compatibility.
  2. Overuse of Colors

    • Excessive styling can reduce readability. Use sparingly for warnings/errors.
    • Tip: Default to monochrome for non-critical output.
  3. Performance

    • ANSI sequences add minimal overhead, but avoid excessive chaining in loops.
    • Tip: Cache styled strings if reused (e.g., headers in CLI tools).
  4. Nested Styles

    • Incorrect nesting (e.g., fg() inside another ansi()) may break rendering.
    • Tip: Use Ansi::ansi()->render() for complex cases to isolate styles.
  5. IDE/Editor Support

    • Some IDEs (e.g., PHPStorm) may not render ANSI colors in the "Run" tool window.
    • Tip: Test in a real terminal or use symfony/console for IDE integration.

Debugging

  • Broken Output: If colors/text appear garbled:
    • Check for missing \r or \n in sequences.
    • Use Ansi::ansi()->render() to isolate the issue.
  • Unsupported Terminals: Fallback to plain text:
    if (!Ansi::isSupported()) {
        echo "Fallback: " . $plainText;
    }
    

Config Quirks

  • No Configuration: The package is stateless—no .env or config files to tweak.
  • Custom Palettes: Extend the library by adding custom color names:
    Ansi::addColor('laravel', '#FF2D20'); // Laravel red
    Ansi::colorize('Laravel', 'laravel');
    

Extension Points

  1. Custom ANSI Sequences Extend the library by adding methods to Ansi class:

    // In a service provider or trait:
    Ansi::macro('underline', function ($text) {
        return $this->ansi($text)->underline()->render();
    });
    

    Usage:

    Ansi::underline('Click here');
    
  2. Integration with Laravel

    • Service Provider: Bind Ansi to the container for dependency injection:
      $this->app->singleton(Ansi::class, function () {
          return new Ansi();
      });
      
    • Facades: Create a facade for cleaner syntax:
      // app/Facades/Ansi.php
      namespace App\Facades;
      use Bramus\Ansi\Ansi;
      use Illuminate\Support\Facades\Facade;
      
      class Ansi extends Facade {
          protected static function getFacadeAccessor() { return Ansi::class; }
      }
      
      Usage:
      \App\Facades\Ansi::colorize('Hello', 'red');
      
  3. Testing

    • Mock Ansi in unit tests to avoid polluting output:
      $this->partialMock(Ansi::class, ['colorize'])
           ->shouldReceive('colorize')
           ->once()
           ->andReturn('Mocked colored text');
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope