Completed
Push — master ( a264ad...237dc5 )
by Richard
02:18
created

TSSValidator::stripComments()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 10
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 10
rs 9.4285
cc 3
eloc 7
nc 3
nop 3
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
        $splitTokens = $braceToken['value']->splitOnToken(Tokenizer::COLON);
34
        array_shift($splitTokens); array_pop($splitTokens);
35
        foreach ($splitTokens as $tokens)
36
            if (!in_array(Tokenizer::SEMI_COLON, array_column(iterator_to_array($tokens), 'type'))) return false;
37
38
        return true;
39
    }
40
41
    private function checkParenthesis($token) {
42
        return substr_count($token['string'], '(') === substr_count($token['string'], ')');
43
    }
44
45
    private function tokenize($tss) {
46
        if (is_file($tss)) $tss = file_get_contents($tss);
47
        $tss = $this->stripComments($tss, '//', "\n");
48
		$tss = $this->stripComments($tss, '/*', '*/');
49
		$tokenizer = new Tokenizer($tss);
50
		return $tokenizer->getTokens();
51
    }
52
53 View Code Duplication
    private function stripComments($str, $open, $close) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
54
		$pos = 0;
55
		while (($pos = strpos($str, $open, $pos)) !== false) {
56
			$end = strpos($str, $close, $pos);
57
			if ($end === false) break;
58
			$str = substr_replace($str, '', $pos, $end-$pos+strlen($close));
59
		}
60
61
		return $str;
62
	}
63
}
64