Completed
Push — master ( d91fed...fd66aa )
by Josh
17:36
created

Blocks::parse()   F

Complexity

Conditions 77
Paths > 20000

Size

Total Lines 388

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 172
CRAP Score 77

Importance

Changes 0
Metric Value
dl 0
loc 388
rs 0
c 0
b 0
f 0
ccs 172
cts 172
cp 1
cc 77
nc 78382081
nop 0
crap 77

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