Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

CodeTrait.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2014 Carsten Brandt
  4. * @license https://github.com/cebe/markdown/blob/master/LICENSE
  5. * @link https://github.com/cebe/markdown#readme
  6. */
  7. namespace cebe\markdown\block;
  8. /**
  9. * Adds the 4 space indented code blocks
  10. */
  11. trait CodeTrait
  12. {
  13. /**
  14. * identify a line as the beginning of a code block.
  15. */
  16. protected function identifyCode($line)
  17. {
  18. // indentation >= 4 or one tab is code
  19. return ($l = $line[0]) === ' ' && $line[1] === ' ' && $line[2] === ' ' && $line[3] === ' ' || $l === "\t";
  20. }
  21. /**
  22. * Consume lines for a code block element
  23. */
  24. protected function consumeCode($lines, $current)
  25. {
  26. // consume until newline
  27. $content = [];
  28. for ($i = $current, $count = count($lines); $i < $count; $i++) {
  29. $line = $lines[$i];
  30. // a line is considered to belong to this code block as long as it is intended by 4 spaces or a tab
  31. if (isset($line[0]) && ($line[0] === "\t" || strncmp($line, ' ', 4) === 0)) {
  32. $line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
  33. $content[] = $line;
  34. // but also if it is empty and the next line is intended by 4 spaces or a tab
  35. } elseif (($line === '' || rtrim($line) === '') && isset($lines[$i + 1][0]) &&
  36. ($lines[$i + 1][0] === "\t" || strncmp($lines[$i + 1], ' ', 4) === 0)) {
  37. if ($line !== '') {
  38. $line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
  39. }
  40. $content[] = $line;
  41. } else {
  42. break;
  43. }
  44. }
  45. $block = [
  46. 'code',
  47. 'content' => implode("\n", $content),
  48. ];
  49. return [$block, --$i];
  50. }
  51. /**
  52. * Renders a code block
  53. */
  54. protected function renderCode($block)
  55. {
  56. $class = isset($block['language']) ? ' class="language-' . $block['language'] . '"' : '';
  57. return "<pre><code$class>" . htmlspecialchars($block['content'] . "\n", ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</code></pre>\n";
  58. }
  59. }