예제 #1
0
 public function setState($value)
 {
     if (!v::string()->notEmpty()->validate($value) || strlen($value) != 2) {
         throw new FieldRequiredException("Estado é uma informação obrigatória");
     }
     $this->_state = strtoupper($value);
 }
예제 #2
0
 public function __construct($webapiKey = null, $userLogin = null, $hashedPassword = null)
 {
     $this->properties['webapiKey'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->length(4)->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($webapiKey)) {
         $this->properties['webapiKey']->set($webapiKey)->lock();
     }
     // --------------------
     $this->properties['userLogin'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->length(4)->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($userLogin)) {
         $this->properties['userLogin']->set($userLogin)->lock();
     }
     // ----------------------
     $this->properties['hashedPassword'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->regex('/^([A-Za-z0-9+\\/]{4})*([A-Za-z0-9+\\/]{4}|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{2}==)$/')->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($hashedPassword)) {
         $this->properties['hashedPassword']->set($hashedPassword)->lock();
     }
 }
예제 #3
0
 public function setJustification($justification)
 {
     if (!v::string()->length(15, 1000)->validate($justification)) {
         throw new FieldRequiredException("A justicativa deve ter entre 15 e 100 caracteres");
     }
     $this->_justification = $justification;
 }
예제 #4
0
 /**
  * Saves a setting as a key/value pair
  *
  * Settings specific to fast-forward start with a `ff.` prefix.
  *
  * You can use the constants of this class to avoid looking up the key names.
  *
  * @param string $key   Unique key name.<br>
  *                      Must contain only letters (a-z, A-Z), digits (0-9) and "."
  * @param string $value
  *
  * @throws \Exception
  */
 public function set($key, $value)
 {
     $out = $this->client->getOutput();
     try {
         v::string()->alnum('.')->noWhitespace()->notEmpty()->assert($key);
     } catch (NestedValidationExceptionInterface $e) {
         $out->error($e->getFullMessage());
         return;
     }
     $setting = $this->get($key, true);
     if ($setting === null) {
         $setting = new Setting();
         $setting->key = $key;
     }
     $oldValue = $setting->value;
     $setting->value = $value;
     if (!$this->validate($setting)) {
         return;
     }
     if ($oldValue === null) {
         $out->writeln("Inserting new setting:\n{$key} = <options=bold>{$value}</>");
     } elseif ($oldValue !== $value) {
         $out->writeln("Changing setting:\n{$key} = {$oldValue} --> <options=bold>{$value}</>");
     } else {
         $out->writeln("Setting already up-to-date:\n{$key} = {$value}");
     }
     $setting->save();
 }
예제 #5
0
 public function validate($data)
 {
     $validator = V::key('name', V::string()->length(0, 100), true)->key('email', V::email()->length(0, 200), true)->key('password', V::string()->length(0, 100), true);
     try {
         $validator->assert($data);
         switch ($data['userable_type']) {
             case 'Designer':
                 $this->designerCreationValidator->validate($data);
                 $data['userable_type'] = DesignerModel::class;
                 break;
             case 'Administrator':
                 $this->adminCreationValidator->validate($data);
                 $data['userable_type'] = AdministratorModel::class;
                 break;
             case 'Buyer':
                 $this->buyerCreationValidator->validate($data);
                 $data['userable_type'] = BuyerModel::class;
                 break;
             default:
                 break;
         }
     } catch (AbstractNestedException $e) {
         $errors = $e->findMessages(['email', 'length', 'in']);
         throw new ValidationException('Could not create user.', $errors);
     }
     return true;
 }
예제 #6
0
 public function validate($prop, $label)
 {
     $value = $this->getValue($prop);
     if (!v::string()->cnpj()->validate($value)) {
         $this->addException("O preenchimento do campo {$label} está inválido");
     }
 }
예제 #7
0
 public function post()
 {
     try {
         $newManufacturer = (object) (['id' => null] + $_POST);
         v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->assert($_POST);
         if ($_FILES['files']['error'] == 4) {
             throw new Exception('O campo imagem é obrigatório');
         }
         if (empty($newManufacturer->manufacturer_featured)) {
             $newManufacturer->manufacturer_featured = null;
         }
         $this->collection->persist($newManufacturer);
         $this->collection->flush();
         foreach ($_FILES as $file) {
             $this->uploaderService->setFile($_POST['name'], 'files');
             $image = (object) ['name' => $this->uploaderService->getFile()->getNameWithExtension(), 'title' => $_POST['name'], 'type' => $this->uploaderService->getFile()->getMimetype(), 'manufacturer_id' => $newManufacturer->id];
             $this->imageCollection->persist($image);
             $this->imageCollection->flush();
             $this->uploaderService->upload();
         }
         header('HTTP/1.1 303 See Other');
         header('Location: /catalog/manufacturers');
     } catch (NestedValidationExceptionInterface $e) {
         return $this->get() + ['manufacturer/addManufacturer' => $newManufacturer, 'messages' => $e->findMessages(['name' => 'O nome deve ser entre 1 e 300 caracteres'])];
     }
 }
예제 #8
0
파일: String.php 프로젝트: dindigital/din
 public function validate($prop, $label)
 {
     $value = $this->getValue($prop);
     if (!v::string()->notEmpty()->validate($value)) {
         $this->addException("O campo {$label} é de preenchimento obrigatório");
     }
 }
예제 #9
0
 public function setName($value)
 {
     if (!v::string()->notEmpty()->validate($value)) {
         throw new FieldRequiredException("Nome/Razão Social é uma informação obrigatória");
     }
     $this->_name = $value;
 }
예제 #10
0
 public function post($manufacturerId)
 {
     $editManufacturer = $this->collection[$manufacturerId]->fetch() ?: new stdClass();
     foreach ($_POST as $k => $v) {
         $editManufacturer->{$k} = $v;
     }
     try {
         v::object()->attribute('name', v::string()->notEmpty()->length(1, 300))->assert($editManufacturer);
         $this->collection->persist($editManufacturer);
         $this->collection->flush();
         if (empty($newManufacturer->manufacturer_featured)) {
             $newManufacturer->manufacturer_featured = null;
         }
         if ($_FILES['files']['error'] != 4) {
             foreach ($_FILES as $file) {
                 $this->uploaderService->setFile($editManufacturer->name, 'files');
                 $image = (object) ['name' => $this->uploaderService->getFile()->getNameWithExtension(), 'title' => $editManufacturer->name, 'type' => $this->uploaderService->getFile()->getMimetype(), 'manufacturer_id' => $editManufacturer->id];
                 $this->imageCollection->persist($image);
                 $this->imageCollection->flush();
                 $this->uploaderService->upload();
             }
         }
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $_SERVER['REQUEST_URI']);
     } catch (NestedValidationExceptionInterface $e) {
         return ['editManufacturer' => $editManufacturer, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars', 'enabled' => 'Could not enable manufacturer'])];
     }
 }
예제 #11
0
 public function setStateRegistration($value)
 {
     if (!v::string()->notEmpty()->validate($value)) {
         throw new FieldRequiredException("Inscrição Estadual é uma informação obrigatória");
     }
     $value = preg_replace('/\\D/', '', $value);
     $this->_stateRegistration = $value;
 }
예제 #12
0
 public function testGetFullMessageShouldIncludeAllValidationMessagesInAChain()
 {
     try {
         Validator::string()->length(1, 15)->assert('');
     } catch (NestedValidationExceptionInterface $e) {
         $this->assertEquals('\\-These rules must pass for ""
\-"" must have a length between 1 and 15', $e->getFullMessage());
     }
 }
예제 #13
0
파일: Account.php 프로젝트: Nyco/movim
 private function validateServer($server)
 {
     $validate_server = Validator::string()->noWhitespace()->length(6, 80);
     if (!$validate_server->validate($server)) {
         return false;
     } else {
         return true;
     }
 }
예제 #14
0
파일: Blog.php 프로젝트: vijo/movim
 private function validateServerNode($server, $node)
 {
     $validate_server = Validator::string()->noWhitespace()->length(6, 40);
     $validate_node = Validator::string()->length(3, 100);
     if (!$validate_server->validate($server) || !$validate_node->validate($node)) {
         return false;
     } else {
         return true;
     }
 }
예제 #15
0
 public function validate($data)
 {
     $validator = V::key('about', V::string()->length(0, 100), false)->key('website', V::string()->length(0, 100), false)->key('twitter_username', V::string()->length(0, 100), false)->key('facebook_url', V::string()->length(0, 100), false)->key('pinterest_url', V::string()->length(0, 100), false)->key('instagram_username', V::string()->length(0, 100), false);
     try {
         $validator->assert($data);
     } catch (AbstractNestedException $e) {
         $errors = $e->findMessages(['about', 'website', 'twitter_username', 'facebook_url', 'pinterest_url', 'instagram_username']);
         throw new ValidationException('Could not update user.', $errors);
     }
     return true;
 }
예제 #16
0
 public function validate($prop, $label)
 {
     $value = $this->getValue($prop);
     $message = "O campo {$label} precisa ter no mínimo {$this->_min} caractere(s)";
     if (!is_null($this->_max)) {
         $message .= " e no máximo {$this->_max} caractere(s)";
     }
     if (!v::string()->length($this->_min, $this->_max)->validate($value)) {
         $this->addException($message);
     }
 }
예제 #17
0
 public function validate($prop, $label)
 {
     $value1 = $this->getValue($prop);
     $value2 = $this->getValue($this->_equal);
     if (!v::string()->notEmpty()->validate($value1)) {
         $this->addException("Os campos de {$label} precisam ser preenchidos");
     }
     if (!v::string()->equals($value1)->validate($value2)) {
         $this->addException("Os campos de {$label} precisam ser iguais");
     }
 }
예제 #18
0
 public function post()
 {
     try {
         $newCategory = (object) (['id' => null] + $_POST);
         v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->assert($_POST);
         $this->collection->persist($newCategory);
         $this->collection->flush();
         header('HTTP/1.1 303 See Other');
         header('Location: /catalog/categories');
     } catch (NestedValidationExceptionInterface $e) {
         return $this->get() + ['category/addCategory' => $newCategory, 'messages' => $e->findMessages(['name' => 'O nome deve ser entre 1 e 300 caracteres'])];
     }
 }
function emailValidate(&$errors, $email)
{
    $emailBlankError = "Вы не заполнили поле Email";
    $emailNotValid = "Укажите правильный Email";
    if ($email != "") {
        $email = filter_var(trim(strip_tags($email)), FILTER_SANITIZE_EMAIL);
        if (!v::string()->notEmpty()->validate($email) || !v::email()->validate($email)) {
            $errors[] = $emailNotValid;
        }
    } else {
        $errors[] = $emailBlankError;
    }
    return $email;
}
function priceValidate(&$errors, $price)
{
    $priceBlankError = "Вы не указали цену товара";
    $priceNotValid = "Цена товара должна быть положительным числом";
    if ($price != "") {
        $price = filter_var(trim(strip_tags($price)), FILTER_SANITIZE_NUMBER_INT);
        if (!v::string()->notEmpty()->validate($price) || !v::numeric()->validate($price) || $price <= 0) {
            $errors[] = $priceNotValid;
        }
    } else {
        $errors[] = $priceBlankError;
    }
    return $price;
}
 public function test_findMessages_should_apply_templates_to_flattened_messages()
 {
     $stringMax256 = v::string()->length(5, 256);
     $alnumDot = v::alnum('.');
     $stringMin8 = v::string()->length(8, null);
     $v = v::allOf(v::attribute('first_name', $stringMax256)->setName('First Name'), v::attribute('last_name', $stringMax256)->setName('Last Name'), v::attribute('desired_login', $alnumDot)->setName('Desired Login'), v::attribute('password', $stringMin8)->setName('Password'), v::attribute('password_confirmation', $stringMin8)->setName('Password Confirmation'), v::attribute('stay_signedin', v::notEmpty())->setName('Stay signed in'), v::attribute('enable_webhistory', v::notEmpty())->setName('Enabled Web History'), v::attribute('security_question', $stringMax256)->setName('Security Question'))->setName('Validation Form');
     try {
         $v->assert((object) array('first_name' => 'fiif', 'last_name' => null, 'desired_login' => null, 'password' => null, 'password_confirmation' => null, 'stay_signedin' => null, 'enable_webhistory' => null, 'security_question' => null));
     } catch (ValidationException $e) {
         $messages = $e->findMessages(array('allOf' => 'Invalid {{name}}', 'first_name.length' => 'Invalid length for {{name}} {{input}}'));
         $this->assertEquals($messages['allOf'], 'Invalid Validation Form');
         $this->assertEquals($messages['first_name_length'], 'Invalid length for "fiif" fiif');
     }
 }
예제 #22
0
 public function __construct($data)
 {
     parent::__construct();
     $this->data = $data;
     $this->fields = array('firstname' => array('value' => $this->data['firstname'], 'validators' => array('notEmpty'), 'errors' => array('Firstname is empty')), 'email' => array('value' => $this->data['email'], 'validators' => array('email', 'notEmpty'), 'errors' => array('Email is not valid', 'Email is empty')), 'url' => array('value' => $this->data['url'], 'validators' => array('notEmpty', 'url'), 'errors' => array('Url is empty', 'Url is not valid')), 'cv' => array('value' => $_FILES['cv'], 'validators' => function () {
         return v::exists()->validate($_FILES['cv']["tmp_name"]);
     }, 'errors' => array('File is empty')), 'content' => array('value' => $this->data['content'], 'validators' => function ($value) {
         return v::when(v::int(), v::positive(), v::notEmpty())->validate($value);
     }, 'errors' => array('content is not valid')), 'int' => array('value' => $this->data['int'], 'validators' => function ($value) {
         return v::allOf(v::int(), v::positive(), v::notEmpty())->validate($value);
     }, 'errors' => array('int is not valid')), 'uppercase' => array('value' => '', 'validators' => function ($value) {
         return v::string()->uppercase()->validate($value);
     }, 'errors' => array('uppercase is not valid')));
 }
function catNameValidate(&$errors, $catName)
{
    $catNameBlankError = "Вы не заполнили название категории";
    $catNameNotValid = "Укажите правильное название категории";
    if ($catName != "") {
        $catName = filter_var(trim(strip_tags($catName)), FILTER_SANITIZE_STRING);
        if (!v::string()->notEmpty()->validate($catName)) {
            $errors[] = $catNameNotValid;
        }
    } else {
        $errors[] = $catNameBlankError;
    }
    return $catName;
}
예제 #24
0
 public function post()
 {
     try {
         v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->key('description', v::string()->length(1, 300))->key('internal_code', v::string()->length(1, 30))->key('about', v::string())->assert($_POST);
         $newProduct = (object) (['id' => null] + $_POST);
         $this->collection->persist($newProduct);
         $this->collection->flush();
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $this->singleProduct->createUri($newProduct->id));
         return $this->get();
     } catch (NestedValidationExceptionInterface $e) {
         return ['category/singleProduct' => $editProduct, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars', 'internal_code' => 'Internal Code must have between 1 and 300 chars', 'description' => 'Description must a maximum of 300 chars', 'enabled' => 'Could not enable product', 'about' => 'Invalid description'])];
     }
 }
예제 #25
0
 public function post()
 {
     try {
         v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->assert($_POST);
         $newCategory = (object) (['id' => null] + $_POST);
         $this->collection->persist($newCategory);
         $this->collection->flush();
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $this->singleFeature->createUri($newCategory->id));
         return $this->get();
     } catch (NestedValidationExceptionInterface $e) {
         return $e->findMessages(['name']);
     }
 }
예제 #26
0
 protected function postEdit($categoryId)
 {
     $editCategory = $this->collection[$categoryId]->fetch() ?: new stdClass();
     foreach ($_POST as $k => $v) {
         $editCategory->{$k} = $v;
     }
     try {
         v::object()->attribute('name', v::string()->notEmpty()->length(1, 300))->attribute('enabled', v::numeric()->between(0, 1, true), false)->assert($editCategory);
         $this->collection->persist($editCategory);
         $this->collection->flush();
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $_SERVER['REQUEST_URI']);
     } catch (NestedValidationExceptionInterface $e) {
         return ['editCategory' => $editCategory, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars', 'enabled' => 'Could not enable category'])];
     }
 }
예제 #27
0
파일: Validator.php 프로젝트: Notesong/acme
 public function isValid($validation_data)
 {
     $errors = [];
     foreach ($validation_data as $name => $value) {
         $rules = explode("|", $value);
         foreach ($rules as $rule) {
             $exploded = explode(":", $rule);
             switch ($exploded[0]) {
                 case 'min':
                     $min = $exploded[1];
                     if (Valid::string()->length($min, null)->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . " must be at least " . $min . " characters long.";
                     }
                     break;
                 case 'max':
                     $max = $exploded[1];
                     if (Valid::string()->length(null, $max)->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . " cannot be more than " . $max . " characters long.";
                     }
                     break;
                 case 'email':
                     if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                         $errors[] = "Must be a valid email address.";
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                         $errors[] = "Values do not match.";
                     }
                     break;
                     // check to see if already exists in database
                 // check to see if already exists in database
                 case 'unique':
                     $model = "Acme\\models\\" . $exploded[1];
                     $table = new $model();
                     $results = $table::where($name, '=', $_REQUEST[$name])->get();
                     foreach ($results as $item) {
                         $errors[] = $_REQUEST[$name] . " already exists in this system.";
                     }
                     break;
                 default:
                     $errors[] = "No value found.";
             }
         }
     }
     return $errors;
 }
예제 #28
0
 public function post($featureId)
 {
     $editFeature = $this->collection[$featureId]->fetch() ?: new stdClass();
     foreach ($_POST as $k => $v) {
         $editFeature->{$k} = $v;
     }
     try {
         v::object()->attribute('name', v::string()->notEmpty()->length(1, 300))->assert($editFeature);
         $this->collection->persist($editFeature);
         $this->collection->flush();
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $_SERVER['REQUEST_URI']);
         return $this->get($featureId);
     } catch (NestedValidationExceptionInterface $e) {
         return ['singleFeature' => $editFeature, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars', 'enabled' => 'Could not enable product'])];
     }
 }
예제 #29
0
function validateProduct(&$product)
{
    $invalids = array();
    if (empty($product['name']) || !Validation::string()->length(1, 255)->validate($product['name'])) {
        array_push($invalids, 'name');
    }
    if (empty($product['price']) || !Validation::float()->min(0, true)->validate($product['price'])) {
        array_push($invalids, 'price');
    }
    if (empty($product['amount']) || !Validation::int()->min(1, true)->validate($product['amount'])) {
        array_push($invalids, 'amount');
    }
    if (empty($product['categoryId']) || !Validation::int()->max(10, true)->validate($product['categoryId'])) {
        array_push($invalids, 'categoryId');
    }
    return $invalids;
}
예제 #30
0
파일: Xen.php 프로젝트: sircamp/xenapi
 public function __construct($url, $user, $password)
 {
     if (!Validator::ip()->validate($url)) {
         throw new \InvalidArgumentException("'url' value mast be an ipv4 address", 1);
     }
     if (!Validator::string()->validate($user)) {
         throw new \InvalidArgumentException("'user' value mast be an non empty string", 1);
     }
     if (!Validator::string()->validate($password)) {
         throw new \InvalidArgumentException("'password' value mast be an non empty string", 1);
     }
     $this->xenconnection = new XenConnection();
     try {
         $this->xenconnection->_setServer($url, $user, $password);
     } catch (Exception $e) {
         dd($e->getMessage());
     }
 }