Completed
Branch 2.5/TaskLists (9a2343)
by Josh
03:17
created

Helper::getStats()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php declare(strict_types=1);
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2020 The s9e authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Plugins\TaskLists;
9
10
use s9e\TextFormatter\Parser;
11
use s9e\TextFormatter\Parser\Tag;
12
13
class Helper
14
{
15 5
	public static function filterListItem(Parser $parser, Tag $listItem, string $text): void
16
	{
17
		// Test whether the list item is followed by a task checkbox
18 5
		$pos  = $listItem->getPos() + $listItem->getLen();
19 5
		$pos += strspn($text, ' ', $pos);
20 5
		$str  = substr($text, $pos, 3);
21 5
		if (!preg_match('/\\[[ Xx]\\]/', $str))
22
		{
23
			return;
24
		}
25
26
		// Create a tag for the task and assign it a random ID
27 5
		$taskId = uniqid();
28 5
		$task   = $parser->addSelfClosingTag('TASK', $pos, 3);
29 5
		$task->setAttribute('id', $taskId);
30 5
		if ($str !== '[ ]')
31
		{
32 5
			$task->setAttribute('state', 'checked');
33
		}
34
35
		// Copy the task's ID to the list item
36 5
		$listItem->setAttribute('task_id', $taskId);
37
	}
38
39
	/**
40
	* 
41
	*
42
	* @return void
43
	*/
44
	public static function x()
45
	{
46
	}
47
48
	/**
49
	* Return stats from a parsed representation
50
	*
51
	* @param  string $xml Parsed XML
52
	* @return array       Number of "checked" and "unchecked" tasks
53
	*/
54 2
	public static function getStats(string $xml): array
55
	{
56
		$stats = [
57 2
			'checked'   => 0,
58
			'unchecked' => 0
59
		];
60
61 2
		preg_match_all('(<TASK(?= )[^>]++)', $xml, $m);
62 2
		foreach ($m[0] as $str)
63
		{
64 1
			$state = (strpos($str, 'state="checked"')) ? 'checked' : 'unchecked';
65 1
			++$stats[$state];
66
		}
67
68 2
		return $stats;
69
	}
70
}