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

Commonmark Laravel Package

fluxbb/commonmark

Laravel-friendly CommonMark utilities from FluxBB: parse, render, and work with Markdown/CommonMark content in PHP with sensible defaults and integration patterns suited to Laravel apps. Lightweight package aimed at consistent, safe content rendering.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require fluxbb/commonmark
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "FluxBB\\CommonMark\\": "vendor/fluxbb/commonmark/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Parse a simple Markdown string:

    use FluxBB\CommonMark\CommonMarkConverter;
    
    $converter = new CommonMarkConverter();
    $html = $converter->convertToHtml('# Hello, **Markdown**!');
    echo $html; // Outputs: <h1>Hello, <strong>Markdown</strong>!</h1>
    
  3. Where to Look First:

    • Documentation (if available; check for README or Wiki).
    • src/CommonMarkConverter.php for core functionality.
    • src/Environment.php for configuration and extensions.

Implementation Patterns

Core Workflows

  1. Basic Parsing:

    $converter = new CommonMarkConverter();
    $html = $converter->convertToHtml($markdownString);
    
    • Use convertToCommonMark() for reverse conversion (if needed).
  2. Extending with Custom Rules:

    • Implement FluxBB\CommonMark\Rule\RuleInterface for custom syntax.
    • Register via Environment:
      $env = new Environment();
      $env->addRule(new MyCustomRule());
      $converter = new CommonMarkConverter($env);
      
  3. Integration with Laravel:

    • Service Provider:
      public function register()
      {
          $this->app->singleton(CommonMarkConverter::class, function ($app) {
              $env = new Environment();
              // Add extensions here (e.g., tables, footnotes)
              return new CommonMarkConverter($env);
          });
      }
      
    • Helper Function (in app/Helpers/markdown.php):
      if (!function_exists('markdown')) {
          function markdown($text) {
              return app(CommonMarkConverter::class)->convertToHtml($text);
          }
      }
      
    • Blade Directive:
      Blade::directive('markdown', function ($expression) {
          return "<?php echo markdown({$expression}); ?>";
      });
      
      Usage in Blade:
      @markdown($post->content)
      
  4. Handling Large Content:

    • Stream processing for long documents (e.g., books):
      $converter = new CommonMarkConverter();
      $stream = fopen('large.md', 'r');
      $html = '';
      while (!feof($stream)) {
          $chunk = fread($stream, 8192);
          $html .= $converter->convertToHtml($chunk);
      }
      fclose($stream);
      
  5. Safe Mode (XSS Protection):

    • Use HTMLPurifier or similar to sanitize output:
      $html = $converter->convertToHtml($markdown);
      $purifier = new HTMLPurifier();
      $safeHtml = $purifier->purify($html);
      

Gotchas and Tips

Pitfalls

  1. Performance:

    • Parsing large documents can be slow. Cache results if possible:
      $cacheKey = 'markdown_' . md5($markdown);
      $html = cache()->remember($cacheKey, now()->addHours(1), function () use ($markdown) {
          return $converter->convertToHtml($markdown);
      });
      
  2. Extension Conflicts:

    • Some extensions (e.g., tables, footnotes) may not be included by default. Check Environment for available extensions:
      $env->addExtension(new TablesExtension());
      $env->addExtension(new FootnotesExtension());
      
  3. Deprecated Features:

    • The package targets PHP 5.4+, but some features may be outdated. Test thoroughly with your PHP version.
  4. HTML Output Quirks:

    • Default output may include unwanted attributes (e.g., class="markdown-body"). Override templates if needed:
      $env->addRenderer(new MyCustomRenderer());
      
  5. Namespace Collisions:

    • If using other fluxbb packages, ensure autoloading is configured correctly to avoid conflicts.

Debugging Tips

  1. Enable Debugging:

    • Set CommonMarkConverter to debug mode (if supported) or log input/output:
      $markdown = '# Test';
      $html = $converter->convertToHtml($markdown);
      Log::debug("Markdown: {$markdown}", ['html' => $html]);
      
  2. Validate Markdown:

  3. Check Extensions:

    • If parsing fails, disable extensions one by one to isolate the issue:
      $env = new Environment();
      // Disable all extensions temporarily
      $env->removeAllExtensions();
      

Extension Points

  1. Custom Renderers:

    • Override RendererInterface for custom HTML output:
      class MyRenderer implements RendererInterface {
          public function renderBlock($block) {
              // Custom logic
          }
      }
      $env->addRenderer(new MyRenderer());
      
  2. Inline/Block Rules:

    • Extend parsing logic by implementing InlineParser or BlockParser interfaces.
  3. Post-Processing:

    • Use Laravel’s Str or Html helpers to modify output:
      $html = str_replace('class="markdown-body"', '', $html);
      
  4. Event Listeners:

    • Hook into Laravel events (e.g., eloquent.saved) to auto-convert Markdown fields:
      Post::saved(function ($post) {
          if ($post->isDirty('content')) {
              $post->content_html = markdown($post->content);
              $post->save();
          }
      });
      
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