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

PatternRule::valueToRegularExpression()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 12
rs 10
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