Completed
Push — master ( 6f977d...fe17d6 )
by Josh
03:28
created

MergeSuffix   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 79
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A processStrings() 0 17 3
A hasMatchingSuffix() 0 13 3
A isEligible() 0 4 2
A pop() 0 18 3
1
<?php
2
3
/**
4
* @package   s9e\RegexpBuilder
5
* @copyright Copyright (c) 2016 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\RegexpBuilder\Passes;
9
10
class MergeSuffix extends AbstractPass
11
{
12
	/**
13
	* {@inheritdoc}
14
	*/
15 8
	protected function processStrings(array $strings)
16
	{
17 8
		if (!$this->isEligible($strings))
18
		{
19 3
			return $strings;
20
		}
21
22 5
		$newString = [];
23 5
		while ($this->hasMatchingSuffix($strings))
24
		{
25 5
			array_unshift($newString, end($strings[0]));
26 5
			$strings = $this->pop($strings);
27
		}
28 5
		array_unshift($newString, $strings);
29
30 5
		return [$newString];
31
	}
32
33
	/**
34
	* Test whether all given strings have the same last element
35
	*
36
	* @param  array[] $strings
37
	* @return bool
38
	*/
39 7
	protected function hasMatchingSuffix(array $strings)
40
	{
41 7
		$suffix = end($strings[1]);
42 7
		foreach ($strings as $string)
43
		{
44 7
			if (end($string) !== $suffix)
45
			{
46 7
				return false;
47
			}
48
		}
49
50 5
		return ($suffix !== false);
51
	}
52
53
	/**
54
	* Test whether this pass can be run on given list of strings
55
	*
56
	* @param  array[] $strings
57
	* @return bool
58
	*/
59 8
	protected function isEligible(array $strings)
60
	{
61 8
		return (count($strings) > 1 && $this->hasMatchingSuffix($strings));
62
	}
63
64
	/**
65
	* Remove the last element of every string
66
	*
67
	* @param  array[] $strings Original strings
68
	* @return array[]          Processed strings
69
	*/
70 5
	protected function pop(array $strings)
71
	{
72 5
		$cnt = count($strings);
73 5
		$i   = $cnt;
74 5
		while (--$i >= 0)
75
		{
76 5
			array_pop($strings[$i]);
77
		}
78
79
		// Remove empty elements then prepend one back at the start of the array if applicable
80 5
		$strings = array_filter($strings);
81 5
		if (count($strings) < $cnt)
82
		{
83 1
			array_unshift($strings, []);
84
		}
85
86 5
		return $strings;
87
	}
88
}