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

Ccdn Component Bb Code Laravel Package

codeconsortium/ccdn-component-bb-code

CCDNComponent BBCode Library for Laravel/PHP projects. Provides a BBCode parsing component to convert forum-style tags into HTML, intended for integrating rich text formatting in applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation Add the package via Composer:

    composer require codeconsortium/ccdn-component-bb-code
    

    Require the autoloader in your Laravel project (if not auto-loaded via Composer).

  2. Basic Setup Initialize the BBCode parser in a Laravel service provider or controller:

    use CCDN\Component\BBCode\BBCode;
    
    $bbcode = new BBCode();
    
  3. First Use Case: Parsing BBCode Parse a simple BBCode string into HTML:

    $input = "[b]Hello[/b], [i]World![/i]";
    $output = $bbcode->parse($input);
    // Output: <strong>Hello</strong>, <em>World!</em>
    
  4. Registering Custom Tags (Optional) Define custom BBCode tags (e.g., [code]):

    $bbcode->addTag('code', function ($text) {
        return '<pre><code>' . htmlspecialchars($text) . '</pre></code>';
    });
    

Implementation Patterns

Common Workflows

  1. Sanitizing User Input Use BBCode parsing to sanitize and convert user-generated content (e.g., forum posts, comments) into safe HTML:

    $userInput = request()->input('content');
    $safeHtml = $bbcode->parse($userInput);
    
  2. Integration with Laravel Blade Create a Blade directive or helper to parse BBCode in views:

    // In a service provider:
    Blade::directive('bbcode', function ($expression) {
        return "<?php echo app('bbcode')->parse({$expression}); ?>";
    });
    

    Usage in Blade:

    @bbcode($post->content)
    
  3. Storing Parsed Output Cache parsed BBCode output to avoid reprocessing (e.g., for static pages or frequent reads):

    $cacheKey = 'bbcode_' . md5($input);
    $parsed = Cache::remember($cacheKey, now()->addHours(1), function () use ($bbcode, $input) {
        return $bbcode->parse($input);
    });
    
  4. Validation Before Parsing Validate BBCode input to restrict allowed tags/attributes (e.g., block [img] tags with src validation):

    if (strpos($input, '[img') !== false) {
        $input = preg_replace('/\[img\b[^\]]*\](.*?)\[\/img\]/i', '[img]$1[/img]', $input);
    }
    

Integration Tips

  • Laravel Events: Trigger parsing during model events (e.g., saved):
    $post->saved(function ($post) {
        $post->content_html = app('bbcode')->parse($post->content);
        $post->save();
    });
    
  • API Responses: Parse BBCode in API responses for rich-text fields:
    return response()->json([
        'content' => $bbcode->parse($request->content),
    ]);
    
  • Middleware: Sanitize BBCode input in middleware for global protection:
    public function handle($request, Closure $next) {
        $request->merge(['safe_content' => $bbcode->parse($request->content)]);
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. XSS Vulnerabilities

    • Risk: Malicious BBCode tags (e.g., [script]) can execute JavaScript.
    • Fix: Disable dangerous tags by default or whitelist only safe ones:
      $bbcode->disableTags(['script', 'iframe']);
      
    • Tip: Combine with Laravel’s Purifier for additional sanitization.
  2. Performance with Large Inputs

    • Risk: Complex BBCode strings may slow parsing.
    • Fix: Cache parsed output or use Laravel’s queue system for async processing.
  3. Nested Tags

    • Risk: Improperly nested tags (e.g., [b][i]text[/b][/i]) may break parsing.
    • Fix: Validate input or use a regex pre-check:
      if (preg_match('/\[(\w+)\].*\[\/\1\]/i', $input) === 0) {
          throw new \InvalidArgumentException('Invalid BBCode nesting.');
      }
      
  4. PHP 5.3 Legacy

    • Risk: Package targets PHP 5.3, which may conflict with modern Laravel (PHP 8+).
    • Fix: Use a wrapper or fork the package for PHP 8 compatibility.

Debugging

  • Enable Debug Mode Toggle debug output to inspect parsing issues:
    $bbcode->setDebug(true);
    $output = $bbcode->parse($input); // Check logs for errors.
    
  • Log Unparsed Tags Track unsupported BBCode tags for customization:
    $bbcode->setUnsupportedTagCallback(function ($tag) {
        Log::warning("Unsupported BBCode tag: {$tag}");
    });
    

Extension Points

  1. Custom Tag Handlers Extend functionality by adding custom tags:

    $bbcode->addTag('highlight', function ($text) {
        return '<mark>' . $text . '</mark>';
    });
    
  2. Attribute Handling Parse attributes in BBCode tags (e.g., [url=https://example.com]Link[/url]):

    $bbcode->addTag('url', function ($text, $attributes) {
        $url = $attributes['href'] ?? '#';
        return "<a href=\"{$url}\">{$text}</a>";
    });
    
  3. Pre/Post Processing Hook into parsing lifecycle:

    $bbcode->setPreProcessCallback(function ($input) {
        return str_replace('[quote]', '<blockquote>', $input);
    });
    $bbcode->setPostProcessCallback(function ($output) {
        return str_replace('</blockquote>', '[/quote]', $output);
    });
    
  4. Laravel Service Container Bind the BBCode parser as a singleton for dependency injection:

    $this->app->singleton('bbcode', function () {
        $bbcode = new BBCode();
        $bbcode->disableTags(['script']);
        return $bbcode;
    });
    

    Usage:

    $parsed = app('bbcode')->parse($input);
    
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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