Completed
Push — master ( c8e302...7e512b )
by Josh
03:51
created

FilterChain::createFilter()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.7333
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 3
1
<?php
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\Collections;
9
10
use InvalidArgumentException;
11
use s9e\TextFormatter\Configurator\Helpers\FilterHelper;
12
use s9e\TextFormatter\Configurator\Items\Filter;
13
use s9e\TextFormatter\Configurator\Items\ProgrammableCallback;
14
15
abstract class FilterChain extends NormalizedList
16
{
17
	/**
18
	* Get the name of the filter class
19
	*
20
	* @return string
21
	*/
22
	abstract protected function getFilterClassName();
23
24
	/**
25
	* Test whether this filter chain contains given callback
26
	*
27
	* @param  callable $callback
28
	* @return bool
29
	*/
30 2
	public function containsCallback(callable $callback)
31
	{
32
		// Normalize the callback
33 2
		$pc = new ProgrammableCallback($callback);
34 2
		$callback = $pc->getCallback();
35 2
		foreach ($this->items as $filter)
36
		{
37 1
			if ($callback === $filter->getCallback())
38
			{
39 1
				return true;
40
			}
41
		}
42
43 1
		return false;
44
	}
45
46
	/**
47
	* Normalize a value into an TagFilter instance
48
	*
49
	* @param  mixed  $value Either a valid callback or an instance of TagFilter
50
	* @return Filter        Normalized filter
51
	*/
52 17
	public function normalizeValue($value)
53
	{
54 17
		if (is_string($value) && strpos($value, '(') !== false)
55
		{
56 1
			return $this->createFilter($value);
57
		}
58
59 17
		$className = $this->getFilterClassName();
60 17
		if ($value instanceof $className)
61
		{
62 3
			return $value;
63
		}
64
65 14
		if (!is_callable($value))
66
		{
67 8
			throw new InvalidArgumentException('Filter ' . var_export($value, true) . ' is neither callable nor an instance of ' . $className);
68
		}
69
70 6
		return new $className($value);
71
	}
72
73
	/**
74
	* Create and return a filter
75
	*
76
	* @param  string $filterString
77
	* @return Filter
78
	*/
79 1
	protected function createFilter($filterString)
80
	{
81 1
		$config = FilterHelper::parse($filterString);
82 1
		$filter = $this->normalizeValue($config['filter']);
83 1
		if (isset($config['params']))
84
		{
85 1
			$filter->resetParameters();
86 1
			foreach ($config['params'] as [$type, $value])
87
			{
88 1
				$methodName = 'addParameterBy' . $type;
89 1
				$filter->$methodName($value);
90
			}
91
		}
92
93 1
		return $filter;
94
	}
95
}