1
|
|
|
<?php |
2
|
|
|
namespace Transphporm; |
3
|
|
|
use Transphporm\Parser\Tokenizer; |
4
|
|
|
class TSSValidator { |
5
|
|
|
private $error; |
6
|
|
|
|
7
|
|
|
public function validate($tss) { |
8
|
|
|
$this->error = null; |
9
|
|
|
$tokens = $this->tokenize($tss); |
10
|
|
|
|
11
|
|
|
foreach ($tokens as $token) |
12
|
|
|
if (!$this->validateRule($token)) return false; |
13
|
|
|
|
14
|
|
|
return true; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function getLastError() { |
18
|
|
|
return $this->error; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
private function validateRule($token) { |
22
|
|
|
if ($token['type'] !== Tokenizer::OPEN_BRACE) return true; |
23
|
|
|
|
24
|
|
|
return $this->checkBraces($token) && $this->checkSemicolons($token) |
25
|
|
|
&& $this->checkParenthesis($token); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
private function checkBraces($token) { |
29
|
|
|
return strpos($token['string'], '{') === false; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function checkSemicolons($braceToken) { |
33
|
|
|
$prevSemicolon = true; |
34
|
|
|
foreach ($braceToken['value'] as $token) { |
35
|
|
|
if ($token['type'] === Tokenizer::SEMI_COLON) $prevSemicolon = true; |
36
|
|
|
if ($token['type'] === Tokenizer::COLON && !$prevSemicolon) return false; |
37
|
|
|
else if ($token['type'] === Tokenizer::COLON) $prevSemicolon = false; |
38
|
|
|
} |
39
|
|
|
return true; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function checkParenthesis($token) { |
43
|
|
|
return substr_count($token['string'], '(') === substr_count($token['string'], ')'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function tokenize($tss) { |
47
|
|
|
if (is_file($tss)) $tss = file_get_contents($tss); |
48
|
|
|
$tss = $this->stripComments($tss, '//', "\n"); |
49
|
|
|
$tss = $this->stripComments($tss, '/*', '*/'); |
50
|
|
|
$tokenizer = new Tokenizer($tss); |
51
|
|
|
return $tokenizer->getTokens(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
View Code Duplication |
private function stripComments($str, $open, $close) { |
|
|
|
|
55
|
|
|
$pos = 0; |
56
|
|
|
while (($pos = strpos($str, $open, $pos)) !== false) { |
57
|
|
|
$end = strpos($str, $close, $pos); |
58
|
|
|
if ($end === false) break; |
59
|
|
|
$str = substr_replace($str, '', $pos, $end-$pos+strlen($close)); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $str; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.