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 Console Highlighter Laravel Package

jakub-onderka/php-console-highlighter

Abandoned package for syntax-highlighting PHP code in the terminal using ANSI colors. Provides a Highlighter that outputs highlighted whole-file or snippet content for CLI display. Suggested alternative: php-parallel-lint/PHP-Console-Highlighter.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jakub-onderka/php-console-highlighter
    

    Ensure your composer.json includes the package under require.

  2. Basic Usage:

    use JakubOnderka\PhpConsoleHighlighter\Highlighter;
    use JakubOnderka\PhpConsoleColor\ConsoleColor;
    
    $highlighter = new Highlighter(new ConsoleColor());
    $highlighted = $highlighter->getWholeFile(file_get_contents('path/to/file.php'));
    echo $highlighted;
    
  3. First Use Case: Highlight a single PHP file in a CLI script (e.g., for debugging or documentation generation):

    $filePath = 'app/Services/UserService.php';
    echo $highlighter->getWholeFile(file_get_contents($filePath));
    

Implementation Patterns

Core Workflows

  1. Syntax Highlighting in CLI Tools: Integrate into custom CLI commands (e.g., php artisan extensions) to display code snippets with syntax highlighting:

    // In a custom Artisan command
    $this->info($highlighter->getWholeFile($this->getFileContent()));
    
  2. Dynamic Code Display: Use in Laravel’s telescope:commands or debugbar extensions to show highlighted code blocks in logs or debug panels.

  3. API Responses: Highlight code snippets in JSON API responses (e.g., for error messages or documentation endpoints):

    return response()->json([
        'error' => 'Invalid query',
        'example' => $highlighter->highlight('SELECT * FROM users WHERE id = ?;')
    ]);
    
  4. Service Provider Bootstrapping: Bind the highlighter to the container for global access:

    // In AppServiceProvider
    $this->app->singleton(Highlighter::class, function ($app) {
        return new Highlighter(new ConsoleColor());
    });
    

    Then inject via constructor:

    public function __construct(private Highlighter $highlighter) {}
    
  5. Partial Highlighting: Highlight specific code segments (e.g., from a string or file range):

    $code = '<?php class User { public $name; }';
    echo $highlighter->highlight($code);
    

Integration Tips

  • Laravel Blade: Use in Blade templates for CLI-generated outputs (e.g., @verbatim + highlighted code).
  • Artisan Commands: Extend Artisan::command() to output highlighted code for help or inspect subcommands.
  • Testing: Highlight test failures or assertions in custom test listeners:
    $this->failures[] = $highlighter->highlight($failedTestCode);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

  2. Tokenizer Dependency:

    • Requires the ext-tokenizer extension. Verify with:
      php -m | grep tokenizer
      
    • Fallback: Use a polyfill like nikic/php-parser if tokenizer is unavailable.
  3. Performance:

    • Highlighting large files (e.g., vendor/ or node_modules/) may cause memory issues. Stream content or limit file sizes:
      $highlighter->highlight(file_get_contents($filePath, false, null, 0, 1024 * 100)); // Read first 100KB
      
  4. Color Compatibility:

    • ANSI colors may not render in all terminals (e.g., Windows CMD). Test in xterm, iTerm2, or enable ANSI support in CMD:
      reg add HKEY_CURRENT_USER\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
      

Debugging

  • Invalid Code:

    • The highlighter may crash on malformed PHP. Wrap usage in a try-catch:
      try {
          echo $highlighter->highlight($invalidCode);
      } catch (\Exception $e) {
          echo "Error highlighting code: " . $e->getMessage();
      }
      
    • Use highlight_string() as a fallback for broken code.
  • Custom Themes:

    • Extend ConsoleColor to modify syntax colors (e.g., for dark terminals):
      $customColor = new ConsoleColor();
      $customColor->setStyle('keyword', 'bold yellow');
      $highlighter = new Highlighter($customColor);
      

Extension Points

  1. Custom Highlighters:

    • Implement JakubOnderka\PhpConsoleHighlighter\HighlighterInterface for custom logic (e.g., language-specific highlighting).
  2. File Caching:

    • Cache highlighted files to avoid reprocessing:
      $cacheKey = 'highlighted_' . md5($filePath);
      $highlighted = Cache::remember($cacheKey, now()->addHours(1), function () use ($highlighter, $filePath) {
          return $highlighter->getWholeFile(file_get_contents($filePath));
      });
      
  3. Web Integration:

    • Convert ANSI colors to HTML/CSS for web use (e.g., with spatie/array-to-html + custom ANSI-to-CSS mapping).
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