|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the FOSRestBundle package. |
| 5 | + * |
| 6 | + * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace FOS\RestBundle\Controller\Annotations; |
| 13 | + |
| 14 | +use Symfony\Component\Validator\Constraint; |
| 15 | +use Symfony\Component\Validator\Constraints\NotBlank; |
| 16 | +use Symfony\Component\Validator\Constraints\All; |
| 17 | +use Symfony\Component\Validator\Constraints\Regex; |
| 18 | + |
| 19 | +/** |
| 20 | + * {@inheritdoc} |
| 21 | + * |
| 22 | + * @author Ener-Getick <[email protected]> |
| 23 | + */ |
| 24 | +abstract class AbstractScalarParam extends AbstractParam |
| 25 | +{ |
| 26 | + /** @var mixed */ |
| 27 | + public $requirements = null; |
| 28 | + /** @var bool */ |
| 29 | + public $map = false; |
| 30 | + /** @var bool */ |
| 31 | + public $allowBlank = true; |
| 32 | + |
| 33 | + /** {@inheritdoc} */ |
| 34 | + public function getConstraints() |
| 35 | + { |
| 36 | + $constraints = parent::getConstraints(); |
| 37 | + |
| 38 | + if ($this->requirements instanceof Constraint) { |
| 39 | + $constraints[] = $this->requirements; |
| 40 | + } elseif (is_scalar($this->requirements)) { |
| 41 | + $constraints[] = new Regex(array( |
| 42 | + 'pattern' => '#^(?:'.$this->requirements.')$#xsu', |
| 43 | + 'message' => sprintf( |
| 44 | + 'Parameter \'%s\' value, does not match requirements \'%s\'', |
| 45 | + $this->getName(), |
| 46 | + $this->requirements |
| 47 | + ), |
| 48 | + )); |
| 49 | + } elseif (is_array($this->requirements) && isset($this->requirements['rule']) && $this->requirements['error_message']) { |
| 50 | + $constraints[] = new Regex(array( |
| 51 | + 'pattern' => '#^(?:'.$this->requirements['rule'].')$#xsu', |
| 52 | + 'message' => $this->requirements['error_message'], |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + if (false === $this->allowBlank) { |
| 57 | + $constraints[] = new NotBlank(); |
| 58 | + } |
| 59 | + |
| 60 | + // If the user wants to map the value |
| 61 | + if ($this->map) { |
| 62 | + $constraints = array( |
| 63 | + new All($constraints), |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + return $constraints; |
| 68 | + } |
| 69 | +} |
0 commit comments