/**
  * Create the Callback validator that will be used to ensure the
  * RowCollectionEditor is valid.  We iterate over all the editors it has,
  * pass data to the editor via isValid() and return an error message if any
  * editor fails.
  *
  * @return Callback
  */
 protected function createCallbackValidator()
 {
     $validator = new Callback();
     $validator->setCallback(function () {
         return $this->rowCollectionEditor->isValid();
     });
     $validator->setMessage("Some errors were found in your {$this->rowCollectionEditor->getPluralTitle()}.\n            Please double-check and try again.", Callback::INVALID_VALUE);
     return $validator;
 }
Example #2
0
 public function testCanAcceptContextWithOptions()
 {
     $value = 'bar';
     $context = array('foo' => 'bar', 'bar' => 'baz');
     $options = array('baz' => 'bat');
     $validator = new Callback(function ($v, $c, $baz) use($value, $context, $options) {
         return $value == $v && $context == $c && $options['baz'] == $baz;
     });
     $validator->setCallbackOptions($options);
     $this->assertTrue($validator->isValid($value, $context));
 }
    /**
     * Constructor
     *
     * @param FacilityService $facilityService
     * @throws InvalidArgumentException
     *
     * */
    public function __construct(
        FacilityService $facilityService
    ) {
        $this->facilityService = $facilityService;

        $this->add(
            [
                'name' => 'name',
                'filters' => [
                    [
                        'name' => 'StripTags'
                    ],
                    [
                        'name' => 'StringTrim'
                    ],
                ],
            ]
        );
        $this->facilityValidator = new Callback(function ($value) {
            if ($value instanceof Facility) {
                return true;
            } else if (!(is_array($value) && isset($value['id']))) {
                $this->facilityValidator->setMessage('No valid identifier specified');
                return false;
            }

            try {
                $this->facilityService->find($value);
                return true;
            } catch (ModelNotFoundException $e) {
                $this->facilityValidator->setMessage($e->getMessage());
            } catch (UnauthorizedException $e) {
                $this->facilityValidator->setMessage($e->getMessage());
            } catch (Exception $e) {
                $this->facilityValidator->setMessage('Unknown error during validation');
            }
            return false;
        });
        $this->add(
            [
                'name' => 'facility',
                'validators' => [
                    $this->facilityValidator
                ]
            ]
        );

    }
Example #4
0
 /**
  * {@inheritDoc}
  */
 public function setOptions($options = [])
 {
     if (isset($options['messageVariables'])) {
         $this->abstractOptions['messageVariables'] = $options['messageVariables'];
     }
     return parent::setOptions($options);
 }
Example #5
0
 public function __construct(EntityManager $objectManager, $type)
 {
     // Firstname
     $firstname = new Input('prenom');
     $firstname->getFilterChain()->attach(new StringTrim())->attach(new StripTags());
     $firstname->getValidatorChain()->attach(new NotEmpty())->attach(new StringLength(array('max' => 50)));
     $this->add($firstname);
     // Lastname
     $lastname = new Input('nom');
     $lastname->getFilterChain()->attach(new StringTrim())->attach(new StripTags());
     $lastname->getValidatorChain()->attach(new NotEmpty())->attach(new StringLength(array('max' => 50)));
     $this->add($lastname);
     //Unique email validator
     $uniqueUserEmail = new UniqueObject(array('object_manager' => $objectManager, 'object_repository' => $objectManager->getRepository('Application\\Entity\\Utilisateur'), 'fields' => 'email', 'use_context' => true));
     $uniqueUserEmail->setMessage('L\'email renseigné est déjà utilisé par un autre utilisateur.', 'objectNotUnique');
     // Email
     $email = new Input('email');
     $email->getFilterChain()->attach(new StringTrim())->attach(new StripTags());
     $email->getValidatorChain()->attach(new NotEmpty())->attach(new StringLength(array('max' => 255)))->attach(new EmailAddress())->attach($uniqueUserEmail);
     $this->add($email);
     $editCallback = new Callback(function ($value) {
         if ($value == '') {
             return true;
         }
         /** @var StringLength $validator */
         $validator = new StringLength(array('min' => 6, 'max' => 32));
         return $validator->isValid($value);
     });
     $editCallback->setMessage('Le mot de passe doit contenir entre 6 et 32 caractères.');
     // Password
     $password = new Input('password');
     $password->setRequired($type == UtilisateurForm::TYPE_ADD)->setContinueIfEmpty(true);
     $password->getFilterChain()->attach(new StringTrim());
     $password->getValidatorChain()->attach($type == UtilisateurForm::TYPE_ADD ? new StringLength(array('min' => 6, 'max' => 32)) : $editCallback);
     $this->add($password);
     // Password Confirmation
     $passwordConfirmation = new Input('passwordConfirmation');
     $passwordConfirmation->setRequired($type == UtilisateurForm::TYPE_ADD)->setContinueIfEmpty(true);
     $passwordConfirmation->getFilterChain()->attach(new StringTrim());
     $passwordConfirmation->getValidatorChain()->attach($type == UtilisateurForm::TYPE_ADD ? new StringLength(array('min' => 6, 'max' => 32)) : $editCallback)->attach(new Identical('password'));
     $this->add($passwordConfirmation);
     $role = new Input('role');
     $role->setRequired(false);
     $role->getFilterChain()->attach(new Digits());
     $this->add($role);
 }
Example #6
0
 /**
  * Create any resources that need to be accessible both for processing
  * and rendering.
  *
  * @return void
  */
 public function init()
 {
     $this->model = Pimple::getResource('users-gateway');
     $this->fields = new Fields();
     $this->row = $this->model->find($this->request->getQuery('user_id'));
     $this->fields->add('password')->setLabel('Password')->setEditable(true)->add('confirm_password')->setLabel('Confirm Password')->setEditable(true);
     $this->inputFilter = new InputFilter();
     $password = new Input('password');
     $this->inputFilter->add($password);
     $password->setRequired(true)->getValidatorChain()->attach(new StringLength(array('min' => 6)));
     $confirm = new Input('confirm_password');
     $this->inputFilter->add($confirm);
     $validator = new Callback(array('callback' => function ($value) {
         return $value === $this->request->getPost('password');
     }));
     $validator->setMessage('Passwords do not match.');
     $confirm->setRequired(true)->getValidatorChain()->attach($validator);
 }
Example #7
0
 public function testAddingValueOptions()
 {
     $valid = new Validator\Callback(array('callback' => array($this, 'optionsCallback'), 'callbackOptions' => 'options'));
     $this->assertEquals(array('options'), $valid->getCallbackOptions());
     $this->assertTrue($valid->isValid('test', 'something'));
 }
Example #8
0
 /**
  * Returns true if and only if $value follows the Luhn algorithm (mod-10 checksum)
  *
  * @param  string $value
  * @return boolean
  */
 public function isValid($value)
 {
     $this->setValue($value);
     if (!is_string($value)) {
         $this->error(self::INVALID, $value);
         return false;
     }
     if (!ctype_digit($value)) {
         $this->error(self::CONTENT, $value);
         return false;
     }
     $length = strlen($value);
     $types = $this->getType();
     $foundp = false;
     $foundl = false;
     foreach ($types as $type) {
         foreach ($this->cardType[$type] as $prefix) {
             if (substr($value, 0, strlen($prefix)) == $prefix) {
                 $foundp = true;
                 if (in_array($length, $this->cardLength[$type])) {
                     $foundl = true;
                     break 2;
                 }
             }
         }
     }
     if ($foundp == false) {
         $this->error(self::PREFIX, $value);
         return false;
     }
     if ($foundl == false) {
         $this->error(self::LENGTH, $value);
         return false;
     }
     $sum = 0;
     $weight = 2;
     for ($i = $length - 2; $i >= 0; $i--) {
         $digit = $weight * $value[$i];
         $sum += floor($digit / 10) + $digit % 10;
         $weight = $weight % 2 + 1;
     }
     if ((10 - $sum % 10) % 10 != $value[$length - 1]) {
         $this->error(self::CHECKSUM, $value);
         return false;
     }
     $service = $this->getService();
     if (!empty($service)) {
         try {
             $callback = new Callback($service);
             $callback->setOptions($this->getType());
             if (!$callback->isValid($value)) {
                 $this->error(self::SERVICE, $value);
                 return false;
             }
         } catch (\Exception $e) {
             $this->error(self::SERVICEFAILURE, $value);
             return false;
         }
     }
     return true;
 }
Example #9
0
 /**
  * Returns true if and only if $value is a valid postalcode
  *
  * @param  string $value
  * @return bool
  * @throws Exception\InvalidArgumentException
  */
 public function isValid($value)
 {
     if (!is_string($value) && !is_int($value)) {
         $this->error(self::INVALID);
         return false;
     }
     $this->setValue($value);
     $service = $this->getService();
     $locale = $this->getLocale();
     $format = $this->getFormat();
     if ((null === $format || '' === $format) && !empty($locale)) {
         $region = Locale::getRegion($locale);
         if ('' === $region) {
             throw new Exception\InvalidArgumentException("Locale must contain a region");
         }
         if (isset(static::$postCodeRegex[$region])) {
             $format = static::$postCodeRegex[$region];
         }
     }
     if (null === $format || '' === $format) {
         throw new Exception\InvalidArgumentException("A postcode-format string has to be given for validation");
     }
     if ($format[0] !== '/') {
         $format = '/^' . $format;
     }
     if ($format[strlen($format) - 1] !== '/') {
         $format .= '$/';
     }
     if (!empty($service)) {
         if (!is_callable($service)) {
             throw new Exception\InvalidArgumentException('Invalid callback given');
         }
         try {
             $callback = new Callback($service);
             $callback->setOptions(array('format' => $format, 'locale' => $locale));
             if (!$callback->isValid($value)) {
                 $this->error(self::SERVICE, $value);
                 return false;
             }
         } catch (\Exception $e) {
             $this->error(self::SERVICEFAILURE, $value);
             return false;
         }
     }
     if (!preg_match($format, $value)) {
         $this->error(self::NO_MATCH);
         return false;
     }
     return true;
 }
Example #10
0
 /**
  * Returns true if and only if $value is a valid postalcode
  *
  * @param  string $value
  * @return boolean
  */
 public function isValid($value)
 {
     $this->setValue($value);
     if (!is_string($value) && !is_int($value)) {
         $this->error(self::INVALID);
         return false;
     }
     $service = $this->getService();
     if (!empty($service)) {
         try {
             $callback = new Callback($service);
             $callback->setOptions(array('format' => $this->options['format'], 'locale' => $this->options['locale']));
             if (!$callback->isValid($value)) {
                 $this->error(self::SERVICE, $value);
                 return false;
             }
         } catch (\Exception $e) {
             $this->error(self::SERVICEFAILURE, $value);
             return false;
         }
     }
     $format = $this->getFormat();
     if (!preg_match($format, $value)) {
         $this->error(self::NO_MATCH);
         return false;
     }
     return true;
 }
Example #11
0
 /**
  * @param callable $callback
  * @param string $message
  * @return CallbackValidator
  */
 public static function callbackValidator(callable $callback, $message = null)
 {
     $validator = new CallbackValidator(compact('callback'));
     if ($message) {
         $validator->setMessage($message);
     } else {
         $validator->setMessage('Input tidak valid.');
     }
     return $validator;
 }
Example #12
0
 /**
  * Add password and confirmation fields to the given fields collection
  *
  * @param Fields $fields
  * @return Component
  */
 protected function addPasswordFields(Fields $fields)
 {
     static $passwordFieldName = 'password', $confirmFieldName = 'confirm_password', $minimumLength = 6;
     $request = $this->getRequest();
     $fields->add($passwordFieldName)->assignHelperCallback('EditControl.Control', function ($helper, View $view) use($passwordFieldName, $request) {
         return $view->inputText(['name' => $passwordFieldName, 'type' => 'password', 'value' => $request->getPost($passwordFieldName)]);
     })->assignHelperCallback('InputFilter', function () use($passwordFieldName, $minimumLength) {
         $input = new Input($passwordFieldName);
         $input->setRequired(true)->getValidatorChain()->attach(new StringLength(['min' => $minimumLength]));
         return $input;
     })->setLabel('Password')->setEditable(true);
     $this->fields->add('confirm_password')->assignHelperCallback('EditControl.Control', function ($helper, View $view) use($confirmFieldName, $request) {
         return $view->inputText(['name' => $confirmFieldName, 'type' => 'password', 'value' => $request->getPost($confirmFieldName)]);
     })->assignHelperCallback('InputFilter', function () use($request, $passwordFieldName, $confirmFieldName) {
         $input = new Input($confirmFieldName);
         $passwordsMatchValidator = new Callback(['callback' => function ($value) use($request, $passwordFieldName) {
             return $value === $request->getPost($passwordFieldName);
         }]);
         $passwordsMatchValidator->setMessage('Passwords do not match.');
         $input->setRequired(true)->getValidatorChain()->attach($passwordsMatchValidator);
         return $input;
     })->setLabel('Confirm Password')->setEditable(true);
     return $this;
 }
 /**
  * Is the data set valid?
  *
  * @throws RuntimeException
  * @return bool
  */
 public function isValid()
 {
     if (true === ($valid = parent::isValid())) {
         $validator = new Callback(array('callback' => function ($values) {
             if (isset($values['query']) || isset($values['latitude']) && isset($values['longitude']) || isset($values['id'])) {
                 return true;
             }
         }, 'messages' => array(Callback::INVALID_VALUE => 'Requires a query, id, or latitude and longitude')));
         if (true === ($valid = $validator->isValid($this->getValues()))) {
             $this->validInputs['atLeastOne'] = $validator;
         } else {
             $this->invalidInputs['atLeastOne'] = $validator;
         }
     }
     return $valid;
 }