Completed
Push — master ( 71ae65...4e11a6 )
by Tom
02:20
created

Formatter::assert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 2
eloc 2
nc 2
nop 2
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2015 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.0                                                             */
7
namespace Transphporm\Hook;
8
/** Handles format: foo bar properties in the stylesheet */
9
class Formatter {
10
	private $formatters = [];
11
12
	public function register($formatter) {
13
		$this->formatters[] = $formatter;
14
	}
15
16
	public function format($value, $rules) {
17
		if (!isset($rules['format'])) return $value;
18
		$tokens = $rules['format'];
19
20
		$functionName = $tokens->from(\Transphporm\Parser\Tokenizer::NAME, true)->read();
21
22
		$options = [];
23
		foreach (new \Transphporm\Parser\TokenFilterIterator($tokens->from(\Transphporm\Parser\Tokenizer::NAME),
24
					[\Transphporm\Parser\Tokenizer::WHITESPACE]) as $token) {
25
			$options[] = $token['value'];
26
		}
27
28
		try {
29
			return $this->processFormat($options, $functionName, $value);
30
		}
31
		catch (\Exception $e) {
32
			throw new \Transphporm\RunException(\Transphporm\Exception::FORMATTER, $functionName, $e);
33
		}
34
	}
35
36
	//TODO: Abstract all error reporting externally with a method for turning it on/off
37
	private function assert($condition, $error) {
0 ignored issues
show
Unused Code introduced by
The parameter $condition is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
		if (!$functionExists) throw new \Exception($error);
0 ignored issues
show
Bug introduced by
The variable $functionExists does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
39
	}
40
41
	private function processFormat($format, $functionName, $value) {
42
		$functionExists = false;
43
		foreach ($value as &$val) {
44
			foreach ($this->formatters as $formatter) {
45
				if (is_callable([$formatter, $functionName])) {
46
					$val = call_user_func_array([$formatter, $functionName], array_merge([$val], $format));
47
					$functionExists = true;
48
				}
49
			}
50
		}
51
52
		$this->assert($functionExists, "Formatter '$functionName' does not exist");
53
		return $value;
54
	}
55
}
56