1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace WsdlToPhp\PackageGenerator\File\Validation; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @see https://www.w3.org/TR/xmlschema-2/#rf-pattern |
9
|
|
|
* Validation Rule: pattern valid |
10
|
|
|
* A literal in a ·lexical space· is facet-valid with respect to ·pattern· if: |
11
|
|
|
* - 1 the literal is among the set of character sequences denoted by the ·regular expression· specified in {value}. |
12
|
|
|
*/ |
13
|
|
|
final class PatternRule extends AbstractRule |
14
|
|
|
{ |
15
|
26 |
|
public const NAME = 'pattern'; |
16
|
|
|
|
17
|
26 |
|
public function name(): string |
18
|
|
|
{ |
19
|
|
|
return self::NAME; |
20
|
26 |
|
} |
21
|
|
|
|
22
|
26 |
|
public function testConditions(string $parameterName, $value, bool $itemType = false): string |
23
|
|
|
{ |
24
|
|
|
if ($itemType || !$this->getAttribute()->isArray()) { |
25
|
26 |
|
$test = sprintf(($itemType ? '' : '!is_null($%1$s) && ').'!preg_match(\'/%2$s/\', $%1$s)', $parameterName, self::valueToRegularExpression($value)); |
26
|
|
|
} else { |
27
|
26 |
|
$this->addArrayValidationMethod($parameterName, $value); |
28
|
|
|
$test = sprintf( |
29
|
|
|
'\'\' !== (%s = self::%s($%s))', |
30
|
26 |
|
$this->getArrayErrorMessageVariableName($parameterName), |
31
|
|
|
$this->getValidationMethodName($parameterName), |
32
|
26 |
|
$parameterName |
33
|
26 |
|
); |
34
|
26 |
|
} |
35
|
26 |
|
|
36
|
26 |
|
return $test; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function exceptionMessageOnTestFailure(string $parameterName, $value, bool $itemType = false): string |
40
|
|
|
{ |
41
|
|
|
if ($itemType || !$this->getAttribute()->isArray()) { |
42
|
|
|
$message = 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
|
|
|
} else { |
44
|
|
|
$message = $this->getArrayErrorMessageVariableName($parameterName); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $message; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public static function valueToRegularExpression($value): string |
51
|
|
|
{ |
52
|
|
|
return implode('|', array_map(static function ($value) { |
53
|
|
|
return addcslashes($value, '\'\\/'); |
54
|
|
|
}, array_map(static function ($value) { |
55
|
|
|
return empty($value) ? '^$' : $value; |
56
|
|
|
}, array_map('trim', is_array($value) ? $value : [$value])))); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
final protected function getArrayExceptionMessageOnTestFailure($value): string |
60
|
|
|
{ |
61
|
|
|
return sprintf( |
62
|
|
|
'Invalid value(s) %%s, please provide literals that are among the set of character sequences denoted by the regular expression /%s/\'', |
63
|
|
|
stripcslashes(self::valueToRegularExpression($value)), |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|