Completed
Push — master ( eb798b...ff250e )
by Josh
07:09
created

FilterSyntaxMatcher::getMatchers()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 2
cts 2
cp 1
rs 8.9381
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1

How to fix   Long Method   

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 declare(strict_types=1);
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2019 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Configurator\Helpers;
9
10
use s9e\TextFormatter\Configurator\Items\Regexp;
11
use s9e\TextFormatter\Configurator\RecursiveParser\AbstractRecursiveMatcher;
12
13
class FilterSyntaxMatcher extends AbstractRecursiveMatcher
14
{
15
	/**
16
	* {@inheritdoc}
17
	*/
18 22
	public function getMatchers(): array
19
	{
20
		return [
21
			'Array' => [
22 22
				'groups' => ['ArrayValue', 'FilterArg'],
23
				'regexp' => '\\[ ((?&ArrayElements))? \\]',
24
			],
25
			'ArrayElement' => [
26
				'regexp' => '(?:((?&ArrayKey)) => )?((?&ArrayValue))',
27
			],
28
			'ArrayElements' => [
29
				'regexp' => '((?&ArrayElement))(?: , ((?&ArrayElements)))?',
30
			],
31
			'DoubleQuotedString' => [
32
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
33
				'regexp' => '"((?:[^\\\\"]|\\\\.)*)"',
34
			],
35
			'False' => [
36
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
37
				'regexp' => '[Ff][Aa][Ll][Ss][Ee]',
38
			],
39
			'FilterArgs' => [
40
				'regexp' => '((?&FilterArg))(?: , ((?&FilterArgs)))?',
41
			],
42
			'FilterCallback' => [
43
				'regexp' => '([#:\\\\\\w]+)(?: \\( ((?&FilterArgs)?) \\))?',
44
			],
45
			'Float' => [
46
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
47
				'regexp' => '([-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*|[0-9]+(?=[Ee]))(?:[Ee]-?[0-9]+)?)',
48
			],
49
			'Integer' => [
50
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
51
				'regexp' => '(-?(?:0[Bb][01]+|0[Xx][0-9A-Fa-f]+|[0-9]+))',
52
			],
53
			'Null' => [
54
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
55
				'regexp' => '[Nn][Uu][Ll][Ll]',
56
			],
57
			'Param' => [
58
				'groups' => ['FilterArg'],
59
				'regexp' => '\\$(\\w+(?:\\.\\w+)*)',
60
			],
61
			'Regexp' => [
62
				'groups' => ['ArrayValue', 'FilterArg'],
63
				'regexp' => '(/(?:[^\\\\/]|\\\\.)*/)([Sgimsu]*)',
64
			],
65
			'SingleQuotedString' => [
66
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
67
				'regexp' => "'((?:[^\\\\']|\\\\.)*)'",
68
			],
69
			'True' => [
70
				'groups' => ['ArrayKey', 'ArrayValue', 'FilterArg'],
71
				'regexp' => '[Tt][Rr][Uu][Ee]'
72
			]
73
		];
74
	}
75
76
	/**
77
	* @param  string $elements
78
	* @return array
79
	*/
80 6
	public function parseArray(string $elements = ''): array
81
	{
82 6
		$array = [];
83 6
		if ($elements !== '')
84
		{
85
			foreach ($this->recurse($elements, 'ArrayElements') as $element)
86
			{
87
				if (array_key_exists('key', $element))
88
				{
89
					$array[$element['key']] = $element['value'];
90
				}
91
				else
92
				{
93
					$array[] = $element['value'];
94
				}
95
			}
96
		}
97
98 6
		return $array;
99
	}
100
101
	/**
102
	* @param  string $key
103
	* @param  string $value
104
	* @return array
105
	*/
106
	public function parseArrayElement(string $key, string $value): array
107
	{
108
		$element['value'] = $this->recurse($value, 'ArrayValue');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$element was never initialized. Although not strictly required by PHP, it is generally a good practice to add $element = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
109
		if ($key !== '')
110
		{
111
			$element['key'] = $this->recurse($key, 'ArrayKey');
112
		}
113
114
		return $element;
115
	}
116
117
	/**
118
	* @param  string $firstElement
119
	* @param  string $otherElements
120
	* @return array
121
	*/
122
	public function parseArrayElements(string $firstElement, string $otherElements = null)
123
	{
124
		$elements = [$this->recurse($firstElement, 'ArrayElement')];
125
		if (isset($otherElements))
126
		{
127
			$elements = array_merge($elements, $this->recurse($otherElements, 'ArrayElements'));
128
		}
129
130
		return $elements;
131
	}
132
133
	/**
134
	* @param  string $str
135
	* @return string
136
	*/
137 2
	public function parseDoubleQuotedString(string $str): string
138
	{
139 2
		return stripcslashes($str);
140
	}
141
142
	/**
143
	* @return bool
144
	*/
145 1
	public function parseFalse(): bool
146
	{
147 1
		return false;
148
	}
149
150
	/**
151
	* @param  string $callback
152
	* @param  string $args
153
	* @return array
154
	*/
155 20
	public function parseFilterCallback(string $callback, string $args = null): array
156
	{
157 20
		$config = ['filter' => $callback];
158 20
		if (isset($args))
159
		{
160 18
			$config['params'] = ($args === '') ? [] : $this->recurse($args, 'FilterArgs');
161
		}
162
163 20
		return $config;
164
	}
165
166
	/**
167
	* @param  string $firstArg
168
	* @param  string $otherArgs
169
	* @return array
170
	*/
171 16
	public function parseFilterArgs(string $firstArg, string $otherArgs = null)
172
	{
173 16
		$parsedArg = $this->parser->parse($firstArg, 'FilterArg');
0 ignored issues
show
Bug introduced by
The property parser does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
174
175 16
		$type = ($parsedArg['match'] === 'Param') ? 'Name' : 'Value';
176 16
		$args = [[$type, $parsedArg['value']]];
177 16
		if (isset($otherArgs))
178
		{
179 7
			$args = array_merge($args, $this->recurse($otherArgs, 'FilterArgs'));
180
		}
181
182 16
		return $args;
183
	}
184
185
	/**
186
	* @return null
187
	*/
188 1
	public function parseNull()
189
	{
190 1
		return null;
191
	}
192
193
	/**
194
	* @param  string $str
195
	* @return float
196
	*/
197 2
	public function parseFloat(string $str): float
198
	{
199 2
		return (float) $str;
200
	}
201
202
	/**
203
	* @param  string $str
204
	* @return integer
205
	*/
206 2
	public function parseInteger(string $str): int
207
	{
208 2
		return intval($str, 0);
209
	}
210
211
	/**
212
	* @param  string $str
213
	* @return string
214
	*/
215 7
	public function parseParam(string $str): string
216
	{
217 7
		return $str;
218
	}
219
220
	/**
221
	* @param  string $str
0 ignored issues
show
Bug introduced by
There is no parameter named $str. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
222
	* @param  string $flags
223
	* @return Regexp
224
	*/
225
	public function parseRegexp(string $regexp, string $flags): Regexp
226
	{
227
		$regexp .= str_replace('g', '', $flags);
228
229
		return new Regexp($regexp, true);
230
	}
231
232
	/**
233
	* @param  string $str
234
	* @return string
235
	*/
236 2
	public function parseSingleQuotedString(string $str): string
237
	{
238 2
		return preg_replace("(\\\\([\\\\']))", '$1', $str);
239
	}
240
241
	/**
242
	* @param  string $str
0 ignored issues
show
Bug introduced by
There is no parameter named $str. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
243
	* @return bool
244
	*/
245 1
	public function parseTrue(): bool
246
	{
247 1
		return true;
248
	}
249
}