Carew\Event\Listener\Body\Markdown::onDocument PHP Method

onDocument() public method

public onDocument ( CarewEvent $event )
$event Carew\Event\CarewEvent
    public function onDocument(CarewEvent $event)
    {
        $document = $event->getSubject();
        if (null === $document->getFile()) {
            return;
        }
        $extension = $document->getFile()->getExtension();
        if ('md' !== $extension) {
            if ('twig' !== $extension) {
                return;
            }
            $extension = pathinfo(str_replace('.twig', '', $document->getFilePath()), PATHINFO_EXTENSION);
            if ('md' !== $extension) {
                return;
            }
        }
        $twig = array();
        // hack to keep twig statements in local $twig variable because MD parser does not work with that
        $body = preg_replace_callback('/(?<twig>{{\\s*[^}}]*\\s*}})/', function ($matches) use(&$twig) {
            $twig[] = $matches['twig'];
            return 'http://%%%%%%%%%%%%%%%%%%%%';
        }, $document->getBody());
        $body = $this->markdownParser->text($body);
        $i = 0;
        $body = preg_replace_callback('/(http:\\/\\/%%%%%%%%%%%%%%%%%%%%)/', function ($matches) use(&$i, $twig) {
            return $twig[$i++];
        }, $body);
        $document->setBody($body);
    }

Usage Example

Example #1
0
 public function testParseTwigLink()
 {
     $document = $this->createDocument('simple.md.twig');
     $document->setBody('[homepage]({{ carew.relativeRoot }})');
     $event = new CarewEvent($document);
     $extraction = new Markdown();
     $extraction->onDocument($event);
     $this->assertSame('<p><a href="{{ carew.relativeRoot }}">homepage</a></p>', $document->getBody());
 }