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 Bundle Laravel Package

codeconsortium/ccdn-component-bb-code-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require codeconsortium/ccdn-component-bb-code-bundle
    

    Register the bundle in app/AppKernel.php:

    new CodeConsortium\CCDNComponentBBCodeBundle\CCDNComponentBBCodeBundle(),
    
  2. Basic Usage Inject the BBCodeParser service into your controller or service:

    use CodeConsortium\CCDNComponentBBCodeBundle\Parser\BBCodeParser;
    
    class MyController extends Controller
    {
        public function showPostAction(Request $request, BBCodeParser $parser)
        {
            $bbcodeText = "[B]Hello[/B] [I]World[/I]!";
            $htmlOutput = $parser->parse($bbcodeText);
            return $this->render('post.html.twig', ['content' => $htmlOutput]);
        }
    }
    
  3. First Use Case Parse user-generated content (e.g., forum posts, comments) in a Twig template:

    {{ post.content|parse_bbcode }}
    

    Ensure the Twig extension is enabled (auto-registered by the bundle).


Implementation Patterns

Core Workflow

  1. Lexing & Parsing The bundle uses a two-step process:

    • Lexing: Converts BBCode into tokens (e.g., [B]OPEN_TAG with name="B").
    • Parsing: Converts tokens into HTML using a symbol table for tag resolution.
    $parser = $this->get('bbcode.parser');
    $html = $parser->parse($rawText);
    
  2. Integration with Forms Sanitize BBCode input in forms (e.g., Symfony\Component\Form\Extension\Core\Type\Textarea):

    $builder->add('content', TextareaType::class, [
        'attr' => ['class' => 'bbcode-input'],
    ]);
    

    Validate output in the controller:

    $html = $parser->parse($request->request->get('content'));
    if ($parser->hasErrors()) {
        // Handle invalid BBCode (e.g., unclosed tags).
    }
    
  3. Twig Integration Use the parse_bbcode filter in templates:

    {{ user.signature|parse_bbcode }}
    

    Customize allowed tags via configuration (see below).

  4. Event-Driven Extensions Listen to bbcode.parse events to modify parsing behavior:

    $dispatcher->addListener('bbcode.parse', function (ParseEvent $event) {
        if ($event->getTag() === 'CUSTOM') {
            $event->setHtml('<div class="custom">...</div>');
        }
    });
    

Advanced Patterns

  1. Custom Tag Support Extend the parser to support custom BBCode tags (e.g., [QUOTE]):

    $parser->addTag('QUOTE', function (TagEvent $event) {
        return '<blockquote>' . $event->getContent() . '</blockquote>';
    });
    
  2. Nested Parsing Parse BBCode within existing HTML (e.g., <div>{{ parsedContent }}</div>):

    $dom = new \DOMDocument();
    $dom->loadHTML($htmlWithPlaceholders);
    $xpath = new \DOMXPath($dom);
    foreach ($xpath->query('//*[contains(@class, "bbcode-placeholder")]') as $node) {
        $node->nodeValue = $parser->parse($node->nodeValue);
    }
    
  3. Caching Parsed Output Cache parsed BBCode to HTML for performance:

    $cacheKey = md5($rawText);
    $html = $cache->get($cacheKey, function () use ($parser, $rawText) {
        return $parser->parse($rawText);
    });
    
  4. Validation & Sanitization Combine with Symfony’s security component to sanitize output:

    use Symfony\Component\Security\Core\Encoder\HtmlEncoder;
    
    $encoder = new HtmlEncoder();
    $safeHtml = $encoder->encode($parser->parse($rawText));
    

Gotchas and Tips

Common Pitfalls

  1. Deprecated Symfony Version

    • The bundle requires Symfony 2.4 and PHP 5.4, which are end-of-life. Use a modern alternative (e.g., bbcode-parser) for new projects.
    • Workaround: Fork the bundle and update dependencies if critical functionality is needed.
  2. Unclosed Tags

    • The parser may silently ignore malformed BBCode (e.g., [B] without [/B]).
    • Fix: Enable strict mode or validate input:
      $parser->setStrict(true); // Throws exceptions on errors.
      
  3. XSS Vulnerabilities

    • BBCode parsers are prone to XSS if not sanitized. Always escape output:
      $safeHtml = $this->get('twig')->getEnvironment()->getRuntime('Twig_Runtime')->escape(
          $parser->parse($rawText),
          'html'
      );
      
  4. Configuration Overrides

    • Default tags (e.g., [B]) may conflict with existing HTML. Override via config.yml:
      ccdn_component_bbcode:
          tags:
              B: '<strong>'
              I: '<em>'
      
  5. Performance with Large Text

    • Lexing/parsing long texts (e.g., 10K+ characters) can be slow. Optimize with:
      • Caching (see Advanced Patterns).
      • Pre-processing (e.g., strip unnecessary whitespace before parsing).

Debugging Tips

  1. Enable Verbose Logging Configure the bundle to log parsing events:

    ccdn_component_bbcode:
        debug: true
    

    Check logs for tokenization/parsing errors.

  2. Inspect Token Stream Dump tokens for debugging:

    $tokens = $parser->tokenize($rawText);
    var_dump($tokens);
    
  3. Test Edge Cases Validate against:

    • Nested tags: [B][I]text[/I][/B].
    • Self-closing tags: [IMG]url[/IMG].
    • Malformed input: [B]unclosed, [/B]extra[/B].

Extension Points

  1. Custom Lexer Replace the default lexer for custom syntax:

    $parser->setLexer(new MyCustomLexer());
    
  2. Tag Whitelisting Restrict allowed tags for security:

    $parser->setAllowedTags(['B', 'I', 'U']);
    
  3. Post-Processing Filters Apply filters after parsing (e.g., auto-link URLs):

    $html = $parser->parse($rawText);
    $html = preg_replace('/(https?:\/\/[^\s]+)/', '<a href="$1">$1</a>', $html);
    
  4. Symfony Event Dispatcher Integrate with Symfony’s event system for granular control:

    $dispatcher->addListener('bbcode.tag.B', function (TagEvent $event) {
        $event->setHtml('<span class="bold">' . $event->getContent() . '</span>');
    });
    

Pro Tips

  • Pair with Markdown: Use BBCode for simple formatting and Markdown for advanced features (e.g., via parsedown).
  • Localization: Extend the bundle to support RTL (right-to-left) languages by modifying the lexer’s direction handling.
  • API Integration: Expose parsing as a microservice (e.g., via API Platform) for decoupled processing.
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php