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