Completed
Push — master ( 49fd3e...ad9c66 )
by Tom
01:25
created

Literals::isRealSubtract()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 4
nc 6
nop 2
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\Parser\Tokenizer;
8
use \Transphporm\Parser\Tokenizer;
9
use \Transphporm\Parser\Tokens;
10
11
class Literals implements \Transphporm\Parser\Tokenizable {
12
13
	public function tokenize(TokenizedString $str, Tokens $tokens) {
14
		$char = $str->identifyChar();
15
		if ($char === Tokenizer::NAME) {
16
17
			$name = $str->read();
18
			$j = 0;
19
20
			while ($this->isLiteral($j+1, $str)) {
21
				$name .= $str->read($j+1);
22
				$j++;
23
			}
24
25
			$str->move($j);
26
27
			$this->processLiterals($tokens, $name, $str);
28
		}
29
	}
30
31
	private function isRealSubtract($n, $str) {
32
		$n--;
33
		// allow foo(2-5)
34
		//but not data(foo2-5)
35
		while (is_numeric($str->read($n))) {
36
			$n--;
37
		}
38
39
		if ($n == 0) return false;
40
		if (in_array($str->read($n), ['(', "\n", ' ', '['])) return true;
41
42
		return false;
43
	}
44
45
	private function isLiteral($n, $str) {
46
		//Is it a normal literal character
47
		return ($str->has($n) && ($str->identifyChar($n, $str) === Tokenizer::NAME
48
		//but a subtract can be part of a class name or a mathematical operation
49
				|| $str->identifyChar($n) == Tokenizer::SUBTRACT && !$this->isRealSubtract($n, $str))
50
			);
51
	}
52
53
	private function processLiterals($tokens, $name, $str) {
54
		if (is_numeric($name)) $tokens->add(['type' => Tokenizer::NUMERIC, 'value' => $name]);
55
		else if (method_exists($this, $name)) $this->$name($tokens);
56
		else $tokens->add(['type' => Tokenizer::NAME, 'value' => $name, 'line' => $str->lineNo()]);
57
	}
58
59
	private function true($tokens) {
60
		$tokens->add(['type' => Tokenizer::BOOL, 'value' => true]);
61
	}
62
63
	private function false($tokens) {
64
		$tokens->add(['type' => Tokenizer::BOOL, 'value' => false]);
65
	}
66
67
	private function in($tokens) {
68
		$tokens->add(['type' => Tokenizer::IN, 'value' => 'in']);
69
	}
70
}