You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.5KB

  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 headline blocks
  10. */
  11. trait HeadlineTrait
  12. {
  13. /**
  14. * identify a line as a headline
  15. */
  16. protected function identifyHeadline($line, $lines, $current)
  17. {
  18. return (
  19. // heading with #
  20. $line[0] === '#'
  21. ||
  22. // underlined headline
  23. !empty($lines[$current + 1]) &&
  24. (($l = $lines[$current + 1][0]) === '=' || $l === '-') &&
  25. preg_match('/^(\-+|=+)\s*$/', $lines[$current + 1])
  26. );
  27. }
  28. /**
  29. * Consume lines for a headline
  30. */
  31. protected function consumeHeadline($lines, $current)
  32. {
  33. if ($lines[$current][0] === '#') {
  34. // ATX headline
  35. $level = 1;
  36. while (isset($lines[$current][$level]) && $lines[$current][$level] === '#' && $level < 6) {
  37. $level++;
  38. }
  39. $block = [
  40. 'headline',
  41. 'content' => $this->parseInline(trim($lines[$current], "# \t")),
  42. 'level' => $level,
  43. ];
  44. return [$block, $current];
  45. } else {
  46. // underlined headline
  47. $block = [
  48. 'headline',
  49. 'content' => $this->parseInline($lines[$current]),
  50. 'level' => $lines[$current + 1][0] === '=' ? 1 : 2,
  51. ];
  52. return [$block, $current + 1];
  53. }
  54. }
  55. /**
  56. * Renders a headline
  57. */
  58. protected function renderHeadline($block)
  59. {
  60. $tag = 'h' . $block['level'];
  61. return "<$tag>" . $this->renderAbsy($block['content']) . "</$tag>\n";
  62. }
  63. abstract protected function parseInline($text);
  64. abstract protected function renderAbsy($absy);
  65. }