ApiMarkdown.php 6.42 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\Inflector;
16
use yii\helpers\Markdown;
17 18 19 20 21 22 23

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

	protected $context;

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

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

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 82
	/**
	 * @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];
	}

83
	/**
84
	 * Renders a code block
85
	 */
86 87 88 89 90 91 92 93 94
	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);
		}
	}
95

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

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

115
		return $text;
116 117
	}

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

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

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

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

133 134
			$object = $matches[1];
			$title = (empty($matches[2]) || $matches[2] == '|') ? null : substr($matches[2], 1);
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 165
			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 {
166 167
						static::$renderer->context->errors[] = [
							'file' => ($context !== null) ? $context->sourceFile : null,
168 169 170 171 172
							'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
173 174 175
						];
					}
				}
176 177 178 179
			} elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) {
				return [
					static::$renderer->subjectLink($subject, $title),
					$offset
180 181
				];
			}
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
			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];
202 203
	}

204 205 206 207 208 209 210 211 212 213 214 215
	/**
	 * @inheritDocs
	 */
	protected function renderHeadline($block)
	{
		$content = $this->parseInline($block['content']);
		$hash = Inflector::slug(strip_tags($content));
		$hashLink = "<a href=\"#$hash\" name=\"$hash\">&para;</a>";
		$tag = 'h' . $block['level'];
		return "<$tag>$content $hashLink</$tag>";
	}

216 217 218 219 220
	/**
	 * Converts markdown into HTML
	 *
	 * @param string $content
	 * @param TypeDoc $context
221
	 * @param bool $paragraph
222 223
	 * @return string
	 */
224
	public static function process($content, $context = null, $paragraph = false)
225
	{
226 227
		if (!isset(Markdown::$flavors['api'])) {
			Markdown::$flavors['api'] = new static;
228 229 230 231 232
		}

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

235 236
		if ($paragraph) {
			return Markdown::processParagraph($content, 'api');
237
		} else {
238
			return Markdown::process($content, 'api');
239 240 241
		}
	}
}