Completed
Push — 2.x ( 7141fe...2a33df )
by Mikaël
47:13 queued 13s
created

PatternRule   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 9
c 3
b 0
f 1
dl 0
loc 40
ccs 6
cts 6
cp 1
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A testConditions() 0 3 2
A exceptionMessageOnTestFailure() 0 3 1
A name() 0 3 1
A valueToRegularExpression() 0 7 3
1
<?php
2
3
namespace WsdlToPhp\PackageGenerator\File\Validation;
4
5
/**
6
 * Class PatternRule
7
 * @link https://www.w3.org/TR/xmlschema-2/#rf-pattern
8
 * Validation Rule: pattern valid
9
 * A literal in a ·lexical space· is facet-valid with respect to ·pattern· if:
10
 *  - 1 the literal is among the set of character sequences denoted by the ·regular expression· specified in {value}.
11
 */
12
class PatternRule extends AbstractRule
13
{
14
15
    /**
16
     * @return string
17
     */
18 78
    public function name()
19
    {
20 78
        return 'pattern';
21
    }
22
23
    /**
24
     * @param string $parameterName
25
     * @param mixed $value
26
     * @param bool $itemType
27
     * @return string
28
     */
29 78
    public function testConditions($parameterName, $value, $itemType = false)
30
    {
31 78
        return sprintf(($itemType ? '' : '!is_null($%1$s) && ') . '!preg_match(\'/%2$s/\', $%1$s)', $parameterName, self::valueToRegularExpression($value));
32
    }
33
34
    /**
35
     * @param string $parameterName
36
     * @param mixed $value
37
     * @param bool $itemType
38
     * @return string
39
     */
40 78
    public function exceptionMessageOnTestFailure($parameterName, $value, $itemType = false)
41
    {
42 78
        return sprintf('sprintf(\'Invalid value %%s, please provide a literal that is among the set of character sequences denoted by the regular expression /%s/\', var_export($%s, true))', self::valueToRegularExpression($value), $parameterName);
43
    }
44
45
    public static function valueToRegularExpression($value)
46
    {
47
        return implode('|', array_map(function ($value) {
48
            return addcslashes($value, '\'\\/');
49
        }, array_map(function ($value) {
50
            return empty($value) ? '^$' : $value;
51
        }, array_map('trim', is_array($value) ? $value : [$value]))));
52
    }
53
}
54