55 lines
1.2KB

  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 fenced code blocks
  10. *
  11. * automatically included 4 space indented code blocks
  12. */
  13. trait FencedCodeTrait
  14. {
  15. use CodeTrait;
  16. /**
  17. * identify a line as the beginning of a fenced code block.
  18. */
  19. protected function identifyFencedCode($line)
  20. {
  21. return ($l = $line[0]) === '`' && strncmp($line, '```', 3) === 0 ||
  22. $l === '~' && strncmp($line, '~~~', 3) === 0;
  23. }
  24. /**
  25. * Consume lines for a fenced code block
  26. */
  27. protected function consumeFencedCode($lines, $current)
  28. {
  29. // consume until ```
  30. $line = rtrim($lines[$current]);
  31. $fence = substr($line, 0, $pos = strrpos($line, $line[0]) + 1);
  32. $language = substr($line, $pos);
  33. $content = [];
  34. for ($i = $current + 1, $count = count($lines); $i < $count; $i++) {
  35. if (rtrim($line = $lines[$i]) !== $fence) {
  36. $content[] = $line;
  37. } else {
  38. break;
  39. }
  40. }
  41. $block = [
  42. 'code',
  43. 'content' => implode("\n", $content),
  44. ];
  45. if (!empty($language)) {
  46. $block['language'] = $language;
  47. }
  48. return [$block, $i];
  49. }
  50. }