ApiMarkdown.php 6.08 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\apidoc\helpers;

10
use cebe\markdown\GithubMarkdown;
11 12 13 14
use phpDocumentor\Reflection\DocBlock\Type\Collection;
use yii\apidoc\models\MethodDoc;
use yii\apidoc\models\TypeDoc;
use yii\apidoc\templates\BaseRenderer;
15
use yii\helpers\Markdown;
16 17 18 19 20 21 22

/**
 * A Markdown helper with support for class reference links.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
23
class ApiMarkdown extends GithubMarkdown
24 25 26 27 28
{
	/**
	 * @var BaseRenderer
	 */
	public static $renderer;
29 30 31

	protected $context;

32 33 34 35 36 37 38 39
	public function prepare()
	{
		parent::prepare();

		// add references to guide pages
		$this->references = array_merge($this->references, static::$renderer->getGuideReferences());
	}

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	/**
	 * @inheritDoc
	 */
	protected function identifyLine($lines, $current)
	{
		if (strncmp($lines[$current], '~~~', 3) === 0) {
			return 'fencedCode';
		}
		return parent::identifyLine($lines, $current);
	}

	/**
	 * Consume lines for a fenced code block
	 */
	protected function consumeFencedCode($lines, $current)
	{
		// consume until ```
		$block = [
			'type' => 'code',
			'content' => [],
		];
		$line = rtrim($lines[$current]);
		if (strncmp($lines[$current], '~~~', 3) === 0) {
			$fence = '~~~';
			$language = 'php';
		} else {
			$fence = substr($line, 0, $pos = strrpos($line, '`') + 1);
			$language = substr($line, $pos);
		}
		if (!empty($language)) {
			$block['language'] = $language;
		}
		for($i = $current + 1, $count = count($lines); $i < $count; $i++) {
			if (rtrim($line = $lines[$i]) !== $fence) {
				$block['content'][] = $line;
			} else {
				break;
			}
		}
		return [$block, $i];
	}

82
	/**
83
	 * Renders a code block
84
	 */
85 86 87 88 89 90 91 92 93
	protected function renderCode($block)
	{
		if (isset($block['language'])) {
			$class = isset($block['language']) ? ' class="language-' . $block['language'] . '"' : '';
			return "<pre><code$class>" . $this->highlight(implode("\n", $block['content']) . "\n", $block['language']) . '</code></pre>';
		} else {
			return parent::renderCode($block);
		}
	}
94

95
	protected function highlight($code, $language)
96
	{
97 98 99 100
		if ($language !== 'php') {
			return htmlspecialchars($code, ENT_NOQUOTES, 'UTF-8');
		}

101
		// TODO improve code highlighting
102 103
		if (strncmp($code, '<?php', 5) === 0) {
			$text = highlight_string(trim($code), true);
104
		} else {
105
			$text = highlight_string("<?php ".trim($code), true);
Carsten Brandt committed
106
			$text = str_replace('&lt;?php', '', $text);
107 108 109
			if (($pos = strpos($text, '&nbsp;')) !== false) {
				$text = substr($text, 0, $pos) . substr($text, $pos + 6);
			}
110
		}
111 112
		// remove <code><span style="color: #000000">\n and </span>tags added by php
		$text = substr(trim($text), 36, -16);
113

114
		return $text;
115 116
	}

117
	protected function inlineMarkers()
118
	{
119 120 121 122
		return array_merge(parent::inlineMarkers(), [
			'[[' => 'parseApiLinks',
		]);
	}
123

124 125 126
	protected function parseApiLinks($text)
	{
		$context = $this->context;
127

128
		if (preg_match('/^\[\[([\w\d\\\\\(\):$]+)(\|[^\]]*)?\]\]/', $text, $matches)) {
129

130
			$offset = strlen($matches[0]);
131

132 133
			$object = $matches[1];
			$title = (empty($matches[2]) || $matches[2] == '|') ? null : substr($matches[2], 1);
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
			if (($pos = strpos($object, '::')) !== false) {
				$typeName = substr($object, 0, $pos);
				$subjectName = substr($object, $pos + 2);
				if ($context !== null) {
					// Collection resolves relative types
					$typeName = (new Collection([$typeName], $context->phpDocContext))->__toString();
				}
				$type = static::$renderer->context->getType($typeName);
				if ($type === null) {
					static::$renderer->context->errors[] = [
						'file' => ($context !== null) ? $context->sourceFile : null,
						'message' => 'broken link to ' . $typeName . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
					];
					return [
						'<span style="background: #f00;">' . $typeName . '::' . $subjectName . '</span>',
						$offset
					];
				} else {
					if (($subject = $type->findSubject($subjectName)) !== null) {
						if ($title === null) {
							$title = $type->name . '::' . $subject->name;
							if ($subject instanceof MethodDoc) {
								$title .= '()';
							}
						}
						return [
							static::$renderer->subjectLink($subject, $title),
							$offset
						];
					} else {
165 166
						static::$renderer->context->errors[] = [
							'file' => ($context !== null) ? $context->sourceFile : null,
167 168 169 170 171
							'message' => 'broken link to ' . $type->name . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
						];
						return [
							'<span style="background: #ff0;">' . $type->name . '</span><span style="background: #f00;">::' . $subjectName . '</span>',
							$offset
172 173 174
						];
					}
				}
175 176 177 178
			} elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) {
				return [
					static::$renderer->subjectLink($subject, $title),
					$offset
179 180
				];
			}
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
			if ($context !== null) {
				// Collection resolves relative types
				$object = (new Collection([$object], $context->phpDocContext))->__toString();
			}
			if (($type = static::$renderer->context->getType($object)) !== null) {
				return [
					static::$renderer->typeLink($type, $title),
					$offset
				];
			}
			static::$renderer->context->errors[] = [
				'file' => ($context !== null) ? $context->sourceFile : null,
				'message' => 'broken link to ' . $object . (($context !== null) ? ' in ' . $context->name : ''),
			];
			return [
				'<span style="background: #f00;">' . $object . '</span>',
				$offset
			];
		}
		return ['[[', 2];
201 202 203 204 205 206 207
	}

	/**
	 * Converts markdown into HTML
	 *
	 * @param string $content
	 * @param TypeDoc $context
208
	 * @param bool $paragraph
209 210
	 * @return string
	 */
211
	public static function process($content, $context = null, $paragraph = false)
212
	{
213 214
		if (!isset(Markdown::$flavors['api'])) {
			Markdown::$flavors['api'] = new static;
215 216 217 218 219
		}

		if (is_string($context)) {
			$context = static::$renderer->context->getType($context);
		}
220
		Markdown::$flavors['api']->context = $context;
221

222 223
		if ($paragraph) {
			return Markdown::processParagraph($content, 'api');
224
		} else {
225
			return Markdown::process($content, 'api');
226 227 228
		}
	}
}