Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@merk
Created March 1, 2012 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merk/1948617 to your computer and use it in GitHub Desktop.
Save merk/1948617 to your computer and use it in GitHub Desktop.
BBCode parser for FOSCommentBundle
<?php
namespace Test\CommentBundle\Markup;
use FOS\CommentBundle\Markup\ParserInterface;
use HTMLPurifier;
class BBCode implements ParserInterface
{
private $parser;
private $purifier;
public function __construct(HtmlPurifier $purifier)
{
$this->purifier = $purifier;
}
/**
* @return \StringParser_BBCode
*/
protected function getParser()
{
if (null === $this->parser) {
$parser = new \StringParser_BBCode();
$parser->setRootParagraphHandling(true);
/**
* Bold
*
* [b][/b] -> <b></b>
*/
$parser->addCode('b', 'simple_replace', null, array(
'start_tag' => '<b>',
'end_tag' => '</b>'
), 'inline', array('listitem', 'block', 'inline', 'link'), array());
/**
* Italics
*
* [i][/i] -> <i></i>
*/
$parser->addCode('i', 'simple_replace', null, array(
'start_tag' => '<i>',
'end_tag' => '</i>'
), 'inline', array('listitem', 'block', 'inline', 'link'), array());
$this->parser = $parser;
}
return $this->parser;
}
/**
* Takes a markup string and returns raw html.
*
* @param string $raw
*
* @return string
*/
public function parse($raw)
{
$raw = $this->purifier->purify($raw);
return $this->getParser()->parse($raw);
}
}
exercise_html_purifier:
bbcode:
HTML.Allowed: ''
fos_comment:
service:
markup: markup.bbcode
services:
markup.bbcode:
class: Test\CommentBundle\Markup\BBCode
arguments:
- @exercise_html_purifier.bbcode
<?php
namespace Test\CommentBundle\Markup;
use FOS\CommentBundle\Markup\ParserInterface;
use HTMLPurifier;
class BBCode implements ParserInterface
{
private $parser;
private $purifier;
public function __construct(HtmlPurifier $purifier)
{
$this->purifier = $purifier;
}
/**
* @return \StringParser_BBCode
*/
protected function getParser()
{
if (null === $this->parser) {
$parser = new \StringParser_BBCode();
$parser->setRootParagraphHandling(true);
/**
* Bold
*
* [b][/b] -> <b></b>
*/
$parser->addCode('b', 'simple_replace', null, array(
'start_tag' => '<b>',
'end_tag' => '</b>'
), 'inline', array('listitem', 'block', 'inline', 'link'), array());
/**
* Italics
*
* [i][/i] -> <i></i>
*/
$parser->addCode('i', 'simple_replace', null, array(
'start_tag' => '<i>',
'end_tag' => '</i>'
), 'inline', array('listitem', 'block', 'inline', 'link'), array());
$this->parser = $parser;
}
return $this->parser;
}
/**
* Takes a markup string and returns raw html.
*
* @param string $raw
*
* @return string
*/
public function parse($raw)
{
$raw = $this->purifier->purify($raw);
return $this->getParser()->parse($raw);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment