1
|
|
|
<?php |
2
|
|
|
/* @description Transformation Style Sheets - Revolutionising PHP templating * |
3
|
|
|
* @author Tom Butler [email protected] * |
4
|
|
|
* @copyright 2017 Tom Butler <[email protected]> | https://r.je/ * |
5
|
|
|
* @license http://www.opensource.org/licenses/bsd-license.php BSD License * |
6
|
|
|
* @version 1.2 */ |
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
|
|
|
public function runOnImmutableElements(): bool { |
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
//TODO: Abstract all error reporting externally with a method for turning it on/off |
41
|
|
|
private function assert($condition, $error) { |
42
|
|
|
if (!$condition) throw new \Exception($error); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function processFormat($format, $functionName, $value) { |
46
|
|
|
$functionExists = false; |
47
|
|
|
foreach ($value as &$val) { |
48
|
|
|
foreach ($this->formatters as $formatter) { |
49
|
|
|
if (is_callable([$formatter, $functionName])) { |
50
|
|
|
$val = call_user_func_array([$formatter, $functionName], array_merge([$val], $format)); |
51
|
|
|
$functionExists = true; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$this->assert($functionExists, "Formatter '$functionName' does not exist"); |
57
|
|
|
return $value; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|