Collection.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  12. /**
  13. * @Annotation
  14. * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class Collection extends Composite
  19. {
  20. public const MISSING_FIELD_ERROR = '2fa2158c-2a7f-484b-98aa-975522539ff8';
  21. public const NO_SUCH_FIELD_ERROR = '7703c766-b5d5-4cef-ace7-ae0dd82304e9';
  22. protected static $errorNames = [
  23. self::MISSING_FIELD_ERROR => 'MISSING_FIELD_ERROR',
  24. self::NO_SUCH_FIELD_ERROR => 'NO_SUCH_FIELD_ERROR',
  25. ];
  26. public $fields = [];
  27. public $allowExtraFields = false;
  28. public $allowMissingFields = false;
  29. public $extraFieldsMessage = 'This field was not expected.';
  30. public $missingFieldsMessage = 'This field is missing.';
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function __construct($options = null)
  35. {
  36. // no known options set? $options is the fields array
  37. if (\is_array($options)
  38. && !array_intersect(array_keys($options), ['groups', 'fields', 'allowExtraFields', 'allowMissingFields', 'extraFieldsMessage', 'missingFieldsMessage'])) {
  39. $options = ['fields' => $options];
  40. }
  41. parent::__construct($options);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function initializeNestedConstraints()
  47. {
  48. parent::initializeNestedConstraints();
  49. if (!\is_array($this->fields)) {
  50. throw new ConstraintDefinitionException(sprintf('The option "fields" is expected to be an array in constraint "%s".', __CLASS__));
  51. }
  52. foreach ($this->fields as $fieldName => $field) {
  53. // the XmlFileLoader and YamlFileLoader pass the field Optional
  54. // and Required constraint as an array with exactly one element
  55. if (\is_array($field) && 1 == \count($field)) {
  56. $this->fields[$fieldName] = $field = $field[0];
  57. }
  58. if (!$field instanceof Optional && !$field instanceof Required) {
  59. $this->fields[$fieldName] = new Required($field);
  60. }
  61. }
  62. }
  63. public function getRequiredOptions()
  64. {
  65. return ['fields'];
  66. }
  67. protected function getCompositeOption()
  68. {
  69. return 'fields';
  70. }
  71. }