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.
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.
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
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);
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);
}
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;
}
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));
}
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
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));
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
]);
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);
});
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();
}
}
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);
}
}
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');
}
Terminal Compatibility:
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>');
}
Markdown Parsing Quirks:
cebe/markdown may not support all Markdown syntax (e.g., tables, complex lists).Performance with Large Files:
$handle = fopen('large_file.md', 'r');
$output = '';
while (!feof($handle)) {
$chunk = fread($handle, 8192);
$output .= (new CliMarkdown())->render($chunk);
}
fclose($handle);
echo $output;
Dependency Conflicts:
cebe/markdown or toolkit/cli-utils.composer.json:
"require": {
"phppkg/cli-markdown": "^
How can I help you explore Laravel packages today?