You are here

public function ReadmeHelpMarkdownConverter::highlightPhp in README Help 8

Highlights PHP file.

@todo add css & js files support.

Parameters

string $file: The absolute path to the file.

int $line_number: The line number to put in the middle of the snippet.

int $padding: The number of lines to add before and after the $line_number.

bool $markup: Whether to return the markup object instead of a string.

Return value

string|\Drupal\Component\Render\MarkupInterface A safe highlighted snippet.

See also

http://php.net/manual/en/function.highlight-file.php

http://php.net/manual/en/function.highlight-string.php

1 call to ReadmeHelpMarkdownConverter::highlightPhp()
ReadmeHelpMarkdownConverter::insertPhpSnippets in src/ReadmeHelpMarkdownConverter.php
Replaces PHP file tokens with a snippet from the file.

File

src/ReadmeHelpMarkdownConverter.php, line 285

Class

ReadmeHelpMarkdownConverter
Default implementation of the ReadmeHelpMarkdownConverter.

Namespace

Drupal\readmehelp

Code

public function highlightPhp($file, $line_number, $padding, $markup = FALSE) {
  if (!$file || !is_readable($file)) {
    return "<span class=\"readmehelp-error\">CAN'T BE READ:</span> {$file} LINE: {$line_number} PADD: {$padding}";
  }

  // An example how to change css on the highlighted code.
  ini_set('highlight.comment', '#CCCCCC; font-style: oblique; color: #a48bad;');
  $highlighted = highlight_file($file, TRUE);
  $padding = is_int($padding) && $padding > 0 ? $padding : 10;
  $valid = is_int($line_number) && $line_number > 0;
  $line_number = $valid ? $line_number : 0;
  if (!$valid) {
    $start = 0;
    $end = 10000;
  }
  else {
    $start = $line_number - $padding;
    $start = $start > 0 ? $start : 1;
    $end = $line_number + $padding;
  }
  $highlighted = preg_replace('{(^<code>)|(</code>$)}s', '', $highlighted);
  $source = explode('<br />', $highlighted);
  $count = count($source);
  $code_line = NULL;
  $number = $line = [];
  foreach ($source as $key => $value) {
    $code_line = $key + 1;
    if (empty($value)) {
      $value = "<span></span>";
    }
    if ($code_line >= $start && $code_line <= $end && $code_line < $count) {
      $number[$code_line] = "<span class=\"line-number\">{$code_line}</span>";
      $line[$code_line] = $value;
      if ($code_line == $line_number) {
        $line[$code_line] = "<strong style=\"background-color:yellow\">{$value}</strong>";
      }
    }
  }
  $numbers = implode('<br>', $number);
  $lines = implode('<br>', $line);
  $snippet = "<table class=\"highlighted-snippet\"><tr><td>{$numbers}</td><td>{$lines}</td></tr></table>";
  return $markup ? Markup::create($snippet) : $snippet;
}