public function isValid(ExecutionContext $context) { $is_valid = $this->start <= $this->end; if (!$is_valid) { $context->addViolationAtSubPath('end', 'cjsissingh_calendar.validation.event_dates', array(), null); } }
/** * {@inheritdoc} */ public function isVoteValid(ExecutionContext $context) { if (!$this->checkValue($this->value)) { $message = 'A vote cannot have a 0 value'; $propertyPath = $context->getPropertyPath() . '.value'; $context->addViolationAtPath($propertyPath, $message); } }
/** * {@inheritdoc} */ public function isVoteValid(ExecutionContext $context) { if (!$this->checkValue($this->value)) { $propertyPath = $context->getPropertyPath() . '.value'; $context->setPropertyPath($propertyPath); $context->addViolation('A vote cannot have a 0 value', array(), null); } }
protected function setUp() { $walker = $this->getMock('Symfony\\Component\\Validator\\GraphWalker', array(), array(), '', false); $factory = $this->getMock('Symfony\\Component\\Validator\\Mapping\\ClassMetadataFactoryInterface'); $context = new ExecutionContext('root', $walker, $factory); $context->setCurrentClass(__CLASS__); $this->validator = new ChoiceValidator(); $this->validator->initialize($context); }
/** * Wrapper for $this->context->addViolation() * * @deprecated */ protected function setMessage($template, array $parameters = array()) { $this->messageTemplate = $template; $this->messageParameters = $parameters; if (!$this->context instanceof ExecutionContext) { throw new ValidatorException('ConstraintValidator::initialize() must be called before setting violation messages'); } $this->context->addViolation($template, $parameters); }
public function validateValueAsYaml(ExecutionContext $context) { try { Inline::load($this->value); } catch (ParserException $e) { $context->setPropertyPath($context->getPropertyPath() . '.value'); $context->addViolation('This value is not valid YAML syntax', array(), $this->value); } }
function it_does_not_validate_attribute_with_non_string_options(AbstractAttribute $attribute, ExecutionContext $context, AttributeOption $option1, AttributeOption $option2, AttributeOption $option3, AttributeOption $option4) { $option1->getCode()->willReturn('ab'); $option2->getCode()->willReturn(0); $option3->getCode()->willReturn('ef'); $option4->getCode()->willReturn('gh'); $attribute->getOptions()->willReturn([$option1, $option2, $option3, $option4]); $context->addViolation('Code must be a string. Type "integer" found.')->shouldBeCalled(); $this->areOptionsValid($attribute, $context); }
function it_validates_if_user_with_given_email_is_already_registered(UserRepository $userRepository, TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, ExecutionContext $context, TokenInterface $token, UniqueReviewerEmail $constraint, ReviewInterface $review, CustomerInterface $customer, CustomerInterface $existingUser) { $tokenStorage->getToken()->willReturn($token); $authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')->willReturn(false); $review->getAuthor()->willReturn($customer); $customer->getEmail()->willReturn('*****@*****.**'); $userRepository->findOneByEmail('*****@*****.**')->willReturn($existingUser); $constraint->message = 'This email is already registered. Please log in.'; $context->addViolationAt('author', 'This email is already registered. Please log in.', [], null)->shouldBeCalled(); $this->validate($review, $constraint); }
public function isEmailValid(ExecutionContext $context) { // somehow you have an array of "fake email" $fakeEmails = array('*****@*****.**'); // check if the name is actually a fake email if (in_array($this->getEmail(), $fakeEmails)) { $propertyPath = $context->getPropertyPath() . '.email'; $context->setPropertyPath($propertyPath); $context->addViolation('Tu ne te moquerais pas un peu de moi avec cet email ?', array(), null); } }
public function it_does_not_add_violation_if_the_given_value_is_valid_json(ExecutionContext $context, ComposerJson $constraint) { $composerJsonContent = <<<'EOT' { "require": { "monolog/monolog": "1.2.*" } } EOT; $context->addViolation(Argument::any())->shouldNotBeCalled(); $this->validate($composerJsonContent, $constraint); }
public static function validateFormChildren(FormInterface $form, ExecutionContext $context) { if ($form->getAttribute('cascade_validation')) { $propertyPath = $context->getPropertyPath(); $graphWalker = $context->getGraphWalker(); // Adjust the property path accordingly if (!empty($propertyPath)) { $propertyPath .= '.'; } $propertyPath .= 'children'; $graphWalker->walkReference($form->getChildren(), Constraint::DEFAULT_GROUP, $propertyPath, true); } }
public function areImagesValid(ExecutionContext $context) { $captured_ids = array_map(function ($image) { return $image->getId(); }, $this->images->toArray()); $property_path = $context->getPropertyPath() . '.images'; if (!count($captured_ids)) { $context->addViolationAt($property_path, 'Please select at least one image!', array(), null); return; } $count = $this->query_builder->andWhere($this->query_builder->expr()->in('i.id', $captured_ids))->select('COUNT(i.id)')->getQuery()->getSingleScalarResult(); if (!$count) { $context->addViolation('Please select images from the list!', array(), null); } }
/** * Validation rule for attribute option values * * @param AbstractAttribute $attribute * @param ExecutionContext $context */ public static function areOptionsValid(AbstractAttribute $attribute, ExecutionContext $context) { $existingValues = array(); foreach ($attribute->getOptions() as $option) { $code = $option->getCode(); if (isset($existingValues[$code])) { $context->addViolation(self::VIOLATION_DUPLICATE_OPTION_CODE); } elseif ($code === null) { $context->addViolation(self::VIOLATION_OPTION_CODE_REQUIRED); } elseif (!is_string($code)) { $context->addViolation(self::VIOLATION_NON_STRING_CODE . sprintf(' Type "%s" found.', gettype($code))); } else { $existingValues[$code] = ''; } } }
public function testNotExistingFormData() { $formConfig = $this->getMock('\\Symfony\\Component\\Form\\FormConfigInterface'); $form = new Form($formConfig); $this->context = $this->getMock('\\Symfony\\Component\\Validator\\ExecutionContextInterface'); $this->context->expects($this->any())->method('getRoot')->will($this->returnValue($form)); $this->validator->initialize($this->context); $this->assertNull($this->validator->validate(false, $this->constraint)); }
/** * Validates the data of a form * * This method is called automatically during the validation process. * * @param FormInterface $form The validated form * @param ExecutionContext $context The current validation context */ public static function validateFormData(FormInterface $form, ExecutionContext $context) { if (is_object($form->getData()) || is_array($form->getData())) { $propertyPath = $context->getPropertyPath(); $graphWalker = $context->getGraphWalker(); // The Execute constraint is called on class level, so we need to // set the property manually $context->setCurrentProperty('data'); // Adjust the property path accordingly if (!empty($propertyPath)) { $propertyPath .= '.'; } $propertyPath .= 'data'; foreach (self::getFormValidationGroups($form) as $group) { $graphWalker->walkReference($form->getData(), $group, $propertyPath, true); } } }
/** * Validates contact method * * @param ContactRequest $object * @param ExecutionContext $context */ public static function validate(ContactRequest $object, ExecutionContext $context) { $emailError = $phoneError = false; switch ($object->getPreferredContactMethod()) { case ContactRequest::CONTACT_METHOD_PHONE: $phoneError = !$object->getPhone(); break; case ContactRequest::CONTACT_METHOD_EMAIL: $emailError = !$object->getEmailAddress(); break; case ContactRequest::CONTACT_METHOD_BOTH: default: $phoneError = !$object->getPhone(); $emailError = !$object->getEmailAddress(); } if ($emailError) { $context->addViolationAt('emailAddress', 'This value should not be blank.'); } if ($phoneError) { $context->addViolationAt('phone', 'This value should not be blank.'); } }
public static function validateFormChildren(FormInterface $form, ExecutionContext $context) { if ($form->getAttribute('cascade_validation')) { $propertyPath = $context->getPropertyPath(); $graphWalker = $context->getGraphWalker(); // The Execute constraint is called on class level, so we need to // set the property manually $context->setCurrentProperty('children'); // Adjust the property path accordingly if (!empty($propertyPath)) { $propertyPath .= '.'; } $propertyPath .= 'children'; foreach (self::getFormValidationGroups($form) as $group) { $graphWalker->walkReference($form->getChildren(), $group, $propertyPath, true); } } }
public function testValidateDataSetsCurrentPropertyToData() { $graphWalker = $this->createMockGraphWalker(); $metadataFactory = $this->createMockMetadataFactory(); $context = new ExecutionContext('Root', $graphWalker, $metadataFactory); $object = $this->getMock('\\stdClass'); $form = new Form('author'); $test = $this; $graphWalker->expects($this->once())->method('walkReference')->will($this->returnCallback(function () use($context, $test) { $test->assertEquals('data', $context->getCurrentProperty()); })); $form->setData($object); $form->validateData($context); }
/** * Validates a value against a constraint. * * @param Constraint $constraint * @param $value * @param $group * @param $propertyPath * @param null $currentClass * @param null $currentProperty * * @deprecated Deprecated since version 2.2, to be removed in 2.3. */ public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath, $currentClass = null, $currentProperty = null) { trigger_error('walkConstraint() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED); $metadata = null; // BC code to make getCurrentClass() and getCurrentProperty() work when // called from within this method if (null !== $currentClass) { $metadata = $this->metadataFactory->getMetadataFor($currentClass); if (null !== $currentProperty && $metadata instanceof PropertyMetadataContainerInterface) { $metadata = current($metadata->getPropertyMetadata($currentProperty)); } } $context = new ExecutionContext($this->visitor, $this->translator, $this->translationDomain, $metadata, $value, $group, $propertyPath); $context->validateValue($value, $constraint); }
public function testGetPropertyPathWithNestedCollectionsAndAllMixed() { $constraints = new Collection(array('shelves' => new All(array('constraints' => array(new Collection(array('name' => new ConstraintA(), 'books' => new All(array('constraints' => array(new ConstraintA())))))))), 'name' => new ConstraintA())); $data = array('shelves' => array(array('name' => 'Research', 'books' => array('foo', 'bar')), array('name' => 'VALID', 'books' => array('foozy', 'VALID', 'bazzy'))), 'name' => 'Library'); $expectedViolationPaths = array('[shelves][0][name]', '[shelves][0][books][0]', '[shelves][0][books][1]', '[shelves][1][books][0]', '[shelves][1][books][2]', '[name]'); $visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), $this->translator); $context = new ExecutionContext($visitor, $this->translator, self::TRANS_DOMAIN); $context->validateValue($data, $constraints); foreach ($context->getViolations() as $violation) { $violationPaths[] = $violation->getPropertyPath(); } $this->assertEquals($expectedViolationPaths, $violationPaths); }
/** * validate * * @param type $data * @param ExecutionContext $context */ public function validate($data, ExecutionContext $context) { if ($data['mode'] !== 'add_favorite') { $context->validateValue($data['product_class_id'], array(new Assert\NotBlank()), '[product_class_id]'); if ($this->Product->getClassName1()) { $context->validateValue($data['classcategory_id1'], array(new Assert\NotBlank(), new Assert\NotEqualTo(array('value' => '__unselected', 'message' => 'form.type.select.notselect'))), '[classcategory_id1]'); } //商品規格2初期状態(未選択)の場合の返却値は「NULL」で「__unselected」ではない if ($this->Product->getClassName2()) { $context->validateValue($data['classcategory_id2'], array(new Assert\NotBlank(), new Assert\NotEqualTo(array('value' => '__unselected', 'message' => 'form.type.select.notselect'))), '[classcategory_id2]'); } } }
/** * @param ExecutionContext $context * @return void * @deprecated */ public function pickedOrderItems(ExecutionContext $context) { $count = 0; foreach ($this->items as $item) { $count += $item->getCount(); } if ($count === 0) { /* $property_path = $context->getPropertyPath() . '.customer.phone'; $property_path = $context->getPropertyPath() . '.items[0].count'; $property_path = $context->getPropertyPath() . '.items.[0].count'; $property_path = $context->getPropertyPath() . '.items.0.count'; */ $property_path = $context->getPropertyPath() . '.items[0].count'; $context->setPropertyPath($property_path); $context->addViolation('You have to pick at least one pizza...', array(), null); } }
/** * {@inheritdoc} */ public function visit(MetadataInterface $metadata, $value, $group, $propertyPath) { $context = new ExecutionContext( $this, $metadata, $value, $group, $propertyPath ); $context->validateValue($value, $metadata->findConstraints($group)); }
public function isRegionValid(ExecutionContext $context) { if ($this->getCountry() && $this->getCountry()->hasRegions() && !$this->state) { $propertyPath = $context->getPropertyPath() . '.state'; $context->addViolationAt($propertyPath, 'State is required for country %country%', array('%country%' => $this->getCountry()->getName())); } }
/** * {@inheritDoc} */ public function validateValue($value, $constraints, $groups = null) { $context = new ExecutionContext($this->createVisitor($value), $this->translator, $this->translationDomain); $constraints = is_array($constraints) ? $constraints : array($constraints); foreach ($constraints as $constraint) { if ($constraint instanceof Valid) { // Why can't the Valid constraint be executed directly? // // It cannot be executed like regular other constraints, because regular // constraints are only executed *if they belong to the validated group*. // The Valid constraint, on the other hand, is always executed and propagates // the group to the cascaded object. The propagated group depends on // // * Whether a group sequence is currently being executed. Then the default // group is propagated. // // * Otherwise the validated group is propagated. throw new ValidatorException(sprintf('The constraint %s cannot be validated. Use the method validate() instead.', get_class($constraint))); } $context->validateValue($value, $constraint, $groups); } return $context->getViolations(); }
public function validateTwo(ExecutionContext $context) { $context->addViolation('Other message', array('other parameter'), 'otherInvalidValue'); }
/** * Validates the data of this form * * This method is called automatically during the validation process. * * @param ExecutionContext $context The current validation context */ public function validateData(ExecutionContext $context) { if (is_object($this->getData()) || is_array($this->getData())) { $groups = $this->getValidationGroups(); $propertyPath = $context->getPropertyPath(); $graphWalker = $context->getGraphWalker(); if (null === $groups) { $groups = array(null); } // The Execute constraint is called on class level, so we need to // set the property manually $context->setCurrentProperty('data'); // Adjust the property path accordingly if (!empty($propertyPath)) { $propertyPath .= '.'; } $propertyPath .= 'data'; foreach ($groups as $group) { $graphWalker->walkReference($this->getData(), $group, $propertyPath, true); } } }
public function testGetPropertyPathWithNestedCollectionsMixed() { $constraints = new Collection(array('foo' => new Collection(array('foo' => new ConstraintA(), 'bar' => new ConstraintA())), 'name' => new ConstraintA())); $visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), $this->translator); $context = new ExecutionContext($visitor, $this->translator, self::TRANS_DOMAIN); $context->validateValue(array('foo' => array('foo' => 'VALID')), $constraints); $violations = $context->getViolations(); $this->assertEquals('[name]', $violations[1]->getPropertyPath()); }
public function isRegionValid(ExecutionContext $context) { if ($this->getCountry() && $this->getCountry()->hasRegions() && !$this->region && !$this->regionText) { // do not allow saving text region in case when region was checked from list // except when in base data region text existed // another way region_text field will be null, logic are placed in form listener $propertyPath = $context->getPropertyPath() . '.region'; $context->addViolationAt($propertyPath, 'Region is required for country %country%', array('%country%' => $this->getCountry()->getName())); } }
public function validateTwo(ExecutionContext $context) { $context->addViolation('Other message', array('{{ value }}' => 'baz'), 'otherInvalidValue'); return false; }