forked from sctr/FOSRestBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractScalarParam.php
More file actions
91 lines (79 loc) · 2.91 KB
/
AbstractScalarParam.php
File metadata and controls
91 lines (79 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\NotNull;
/**
* {@inheritdoc}
*
* @author Ener-Getick <egetick@gmail.Com>
*/
abstract class AbstractScalarParam extends AbstractParam
{
/** @var mixed */
public $requirements = null;
/** @var bool */
public $map = false;
/** @var bool */
public $allowBlank = true;
/** {@inheritdoc} */
public function getConstraints()
{
$constraints = parent::getConstraints();
if ($this->requirements instanceof Constraint) {
$constraints[] = $this->requirements;
} elseif (is_scalar($this->requirements)) {
$constraints[] = new Regex(
'#^(?:'.$this->requirements.')$#xsu',
sprintf(
'Parameter \'%s\' value, does not match requirements \'%s\'',
$this->getName(),
$this->requirements
),
);
} elseif (is_array($this->requirements) && isset($this->requirements['rule']) && $this->requirements['error_message']) {
$constraints[] = new Regex(
'#^(?:'.$this->requirements['rule'].')$#xsu',
$this->requirements['error_message'],
);
} elseif (is_array($this->requirements)) {
foreach ($this->requirements as $index => $requirement) {
if ($requirement instanceof Constraint) {
$constraints[] = $requirement;
} else {
throw new \TypeError(sprintf('Expected the requirements to be an array of %s instances but got %s at position %d.', Constraint::class, is_object($requirement) ? get_class($requirement) : gettype($requirement), $index));
}
}
}
if (false === $this->allowBlank) {
$notBlank = new NotBlank();
if (property_exists(NotBlank::class, 'allowNull')) {
$notBlank->allowNull = $this->nullable;
}
$constraints[] = $notBlank;
}
// If the user wants to map the value, apply all constraints to every
// value of the map
if ($this->map) {
if ([] !== $constraints) {
$constraints = [
new All($constraints),
];
}
if (false === $this->nullable) {
$constraints[] = new NotNull();
}
}
return $constraints;
}
}