1 | <?php |
||
21 | class TableParser extends AbstractBlockParser |
||
22 | { |
||
23 | const REGEXP_DEFINITION = '/(?: *(:?) *-+ *(:?) *)+(?=\||$)/'; |
||
24 | const REGEXP_CELLS = '/(?:`[^`]*`|\\\\\||\\\\|[^|`\\\\]+)+(?=\||$)/'; |
||
25 | const REGEXP_CAPTION = '/^\[(.+?)\](?:\[(.+)\])?\s*$/'; |
||
26 | |||
27 | 17 | public function parse(ContextInterface $context, Cursor $cursor) |
|
28 | { |
||
29 | 17 | $container = $context->getContainer(); |
|
30 | |||
31 | 17 | if (!$container instanceof Paragraph) { |
|
32 | 17 | return false; |
|
33 | } |
||
34 | |||
35 | 17 | $lines = $container->getStrings(); |
|
36 | 17 | if (count($lines) < 1) { |
|
37 | return false; |
||
38 | } |
||
39 | |||
40 | 17 | $expressionOffset = $cursor->getNextNonSpacePosition(); |
|
41 | |||
42 | 17 | $match = RegexHelper::matchAll(self::REGEXP_DEFINITION, $cursor->getLine(), $expressionOffset); |
|
43 | 17 | if (null === $match) { |
|
44 | 2 | return false; |
|
45 | } |
||
46 | |||
47 | 17 | $columns = $this->parseColumns($match); |
|
48 | 17 | $head = $this->parseRow(trim(array_pop($lines)), $columns, TableCell::TYPE_HEAD); |
|
49 | 17 | if (null === $head) { |
|
50 | return false; |
||
51 | } |
||
52 | |||
53 | 17 | $table = new Table(function (Cursor $cursor) use (&$table, $columns) { |
|
54 | 17 | $row = $this->parseRow($cursor->getLine(), $columns); |
|
55 | 17 | if (null === $row) { |
|
56 | 6 | if (null !== $table->getCaption()) { |
|
57 | 2 | return false; |
|
58 | } |
||
59 | |||
60 | 6 | if (null !== ($caption = $this->parseCaption($cursor->getLine()))) { |
|
61 | 2 | $table->setCaption($caption); |
|
62 | |||
63 | 2 | return true; |
|
64 | } |
||
65 | |||
66 | 4 | return false; |
|
67 | } |
||
68 | |||
69 | 17 | $table->getBody()->appendChild($row); |
|
70 | |||
71 | 17 | return true; |
|
72 | 17 | }); |
|
73 | |||
74 | 17 | $table->getHead()->appendChild($head); |
|
75 | |||
76 | 17 | if (count($lines) >= 1) { |
|
77 | 2 | $paragraph = new Paragraph(); |
|
78 | 2 | foreach ($lines as $line) { |
|
79 | 2 | $paragraph->addLine($line); |
|
80 | } |
||
81 | |||
82 | 2 | $context->replaceContainerBlock($paragraph); |
|
83 | 2 | $context->addBlock($table); |
|
84 | } else { |
||
85 | 16 | $context->replaceContainerBlock($table); |
|
86 | } |
||
87 | |||
88 | 17 | return true; |
|
89 | } |
||
90 | |||
91 | 17 | private function parseColumns(array $match) |
|
108 | |||
109 | 17 | private function parseRow($line, array $columns, $type = TableCell::TYPE_BODY) |
|
133 | |||
134 | 6 | private function parseCaption($line) |
|
144 | } |
||
145 |