コード例 #1
0
ファイル: Validator.php プロジェクト: KasaiDot/FoolFrame
 /**
  * Runs the validation against the provided array of fields
  *
  * @param array $data
  */
 public function validate(array $data)
 {
     $this->original_values = $data;
     $this->final_values = $data;
     $validator = SymfonyValidation::createValidator();
     $violations_arr = [];
     $this->violations = new ViolationCollection([]);
     foreach ($this->constraints as $key => $constraint) {
         // we always keep the variables set someway
         if (!isset($this->final_values[$key])) {
             $this->final_values[$key] = false;
         }
         // if it isn't an array and we just request a Trim
         if (!is_array($constraint) && $constraint instanceof ActiveConstraint) {
             $this->final_values[$key] = $constraint->run($this->final_values[$key]);
             // it's not a classic symfony constraint, get rid of it
             $constraint = [];
         }
         if (is_array($constraint)) {
             foreach ($constraint as $k => $c) {
                 if ($c instanceof ActiveConstraint) {
                     $this->final_values[$key] = $c->run($this->final_values[$key]);
                     // it's not a classic symfony constraint, get rid of it
                     unset($constraint[$k]);
                 }
             }
         }
         $violations = $validator->validateValue($this->final_values[$key], $constraint);
         if ($violations->count() > 0) {
             $violations_arr[$key] = new Violation($violations, $key, $this->labels[$key]);
         }
         $this->violations = new ViolationCollection($violations_arr);
     }
 }
コード例 #2
0
 public function __construct()
 {
     $builder = Validation::createValidatorBuilder();
     $builder->setConstraintValidatorFactory(new ConstraintValidatorFactory());
     $builder->setMetadataFactory(new LazyLoadingMetadataFactory(new StaticMethodLoader()));
     parent::__construct($builder->getValidator());
 }
コード例 #3
0
 public function getMetaValidator($allowedLocales = array(), $intlExtension = false, $strict = false)
 {
     $factory = new ConstraintValidatorFactory($this->getLocaleValidator($intlExtension), $this->getLocaleAllowedValidator($intlExtension, $allowedLocales, $strict));
     $validator = Validation::createValidatorBuilder();
     $validator->setConstraintValidatorFactory($factory);
     return new MetaValidator($validator->getValidator());
 }
コード例 #4
0
 public function register(Application $app)
 {
     $app['validator'] = $app->share(function ($app) {
         return $app['validator.builder']->getValidator();
     });
     $app['validator.builder'] = $app->share(function ($app) {
         $builder = Validation::createValidatorBuilder();
         $builder->setConstraintValidatorFactory($app['validator.validator_factory']);
         $builder->setTranslationDomain('validators');
         $builder->addObjectInitializers($app['validator.object_initializers']);
         $builder->setMetadataFactory($app['validator.mapping.class_metadata_factory']);
         if (isset($app['translator'])) {
             $builder->setTranslator($app['translator']);
         }
         return $builder;
     });
     $app['validator.mapping.class_metadata_factory'] = $app->share(function ($app) {
         if (class_exists('Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory')) {
             return new LazyLoadingMetadataFactory(new StaticMethodLoader());
         }
         return new ClassMetadataFactory(new StaticMethodLoader());
     });
     $app['validator.validator_factory'] = $app->share(function () use($app) {
         return new ConstraintValidatorFactory($app, $app['validator.validator_service_ids']);
     });
     $app['validator.object_initializers'] = $app->share(function ($app) {
         return array();
     });
     $app['validator.validator_service_ids'] = array();
 }
コード例 #5
0
 /**
  * @return array
  */
 protected function getExtensions()
 {
     $accountUserRoleSelectType = new EntitySelectTypeStub($this->getRoles(), AccountUserRoleSelectType::NAME, new AccountUserRoleSelectType());
     $addressEntityType = new EntityType($this->getAddresses(), 'test_address_entity');
     $accountSelectType = new AccountSelectTypeStub($this->getAccounts(), AccountSelectType::NAME);
     return [new PreloadedExtension([OroDateType::NAME => new OroDateType(), AccountUserRoleSelectType::NAME => $accountUserRoleSelectType, $accountSelectType->getName() => $accountSelectType, AddressCollectionTypeStub::NAME => new AddressCollectionTypeStub(), $addressEntityType->getName() => $addressEntityType], []), new ValidatorExtension(Validation::createValidator())];
 }
コード例 #6
0
 /**
  * @param Reader $reader
  *
  * @return ValidatorInterface
  */
 public function getValidator(Reader $reader = null)
 {
     if (null === $reader) {
         $reader = new AnnotationReader();
     }
     return Validation::createValidatorBuilder()->enableAnnotationMapping($reader)->getValidator();
 }
コード例 #7
0
 protected function setUp()
 {
     parent::setUp();
     $this->serializer = SerializerBuilder::create()->build();
     $this->validator = Validation::createValidator();
     $this->action->setSerializer($this->serializer)->setValidator($this->validator);
 }
コード例 #8
0
 public function validate(array $parameters)
 {
     $validator = Validation::createValidator();
     $constraints = new Collection(['method' => new Assert\Required(), 'source_id' => [new Assert\Required(), new Assert\Length(['max' => 45])], 'amount' => [new Assert\GreaterThan(0), new Assert\Required()], 'currency' => [new Assert\Length(3), new Assert\Optional()], 'description' => [new Assert\Length(['max' => 250]), new Assert\Required()], 'order_id' => [new Assert\Length(['max' => 100]), new Assert\Optional()], 'device_session_id' => [new Assert\Length(['max' => 255]), new Assert\Optional()], 'capture' => new Assert\Optional(), 'customer' => new Assert\Optional(), 'metadata' => new Assert\Optional(), 'use_card_points' => new Assert\Optional()]);
     $violations = $validator->validate($parameters, $constraints);
     return $violations;
 }
コード例 #9
0
 public function register(Container $app)
 {
     $app['validator'] = function ($app) {
         if (isset($app['translator'])) {
             $r = new \ReflectionClass('Symfony\\Component\\Validator\\Validation');
             $file = dirname($r->getFilename()) . '/Resources/translations/validators.' . $app['locale'] . '.xlf';
             if (file_exists($file)) {
                 $app['translator']->addResource('xliff', $file, $app['locale'], 'validators');
             }
         }
         return $app['validator.builder']->getValidator();
     };
     $app['validator.builder'] = function ($app) {
         $builder = Validation::createValidatorBuilder();
         $builder->setConstraintValidatorFactory($app['validator.validator_factory']);
         $builder->setTranslationDomain('validators');
         $builder->addObjectInitializers($app['validator.object_initializers']);
         $builder->setMetadataFactory($app['validator.mapping.class_metadata_factory']);
         if (isset($app['translator'])) {
             $builder->setTranslator($app['translator']);
         }
         return $builder;
     };
     $app['validator.mapping.class_metadata_factory'] = function ($app) {
         return new LazyLoadingMetadataFactory(new StaticMethodLoader());
     };
     $app['validator.validator_factory'] = function () use($app) {
         $validators = isset($app['validator.validator_service_ids']) ? $app['validator.validator_service_ids'] : array();
         return new ConstraintValidatorFactory($app, $validators);
     };
     $app['validator.object_initializers'] = function ($app) {
         return array();
     };
 }
コード例 #10
0
 public function validate(array $parameters)
 {
     $validator = Validation::createValidator();
     $constraints = new Collection(['token_id' => new Assert\Required(), 'device_session_id' => new Assert\Optional()]);
     $violations = $validator->validate($parameters, $constraints);
     return $violations;
 }
コード例 #11
0
 public function validate(array $parameters)
 {
     $validator = Validation::createValidator();
     $constraints = new Collection(['line1' => new Assert\Required(), 'line2' => new Assert\Optional(), 'line3' => new Assert\Optional(), 'postal_code' => new Assert\Length(['min' => 5]), 'state' => [new Assert\Length(['min' => 2]), new Assert\Required()], 'city' => new Assert\Required(), 'country_code' => [new Assert\Length(['min' => 2, 'max' => 2]), new Assert\Required()]]);
     $violations = $validator->validate($parameters, $constraints);
     return $violations;
 }
コード例 #12
0
 public function testConstraintsValidatorCanBeModified()
 {
     $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     Configuration::setConstraintsValidator($validator);
     $returnedValidator = Configuration::getConstraintsValidator();
     $this->assertEquals($validator, $returnedValidator);
 }
コード例 #13
0
 public function validate(array $parameters)
 {
     $validator = Validation::createValidator();
     $constraints = new Collection(['customer_id' => [new Assert\Required(), new Assert\Length(['max' => 45])], 'amount' => [new Assert\GreaterThan(0), new Assert\Required()], 'description' => [new Assert\Length(['max' => 250]), new Assert\Required()], 'order_id' => [new Assert\Length(['max' => 100]), new Assert\Optional()]]);
     $violations = $validator->validate($parameters, $constraints);
     return $violations;
 }
コード例 #14
0
ファイル: SetScoreTest.php プロジェクト: pdt256/vbscraper
 public function testPassesValidationWithNullScoreWithForfeit()
 {
     $setScore = new SetScore();
     $setScore->setTeamBForfeit();
     $validator = Validation::createValidatorBuilder()->addMethodMapping('loadValidatorMetadata')->getValidator();
     $this->assertEmpty($validator->validate($setScore));
 }
コード例 #15
0
 /**
  * Setting up the validator.
  */
 protected function setUp()
 {
     $this->now = new \DateTime();
     $this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     $this->baseVacancy = new Vacancy();
     $this->baseVacancy = $this->baseVacancy->setId(1)->setTitle("this is a title")->setDescription("this is a description for a vacancy")->setStartDate($this->now)->setUrlid("/vacancy/this_is_a_title");
 }
コード例 #16
0
ファイル: TwigView.php プロジェクト: deltaphp/deltacore
 protected function getFormValidator()
 {
     if (is_null($this->formValidator)) {
         $this->formValidator = \Symfony\Component\Validator\Validation::createValidator();
     }
     return $this->formValidator;
 }
コード例 #17
0
 /**
  * @param      $type
  * @param      $value
  * @param null $f
  *
  * @return array
  */
 public function validateFieldValue($type, $value, $f = null)
 {
     $errors = array();
     if (isset($this->types[$type]['constraints'])) {
         $validator = Validation::createValidator();
         foreach ($this->types[$type]['constraints'] as $constraint => $opts) {
             //don't check empty values unless the constraint is NotBlank
             if (strpos($constraint, 'NotBlank') === false && empty($value)) {
                 continue;
             }
             if ($type == 'captcha' && strpos($constraint, 'EqualTo') !== false) {
                 $props = $f->getProperties();
                 $opts['value'] = $props['captcha'];
             }
             $violations = $validator->validateValue($value, new $constraint($opts));
             if (count($violations)) {
                 foreach ($violations as $v) {
                     $transParameters = $v->getMessageParameters();
                     if ($f !== null) {
                         $transParameters['%label%'] = """ . $f->getLabel() . """;
                     }
                     $errors[] = $this->translator->trans($v->getMessage(), $transParameters, 'validators');
                 }
             }
         }
     }
     return $errors;
 }
コード例 #18
0
 public function validate()
 {
     $this->helper = (include FrontController::getRootPath() . "/src/cli_config.php");
     $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     $violations = $validator->validate($this);
     return $violations;
 }
コード例 #19
0
ファイル: MatchTest.php プロジェクト: pdt256/vbscraper
 public function testCreate()
 {
     $teamA = new Team();
     $teamA->setPlayerA(new Player(1, 'John Doe'));
     $teamA->setPlayerB(new Player(2, 'James Doe'));
     $teamB = new Team();
     $teamB->setPlayerA(new Player(3, 'John Smith'));
     $teamB->setPlayerB(new Player(4, 'James Smith'));
     $setScore = new SetScore();
     $setScore->setScoresByString('21-18');
     $match = new Match();
     $match->setTeamA($teamA);
     $match->setTeamB($teamB);
     $match->addSetScore($setScore);
     $match->addSetScoreByString('21-16');
     $match->setGameTimeLengthInSeconds(5);
     $validator = Validation::createValidatorBuilder()->addMethodMapping('loadValidatorMetadata')->getValidator();
     $this->assertEmpty($validator->validate($match));
     $this->assertTrue($match->getTeamA() instanceof Team);
     $this->assertTrue($match->getTeamB() instanceof Team);
     $this->assertSame(2, count($match->getSetScores()));
     $this->assertTrue($match->getSetscores()[0] instanceof SetSCore);
     $this->assertTrue($match->getSetscore(1) instanceof SetSCore);
     $this->assertSame(null, $match->getSetScore(3));
     $this->assertSame(5, $match->getGameTimeLengthInSeconds());
     $this->assertSame('[(1) John Doe, (2) James Doe] def [(3) John Smith, (4) James Smith]', $match->__toString());
 }
コード例 #20
0
 public function __construct()
 {
     $this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     $this->getSetNormalizer = new GetSetMethodNormalizer();
     $this->builder = new Builder();
     $this->annotationReader = new AnnotationReader();
 }
コード例 #21
0
 /**
  * @return ValidatorInterface
  */
 public function getValidator()
 {
     if (is_null($this->validator)) {
         $this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping($this->getAnnotationReader())->getValidator();
     }
     return $this->validator;
 }
コード例 #22
0
 public function register(Container $app)
 {
     $app['validator'] = function ($app) {
         return $app['validator.builder']->getValidator();
     };
     $app['validator.builder'] = function ($app) {
         $builder = Validation::createValidatorBuilder();
         $builder->setConstraintValidatorFactory($app['validator.validator_factory']);
         $builder->setTranslationDomain('validators');
         $builder->addObjectInitializers($app['validator.object_initializers']);
         $builder->setMetadataFactory($app['validator.mapping.class_metadata_factory']);
         if (isset($app['translator'])) {
             $builder->setTranslator($app['translator']);
         }
         return $builder;
     };
     $app['validator.mapping.class_metadata_factory'] = function ($app) {
         return new LazyLoadingMetadataFactory(new StaticMethodLoader());
     };
     $app['validator.validator_factory'] = function () use($app) {
         return new ConstraintValidatorFactory($app, $app['validator.validator_service_ids']);
     };
     $app['validator.object_initializers'] = function ($app) {
         return array();
     };
     $app['validator.validator_service_ids'] = array();
 }
コード例 #23
0
 /**
  * Search by isbn
  *
  * @param  string $isbn
  * @return array
  */
 public function searchByIsbn($isbn)
 {
     $isbn = trim($isbn);
     $isbn = str_replace('-', '', $isbn);
     // Validate isbn
     $validator = Validation::createValidator();
     $violations = $validator->validateValue($isbn, new Isbn());
     if (count($violations) > 0) {
         return false;
     }
     // Use providers to search for book
     foreach ($this->providers as $provider) {
         $result = $provider['provider']->searchByIsbn($isbn)->getResult();
         if ($result) {
             if (isset($provider['name']) && null !== $provider['name']) {
                 $providerName = $provider['name'];
             } else {
                 $providerName = $provider['provider']->getDefaultName();
             }
             $response = new BookFinderResponse();
             $response->setProvider($provider['provider']);
             $response->setResult($result);
             $response->setProviderName($providerName);
             return $response;
         }
     }
     return false;
 }
コード例 #24
0
ファイル: UsersController.php プロジェクト: swos-/slim-api
 public function createUser()
 {
     $user = new Test\User();
     $post = $this->app->request()->getBody();
     $data = json_decode($post);
     var_dump($data);
     $user->name = $data->name;
     $user->email = $data->email;
     var_dump($user);
     /*
             $validator = Validation::createValidator();
     $constraint = new Assert\Collection(array(
                 'email' => new Assert\Email(),
                 'name' => new Assert\Length(array('min' => 10)),
             ));
     $violations = $validator->validateValue($data, $constraint);
     */
     $builder = Validation::createValidatorBuilder();
     $builder->addYamlMapping(__DIR__ . '/rules.yml');
     $validator = $builder->getValidator();
     $violations = $validator->validate($user);
     if (0 === count($violations)) {
         echo 'valid';
     } else {
         foreach ($violations as $violation) {
             echo $violation->getMessage();
         }
     }
 }
コード例 #25
0
ファイル: BaseForm.php プロジェクト: alex63530/thelia
 public function __construct(Request $request, $type = "form", $data = array(), $options = array())
 {
     $this->request = $request;
     $validator = Validation::createValidatorBuilder();
     if (!isset($options["attr"]["name"])) {
         $options["attr"]["thelia_name"] = $this->getName();
     }
     $builder = Forms::createFormFactoryBuilder()->addExtension(new HttpFoundationExtension());
     if (!isset($options["csrf_protection"]) || $options["csrf_protection"] !== false) {
         $builder->addExtension(new CsrfExtension(new SessionCsrfProvider($request->getSession(), isset($options["secret"]) ? $options["secret"] : ConfigQuery::read("form.secret", md5(__DIR__)))));
     }
     $translator = Translator::getInstance();
     $validator->setTranslationDomain('validators')->setTranslator($translator);
     $this->formBuilder = $builder->addExtension(new ValidatorExtension($validator->getValidator()))->getFormFactory()->createNamedBuilder($this->getName(), $type, $data, $this->cleanOptions($options));
     $this->buildForm();
     // If not already set, define the success_url field
     // This field is not included in the standard form hidden fields
     // This field is not included in the hidden fields generated by form_hidden_fields Smarty function
     if (!$this->formBuilder->has('success_url')) {
         $this->formBuilder->add("success_url", "hidden");
     }
     // The "error_message" field defines the error message displayed if
     // the form could not be validated. If it is empty, a standard error message is displayed instead.
     // This field is not included in the hidden fields generated by form_hidden_fields Smarty function
     if (!$this->formBuilder->has('error_message')) {
         $this->formBuilder->add("error_message", "hidden");
     }
     $this->form = $this->formBuilder->getForm();
 }
コード例 #26
0
 /**
  * FormFactory constructor.
  * @param Container $container
  */
 public function __construct(Container $container)
 {
     # configuring the form factory
     $this->formFactory = Forms::createFormFactoryBuilder()->addExtension(new DoctrineOrmExtension(new ExtendedEntityManager($container->get('models'))))->addExtension(new ValidatorExtension(Validation::createValidator()))->getFormFactory();
     # registering all necessary smarty plugins
     new SmartyPlugins($this->getFormHelper(), $container->get('template'));
 }
コード例 #27
0
 public function __construct($form_config, $csrf_provider_service)
 {
     FormService::validate($form_config);
     $this->config = $form_config;
     // $csrfProvider = new DefaultCsrfProvider( $form_config['csrf_secret'] );
     // setup forms to use csrf and validator component
     $this->formFactory = Forms::createFormFactoryBuilder()->addExtension(new CsrfExtension($csrf_provider_service))->addExtension(new ValidatorExtension(Validation::createValidator()))->addExtension(new HttpFoundationExtension())->getFormFactory();
 }
コード例 #28
0
ファイル: ObjectValidationTrait.php プロジェクト: fliglio/web
 public function validate()
 {
     $validator = SymphonyValidation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     $violations = $validator->validate($this);
     if ($violations->count() > 0) {
         throw new ValidationException($violations);
     }
 }
コード例 #29
0
ファイル: BinderTest.php プロジェクト: pugx/bindto
 /**
  * @test
  * @expectedException \Bindto\Exception\MapperNotFoundException
  */
 public function shouldRaiseException()
 {
     $vars = ['title' => 'yes', 'body' => 'Lorem ipsum dolor sit amet, consectetuer adipi', 'seoTitle' => 'slug of lorem ', 'seoDescription' => 'Lorem ipsum dolor sit amet, consectetuer adipi'];
     $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
     $mapper = new MapperStrategy();
     $binder = new Binder($validator, $mapper);
     $binder->bind($vars, \Bindto\Fixtures\DTOCreatePage::class);
 }
コード例 #30
0
 /**
  * @return array
  */
 protected function getExtensions()
 {
     $entityType = new EntityType([1 => $this->getEntity('OroB2B\\Bundle\\PricingBundle\\Entity\\PriceList', 1), 2 => $this->getEntity('OroB2B\\Bundle\\PricingBundle\\Entity\\PriceList', 2)]);
     $productUnitSelection = new EntityType($this->prepareProductUnitSelectionChoices(), ProductUnitSelectionType::NAME);
     $priceType = new PriceType();
     $priceType->setDataClass('Oro\\Bundle\\CurrencyBundle\\Model\\Price');
     return [new PreloadedExtension([$entityType->getName() => $entityType, PriceListSelectType::NAME => new PriceListSelectTypeStub(), ProductUnitSelectionType::NAME => $productUnitSelection, PriceType::NAME => $priceType, CurrencySelectionType::NAME => new CurrencySelectionTypeStub()], []), new ValidatorExtension(Validation::createValidator())];
 }