php Symfony-Component-Validator-ConstraintViolationList类(方法)实例源码

下面列出了php Symfony-Component-Validator-ConstraintViolationList 类(方法)源码代码实例,从而了解它的用法。

作者:vpetrovyc    项目:pim-community-de   
/**
  * {@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;
 }

作者:RomanShumko    项目:EcentriaRestBundl   
/**
  * 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());
 }

作者:ibrow    项目:datatran   
public function testViolations()
 {
     $errorHandler = $this->getErrorHandler();
     $violations = new ConstraintViolationList();
     $violations->add($this->createViolation('test'));
     $errorHandler->violations($violations);
 }

作者:netixpr    项目:symfon   
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());
 }

作者:vdumontie    项目:symfon   
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());
 }

作者:ddeboe    项目:data-impor   
function it_validates_an_item_and_the_validation_fails_with_exception(ValidatorInterface $validator, Constraint $constraint, ConstraintViolationList $list)
 {
     $list->count()->willReturn(1);
     $validator->validate($this->item1, Argument::type('Symfony\\Component\\Validator\\Constraints\\Collection'))->willReturn($list);
     $this->throwExceptions(true);
     $this->add('key1', $constraint);
     $this->shouldThrow('Ddeboer\\DataImport\\Exception\\ValidationException')->during__invoke($this->item1);
     $this->getViolations()->shouldReturn([1 => $list]);
 }

作者:Starbuck251    项目:siesta-ke   
private function handleConstraintViolationList(ConstraintViolationList $violationList)
 {
     $errors = [];
     for ($i = 0; $i < $violationList->count(); $i++) {
         $errors['message'] = $violationList[$i]->getMessage();
         $errors['field'] = $violationList[$i]->getPropertyPath();
         $errors['code'] = $violationList[$i]->getCode();
     }
     return $this->errorProcessor->processErrors($errors);
 }

作者:rooste    项目:symfon   
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());
 }

作者:sententiaregu    项目:sententiaregu   
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]);
 }

作者:alexisfroge    项目:pim-community-de   
/**
  * {@inheritdoc}
  */
 public function validate($prices, array $options = [], $attributeCode)
 {
     $violations = new ConstraintViolationList();
     foreach ($prices as $price) {
         if (isset($price['data']) && ($valid = parent::validate($price['data'], $options, $attributeCode))) {
             $violations->addAll($valid);
         }
     }
     return $violations->count() > 0 ? $violations : null;
 }

作者:ddeboe    项目:data-impor   
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());
 }

作者:web3    项目:mincar   
function it_throws_exception_on_validation_failure(MethodInterface $method, ValidatorInterface $validator, ConstraintViolationList $violations)
 {
     $attributes = ['field' => 'value'];
     $constraints = ['constraints'];
     $method->getValidationConstraints()->shouldBeCalled()->willReturn($constraints);
     $method->getAttributes()->shouldBeCalled()->willReturn($attributes);
     $violations->count()->willReturn(1);
     $violations->__toString()->willReturn('');
     $validator->validate($attributes, $constraints)->willReturn($violations);
     $this->shouldThrow('Cardinity\\Exception\\InvalidAttributeValue')->duringValidate($method);
 }

作者:alexisfroge    项目:pim-community-de   
function it_returns_a_constraint_if_the_decimal_separator_is_not_valid($validator)
 {
     $constraintUSD = new ConstraintViolation('Error on number validator', '', [], '', '', '');
     $constraintEUR = new ConstraintViolation('Error on number validator', '', [], '', '', '');
     $constraints = new ConstraintViolationList([$constraintEUR, $constraintUSD]);
     $validator->validate('10,00', Argument::any())->willReturn($constraints);
     $validator->validate('10,05', Argument::any())->willReturn(null);
     $prices = [['data' => '10,00', 'currency' => 'EUR'], ['data' => '10,05', 'currency' => 'USD']];
     $allConstraints = new ConstraintViolationList();
     $allConstraints->addAll($constraints);
     $this->validate($prices, ['decimal_separator' => ','], 'prices')->shouldHaveCount(2);
 }

作者:robstol    项目:PuM   
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;
 }

作者:hunter68    项目:hitechonlin   
/**
  * Get the validation errors
  *
  * @param ConstraintViolationList $errors Validator error list
  *
  * @return View
  */
 protected function getErrorsView(ConstraintViolationList $errors)
 {
     $msgs = array();
     $errorIterator = $errors->getIterator();
     foreach ($errorIterator as $validationError) {
         $msg = $validationError->getMessage();
         $params = $validationError->getMessageParameters();
         $msgs[][] = $this->get('translator')->trans($msg, $params, 'validators');
     }
     $view = View::create($msgs);
     $view->setStatusCode(400);
     return $view;
 }

作者:keek    项目:framewor   
/**
  * 
  * @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;
 }

作者:neokenso    项目:symfon   
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);
 }

作者:vpetrovyc    项目:pim-community-de   
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']]]);
 }

作者:Maksol    项目:platfor   
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);
 }

作者:honeybe    项目:honeybee-agavi-cmf-vendo   
/**
  * Checks whether the given value is a valid URL that may probably be safely used as a redirect url.
  *
  * @param string $value URL to validate
  *
  * @return boolean true if the url is correct
  */
 protected function isValidRedirectUrl($value)
 {
     $validator = Validation::createValidator();
     $constraints = array(new Constraints\Type(array('type' => 'string')), new Constraints\Length(array('min' => $this->getParameter('min_length', 10), 'max' => $this->getParameter('max_length', 1000))), new Constraints\Url(array('protocols' => $this->getParameter('allowed_protocols', array('http', 'https')))));
     if ($this->getParameter('check_base_href', true)) {
         $constraints[] = new Constraints\Callback(array('methods' => array(array($this, 'hasCorrectBaseHref'))));
     }
     $violations = new ConstraintViolationList();
     foreach ($constraints as $constraint) {
         $violations->addAll($validator->validateValue($value, $constraint));
     }
     if ($violations->count() === 0) {
         return true;
     } else {
         $this->getContext()->getLoggerManager()->logTo('default', \AgaviLogger::WARNING, __METHOD__, $violations->__toString());
         return false;
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号