Completed
Push — master ( 39abe4...b867be )
by Richard
02:31
created

Formatter::format()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 12
nc 5
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
	private function processFormat($format, $functionName, $value) {
37
		$functionExists = false;
38
		foreach ($value as &$val) {
39
			foreach ($this->formatters as $formatter) {
40
				if (is_callable([$formatter, $functionName])) {
41
					$val = call_user_func_array([$formatter, $functionName], array_merge([$val], $format));
42
					$functionExists = true;
43
				}
44
			}
45
		}
46
		if (!$functionExists) throw new \Exception("Formatter '$functionName' does not exist");
47
		return $value;
48
	}
49
}
50