Passed
Push — master ( 6ee9d0...d995fb )
by Andreas
17:39
created

phpValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 33
ccs 0
cts 28
cp 0
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A lint() 0 19 3
A validate() 0 9 3
1
<?php
2
/**
3
 * @copyright CONTENT CONTROL GmbH, http://www.contentcontrol-berlin.de
4
 */
5
6
namespace midcom\datamanager\validation;
7
8
use Symfony\Component\Validator\Constraint;
9
use Symfony\Component\Validator\ConstraintValidator;
10
use midcom;
11
12
class phpValidator extends ConstraintValidator
13
{
14
    public function validate($value, Constraint $constraint)
15
    {
16
        if (trim($value) == '') {
17
            return;
18
        }
19
        if ($error = self::lint($value)) {
20
            $this->context
21
                ->buildViolation($error)
22
                ->addViolation();
23
        }
24
    }
25
26
    public static function lint(string $input) : ?string
27
    {
28
        $return_status = 0;
29
        $parse_results = [];
30
        exec(sprintf('echo %s | php -l', escapeshellarg($input)) . " 2>&1", $parse_results, $return_status);
31
        debug_print_r("php -l returned:", $parse_results);
32
        if ($return_status !== 0) {
33
            $parse_result = array_pop($parse_results);
34
            if (str_contains($parse_result, 'No syntax errors detected in ')) {
35
                // We have an error, but it's most likely a false positive, e.g. a PHP startup error
36
                return null;
37
            }
38
            $parse_result = array_pop($parse_results);
39
            $line = preg_replace('/^.+?on line (\d+).*?$/s', '\1', $parse_result);
40
            $l10n = midcom::get()->i18n->get_l10n('midcom.datamanager');
41
42
            return sprintf($l10n->get('type php: parse error in line %s'), $line);
43
        }
44
        return null;
45
    }
46
}
47