Add a ConstraintViolation to this list.
public add ( |
||
$violation |
public function testExecuteMultipleMethods() { $object = new ExecuteValidatorTest_Object(); $this->assertTrue($this->validator->isValid($object, new Execute(array('validateOne', 'validateTwo')))); $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('My message', array('parameter'), 'Root', 'foo.bar', 'invalidValue')); // context was reset $violations->add(new ConstraintViolation('Other message', array('other parameter'), 'Root', 'initial.property.path', 'otherInvalidValue')); $this->assertEquals($violations, $this->context->getViolations()); }
private function validate($month, array $months) { $errors = new ConstraintViolationList(); if (count($months) == 0) { //TODO check if this is the first month which is terminated => there does not exist a purchase which is done in an earlier month $errors->add(new ConstraintViolation('accounting.previousMonthNotTerminated', 'accounting.previousMonthNotTerminated', ['%prev' => $month - 1, '%current' => $month], $month, 'month', null)); } else { if (count($months) == 2 && !$months[0]->isReopened()) { $errors->add(new ConstraintViolation('accounting.givenMonthAlreadyTerminated', 'accounting.givenMonthAlreadyTerminated', ['%month' => $month], $month, 'month', null)); } } return $errors; }
public function testValidate_multipleGroups() { $entity = new Entity(); $metadata = new ClassMetadata(get_class($entity)); $metadata->addPropertyConstraint('firstName', new FailingConstraint(array('groups' => 'First'))); $metadata->addPropertyConstraint('lastName', new FailingConstraint(array('groups' => 'Second'))); $this->factory->addClassMetadata($metadata); // The constraints of both groups failed $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('', array(), $entity, 'firstName', '')); $violations->add(new ConstraintViolation('', array(), $entity, 'lastName', '')); $result = $this->validator->validate($entity, array('First', 'Second')); $this->assertEquals($violations, $result); }
/** * Test creation of new object * * @return void */ public function testCreateNewObject() { $objectContent = ['id' => 'one', 'second_id' => 'two']; $object = new EntityConverterEntity(); $object->setIds($objectContent); $badProperties = new ConstraintViolationList(); $badProperties->add(new ConstraintViolation('This is not a valid property of CLASS', 'This is not a valid property of CLASS', array(), null, null, null)); $this->crudTransformer->expects($this->any())->method('arrayToObject')->willReturn($object); $this->crudTransformer->expects($this->any())->method('arrayToObjectPropertyValidation')->willReturn($badProperties); $referenceObject = new CircularReferenceEntity(); $this->entityConverter->expects($this->any())->method('find')->willReturn($referenceObject); /** @var EntityConverterEntity $newObject */ $newObject = $this->entityConverter->createOrUpdateNewObject('\\Ecentria\\Libraries\\EcentriaRestBundle\\Tests\\Entity\\EntityConverterEntity', new Request(array(), array(), array(), array(), array(), array(), json_encode($objectContent)), EntityConverter::MODE_CREATE, array('references' => array('class' => 'CircularReferenceEntity', 'name' => 'CircularReferenceEntity')), false); //test validation and references conversion $this->assertEquals($referenceObject, $newObject->getCircularReferenceEntity()); $this->assertEquals($badProperties, $newObject->getViolations()); $this->assertFalse($newObject->isValid()); $secondIds = array('id' => 'test ONE', 'second_id' => 'test TWO'); /** @var EntityConverterEntity $secondObject */ $secondObject = $this->entityConverter->createOrUpdateNewObject('\\Ecentria\\Libraries\\EcentriaRestBundle\\Tests\\Entity\\EntityConverterEntity', new Request(array(), array(), $secondIds, array(), array(), array(), json_encode($objectContent)), EntityConverter::MODE_RETRIEVE, array(), false); //test set ids $this->assertEquals($secondIds, $secondObject->getIds()); // Testing set Ids for update mode $secondObject = $this->entityConverter->createOrUpdateNewObject('\\Ecentria\\Libraries\\EcentriaRestBundle\\Tests\\Entity\\EntityConverterEntity', new Request(array(), array(), $secondIds, array(), array(), array(), json_encode($objectContent)), EntityConverter::MODE_UPDATE, array(), false); //test set ids $this->assertEquals($secondIds, $secondObject->getIds()); }
/** * {@inheritdoc} * * Expected input format : * { * 'attribute': 'maximum_print_size', * 'code': '210_x_1219_mm', * 'sort_order': 2, * 'labels': { * 'de_DE': '210 x 1219 mm', * 'en_US': '210 x 1219 mm', * 'fr_FR': '210 x 1219 mm' * } * } * * @throws BusinessValidationException */ public function update($attributeOption, array $data, array $options = []) { if (!$attributeOption instanceof AttributeOptionInterface) { throw new \InvalidArgumentException(sprintf('Expects a "Pim\\Bundle\\CatalogBundle\\Model\\AttributeOptionInterface", "%s" provided.', ClassUtils::getClass($attributeOption))); } // TODO: ugly fix to workaround issue with "attribute.group.code: This value should not be blank." // in case of existing option, attribute is a proxy, attribute group too, the validated group code is null $attributeOption->getAttribute() !== null ? $attributeOption->getAttribute()->getGroup()->getCode() : null; $isNew = $attributeOption->getId() === null; $readOnlyFields = ['attribute', 'code']; $updateViolations = new ConstraintViolationList(); foreach ($data as $field => $data) { $isReadOnlyField = in_array($field, $readOnlyFields); if ($isNew || !$isReadOnlyField) { try { $this->setData($attributeOption, $field, $data); } catch (\InvalidArgumentException $e) { $setViolation = new ConstraintViolation($e->getMessage(), $e->getMessage(), [], $attributeOption, null, null); $updateViolations->add($setViolation); } } } $validatorViolations = $this->validator->validate($attributeOption); $updateViolations->addAll($validatorViolations); if ($updateViolations->count() > 0) { throw new BusinessValidationException($updateViolations); } return $this; }
public function testViolations() { $errorHandler = $this->getErrorHandler(); $violations = new ConstraintViolationList(); $violations->add($this->createViolation('test')); $errorHandler->violations($violations); }
public function testWalkConstraintBuildsAViolationIfFailed() { $constraint = new ConstraintA(); $this->walker->walkConstraint($constraint, 'foobar', 'Default', 'firstName.path'); $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('message', array('param' => 'value'), 'Root', 'firstName.path', 'foobar')); $this->assertEquals($violations, $this->walker->getViolations()); }
public function testValidateWithErrors() { $violationList = new ConstraintViolationList(); $violation1 = $this->getMockBuilder('Symfony\\Component\\Validator\\ConstraintViolation')->disableOriginalConstructor()->getMock(); $violation1->expects($this->any())->method('getPropertyPath')->will($this->returnValue('from')); $violationList->add($violation1); $violation2 = $this->getMockBuilder('Symfony\\Component\\Validator\\ConstraintViolation')->disableOriginalConstructor()->getMock(); $violation2->expects($this->any())->method('getPropertyPath')->will($this->returnValue('to')); $violationList->add($violation2); $violation3 = $this->getMockBuilder('Symfony\\Component\\Validator\\ConstraintViolation')->disableOriginalConstructor()->getMock(); $violation3->expects($this->any())->method('getPropertyPath')->will($this->returnValue('cc')); $violationList->add($violation3); $this->context->expects($this->any())->method('getViolations')->will($this->returnValue($violationList)); $this->context->expects($this->any())->method('addViolation')->with($this->constraint->message); $this->context->expects($this->any())->method('getPropertyPath')->will($this->returnValue('cc')); $this->getValidator()->validate(['test wrong email 1', 'test wrong email 2'], $this->constraint); }
public function testWalkConstraintBuildsAViolationIfFailed() { $constraint = new ConstraintA(); $this->interpolator->expects($this->once())->method('interpolate')->with($this->equalTo('message'), $this->equalTo(array('param' => 'value')))->will($this->returnValue('interpolated text')); $this->walker->walkConstraint($constraint, 'foobar', 'Default', 'firstName.path'); $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('interpolated text', 'Root', 'firstName.path', 'foobar')); $this->assertEquals($violations, $this->walker->getViolations()); }
/** * {@inheritdoc} */ public function addViolation($message, array $parameters = array(), $invalidValue = NULL, $plural = NULL, $code = NULL) { // The parameters $invalidValue and following are ignored by the new // API, as they are not present in the new interface anymore. // You should use buildViolation() instead. if (func_num_args() > 2) { throw new \LogicException('Legacy validator API is unsupported.'); } $this->violations->add(new ConstraintViolation($this->translator->trans($message, $parameters, $this->translationDomain), $message, $parameters, $this->root, $this->propertyPath, $this->value, NULL, NULL, $this->constraint)); }
/** * {@inheritdoc} */ public function addViolation($message, array $parameters = array(), $invalidValue = null, $plural = null, $code = null) { // The parameters $invalidValue and following are ignored by the new // API, as they are not present in the new interface anymore. // You should use buildViolation() instead. if (func_num_args() > 2) { throw new BadMethodCallException('The parameters $invalidValue, $plural and $code are ' . 'not supported anymore as of Symfony 2.5. Please use ' . 'buildViolation() instead or enable the legacy mode.'); } $this->violations->add(new ConstraintViolation($this->translator->trans($message, $parameters, $this->translationDomain), $message, $parameters, $this->root, $this->propertyPath, $this->value, null, null, $this->constraint)); }
public function testPluralization() { $translator = new IdentityTranslator(); $translator->setLocale('fr'); $service = new I18nResponseFormatBuilder($translator); $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('Two apples', '{0}No apples|{1}One apple|]2,Inf]%count% apples', ['%count%' => 1], null, 'property', 'anything', 1)); $result = $service->formatTranslatableViolationList($violations, false, true, ['en']); $this->assertSame('One apple', $result['en'][0]); }
public function testProcessWithAllowedExtraFields() { $this->filter->addOption('allowExtraFields', true); $data = ['title' => null, 'telephone' => '0155/555-555']; $this->filter->add('title', $constraint = new Constraints\NotNull()); $list = new ConstraintViolationList(); $list->add($this->buildConstraintViolation()); $this->validator->expects($this->once())->method('validate')->willReturn($list); $this->assertFalse($this->filter->process($data)); $this->assertEquals([1 => $list], $this->filter->getViolations()); }
/** * {@inheritdoc} */ public function addViolation($message, array $parameters = array(), $invalidValue = null, $plural = null, $code = null) { // The parameters $invalidValue and following are ignored by the new // API, as they are not present in the new interface anymore. // You should use buildViolation() instead. if (func_num_args() > 2) { @trigger_error('The parameters $invalidValue, $plural and $code in method ' . __METHOD__ . ' are deprecated since version 2.5 and will be removed in 3.0. Use the ' . __CLASS__ . '::buildViolation method instead.', E_USER_DEPRECATED); $this->buildViolation($message, $parameters)->setInvalidValue($invalidValue)->setPlural($plural)->setCode($code)->addViolation(); return; } $this->violations->add(new ConstraintViolation($this->translator->trans($message, $parameters, $this->translationDomain), $message, $parameters, $this->root, $this->propertyPath, $this->value, null, null, $this->constraint)); }
/** * {@inheritdoc} */ public function addViolation() { if (null === $this->plural) { $translatedMessage = $this->translator->trans($this->message, $this->parameters, $this->translationDomain); } else { try { $translatedMessage = $this->translator->transChoice($this->message, $this->plural, $this->parameters, $this->translationDomain); } catch (\InvalidArgumentException $e) { $translatedMessage = $this->translator->trans($this->message, $this->parameters, $this->translationDomain); } } $this->violations->add(new ConstraintViolation($translatedMessage, $this->message, $this->parameters, $this->root, $this->propertyPath, $this->invalidValue, $this->plural, $this->code, $this->constraint, $this->cause)); }
/** * * @return ConstraintViolationList */ public function getViolations() { $list = new ConstraintViolationList(); $errors = $this->get('errors'); if ($errors !== null) { if ($errors instanceof ConstraintViolationList) { return $errors; } foreach ($errors as $error) { $list->add(new ConstraintViolation($error, '', [], '', '', null)); } } return $list; }
function it_throws_an_exception_when_attribute_option_is_not_valid($attributeRepository, $validator, AttributeOptionInterface $attributeOption, AttributeInterface $attribute, AttributeGroupInterface $attributeGroup, AttributeOptionValueInterface $attributeOptionValue) { $attributeOption->getId()->willReturn(null); $attributeOption->getAttribute()->willReturn($attribute); $attribute->getGroup()->willReturn($attributeGroup); $attributeOption->setCode('mycode')->shouldBeCalled(); $attributeRepository->findOneByIdentifier('myattribute')->willReturn(null); $attributeOption->setAttribute($attribute)->shouldNotBeCalled(); $attributeOption->setSortOrder(12)->shouldBeCalled(); $attributeOption->setLocale('de_DE')->shouldBeCalled(); $attributeOption->getTranslation()->willReturn($attributeOptionValue); $attributeOptionValue->setLabel('210 x 1219 mm')->shouldBeCalled(); $violationList = new ConstraintViolationList(); $violationList->add(new ConstraintViolation('', '', [], $attributeOption, null, null)); $validator->validate($attributeOption)->willReturn($violationList); $this->shouldThrow('Pim\\Bundle\\CatalogBundle\\Exception\\BusinessValidationException')->during('update', [$attributeOption, ['code' => 'mycode', 'attribute' => 'myattribute', 'sort_order' => 12, 'labels' => ['de_DE' => '210 x 1219 mm']]]); }
/** * {@inheritDoc} */ public function validateObjectByVarTags($object) { if (!is_object($object)) { throw UnexpectedTypeException::create($object, 'object'); } $classMetadata = $this->metadataFactory->loadMetadata(get_class($object)); $constraintViolationList = new ConstraintViolationList(); foreach ($classMetadata->getProperties() as $propertyName => $propertyMetadata) { $availableVarTypes = $propertyMetadata->getTypes(); if (!count($availableVarTypes)) { continue; } $violationListForProperty = $this->validatePropertyValueByTypes($object, $propertyName, $availableVarTypes); if ($violationListForProperty && count($violationListForProperty)) { foreach ($violationListForProperty as $violationForProperty) { // Recreate violation for save property path $violation = new ConstraintViolation($violationForProperty->getMessage(), $violationForProperty->getMessageTemplate(), $violationForProperty->getMessageParameters(), $violationForProperty->getRoot(), $propertyName, $violationForProperty->getInvalidValue(), $violationForProperty->getMessagePluralization(), $violationForProperty->getCode()); $constraintViolationList->add($violation); } } } return $constraintViolationList; }
private function translateErrors(ConstraintViolationList $errorList, $posNumber) { $list = new ConstraintViolationList(); $translator = $this->get('translator'); foreach ($errorList as $constraint) { $message = $translator->trans($constraint->getMessage(), ["pos" => $posNumber], 'validators'); $list->add(new ConstraintViolation($message, $constraint->getMessageTemplate(), $constraint->getMessageParameters(), $constraint->getRoot(), $constraint->getPropertyPath(), $constraint->getInvalidValue())); } return $list; }
/** * {@inheritdoc} */ public function addViolation($message, array $parameters = array()) { $this->violations->add(new ConstraintViolation($this->translator->trans($message, $parameters, $this->translationDomain), $message, $parameters, $this->root, $this->propertyPath, $this->value, null, null, $this->constraint)); }
/** * Validate params. * * @param \Symfony\Component\Validator\Validator $validator * @param array $params * @param \Symfony\Component\HttpFoundation\ParameterBag $values * * @return \Symfony\Component\Validator\ConstraintViolationList */ protected function validateParams(Validator $validator, array $params, ParameterBag $values) { $violations = new ConstraintViolationList(); foreach ($params as $param) { if (empty($param['requirements'])) { continue; } $value = $values->get($param['name']); $paramViolations = $validator->validateValue($value, $param['requirements']); // add missing data foreach ($paramViolations as $violation) { $extendedViolation = new ConstraintViolation($violation->getMessage(), $violation->getMessageTemplate(), $violation->getMessageParameters(), $violation->getRoot(), $param['name'] . $violation->getPropertyPath(), $violation->getInvalidValue(), $violation->getMessagePluralization(), $violation->getCode()); $violations->add($extendedViolation); } } return $violations; }
/** * @param $userId * @param $workTimeId * @param $endDateRequest * @param $durationRequest * @param $descriptionRequest * @return WorkTimeDTO * @throws ValidationException * @throws WorkTimeNotActiveException * @throws WorkTimeNotFoundException */ public function stopWorkTime($userId, $workTimeId, $endDateRequest, $durationRequest, $descriptionRequest) { $workTime = $this->workTimeRepository->findWorkTimeByUserAndId($userId, $workTimeId); if ($workTime === null) { throw new WorkTimeNotFoundException(); } if ($workTime->getEndDate() !== null) { throw new WorkTimeNotActiveException(); } $validations = array(array($endDateRequest, array(new NotNull(), new DateTime()), 'endDate'), array($durationRequest, array(new NotNull(), new Regex(array('value' => '/([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]/'))), 'duration'), array($descriptionRequest, array(new Length(array('min' => 5, 'max' => '255'))))); $validationErrors = new ConstraintViolationList(); foreach ($validations as $values) { $errors = $this->validator->validate($values[0], $values[1]); if ($errors->count() > 0) { foreach ($errors as $error) { /* @var $error ConstraintViolationInterface */ $validationErrors->add(new ConstraintViolation($error->getMessage(), $error->getMessageTemplate(), $error->getMessageParameters(), $error->getRoot(), $values[2], $error->getInvalidValue())); } } } if ($validationErrors->count() > 0) { throw new ValidationException($validationErrors); } $duration = new \DateTime(); $durationRequest = explode(':', $durationRequest); $duration->setTime($durationRequest[0], $durationRequest[1], 0); $endDate = new \DateTime($endDateRequest); $this->workTimeRepository->stopWorkTime($workTime, $endDate, $duration, $descriptionRequest); return WorkTimeDTO::withEntity($workTime); }
public function testConstraintViolationList() { $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('Message of violation', "Message of violation", array(), null, 'foo', null)); $violations->add(new ConstraintViolation('Message of another violation', "Message of another violation", array(), null, 'bar', null)); $this->assertEquals($this->getContent('constraint_violation_list'), $this->serialize($violations)); }
/** * Bulk permissions create/update. * * * @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER')") */ public function postPermissionMapAction(Request $request) { $permissionMap = $request->request->all(); $aclManager = $this->getContainer()->get("security.acl_manager"); $violations = new ConstraintViolationList(); foreach ($permissionMap as $i => $objectMap) { $permissions = $objectMap['permissions']; if (!isset($objectMap['object_class'])) { $violations->add(new ConstraintViolation("Object class not supllied", "Object class not supllied", [], sprintf('%s[object_class]', $i), sprintf('%s[object_class]', $i), null)); continue; } $objectClass = $objectMap['object_class']; $objectId = null; if (!class_exists($objectClass)) { $violations->add(new ConstraintViolation("Class {$objectClass} doesn't exist", "Class {$objectClass} doesn't exist", [], sprintf('%s[object_class]', $i), sprintf('%s[object_class]', $i), $objectClass)); continue; } $objectIdentity = null; if (isset($objectMap['object_id'])) { $objectId = $objectMap['object_id']; // object scope $objectIdentity = new ObjectIdentity($objectId, $objectClass); } else { // class scope $objectIdentity = new ObjectIdentity('class', $objectClass); } if (!isset($objectMap['sid'])) { $violations->add(new ConstraintViolation("Security ID not supllied", "Security ID not supllied", [], sprintf('%s[sid]', $i), sprintf('%s[sid]', $i), null)); continue; } $sid = $objectMap['sid']; $securityIdentity = new UserSecurityIdentity($sid, 'BackBee\\Security\\Group'); // convert values to booleans $permissions = array_map(function ($val) { return \BackBee\Utils\StringUtils::toBoolean((string) $val); }, $permissions); // remove false values $permissions = array_filter($permissions); $permissions = array_keys($permissions); $permissions = array_unique($permissions); try { $mask = $aclManager->getMask($permissions); } catch (\BackBee\Security\Acl\Permission\InvalidPermissionException $e) { $violations->add(new ConstraintViolation($e->getMessage(), $e->getMessage(), [], sprintf('%s[permissions]', $i), sprintf('%s[permissions]', $i), $e->getPermission())); continue; } if ($objectId) { $aclManager->insertOrUpdateObjectAce($objectIdentity, $securityIdentity, $mask); } else { $aclManager->insertOrUpdateClassAce($objectIdentity, $securityIdentity, $mask); } } if (count($violations) > 0) { throw new ValidationException($violations); } return new Response('', 204); }
/** * {@inheritdoc} */ public function add(ConstraintViolationInterface $violation) { parent::add($violation); $this->violationOffsetsByField = NULL; $this->entityViolationOffsets = NULL; }
/** * Moves the property path to be relative to field level. * * @param string $field_name * The field name. * @param \Symfony\Component\Validator\ConstraintViolationListInterface $violations * The violations. * * @return \Symfony\Component\Validator\ConstraintViolationList * A new constraint violation list with the changed property path. */ protected function movePropertyPathViolationsRelativeToField($field_name, ConstraintViolationListInterface $violations) { $new_violations = new ConstraintViolationList(); foreach ($violations as $violation) { // All the logic below is necessary to change the property path of the // violations to be relative to the item list, so like title.0.value gets // changed to 0.value. Sadly constraints in Symfony don't have setters so // we have to create new objects. /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */ // Create a new violation object with just a different property path. $violation_path = $violation->getPropertyPath(); $path_parts = explode('.', $violation_path); if ($path_parts[0] === $field_name) { unset($path_parts[0]); } $new_path = implode('.', $path_parts); $constraint = NULL; $cause = NULL; $parameters = []; $plural = NULL; if ($violation instanceof ConstraintViolation) { $constraint = $violation->getConstraint(); $cause = $violation->getCause(); $parameters = $violation->getParameters(); $plural = $violation->getPlural(); } $new_violation = new ConstraintViolation($violation->getMessage(), $violation->getMessageTemplate(), $parameters, $violation->getRoot(), $new_path, $violation->getInvalidValue(), $plural, $violation->getCode(), $constraint, $cause); $new_violations->add($new_violation); } return $new_violations; }
/** * Array to object property validation * * @param array $data Object fields * @param string $class Class name of object to test * @return ConstraintViolationList */ public function arrayToObjectPropertyValidation(array $data, $class) { $badProperties = new ConstraintViolationList(); foreach ($data as $property => $value) { if (!$this->isPropertyAccessible($property, PropertyRestriction::CREATE)) { $badProperties->add(new ConstraintViolation("This is not a valid property of {$class}", "This is not a valid property of {$class}", array(), null, $property, $value)); } } return $badProperties; }
public function testValidateValue() { $violations = new ConstraintViolationList(); $violations->add(new ConstraintViolation('Failed', 'Failed', array(), 'Bernhard', '', 'Bernhard')); $this->assertEquals($violations, $this->validator->validateValue('Bernhard', new FailingConstraint())); }
/** * Preparing Violation List * * @return ConstraintViolationList */ private function prepareViolationList() { $violationList = new ConstraintViolationList(); $violation = $this->prepareViolation(); $violationList->add($violation); return $violationList; }