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;
 }
 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;
 }
Example #3
0
 protected function getFormValidator()
 {
     if (is_null($this->formValidator)) {
         $this->formValidator = \Symfony\Component\Validator\Validation::createValidator();
     }
     return $this->formValidator;
 }
 /**
  * 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'));
 }
Example #5
0
 /**
  * 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);
     }
 }
Example #6
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;
 }
 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;
 }
 /**
  * @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;
 }
 /**
  * @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())];
 }
 protected function setUp()
 {
     parent::setUp();
     $this->serializer = SerializerBuilder::create()->build();
     $this->validator = Validation::createValidator();
     $this->action->setSerializer($this->serializer)->setValidator($this->validator);
 }
 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;
 }
 /**
  * @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())];
 }
 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();
 }
Example #14
0
 public function validate()
 {
     $validator = SymphonyValidation::createValidator();
     $violations = $validator->validateValue($this->val, $this->constraints);
     if ($violations->count() > 0) {
         throw new ValidationException($violations);
     }
 }
Example #15
0
 /**
  * @param $data
  * @param $service
  * @return \Symfony\Component\Validator\ConstraintViolationListInterface
  */
 public static function validateData($data, $service)
 {
     $translator = Translator::getInstance();
     $validator = Validation::createValidator();
     $constraints = new Constraints\Collection(['fields' => ['tnt_service' => [new Constraints\Choice(['choices' => array('INDIVIDUAL', 'ENTERPRISE', 'DEPOT', 'DROPOFFPOINT'), 'message' => $translator->trans('Unknown service', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['INDIVIDUAL', 'ENTERPRISE', 'DEPOT', 'DROPOFFPOINT']])], 'tnt_serviceCode' => [new Constraints\Length(['min' => 1, 'minMessage' => $translator->trans('The service is not valid', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['INDIVIDUAL', 'ENTERPRISE', 'DEPOT', 'DROPOFFPOINT']])], 'tnt_instructions' => [new Constraints\Length(['min' => 0, 'max' => 60, 'maxMessage' => $translator->trans('Instructions are too long', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['INDIVIDUAL', 'ENTERPRISE', 'DEPOT', 'DROPOFFPOINT']])], 'tnt_contactLastName' => [new Constraints\NotBlank(['groups' => ['DEPOT', 'DROPOFFPOINT']]), new Constraints\Length(['min' => 0, 'max' => 19, 'maxMessage' => $translator->trans('Last name is too long', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['DEPOT', 'DROPOFFPOINT']])], 'tnt_contactFirstName' => [new Constraints\NotBlank(['groups' => ['DEPOT', 'DROPOFFPOINT']]), new Constraints\Length(['min' => 0, 'max' => 12, 'maxMessage' => $translator->trans('First name is too long', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['DEPOT', 'DROPOFFPOINT']])], 'tnt_emailAdress' => [new Constraints\Email(['groups' => ['DEPOT', 'DROPOFFPOINT']]), new Constraints\Length(['min' => 0, 'max' => 60, 'maxMessage' => $translator->trans('Email is too long', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['DEPOT', 'DROPOFFPOINT']])], 'tnt_phoneNumber' => [new Constraints\NotBlank(['groups' => ['INDIVIDUAL', 'DROPOFFPOINT']]), new Constraints\Length(['min' => 0, 'max' => 60, 'maxMessage' => $translator->trans('Phone number is too long', [], TNTFrance::MESSAGE_DOMAIN), 'groups' => ['INDIVIDUAL', 'DROPOFFPOINT']])], 'tnt_pexcode' => new Constraints\NotBlank(['groups' => ['DEPOT']]), 'tnt_depot_address' => new Constraints\NotBlank(['groups' => ['DEPOT']]), 'tnt_xettcode' => new Constraints\NotBlank(['groups' => ['DROPOFFPOINT']]), 'tnt_dop_address' => new Constraints\NotBlank(['groups' => ['DROPOFFPOINT']])], 'allowMissingFields' => true, 'allowExtraFields' => true]);
     $errors = $validator->validateValue($data, $constraints, [$service]);
     return $errors;
 }
Example #16
0
 /**
  * {inheritdoc}.
  */
 public function isValid($data)
 {
     $validator = Validation::createValidator();
     $constraint = new Assert\Collection(array('tag' => array(new Assert\NotNull(), new Assert\NotBlank(), new Assert\Type(array('type' => 'string')), new Assert\Regex(array('pattern' => '/(^v?)\\d+\\.\\d+(\\.\\d+)?$/')))));
     if (count($validator->validate(array('tag' => $data), $constraint)) > 0) {
         return false;
     }
     return true;
 }
Example #17
0
 protected function setUp()
 {
     $this->repository = $this->getMockBuilder('Trismegiste\\SocialBundle\\Repository\\PublishingRepository')->disableOriginalConstructor()->getMock();
     $this->repository->expects($this->any())->method('create')->will($this->returnValue($this->createData()));
     $validator = Validation::createValidator();
     $type = $this->createType();
     $this->factory = Forms::createFormFactoryBuilder()->addExtension(new ValidatorExtension($validator))->addType(new PublishingType($this->repository))->addType($type)->getFormFactory();
     $this->sut = $this->factory->create($type->getName());
 }
Example #18
0
 /**
  * FormFieldHelper constructor.
  *
  * @param TranslatorInterface $translator
  * @param ValidatorInterface  $validator
  */
 public function __construct(TranslatorInterface $translator, ValidatorInterface $validator = null)
 {
     $this->translator = $translator;
     if (null === $validator) {
         $validator = $validator = Validation::createValidator();
     }
     $this->validator = $validator;
     parent::__construct();
 }
 protected function setUp()
 {
     parent::setUp();
     /** @var Serializer $serializer */
     $serializer = self::$kernel->getContainer()->get('tpg_extjs.orm_serializer');
     $this->serializer = $serializer;
     $this->validator = Validation::createValidator();
     $this->action->setSerializer($this->serializer)->setValidator($this->validator);
 }
Example #20
0
 /**
  * Public factory method to create instance of Client.
  *
  * @param array $options Available properties: [
  *     'apiKey' => 'xxxxxx',
  *     'sandbox' => true,
  *     'url' => 'https://api.isign.io',
  *     'sandboxUrl' => 'https://developers.isign.io',
  * ]
  * @param LoggerInterface|callable|resource|null $logger Logger used to log
  *     messages. Pass a LoggerInterface to use a PSR-3 logger. Pass a
  *     callable to log messages to a function that accepts a string of
  *     data. Pass a resource returned from ``fopen()`` to log to an open
  *     resource. Pass null or leave empty to write log messages using
  *     ``echo()``.
  * @return self
  */
 public static function create(array $options = [], $log = false)
 {
     $client = new \GuzzleHttp\Client();
     if ($log !== false) {
         $subscriber = new LogSubscriber($log);
         $client->getEmitter()->attach($subscriber);
     }
     return new self(new GuzzleClientAdapter($client), new ResponseMapper(), Validation::createValidator(), $options);
 }
Example #21
0
 public function setUp()
 {
     $factoryBuilder = Forms::createFormFactoryBuilder();
     $factoryBuilder->addExtension(new ValidatorExtension(Validation::createValidator()));
     $this->factory = $factoryBuilder->getFormFactory();
     $storage = new InMemoryStorage();
     $this->builder = new Schema\Builder();
     $this->registry = new MetadataAccessRegistry($storage, $this->builder, new DefaultHydrator($storage));
 }
 public function register(Container $container)
 {
     $container['formValidator'] = function ($c) {
         return Validation::createValidator();
     };
     $container['formFactory'] = function ($c) {
         return Forms::createFormFactoryBuilder()->addExtension(new HttpFoundationExtension())->addExtension(new CsrfExtension($c['csrfTokenManager']))->addExtension(new ValidatorExtension($c['formValidator']))->getFormFactory();
     };
     return $container;
 }
Example #23
0
 /** @test */
 public function it_serializes_exception_to_json()
 {
     $validator = Validation::createValidator();
     $formFactory = Forms::createFormFactoryBuilder()->addExtension(new ValidatorExtension($validator))->getFormFactory();
     $form = $formFactory->create('Jsor\\Stack\\Hal\\Fixtures\\Form\\FormType');
     $data = ['family' => [['name' => ['first_name' => 'Jan']]], 'additional' => 'foo'];
     $form->submit($data);
     $exception = new FormErrorException($form, 'Invalid form', 100);
     $this->assertSame(400, $exception->getStatusCode());
     $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'Invalid form', 'logref' => 100, '_embedded' => ['errors' => [['message' => 'This form should not contain extra fields.', 'path' => '/'], ['message' => 'This collection should contain 1 element or more.', 'path' => '/friends'], ['message' => 'This value should not be blank.', 'path' => '/person/gender'], ['message' => 'This value should not be blank.', 'path' => '/person/name/first_name'], ['message' => 'This value should not be blank.', 'path' => '/person/name/last_name'], ['message' => 'This value should not be blank.', 'path' => '/family/0/gender'], ['message' => 'This value should not be blank.', 'path' => '/family/0/name/last_name'], ['message' => 'This value should not be blank.', 'path' => '/newsletter']]]]), $exception->getHal()->asJson());
 }
Example #24
0
 /**
  * Initialize default resolver
  */
 public function __construct($assertKey = null)
 {
     if (self::$groupResolver == null) {
         self::$groupResolver = new OptionsResolver();
         self::$groupResolver->setRequired(array("id"));
         self::$groupResolver->setOptional(array("name", "member", "min", "min_percent", "max", "max_percent", "percent", "constraints"));
         self::$groupResolver->setAllowedTypes(array("name" => "string", "member" => "numeric", "min" => "numeric", "min_percent" => "numeric", "max" => "numeric", "max_percent" => "numeric", "percent" => "numeric", "constraints" => "array"));
         self::$validator = Validation::createValidator();
     }
     $this->assertKey = $assertKey;
 }
Example #25
0
 /**
  * Public factory method to create instance of Client.
  *
  * @param array $options Available properties: [
  *     'consumerKey' => 'foo',
  *     'consumerSecret' => 'bar',
  * ]
  * @param mixed $logger Logger used to log
  *     messages. Pass a LoggerInterface to use a PSR-3 logger. Pass a
  *     callable to log messages to a function that accepts a string of
  *     data. Pass a resource returned from ``fopen()`` to log to an open
  *     resource. Pass null or leave empty to write log messages using
  *     ``echo()``.
  * @return self
  */
 public static function create(array $options = [], $logger = Client::LOG_NONE)
 {
     $client = new \GuzzleHttp\Client(['base_url' => self::$url, 'defaults' => ['auth' => 'oauth']]);
     if ($logger !== false) {
         $subscriber = new LogSubscriber($logger, Formatter::DEBUG);
         $client->getEmitter()->attach($subscriber);
     }
     $oauth = new Oauth1(['consumer_key' => $options['consumerKey'], 'consumer_secret' => $options['consumerSecret']]);
     $client->getEmitter()->attach($oauth);
     $mapper = new ResultObjectMapper();
     return new self(new Guzzle\ClientAdapter($client, new Guzzle\ExceptionMapper($mapper)), new Validator(Validation::createValidator()), $mapper);
 }
Example #26
0
 /**
  * @param array $validatorList
  * @param array $data
  * @return mixed
  */
 public function validate($validatorList, array $data)
 {
     $validatorObject = Validation::createValidator();
     $result = array();
     foreach ($data as $field => $value) {
         $result[$field] = array();
         if (isset($validatorList[$field])) {
             $result[$field] = $validatorObject->validate($value, $validatorList[$field]);
         }
     }
     return $result;
 }
 /**
  * @return array
  */
 protected function getExtensions()
 {
     $account = $this->getAccount(1);
     $user = new AccountUser();
     $user->setAccount($account);
     $this->securityFacade->expects($this->any())->method('getLoggedUser')->willReturn($user);
     $frontendUserRoleSelectType = new EntitySelectTypeStub($this->getRoles(), FrontendAccountUserRoleSelectType::NAME, new AccountUserRoleSelectType());
     $addressEntityType = new EntityType($this->getAddresses(), 'test_address_entity');
     $accountSelectType = new AccountSelectTypeStub($this->getAccounts(), 'orob2b_account_select');
     $accountUserType = new AccountUserType($this->securityFacade);
     $accountUserType->setDataClass(self::DATA_CLASS);
     $accountUserType->setAddressClass(self::ADDRESS_CLASS);
     return [new PreloadedExtension([OroDateType::NAME => new OroDateType(), AccountUserType::NAME => $accountUserType, FrontendAccountUserRoleSelectType::NAME => $frontendUserRoleSelectType, $accountSelectType->getName() => $accountSelectType, AddressCollectionTypeStub::NAME => new AddressCollectionTypeStub(), $addressEntityType->getName() => $addressEntityType], []), new ValidatorExtension(Validation::createValidator())];
 }
 /**
  * FormFactory constructor.
  * @param ContainerInterface $container
  * @param null $theme
  * @param array $extensions
  * @param array $typeExtensions
  */
 public function __construct(ContainerInterface $container, $theme = null, array $extensions = array(), array $typeExtensions = array())
 {
     # adding custom theme path
     $this->theme = $theme;
     $formFactoryBuilder = Forms::createFormFactoryBuilder();
     # adding custom form extensions
     $formFactoryBuilder->addExtensions($extensions);
     # adding custom form type extensions
     $formFactoryBuilder->addTypeExtensions($typeExtensions);
     # configuring the form factory
     $this->formFactory = $formFactoryBuilder->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'));
 }
 /**
  * @return array
  */
 protected function getExtensions()
 {
     $entityType = new EntityType([1 => $this->getProductEntityWithPrecision(1, 'kg', 3), 2 => $this->getProductEntityWithPrecision(2, 'kg', 3)]);
     $productUnitSelection = new EntityType($this->prepareProductUnitSelectionChoices(), ProductUnitSelectionType::NAME);
     /** @var \PHPUnit_Framework_MockObject_MockObject|ConfigManager $configManager */
     $configManager = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\ConfigManager')->disableOriginalConstructor()->getMock();
     $configManager->expects($this->any())->method('get')->with('oro_currency.allowed_currencies')->will($this->returnValue(['USD', 'EUR']));
     /** @var \PHPUnit_Framework_MockObject_MockObject|LocaleSettings $localeSettings */
     $localeSettings = $this->getMockBuilder('Oro\\Bundle\\LocaleBundle\\Model\\LocaleSettings')->disableOriginalConstructor()->getMock();
     $productSelect = new ProductSelectTypeStub();
     $priceType = new PriceType();
     $priceType->setDataClass('Oro\\Bundle\\CurrencyBundle\\Model\\Price');
     return [new PreloadedExtension([$entityType->getName() => $entityType, ProductSelectType::NAME => $productSelect, ProductUnitSelectionType::NAME => $productUnitSelection, PriceType::NAME => $priceType, CurrencySelectionType::NAME => new CurrencySelectionType($configManager, $localeSettings)], []), new ValidatorExtension(Validation::createValidator())];
 }
 /**
  * @param array $parameters
  * @return mixed
  */
 public function validate(array $parameters)
 {
     $validator = Validation::createValidator();
     $constraints = new Collection(['name' => [new Assert\Length(['min' => 2]), new Assert\Required()], 'last_name' => new Assert\Length(['min' => 2]), 'email' => [new Assert\Email(), new Assert\Required()], 'id' => new Assert\Optional(), 'requires_account' => new Assert\Optional(), 'phone_number' => new Assert\Optional(), 'external_id' => new Assert\Optional(), 'status' => new Assert\Optional(), 'balance' => new Assert\Optional(), 'address' => new Assert\Optional(), 'clabe' => new Assert\Optional()]);
     if (isset($parameters['address'])) {
         $addressValidator = new OpenpayAddressValidator();
         $addressViolations = $addressValidator->validate($parameters['address']);
     }
     $customerViolations = $validator->validate($parameters, $constraints);
     if (isset($addressViolations)) {
         $customerViolations->addAll($addressViolations);
     }
     return $customerViolations;
 }