Class yii\apidoc\helpers\ApiMarkdown
| Inheritance | yii\apidoc\helpers\ApiMarkdown » cebe\markdown\GithubMarkdown |
|---|---|
| Uses Traits | yii\apidoc\helpers\ApiMarkdownTrait, yii\apidoc\helpers\MarkdownHighlightTrait |
| Available since extension's version | 2.0 |
| Source Code | https://github.com/yiisoft/yii2-apidoc/blob/master/helpers/ApiMarkdown.php |
A Markdown helper with support for class reference links.
Public Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $blockTranslations | array | Translation for guide block types | yii\apidoc\helpers\ApiMarkdown |
| $renderer | yii\apidoc\renderers\BaseRenderer|null | yii\apidoc\helpers\ApiMarkdown |
Protected Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $headings | array | yii\apidoc\helpers\ApiMarkdown | |
| $renderingContext | yii\apidoc\models\TypeDoc|null | yii\apidoc\helpers\ApiMarkdown |
Public Methods
| Method | Description | Defined By |
|---|---|---|
| getHeadings() | yii\apidoc\helpers\ApiMarkdown | |
| highlight() | Highlights code | yii\apidoc\helpers\MarkdownHighlightTrait |
| parse() | yii\apidoc\helpers\ApiMarkdown | |
| process() | Converts markdown into HTML | yii\apidoc\helpers\ApiMarkdown |
| renderTable() | Add bootstrap classes to tables. | yii\apidoc\helpers\ApiMarkdown |
Protected Methods
| Method | Description | Defined By |
|---|---|---|
| applyToc() | yii\apidoc\helpers\ApiMarkdown | |
| consumeQuote() | Consume lines for a blockquote element | yii\apidoc\helpers\ApiMarkdownTrait |
| parseApiLinkForContext() | Attempts to parse an API link for the given context. | yii\apidoc\helpers\ApiMarkdownTrait |
| parseApiLinks() | yii\apidoc\helpers\ApiMarkdownTrait | |
| prepare() | yii\apidoc\helpers\ApiMarkdown | |
| renderApiLink() | Renders API link | yii\apidoc\helpers\ApiMarkdownTrait |
| renderApiLinkText() | yii\apidoc\helpers\ApiMarkdownTrait | |
| renderBrokenApiLink() | Renders API link that is broken i.e. points nowhere | yii\apidoc\helpers\ApiMarkdownTrait |
| renderCode() | yii\apidoc\helpers\MarkdownHighlightTrait | |
| renderHeadline() | yii\apidoc\helpers\ApiMarkdown | |
| renderLink() | yii\apidoc\helpers\ApiMarkdown | |
| renderQuote() | Renders a blockquote | yii\apidoc\helpers\ApiMarkdownTrait |
| translateBlockType() | yii\apidoc\helpers\ApiMarkdown |
Constants
| Constant | Value | Description | Defined By |
|---|---|---|---|
| INLINE_TAG_LINK | 'link' | yii\apidoc\helpers\ApiMarkdown | |
| INLINE_TAG_SEE | 'see' | yii\apidoc\helpers\ApiMarkdown | |
| PHP_FUNCTION_BASE_URL | 'https://www.php.net/manual/en/function.' | yii\apidoc\helpers\ApiMarkdown |
Property Details
Translation for guide block types
Method Details
| protected mixed applyToc ( mixed $content ) | ||
| $content | mixed | |
protected function applyToc($content)
{
// generate TOC if there is more than one headline
if (!empty($this->headings) && count($this->headings) > 1) {
$toc = [];
foreach ($this->headings as $heading) {
$toc[] = '<li>' . Html::a(strip_tags((string) $heading['title']), '#' . $heading['id']) . '</li>';
}
$toc = '<div class="toc"><ol>' . implode("\n", $toc) . "</ol></div>\n";
$needle = '</h1>';
$pos = strpos((string) $content, $needle);
if ($pos !== false) {
$content = substr_replace($content, "$needle\n$toc", $pos, strlen($needle));
} else {
$content = $toc . $content;
}
}
return $content;
}
Defined in: yii\apidoc\helpers\ApiMarkdownTrait::consumeQuote()
Consume lines for a blockquote element
| protected mixed consumeQuote ( mixed $lines, mixed $current ) | ||
| $lines | mixed | |
| $current | mixed | |
protected function consumeQuote($lines, $current)
{
$block = parent::consumeQuote($lines, $current);
$blockTypes = [
'warning',
'note',
'info',
'tip',
];
// check whether this is a special Info, Note, Warning, Tip block
$content = $block[0]['content'];
$first = reset($content);
if (isset($first[0]) && $first[0] === 'paragraph') {
$parfirst = reset($first['content']);
if (isset($parfirst[0]) && $parfirst[0] === 'text') {
foreach ($blockTypes as $type) {
if (strncasecmp("$type: ", (string) $parfirst[1], $len = strlen($type) + 2) === 0) {
// remove block indicator
$block[0]['content'][0]['content'][0][1] = substr((string) $parfirst[1], $len);
// add translated block indicator as bold text
array_unshift($block[0]['content'][0]['content'], [
'strong',
[
['text', $this->translateBlockType($type)],
],
]);
$block[0]['blocktype'] = $type;
break;
}
}
}
}
return $block;
}
| public array getHeadings ( ) | ||
| return | array |
The headlines of this document |
|---|---|---|
public function getHeadings()
{
return $this->headings;
}
Defined in: yii\apidoc\helpers\MarkdownHighlightTrait::highlight()
Highlights code
| public static string highlight ( string $code, string $language ) | ||
| $code | string |
Code to highlight |
| $language | string |
Language of the code to highlight |
| return | string |
HTML of highlighted code |
|---|---|---|
public static function highlight($code, $language)
{
if ($language !== 'php') {
return htmlspecialchars($code, ENT_NOQUOTES | ENT_SUBSTITUTE);
}
if (str_starts_with($code, '<?php')) {
$text = @highlight_string(trim($code), true);
} else {
$text = highlight_string('<?php ' . trim($code), true);
$text = str_replace('<?php', '', $text);
if (($pos = strpos($text, ' ')) !== false) {
$text = substr($text, 0, $pos) . substr($text, $pos + 6);
}
}
// Remove prefixes and suffixes added by php
if (PHP_VERSION_ID >= 80300) {
// The `highlight_string` result format has changed since PHP8.3
$text = substr($text, 34, -13);
} else {
$text = substr($text, 36, -16);
}
return $text;
}
| public mixed parse ( mixed $text ) | ||
| $text | mixed | |
public function parse($text)
{
$markup = parent::parse($text);
$markup = $this->applyToc($markup);
return $markup;
}
Defined in: yii\apidoc\helpers\ApiMarkdownTrait::parseApiLinkForContext()
Attempts to parse an API link for the given context.
| protected array parseApiLinkForContext ( integer $offset, string $object, string|null $title, yii\apidoc\models\TypeDoc|null $context ) | ||
| $offset | integer | |
| $object | string | |
| $title | string|null | |
| $context | yii\apidoc\models\TypeDoc|null | |
| throws | yii\apidoc\helpers\BrokenLinkException |
if the object can't be resolved |
|---|---|---|
protected function parseApiLinkForContext($offset, $object, $title, $context)
{
if (($pos = strpos($object, '::')) !== false) {
$typeName = substr($object, 0, $pos);
$subjectName = substr($object, $pos + 2);
if ($context !== null) {
if (!$context->phpDocContext) {
throw new BrokenLinkException($object, $context);
}
if (isset($context->phpDocContext->getNamespaceAliases()[$typeName])) {
$typeName = $context->phpDocContext->getNamespaceAliases()[$typeName];
} else {
$typeName = $context->phpDocContext->getNamespace() . '\\' . $typeName;
}
}
/** @var TypeDoc|null $type */
$type = static::$renderer->apiContext->getType($typeName);
if ($type === null || $subjectName === '') {
throw new BrokenLinkException($typeName . '::' . $subjectName, $context);
}
if (($subject = $type->findSubject($subjectName)) === null) {
throw new BrokenLinkException($type->name . '::' . $subjectName, $context);
}
if ($title === null) {
$title = $type->name . '::' . $subject->name;
if ($subject instanceof MethodDoc) {
$title .= '()';
}
}
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset,
];
}
if ($context !== null) {
if (($subject = $context->findSubject($object)) !== null) {
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset,
];
}
if (!$context->phpDocContext) {
throw new BrokenLinkException($object, $context);
}
if (isset($context->phpDocContext->getNamespaceAliases()[$object])) {
$object = $context->phpDocContext->getNamespaceAliases()[$object];
} else {
$object = $context->phpDocContext->getNamespace() . '\\' . $object;
}
}
if (($type = static::$renderer->apiContext->getType($object)) !== null) {
return [
['apiLink', static::$renderer->createTypeLink($type, null, $title)],
$offset,
];
}
if (str_contains((string) $typeLink = static::$renderer->createTypeLink($object, null, $title), '<a href')) {
return [
['apiLink', $typeLink],
$offset,
];
}
throw new BrokenLinkException($object, $context);
}
| protected mixed parseApiLinks ( mixed $text ) | ||
| $text | mixed | |
protected function parseApiLinks($text)
{
if (!preg_match('/^\[\[([\w\d\\\\():$]+)(\|[^]]*)?]]/', (string) $text, $matches)) {
return [['text', '[['], 2];
}
$offset = strlen($matches[0]);
$object = $matches[1];
$title = (empty($matches[2]) || $matches[2] === '|') ? null : substr($matches[2], 1);
$title = $this->renderApiLinkText($title);
$contexts = [];
$this->findContexts($this->renderingContext, $contexts);
$contexts = array_unique($contexts, SORT_REGULAR);
$contexts[] = null;
$exceptions = [];
foreach ($contexts as $context) {
try {
return $this->parseApiLinkForContext($offset, $object, $title, $context);
} catch (BrokenLinkException $e) {
$exceptions[] = $e;
}
}
$lastException = $exceptions[array_key_last($exceptions)];
static::$renderer->apiContext->errors[] = [
'file' => $lastException->context !== null ? $lastException->context->sourceFile : null,
'message' => $lastException->getMessage(),
];
return [
['brokenApiLink', '<span class="broken-link">' . $object . '</span>'],
$offset,
];
}
| protected mixed prepare ( ) |
protected function prepare()
{
parent::prepare();
$this->headings = [];
}
Converts markdown into HTML
| public static string process ( ?string $content, yii\apidoc\models\TypeDoc|string|null $context = null, boolean $paragraph = false ) | ||
| $content | ?string | |
| $context | yii\apidoc\models\TypeDoc|string|null | |
| $paragraph | boolean | |
public static function process(?string $content, $context = null, bool $paragraph = false): string
{
if (!$content) {
return '';
}
if (!isset(Markdown::$flavors['api'])) {
Markdown::$flavors['api'] = new static();
}
if (is_string($context)) {
$context = static::$renderer->apiContext->getType($context);
}
Markdown::$flavors['api']->renderingContext = $context;
$result = self::processInlineTags($context, $content, self::INLINE_TAG_LINK);
$result = self::processInlineTags($context, $result, self::INLINE_TAG_SEE);
return $paragraph ? Markdown::processParagraph($result, 'api') : Markdown::process($result, 'api');
}
Defined in: yii\apidoc\helpers\ApiMarkdownTrait::renderApiLink()
Renders API link
| protected string renderApiLink ( array $block ) | ||
| $block | array | |
protected function renderApiLink($block)
{
return $block[1];
}
| protected null|string renderApiLinkText ( null|string $title ) | ||
| $title | null|string | |
protected function renderApiLinkText($title)
{
if (!$title) {
return $title;
}
$title = Markdown::process($title);
$title = EncodingHelper::convertToUtf8WithHtmlEntities($title);
$doc = new DOMDocument();
$doc->loadHTML($title);
return $doc->getElementsByTagName('p')[0]->childNodes[0]->c14n();
}
Defined in: yii\apidoc\helpers\ApiMarkdownTrait::renderBrokenApiLink()
Renders API link that is broken i.e. points nowhere
| protected string renderBrokenApiLink ( array $block ) | ||
| $block | array | |
protected function renderBrokenApiLink($block)
{
return $block[1];
}
| protected renderCode ( mixed $block ) | ||
| $block | mixed | |
protected function renderCode($block)
{
if (self::$_highlighter === null) {
self::$_highlighter = new Highlighter();
self::$_highlighter->setAutodetectLanguages([
'apache', 'nginx',
'bash', 'dockerfile', 'http',
'css', 'less', 'scss',
'javascript', 'json', 'markdown',
'php', 'sql', 'twig', 'xml',
]);
}
try {
if (isset($block['language'])) {
if ($block['language'] === 'php' && str_contains((string) $block['content'], '<?=')) {
$block['language'] = 'html';
}
$result = self::$_highlighter->highlight($block['language'], $block['content'] . "\n");
return "<pre><code class=\"hljs {$result->language} language-{$block['language']}\">{$result->value}</code></pre>\n";
} else {
$result = self::$_highlighter->highlightAuto($block['content'] . "\n");
return "<pre><code class=\"hljs {$result->language}\">{$result->value}</code></pre>\n";
}
} catch (DomainException) {
return parent::renderCode($block);
}
}
| protected mixed renderHeadline ( mixed $block ) | ||
| $block | mixed | |
protected function renderHeadline($block)
{
$content = $this->renderAbsy($block['content']);
if (preg_match('~<span id="(.*?)"></span>~', (string) $content, $matches)) {
$hash = $matches[1];
$content = preg_replace('~<span id=".*?"></span>~', '', (string) $content);
} else {
$hash = Inflector::slug(strip_tags((string) $content));
}
$hashLink = "<span id=\"$hash\"></span><a href=\"#$hash\" class=\"hashlink\">¶</a>";
if ($block['level'] == 2) {
$this->headings[] = [
'title' => trim((string) $content),
'id' => $hash,
];
} elseif ($block['level'] > 2) {
if (end($this->headings)) {
$this->headings[key($this->headings)]['sub'][] = [
'title' => trim((string) $content),
'id' => $hash,
];
}
}
$tag = 'h' . $block['level'];
return "<$tag>$content $hashLink</$tag>";
}
| protected renderLink ( mixed $block ) | ||
| $block | mixed | |
protected function renderLink($block)
{
$url = $block['url'];
if (!$url) {
static::$renderer->apiContext->errors[] = [
'line' => null,
'file' => null,
'message' => 'Using empty link.',
];
return parent::renderLink($block);
}
$linkHtml = parent::renderLink($block);
// add special syntax for linking to the guide
$guideLinkHtml = preg_replace_callback(
'/href="guide:([A-z0-9-.#]+)"/i',
fn($matches) => 'href="' . static::$renderer->generateGuideUrl($matches[1]) . '"',
(string) $linkHtml,
1
);
if ($guideLinkHtml !== $linkHtml) {
return $guideLinkHtml;
}
if (!property_exists(static::$renderer, 'repoUrl')) {
return $linkHtml;
}
$repoUrl = static::$renderer->repoUrl;
if (!$repoUrl) {
if (Url::isRelative($url)) {
static::$renderer->apiContext->errors[] = [
'line' => null,
'file' => null,
'message' => "Using relative link ($url) but repoUrl is not set.",
];
}
return $linkHtml;
}
return preg_replace_callback('/href="(.+)"/i', fn($matches) => 'href="' . $repoUrl . '/' . $matches[1] . '"', (string) $linkHtml, 1);
}
Defined in: yii\apidoc\helpers\ApiMarkdownTrait::renderQuote()
Renders a blockquote
| protected mixed renderQuote ( mixed $block ) | ||
| $block | mixed | |
protected function renderQuote($block)
{
$class = '';
if (isset($block['blocktype'])) {
$class = ' class="' . $block['blocktype'] . '"';
}
return "<blockquote{$class}>" . $this->renderAbsy($block['content']) . "</blockquote>\n";
}
Add bootstrap classes to tables.
| public renderTable ( mixed $block ) | ||
| $block | mixed | |
public function renderTable($block)
{
return str_replace('<table>', '<table class="table table-bordered table-striped">', parent::renderTable($block));
}
| protected translateBlockType ( mixed $type ) | ||
| $type | mixed | |
protected function translateBlockType($type)
{
$key = ucfirst((string) $type) . ':';
if (isset(static::$blockTranslations[$key])) {
$translation = static::$blockTranslations[$key];
} else {
$translation = $key;
}
return "$translation ";
}