FencedCodeTrait.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 ($line[0] === '`' && strncmp($line, '```', 3) === 0) ||
  22. ($line[0] === '~' && strncmp($line, '~~~', 3) === 0) ||
  23. (isset($line[3]) && (
  24. ($line[3] === '`' && strncmp(ltrim($line), '```', 3) === 0) ||
  25. ($line[3] === '~' && strncmp(ltrim($line), '~~~', 3) === 0)
  26. ));
  27. }
  28. /**
  29. * Consume lines for a fenced code block
  30. */
  31. protected function consumeFencedCode($lines, $current)
  32. {
  33. $line = ltrim($lines[$current]);
  34. $fence = substr($line, 0, $pos = strrpos($line, $line[0]) + 1);
  35. $language = rtrim(substr($line, $pos));
  36. // consume until end fence
  37. $content = [];
  38. for ($i = $current + 1, $count = count($lines); $i < $count; $i++) {
  39. if (($pos = strpos($line = $lines[$i], $fence)) === false || $pos > 3) {
  40. $content[] = $line;
  41. } else {
  42. break;
  43. }
  44. }
  45. $block = [
  46. 'code',
  47. 'content' => implode("\n", $content),
  48. ];
  49. if (!empty($language)) {
  50. $block['language'] = $language;
  51. }
  52. return [$block, $i];
  53. }
  54. }