Completed
Branch wip/litedown (ab3410)
by Josh
31:08
created

Blocks::parse()   F

Complexity

Conditions 79
Paths > 20000

Size

Total Lines 399
Code Lines 184

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 245
CRAP Score 79

Importance

Changes 0
Metric Value
dl 0
loc 399
ccs 245
cts 245
cp 1
rs 2
c 0
b 0
f 0
cc 79
eloc 184
nc 78382081
nop 0
crap 79

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2017 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Plugins\Litedown\Parser\Passes;
9
10
use s9e\TextFormatter\Parser as Rules;
11
12
class Blocks extends AbstractPass
13
{
14
	/**
15
	* @var array
16
	*/
17 263
	protected setextLines = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
18
19 263
	/**
20
	* {@inheritdoc}
21 263
	*/
22 263
	public function parse()
23 263
	{
24 263
		$this->matchSetextLines();
25 263
26 263
		$codeFence    = null;
27 263
		$codeIndent   = 4;
28 263
		$codeTag      = null;
29 263
		$lineIsEmpty  = true;
30 263
		$lists        = [];
31
		$listsCnt     = 0;
32 263
		$newContext   = false;
33 263
		$quotes       = [];
34
		$quotesCnt    = 0;
35 263
		$textBoundary = 0;
36
37 263
		$regexp = '/^(?:(?=[-*+\\d \\t>`~#_])((?: {0,3}> ?)+)?([ \\t]+)?(\\* *\\* *\\*[* ]*$|- *- *-[- ]*$|_ *_ *_[_ ]*$|=+$)?((?:[-*+]|\\d+\\.)[ \\t]+(?=\\S))?[ \\t]*(#{1,6}[ \\t]+|```+[^`\\n]*$|~~~+[^~\\n]*$)?)?/m';
38 263
		preg_match_all($regexp, $this->text, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
39 263
40 263
		foreach ($matches as $m)
41
		{
42
			$matchPos   = $m[0][1];
43 263
			$matchLen   = strlen($m[0][0]);
44
			$ignoreLen  = 0;
45
			$quoteDepth = 0;
46 263
47 263
			// If the last line was empty then this is not a continuation, and vice-versa
48
			$continuation = !$lineIsEmpty;
49
50 263
			// Capture the position of the end of the line and determine whether the line is empty
51
			$lfPos       = $this->text->indexOf("\n", $matchPos);
52
			$lineIsEmpty = ($lfPos === $matchPos + $matchLen && empty($m[3][0]) && empty($m[4][0]) && empty($m[5][0]));
53 263
54 263
			// If the line is empty and it's the first empty line then we break current paragraph.
55 31
			$breakParagraph = ($lineIsEmpty && $continuation);
56 31
57 31
			// Count quote marks
58 31
			if (!empty($m[1][0]))
59 4
			{
60 4
				$quoteDepth = substr_count($m[1][0], '>');
61 4
				$ignoreLen  = strlen($m[1][0]);
62
				if (isset($codeTag) && $codeTag->hasAttribute('quoteDepth'))
63
				{
64 31
					$quoteDepth = min($quoteDepth, $codeTag->getAttribute('quoteDepth'));
65 31
					$ignoreLen  = $this->computeQuoteIgnoreLen($m[1][0], $quoteDepth);
66
				}
67
68 263
				// Overwrite quote markup
69 263
				$this->text->overwrite($matchPos, $ignoreLen);
70 30
			}
71
72
			// Close supernumerary quotes
73
			if ($quoteDepth < $quotesCnt && !$continuation)
74 30
			{
75 30
				$newContext = true;
76
77 30
				do
78 30
				{
79
					$this->parser->addEndTag('QUOTE', $textBoundary, 0)
80
					             ->pairWith(array_pop($quotes));
81 263
				}
82 263
				while ($quoteDepth < --$quotesCnt);
83 30
			}
84
85
			// Open new quotes
86
			if ($quoteDepth > $quotesCnt && !$lineIsEmpty)
87 30
			{
88 30
				$newContext = true;
89
90 30
				do
91 30
				{
92
					$tag = $this->parser->addStartTag('QUOTE', $matchPos, 0, $quotesCnt - 999);
93
					$quotes[] = $tag;
94 263
				}
95 263
				while ($quoteDepth > ++$quotesCnt);
96 263
			}
97 263
98 39
			// Compute the width of the indentation
99 39
			$indentWidth = 0;
100
			$indentPos   = 0;
101
			if (!empty($m[2][0]) && !$codeFence)
102 39
			{
103 39
				$indentStr = $m[2][0];
104 37
				$indentLen = strlen($indentStr);
105 37
				do
106
				{
107
					if ($indentStr[$indentPos] === ' ')
108 4
					{
109
						++$indentWidth;
110
					}
111 39
					else
112 39
					{
113
						$indentWidth = ($indentWidth + 4) & ~3;
114
					}
115 263
				}
116 263
				while (++$indentPos < $indentLen && $indentWidth < $codeIndent);
117 18
			}
118 18
119
			// Test whether we're out of a code block
120
			if (isset($codeTag) && !$codeFence && $indentWidth < $codeIndent && !$lineIsEmpty)
121 263
			{
122 45
				$newContext = true;
123
			}
124
125 45
			if ($newContext)
126 45
			{
127 18
				$newContext = false;
128 18
129
				// Close the code block if applicable
130 16
				if (isset($codeTag))
131
				{
132 16
					if ($textBoundary > $codeTag->getPos())
133 16
					{
134 16
						// Overwrite the whole block
135
						$this->text->overwrite($codeTag->getPos(), $textBoundary - $codeTag->getPos());
136
137
						$endTag = $this->parser->addEndTag('CODE', $textBoundary, 0, -1);
138 2
						$endTag->pairWith($codeTag);
139
					}
140
					else
141 18
					{
142 18
						// The code block is empty
143 18
						$codeTag->invalidate();
144
					}
145
146 45
					$codeTag = null;
147
					$codeFence = null;
148 2
				}
149 45
150 45
				// Close all the lists
151 45
				foreach ($lists as $list)
152
				{
153
					$this->closeList($list, $textBoundary);
154
				}
155 45
				$lists    = [];
156 45
				$listsCnt = 0;
157 45
158 45
				// Mark the block boundary
159
				if ($matchPos)
160 263
				{
161 263
					$this->text->markBoundary($matchPos - 1);
162 19
				}
163 19
			}
164
165 18
			if ($indentWidth >= $codeIndent)
166
			{
167 18
				if (isset($codeTag) || !$continuation)
168 18
				{
169
					// Adjust the amount of text being ignored
170 18
					$ignoreLen += $indentPos;
171 18
172
					if (!isset($codeTag))
173
					{
174 18
						// Create code block
175 18
						$codeTag = $this->parser->addStartTag('CODE', $matchPos + $ignoreLen, 0, -999);
176 19
					}
177
178
					// Clear the captures to prevent any further processing
179 263
					$m = [];
180
				}
181 263
			}
182 263
			else
183
			{
184 263
				$hasListItem = !empty($m[4][0]);
185 263
186 262
				if (!$indentWidth && !$continuation && !$hasListItem)
187
				{
188
					// Start of a new context
189 262
					$listIndex = -1;
190 262
				}
191 30
				elseif ($continuation && !$hasListItem)
192
				{
193
					// Continuation of current list item or paragraph
194
					$listIndex = $listsCnt - 1;
195
				}
196 30
				elseif (!$listsCnt)
197 30
				{
198
					// We're not inside of a list already, we can start one if there's a list item
199 27
					// and it's either not in continuation of a paragraph or immediately after a
200 27
					// block
201
					if ($hasListItem && (!$continuation || $this->text->charAt($matchPos - 1) === "\x17"))
202
					{
203
						// Start of a new list
204 4
						$listIndex = 0;
205
					}
206 30
					else
207
					{
208
						// We're in a normal paragraph
209
						$listIndex = -1;
210 20
					}
211 20
				}
212
				else
213 6
				{
214 6
					// We're inside of a list but we need to compute the depth
215
					$listIndex = 0;
216
					while ($listIndex < $listsCnt && $indentWidth > $lists[$listIndex]['maxIndent'])
217
					{
218 263
						++$listIndex;
219
					}
220 26
				}
221 26
222 26
				// Close deeper lists
223
				while ($listIndex < $listsCnt - 1)
224
				{
225
					$this->closeList(array_pop($lists), $textBoundary);
226 263
					--$listsCnt;
227 263
				}
228 1
229 1
				// If there's no list item at current index, we'll need to either create one or
230
				// drop down to previous index, in which case we have to adjust maxIndent
231 263
				if ($listIndex === $listsCnt && !$hasListItem)
232 263
				{
233 27
					--$listIndex;
234
				}
235
236 27
				if ($hasListItem && $listIndex >= 0)
237 27
				{
238
					$breakParagraph = true;
239
240 27
					// Compute the position and amount of text consumed by the item tag
241
					$tagPos = $matchPos + $ignoreLen + $indentPos;
242
					$tagLen = strlen($m[4][0]);
243 27
244
					// Create a LI tag that consumes its markup
245
					$itemTag = $this->parser->addStartTag('LI', $tagPos, $tagLen);
246
247
					// Overwrite the markup
248 27
					$this->text->overwrite($tagPos, $tagLen);
249 27
250 20
					// If the list index is within current lists count it means this is not a new
251 20
					// list and we have to close the last item. Otherwise, it's a new list that we
252
					// have to create
253
					if ($listIndex < $listsCnt)
254 20
					{
255 20
						$this->parser->addEndTag('LI', $textBoundary, 0)
256 20
						             ->pairWith($lists[$listIndex]['itemTag']);
257
258
						// Record the item in the list
259 27
						$lists[$listIndex]['itemTag']    = $itemTag;
260
						$lists[$listIndex]['itemTags'][] = $itemTag;
261
					}
262 27
					else
263 5
					{
264 5
						++$listsCnt;
265 5
266
						if ($listIndex)
267
						{
268 27
							$minIndent = $lists[$listIndex - 1]['maxIndent'] + 1;
269 27
							$maxIndent = max($minIndent, $listIndex * 4);
270
						}
271
						else
272
						{
273 27
							$minIndent = 0;
274
							$maxIndent = $indentWidth;
275
						}
276 27
277 27
						// Create a 0-width LIST tag right before the item tag LI
278 10
						$listTag = $this->parser->addStartTag('LIST', $tagPos, 0);
279
280 10
						// Test whether the list item ends with a dot, as in "1."
281 10
						if (strpos($m[4][0], '.') !== false)
282 10
						{
283 2
							$listTag->setAttribute('type', 'decimal');
284 2
285 10
							$start = (int) $m[4][0];
286
							if ($start !== 1)
287
							{
288 27
								$listTag->setAttribute('start', $start);
289 27
							}
290 27
						}
291 27
292 27
						// Record the new list depth
293 27
						$lists[] = [
294
							'listTag'   => $listTag,
295 27
							'itemTag'   => $itemTag,
296
							'itemTags'  => [$itemTag],
297 27
							'minIndent' => $minIndent,
298
							'maxIndent' => $maxIndent,
299
							'tight'     => true
300 263
						];
301 263
					}
302
				}
303 23
304 23
				// If we're in a list, on a non-empty line preceded with a blank line...
305
				if ($listsCnt && !$continuation && !$lineIsEmpty)
306 5
				{
307
					// ...and this is not the first item of the list...
308 5
					if (count($lists[0]['itemTags']) > 1 || !$hasListItem)
309 5
					{
310 5
						// ...every list that is currently open becomes loose
311 5
						foreach ($lists as &$list)
312 23
						{
313
							$list['tight'] = false;
314 263
						}
315
						unset($list);
316
					}
317 263
				}
318 263
319
				$codeIndent = ($listsCnt + 1) * 4;
320 36
			}
321 36
322 17
			if (isset($m[5]))
323 17
			{
324 17
				// Headers
325 17
				if ($m[5][0][0] === '#')
326
				{
327 17
					$startLen = strlen($m[5][0]);
328
					$startPos = $matchPos + $matchLen - $startLen;
329
					$endLen   = $this->getAtxHeaderEndTagLen($matchPos + $matchLen, $lfPos);
330 17
					$endPos   = $lfPos - $endLen;
331 17
332
					$this->parser->addTagPair('H' . strspn($m[5][0], '#', 0, 6), $startPos, $startLen, $endPos, $endLen);
333
334 17
					// Mark the start and the end of the header as boundaries
335 2
					$this->text->markBoundary($startPos);
336 2
					$this->text->markBoundary($lfPos);
337 17
338
					if ($continuation)
339 19
					{
340
						$breakParagraph = true;
341 19
					}
342 19
				}
343
				// Code fence
344 19
				elseif ($m[5][0][0] === '`' || $m[5][0][0] === '~')
345 19
				{
346 19
					$tagPos = $matchPos + $ignoreLen;
347 19
					$tagLen = $lfPos - $tagPos;
348
349 19
					if (isset($codeTag) && $m[5][0] === $codeFence)
350
					{
351
						$endTag = $this->parser->addEndTag('CODE', $tagPos, $tagLen, -1);
352 19
						$endTag->pairWith($codeTag);
353 19
354 19
						$this->parser->addIgnoreTag($textBoundary, $tagPos - $textBoundary);
355 19
356 19
						// Overwrite the whole block
357
						$this->text->overwrite($codeTag->getPos(), $tagPos + $tagLen - $codeTag->getPos());
358
						$codeTag = null;
359 19
						$codeFence = null;
360 19
					}
361 19
					elseif (!isset($codeTag))
362
					{
363
						// Create code block
364 19
						$codeTag   = $this->parser->addStartTag('CODE', $tagPos, $tagLen);
365
						$codeFence = substr($m[5][0], 0, strspn($m[5][0], '`~'));
366
						$codeTag->setAttribute('quoteDepth', $quoteDepth);
367 19
368 19
						// Ignore the next character, which should be a newline
369 19
						$this->parser->addIgnoreTag($tagPos + $tagLen, 1);
370 4
371 4
						// Add the language if present, e.g. ```php
372 19
						$lang = trim(trim($m[5][0], '`~'));
373 19
						if ($lang !== '')
374 36
						{
375 263
							$codeTag->setAttribute('lang', $lang);
376
						}
377
					}
378 9
				}
379 9
			}
380
			elseif (!empty($m[3][0]) && !$listsCnt && $this->text->charAt($matchPos + $matchLen) !== "\x17")
381
			{
382 9
				// Horizontal rule
383 9
				$this->parser->addSelfClosingTag('HR', $matchPos + $ignoreLen, $matchLen - $ignoreLen);
384 263
				$breakParagraph = true;
385
386
				// Mark the end of the line as a boundary
387 11
				$this->text->markBoundary($lfPos);
388 11
			}
389 11
			elseif (isset($this->setextLines[$lfPos]) && $this->setextLines[$lfPos]['quoteDepth'] === $quoteDepth && !$lineIsEmpty && !$listsCnt && !isset($codeTag))
390 11
			{
391 11
				// Setext-style header
392 11
				$this->parser->addTagPair(
393 11
					$this->setextLines[$lfPos]['tagName'],
394
					$matchPos + $ignoreLen,
395
					0,
396 11
					$this->setextLines[$lfPos]['endPos'],
397 11
					$this->setextLines[$lfPos]['endLen']
398
				);
399
400 263
				// Mark the end of the Setext line
401 262
				$this->text->markBoundary($this->setextLines[$lfPos]['endPos'] + $this->setextLines[$lfPos]['endLen']);
402 262
			}
403 262
404
			if ($breakParagraph)
405 263
			{
406 263
				$this->parser->addParagraphBreak($textBoundary);
407 263
				$this->text->markBoundary($textBoundary);
408 263
			}
409
410
			if (!$lineIsEmpty)
411 263
			{
412 45
				$textBoundary = $lfPos;
413 45
			}
414 263
415 263
			if ($ignoreLen)
416
			{
417
				$this->parser->addIgnoreTag($matchPos, $ignoreLen, 1000);
418
			}
419
		}
420
	}
421
422
	/**
423
	* Close a list at given offset
424 27
	*
425
	* @param  array   $list
426 27
	* @param  integer $textBoundary
427 27
	* @return void
428
	*/
429 27
	protected function closeList(array $list, $textBoundary)
430 27
	{
431 25
		$this->parser->addEndTag('LIST', $textBoundary, 0)->pairWith($list['listTag']);
432
		$this->parser->addEndTag('LI',   $textBoundary, 0)->pairWith($list['itemTag']);
433 25
434 25
		if ($list['tight'])
435 25
		{
436 27
			foreach ($list['itemTags'] as $itemTag)
437
			{
438
				$itemTag->removeFlags(Rules::RULE_CREATE_PARAGRAPHS);
439
			}
440
		}
441
	}
442
443
	/**
444
	* Compute the amount of text to ignore at the start of a quote line
445 4
	*
446
	* @param  string  $str           Original quote markup
447 4
	* @param  integer $maxQuoteDepth Maximum quote depth
448 4
	* @return integer                Number of characters to ignore
449
	*/
450 3
	protected function computeQuoteIgnoreLen($str, $maxQuoteDepth)
451 3
	{
452
		$remaining = $str;
453 4
		while (--$maxQuoteDepth >= 0)
454
		{
455
			$remaining = preg_replace('/^ *> ?/', '', $remaining);
456
		}
457
458
		return strlen($str) - strlen($remaining);
459
	}
460
461
	/**
462
	* Return the length of the markup at the end of an ATX header
463 17
	*
464
	* @param  integer $startPos Start of the header's text
465 17
	* @param  integer $endPos   End of the header's text
466 17
	* @return integer
467
	*/
468 17
	protected function getAtxHeaderEndTagLen($startPos, $endPos)
469
	{
470
		$content = substr($this->text, $startPos, $endPos - $startPos);
471
		preg_match('/[ \\t]*#*[ \\t]*$/', $content, $m);
472
473
		return strlen($m[0]);
474
	}
475
476 263
	/**
477
	* Capture and store lines that contain a Setext-tyle header
478 263
	*
479 263
	* @return void
480 263
	*/
481 231
	protected function matchSetextLines()
482
	{
483
		if ($this->text->indexOf('-') === false && $this->text->indexOf('=') === false)
484
		{
485
			return;
486 32
		}
487 32
488 32
		// Capture the any series of - or = alone on a line, optionally preceded with the
489 13
		// angle brackets notation used in blockquotes
490
		$regexp = '/^(?=[-=>])(?:> ?)*(?=[-=])(?:-+|=+) *$/m';
491
		if (!preg_match_all($regexp, $this->text, $matches, PREG_OFFSET_CAPTURE))
492 19
		{
493
			return;
494
		}
495
496 19
		foreach ($matches[0] as list($match, $matchPos))
497 19
		{
498
			// Compute the position of the end tag. We start on the LF character before the
499 5
			// match and keep rewinding until we find a non-space character
500 5
			$endPos = $matchPos - 1;
501
			while ($endPos > 0 && $this->text->charAt($endPos - 1) === ' ')
502
			{
503 19
				--$endPos;
504 19
			}
505 19
506 19
			// Store at the offset of the LF character
507 19
			$this->setextLines[$matchPos - 1] = [
508 19
				'endLen'     => $matchPos + strlen($match) - $endPos,
509 19
				'endPos'     => $endPos,
510 19
				'quoteDepth' => substr_count($match, '>'),
511
				'tagName'    => ($match[0] === '=') ? 'H1' : 'H2'
512
			];
513
		}
514
	}
515
}