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

Code Outliner Laravel Package

spatie/code-outliner

CLI tool to visualize your code structure by generating outline images of files or directories. Overlay multiple files to spot dense or repetitive areas and improve readability. Requires Puppeteer via spatie/browsershot; install globally via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/code-outliner
    

    Add the service provider to config/app.php:

    Spatie\CodeOutliner\CodeOutlinerServiceProvider::class,
    
  2. First Use Case: Generate an outline for a single file:

    use Spatie\CodeOutliner\Facades\CodeOutliner;
    
    $outline = CodeOutliner::generate('path/to/YourController.php');
    $outline->save('path/to/output.png');
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. On-Demand Generation: Use the facade in controllers or commands to generate outlines dynamically (e.g., for documentation or PR reviews):

    $outline = CodeOutliner::generate('app/Http/Controllers/UserController.php');
    return response()->file($outline->getPath());
    
  2. Batch Processing: Process multiple files via CLI (e.g., for a code review session):

    php artisan code-outliner:generate app/Http/Controllers --output=docs/outlines
    
  3. Integration with Laravel Events: Trigger outline generation post-commit or pre-deploy:

    // In a service provider or event listener
    event(new RepositoryPushed($repository));
    CodeOutliner::generate('app/Service/'.class_basename($repository->getPath()))
        ->save(storage_path('app/outlines/'.basename($repository->getPath()).'.png'));
    
  4. Customizing Output: Override defaults in config/code-outliner.php:

    'colors' => [
        'background' => '#f5f5f5',
        'keyword' => '#0000ff',
        'string' => '#a31515',
    ],
    'line-height' => 1.5,
    
  5. Webhook-Driven Workflows: Use the package in a webhook endpoint to generate outlines for pull requests:

    public function handle(PullRequestEvent $event) {
        $outline = CodeOutliner::generate($event->filePath)
            ->save(storage_path("temp/pr_{$event->id}.png"));
        // Attach to PR comment or Slack notification
    }
    

Integration Tips

  • Storage: Use Laravel’s filesystem to store outlines (e.g., storage/app/outlines).
  • Caching: Cache generated outlines for performance (e.g., Cache::remember).
  • Queue Jobs: Offload generation to a queue for large files:
    GenerateOutlineJob::dispatch('app/Service/HeavyClass.php');
    
  • Testing: Mock the facade in unit tests:
    $this->partialMock(Spatie\CodeOutliner\Facades\CodeOutliner::class, function ($mock) {
        $mock->shouldReceive('generate')->andReturn(new MockOutline());
    });
    

Gotchas and Tips

Pitfalls

  1. Performance:

    • Large files (>1000 lines) may time out or crash. Use batch processing or queue jobs.
    • Fix: Split files into logical chunks or use --limit in CLI.
  2. Syntax Highlighting:

    • The package uses PHP’s built-in tokenizer, which may misinterpret custom syntax (e.g., DSLs, macros).
    • Fix: Pre-process files or extend the tokenizer logic (see extension points).
  3. Path Handling:

    • Relative paths in generate() are resolved from the root directory, not the working directory.
    • Fix: Use absolute paths or realpath():
      CodeOutliner::generate(realpath('app/Http/Controllers/UserController.php'));
      
  4. Output Overwriting:

    • save() overwrites files by default. Use unique filenames for batch processing:
      $outline->save("outlines/{$fileName}-".time().'.png');
      
  5. Deprecated Methods:

    • The package is outdated (last release 2018). Some methods may not exist in newer Laravel versions.
    • Fix: Check the source code for compatibility.

Debugging

  • Verify Input: Ensure the file exists and is readable:
    if (!file_exists($path)) {
        throw new \InvalidArgumentException("File not found: {$path}");
    }
    
  • Check Dependencies: The package relies on imagick or gd for image generation. Install via:
    sudo apt-get install php-imagick  # Ubuntu/Debian
    
  • Log Errors: Wrap generation in a try-catch to log issues:
    try {
        $outline = CodeOutliner::generate($path);
    } catch (\Exception $e) {
        Log::error("Outline generation failed for {$path}: {$e->getMessage()}");
    }
    

Config Quirks

  • Default Config: The package ships with hardcoded defaults. Override in config/code-outliner.php:
    'font' => resource_path('fonts/consolas.ttf'), // Custom font
    'dpi' => 96, // Adjust resolution
    
  • Color Schemes: Use valid CSS color strings (e.g., #hex, rgb(0,0,0), or named colors like red).

Extension Points

  1. Custom Tokenizers: Extend Spatie\CodeOutliner\Tokenizers\TokenizerInterface to support new languages or syntax:

    class CustomTokenizer implements TokenizerInterface {
        public function tokenize(string $code): array {
            // Implement custom logic
        }
    }
    

    Register it in the service provider:

    $this->app->bind(
        TokenizerInterface::class,
        CustomTokenizer::class
    );
    
  2. Post-Processing: Hook into the outline-generated event to modify the output:

    // In a service provider
    event(new OutlineGenerated($outline));
    

    Listen to it in another provider:

    event(new OutlineGenerated($outline));
    $outline->addWatermark('Confidential');
    
  3. CLI Customization: Extend the GenerateCommand to add flags or logic:

    class CustomGenerateCommand extends GenerateCommand {
        protected function getOptions() {
            return [
                ['recursive', 'r', InputOption::VALUE_NONE, 'Generate outlines recursively'],
                // ...
            ];
        }
    }
    

    Bind it in the service provider:

    $this->app->bind(
        'command.code-outliner.generate',
        CustomGenerateCommand::class
    );
    
  4. Output Formats: The package outputs PNGs by default. Extend to support other formats (e.g., SVG) by modifying the Renderer class.

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
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
twbs/bootstrap4