|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Nicofuma\SwaggerBundle\JsonSchema\Constraints; |
|
4
|
|
|
|
|
5
|
|
|
use JsonSchema\Constraints\Factory; |
|
|
|
|
|
|
6
|
|
|
use JsonSchema\Constraints\FormatConstraint as FormatConstraintBase; |
|
7
|
|
|
use JsonSchema\Uri\UriRetriever; |
|
8
|
|
|
use Nicofuma\SwaggerBundle\Exception\FormatConstraintException; |
|
9
|
|
|
use Nicofuma\SwaggerBundle\JsonSchema\Constraints\Format\FormatValidatorInterface; |
|
10
|
|
|
|
|
11
|
|
|
class FormatConstraint extends FormatConstraintBase |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var FormatValidatorInterface[] */ |
|
14
|
|
|
private $formatMap = []; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct($checkMode, UriRetriever $uriRetriever, Factory $factory) |
|
17
|
4 |
|
{ |
|
18
|
|
|
parent::__construct($checkMode, $uriRetriever, $factory); |
|
19
|
4 |
|
|
|
20
|
1 |
|
if ($factory instanceof \Nicofuma\SwaggerBundle\JsonSchema\Constraints\Factory) { |
|
21
|
|
|
$this->formatMap = $factory->getFormatValidators(); |
|
22
|
|
|
} |
|
23
|
3 |
|
} |
|
24
|
|
|
|
|
25
|
1 |
|
/** |
|
26
|
1 |
|
* {@inheritdoc} |
|
27
|
1 |
|
*/ |
|
28
|
1 |
|
public function check($element, $schema = null, $path = null, $i = null) |
|
29
|
1 |
|
{ |
|
30
|
|
|
if (!isset($schema->format)) { |
|
31
|
|
|
return; |
|
32
|
1 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
if (array_key_exists($schema->format, $this->formatMap)) { |
|
35
|
2 |
|
try { |
|
36
|
2 |
|
$this->formatMap[$schema->format]->validate($element); |
|
37
|
|
|
} catch (FormatConstraintException $e) { |
|
38
|
|
|
foreach ($e->getErrors() as $error) { |
|
39
|
|
|
$this->addError($path, $error, 'format'); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
return; |
|
44
|
1 |
|
} |
|
45
|
|
|
|
|
46
|
1 |
|
parent::check($element, $schema, $path, $i); |
|
47
|
1 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Add a format validator. |
|
51
|
|
|
* |
|
52
|
|
|
* @param string $format |
|
53
|
|
|
* @param FormatValidatorInterface $formatValidator |
|
54
|
|
|
*/ |
|
55
|
|
|
public function addFormatValidator($format, FormatValidatorInterface $formatValidator) |
|
56
|
|
|
{ |
|
57
|
|
|
$this->formatMap[$format] = $formatValidator; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: