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