1<?php 2 3/* 4 * This file is part of the clockoon/dokuwiki-commonmark-plugin package. 5 * 6 * (c) Sungbin Jeon <clockoon@gmail.com> 7 * 8 * Original code based on the followings: 9 * - CommonMark JS reference parser (https://bitly.com/commonmark-js) (c) John MacFarlane 10 * - league/commonmark (https://github.com/thephpleague/commonmark) (c) Colin O'Dell <colinodell@gmail.com> 11 * 12 * For the full copyright and license information, please view the LICENSE 13 * file that was distributed with this source code. 14 */ 15 16namespace Dokuwiki\Plugin\Commonmark; 17 18use League\CommonMark\Node\Block\AbstractBlock; 19use League\CommonMark\Renderer\NodeRendererInterface; 20use League\CommonMark\Node\Inline\AbstractInline; 21use League\CommonMark\Renderer\ChildNodeRendererInterface; 22use League\CommonMark\Environment\EnvironmentInterface; 23use League\CommonMark\Node\Block\Document; 24use League\CommonMark\Node\Node; 25 26/** 27 * Renders a parsed AST to DW 28 */ 29final class DWRenderer implements ChildNodeRendererInterface 30{ 31 /** 32 * @var EnvironmentInterface 33 */ 34 protected $environment; 35 36 /** 37 * @param EnvironmentInterface $environment 38 */ 39 public function __construct(EnvironmentInterface $environment) 40 { 41 $this->environment = $environment; 42 } 43 44 public function getBlockSeparator(): string 45 { 46 return $this->environment->getConfiguration()->get('renderer/block_separator'); 47 } 48 49 public function getInnerSeparator(): string 50 { 51 return $this->environment->getConfiguration()->get('renderer/inner_separator'); 52 } 53 54 /** 55 * @param string $option 56 * @param mixed $default 57 * 58 * @return mixed|null 59 */ 60 public function getOption(string $option, bool $getCommonmarkOption = false) 61 { 62 if ($getCommonmarkOption) { 63 return $this->environment->getConfiguration()->get('commonmark/' . $option); 64 } 65 return $this->environment->getConfiguration()->get('renderer/' . $option); 66 // Note: function 'get' does not have a parameter 'default' any more, so I removed it. 67 } 68 69 public function renderNodes(iterable $nodes): string 70 { 71 $output = ''; 72 73 $isFirstItem = true; 74 75 foreach ($nodes as $node) { 76 if (! $isFirstItem && $node instanceof AbstractBlock) { 77 $output .= $this->getBlockSeparator(); 78 } 79 80 $output .= $this->renderNode($node); 81 82 $isFirstItem = false; 83 } 84 85 return $output; 86 } 87 88 public function renderNode(Node $node) 89 { 90 $renderers = $this->environment->getRenderersForClass(\get_class($node)); 91 92 foreach ($renderers as $renderer) { 93 \assert($renderer instanceof NodeRendererInterface); 94 if (($result = $renderer->render($node, $this)) !== null) { 95 return $result; 96 } 97 } 98 99 throw new \RuntimeException('Unable to find corresponding renderer for node type ' . \get_class($node)); 100 101 } 102 103 104}