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

Cli Markdown Laravel Package

phppkg/cli-markdown

CLI-Markdown renders Markdown with ANSI colors in your terminal. Built on cebe/markdown and toolkit/cli-utils, it supports automatic color rendering and customizable CLI color tags. Load Markdown text, call render(), and echo the result for a styled console output.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require phppkg/cli-markdown
    

    Add the package to your composer.json under require or require-dev depending on your use case.

  2. First Use Case - Artisan Command Help Text: Modify an existing Artisan command to render Markdown in its help output:

    use PhpPkg\CliMarkdown\CliMarkdown;
    use Illuminate\Console\Command;
    
    class MyCommand extends Command
    {
        protected $signature = 'my:command';
        protected $description = 'A command with Markdown help text.';
    
        public function handle()
        {
            $this->info('Command executed!');
        }
    
        public function getHelp()
        {
            $markdownHelp = <<<MD
            ## My Command
    
            This command does amazing things.
    
            ### Usage
            ```bash
            php artisan my:command --option=value
            ```
    
            ### Options
            - `--option`: Specify an option value.
            MD;
            return (new CliMarkdown())->render($markdownHelp);
        }
    }
    

    Run the command with --help to see the formatted output:

    php artisan my:command --help
    
  3. Quick Debugging: Use the package to render Markdown directly in Tinker or a script:

    use PhpPkg\CliMarkdown\CliMarkdown;
    
    $markdown = <<<MD
    # Debugging Info
    - **Status**: Active
    - **Last Run**: 2025-04-22
    - **Logs**:
      ```log
      [INFO] Command executed successfully.
    

    MD;

    echo (new CliMarkdown())->render($markdown);

    
    

Implementation Patterns

Usage Patterns

  1. Artisan Command Integration: Override the getHelp() or getExamples() methods to return Markdown strings:

    public function getExamples()
    {
        $examples = <<<MD
        ## Examples
    
        - Run the command with default options:
          ```bash
          php artisan my:command
          ```
    
        - Specify a custom option:
          ```bash
          php artisan my:command --option=custom_value
          ```
        MD;
        return (new CliMarkdown())->render($examples);
    }
    
  2. Dynamic Markdown Generation: Generate Markdown dynamically based on application state or data:

    public function handle()
    {
        $markdown = $this->generateDynamicMarkdown();
        $this->output->writeln((new CliMarkdown())->render($markdown));
    }
    
    private function generateDynamicMarkdown(): string
    {
        $data = [
            'status' => 'success',
            'items' => ['item1', 'item2', 'item3'],
        ];
    
        return <<<MD
        ## Command Results
    
        - **Status**: {$data['status']}
        - **Items**:
          - {$data['items'][0]}
          - {$data['items'][1]}
          - {$data['items'][2]}
        MD;
    }
    
  3. Exception Handling: Format exception messages or stack traces in Markdown for better readability:

    try {
        // Risky operation
    } catch (\Exception $e) {
        $errorMarkdown = <<<MD
        ## Error Encountered
    
        **Message**: {$e->getMessage()}
    
        **Stack Trace**:
        ```
        {$e->getTraceAsString()}
        ```
        MD;
        $this->error((new CliMarkdown())->render($errorMarkdown));
    }
    
  4. Custom CLI Tools: Use the package in standalone PHP scripts or custom CLI tools:

    // script.php
    use PhpPkg\CliMarkdown\CliMarkdown;
    
    $markdown = file_get_contents('README.md');
    echo (new CliMarkdown())->render($markdown);
    

    Run with:

    php script.php
    

Workflows

  1. Markdown Authoring: Write Markdown in .md files and render them dynamically:

    $markdownContent = file_get_contents('docs/command_guide.md');
    $this->output->writeln((new CliMarkdown())->render($markdownContent));
    
  2. Theming and Branding: Customize colors to match your application’s branding. While the package doesn’t directly support global theming, you can extend it:

    $renderer = new CliMarkdown();
    $renderer->setCustomColors([
        'heading' => '#FF5722', // Custom orange for headings
        'code' => '#4CAF50',   // Custom green for code blocks
    ]);
    
  3. Integration with Laravel Events: Trigger Markdown rendering during events (e.g., after deployment):

    use Illuminate\Support\Facades\Event;
    use PhpPkg\CliMarkdown\CliMarkdown;
    
    Event::listen('deployed', function () {
        $markdown = <<<MD
        ## Deployment Successful
    
        **Environment**: production
        **Version**: 1.0.0
        **Changes**:
        - Fixed bug #123
        - Added new feature XYZ
        MD;
        echo (new CliMarkdown())->render($markdown);
    });
    

Integration Tips

  1. Service Provider Binding: Bind the CliMarkdown class to the Laravel container for easier dependency injection:

    // app/Providers/AppServiceProvider.php
    use PhpPkg\CliMarkdown\CliMarkdown;
    
    public function register()
    {
        $this->app->singleton(CliMarkdown::class, function ($app) {
            return new CliMarkdown();
        });
    }
    

    Now you can inject it into commands or services:

    use PhpPkg\CliMarkdown\CliMarkdown;
    
    class MyCommand extends Command
    {
        public function __construct(private CliMarkdown $markdown)
        {
            parent::__construct();
        }
    }
    
  2. Helper Methods: Create helper methods in a base command class to avoid repetition:

    // app/Console/Commands/BaseCommand.php
    use PhpPkg\CliMarkdown\CliMarkdown;
    
    abstract class BaseCommand extends Command
    {
        protected function renderMarkdown(string $content): string
        {
            return (new CliMarkdown())->render($content);
        }
    }
    
  3. Testing: Mock the CliMarkdown class in tests to avoid rendering issues:

    use PhpPkg\CliMarkdown\CliMarkdown;
    use Mockery;
    
    public function testCommandHelp()
    {
        $mockRenderer = Mockery::mock(CliMarkdown::class);
        $mockRenderer->shouldReceive('render')
            ->once()
            ->andReturn('Rendered Markdown');
    
        $this->app->instance(CliMarkdown::class, $mockRenderer);
        $this->artisan('my:command --help')->expectsOutput('Rendered Markdown');
    }
    

Gotchas and Tips

Pitfalls

  1. Terminal Compatibility:

    • Issue: Colors may not render correctly on all terminals (e.g., Windows CMD without ANSI support).
    • Solution: Use toolkit/cli-utils's built-in cross-platform support or add a fallback:
      if (!str_contains(PHP_OS, 'WIN') || getenv('ANSICON') || getenv('ConEmuANSI') || php_sapi_name() === 'phpin')) {
          echo (new CliMarkdown())->render($markdown);
      } else {
          echo strip_tags((new CliMarkdown())->render($markdown), '<br><p>');
      }
      
  2. Markdown Parsing Quirks:

    • Issue: cebe/markdown may not support all Markdown syntax (e.g., tables, complex lists).
    • Solution: Validate your Markdown against the cebe/markdown supported features. For unsupported features, pre-process the Markdown or use a different parser.
  3. Performance with Large Files:

    • Issue: Rendering large Markdown files (e.g., multi-page docs) may cause memory issues.
    • Solution: Stream the output or process the file in chunks:
      $handle = fopen('large_file.md', 'r');
      $output = '';
      while (!feof($handle)) {
          $chunk = fread($handle, 8192);
          $output .= (new CliMarkdown())->render($chunk);
      }
      fclose($handle);
      echo $output;
      
  4. Dependency Conflicts:

    • Issue: Conflicts with other packages using cebe/markdown or toolkit/cli-utils.
    • Solution: Pin versions in composer.json:
      "require": {
          "phppkg/cli-markdown": "^
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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