codeconsortium/ccdn-component-bb-code-bundle
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(),
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]);
}
}
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).
Lexing & Parsing The bundle uses a two-step process:
[B] → OPEN_TAG with name="B").$parser = $this->get('bbcode.parser');
$html = $parser->parse($rawText);
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).
}
Twig Integration
Use the parse_bbcode filter in templates:
{{ user.signature|parse_bbcode }}
Customize allowed tags via configuration (see below).
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>');
}
});
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>';
});
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);
}
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);
});
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));
Deprecated Symfony Version
bbcode-parser) for new projects.Unclosed Tags
[B] without [/B]).$parser->setStrict(true); // Throws exceptions on errors.
XSS Vulnerabilities
$safeHtml = $this->get('twig')->getEnvironment()->getRuntime('Twig_Runtime')->escape(
$parser->parse($rawText),
'html'
);
Configuration Overrides
[B]) may conflict with existing HTML. Override via config.yml:
ccdn_component_bbcode:
tags:
B: '<strong>'
I: '<em>'
Performance with Large Text
Enable Verbose Logging Configure the bundle to log parsing events:
ccdn_component_bbcode:
debug: true
Check logs for tokenization/parsing errors.
Inspect Token Stream Dump tokens for debugging:
$tokens = $parser->tokenize($rawText);
var_dump($tokens);
Test Edge Cases Validate against:
[B][I]text[/I][/B].[IMG]url[/IMG].[B]unclosed, [/B]extra[/B].Custom Lexer Replace the default lexer for custom syntax:
$parser->setLexer(new MyCustomLexer());
Tag Whitelisting Restrict allowed tags for security:
$parser->setAllowedTags(['B', 'I', 'U']);
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);
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>');
});
parsedown).How can I help you explore Laravel packages today?