Trait yii\apidoc\helpers\MarkdownHighlightTrait

Implemented byyii\apidoc\helpers\ApiMarkdown
Available since version2.1.1
Source Code https://github.com/yiisoft/yii2-apidoc/blob/master/helpers/MarkdownHighlightTrait.php

MarkdownHighlightTrait provides code highlighting functionality for Markdown Parsers.

Public Methods

Hide inherited methods

Method Description Defined By
highlight() Highlights code yii\apidoc\helpers\MarkdownHighlightTrait

Protected Methods

Hide inherited methods

Method Description Defined By
renderCode() yii\apidoc\helpers\MarkdownHighlightTrait

Method Details

Hide inherited methods

highlight() public static method

Highlights code

public static string highlight ( $code, $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 (strncmp($code, '<?php', 5) === 0) {
        $text = @highlight_string(trim($code), true);
    } else {
        $text = highlight_string("<?php " . trim($code), true);
        $text = str_replace('&lt;?php', '', $text);
        if (($pos = strpos($text, '&nbsp;')) !== false) {
            $text = substr($text, 0, $pos) . substr($text, $pos + 6);
        }
    }
    // remove <code><span style="color: #000000">\n and </span>tags added by php
    $text = substr(trim($text), 36, -16);
    return $text;
}

            
renderCode() protected method

protected void renderCode ( $block )
$block

                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' && strpos($block['content'], '<?=') !== false) {
                $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 $e) {
        return parent::renderCode($block);
    }
}