コード例 #1
0
ファイル: Validator.php プロジェクト: pivnicki/acme
 public function isValid($validation_data)
 {
     $errors = [];
     foreach ($validation_data as $name => $value) {
         if (isset($_REQUEST[$name])) {
             $rules = explode("|", $value);
             foreach ($rules as $rule) {
                 $exploded = explode(":", $rule);
                 switch ($exploded[0]) {
                     case 'min':
                         $min = $exploded[1];
                         if (Valid::stringType()->length($min)->Validate($_REQUEST[$name]) == false) {
                             $errors[] = $name . " must be at least " . $min . " characters long";
                         }
                         break;
                     case 'email':
                         if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                             $errors[] = $name . " must be a valid email ";
                         }
                         break;
                     case 'equalTo':
                         if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                             $errors[] = "Values do not match";
                         }
                         break;
                     default:
                         //do nothing
                 }
             }
         } else {
             $errors = "No value found";
         }
     }
     return $errors;
 }
コード例 #2
0
ファイル: Settings.php プロジェクト: nochso/fast-forward
 /**
  * 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::stringType()->alnum('.')->noWhitespace()->notEmpty()->assert($key);
     } catch (NestedValidationException $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();
 }
コード例 #3
0
ファイル: Validator.php プロジェクト: Damien1990/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::stringType()->length($min, null)->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . " must be at least " . $min . " characters long!";
                     }
                     break;
                 case 'email':
                     if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . " must be a valid email address!";
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                         $errors[] = "Value does not match verification value!";
                     }
                     break;
                 default:
                     $errors[] = "No value found!";
             }
         }
     }
     return $errors;
 }
コード例 #4
0
 public function isValid($validation_data)
 {
     $errors = [];
     foreach ($validation_data as $name => $value) {
         $exploded = explode(":", $value);
         switch ($exploded[0]) {
             case 'min':
                 $min = $exploded[1];
                 if (Valid::stringType()->length($min, null)->Validate($_REQUEST[$name]) == false) {
                     $errors[] = $exploded[2] . " must be at least " . $min . " characters long ";
                 }
                 break;
             case 'email':
                 if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                     $errors[] = "Please enter a valid email";
                 }
                 break;
             case 'equalTo':
                 if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                     $errors[] = $exploded[2] . " value does not match " . $exploded[3] . " value";
                 }
                 break;
             default:
                 //do nothing
                 $errors[] = "No values found";
         }
     }
     return $errors;
 }
コード例 #5
0
 /**
  *  init valid rule
  */
 protected function initRule()
 {
     $this->validRule['id'] = v::numeric();
     $this->validRule['name'] = v::stringType()->length(1, 10);
     $this->validRule['email'] = v::email();
     $this->validRule['sex'] = v::intVal()->between(0, 1);
 }
コード例 #6
0
 /**
  * Returns the number of characters in memory after parsing given string.
  * @param string $string
  * @return int
  * @throws ParseException
  */
 public static function charsInMemory($string)
 {
     if (!Validator::stringType()->regex('/".*"/')->validate($string)) {
         throw new ParseException('String must be surrounded by double quotes (")');
     }
     return preg_match_all("/(\\\\\\\\|\\\\\"|\\\\x[[:xdigit:]]{2}|.)/", substr($string, 1, strlen($string) - 2));
 }
コード例 #7
0
 protected function validateName()
 {
     $value = v::stringType()->notEmpty()->validate($this->getName());
     if (!$value) {
         msg::showMsg('O campo Nome deve ser preenchido corretamente.' . '<script>focusOn("name");</script>', 'danger');
     }
     return $this;
 }
コード例 #8
0
ファイル: CityMap.php プロジェクト: hamdrew/adventofcode
 /**
  * Sets the distance between two {@link City}s
  * @param string $cityA name of city
  * @param string $cityB name of city
  * @param int $distance distance between cities
  */
 public function setCityDistance($cityA, $cityB, $distance)
 {
     Validator::stringType()->notBlank()->check($cityA);
     Validator::stringType()->notBlank()->check($cityB);
     Validator::intType()->positive()->check($distance);
     $this->adjacencyMatrix[$cityA][$cityB] = $distance;
     $this->adjacencyMatrix[$cityB][$cityA] = $distance;
 }
コード例 #9
0
ファイル: Usuario.php プロジェクト: jokeronaldo/crud-slim3
 public function validatePatchVars($vars)
 {
     $validations = [v::intVal()->validate($vars['id']), v::stringType()->length(2)->validate($vars['nome']), v::stringType()->length(2)->validate($vars['sobrenome'])];
     if ($vars['nascimento']) {
         $validations[] = v::date()->validate($vars['nascimento']);
     }
     return $validations;
 }
コード例 #10
0
 /**
  *  init valid rule
  */
 protected function initRule()
 {
     $this->validRule['uid'] = v::numeric();
     $this->validRule['expid'] = v::numeric();
     $this->validRule['firmName'] = v::stringType()->length(1, 32);
     $this->validRule['indCatNo'] = v::stringType()->length(1, 32);
     $this->validRule['jobName'] = v::stringType()->length(1, 32);
     $this->validRule['areaNo'] = v::stringType()->length(1, 32);
 }
コード例 #11
0
 public function testRespectValidatorsAreCallable()
 {
     $filter = v::key('cake', v::stringType());
     static::assertTrue($filter(['cake' => 'a string']));
     static::assertTrue($filter(['cake' => 'a string', 'other']));
     static::assertFalse($filter(['cake' => 12]));
     static::assertFalse($filter([]));
     static::assertFalse($filter(['other']));
 }
コード例 #12
0
ファイル: Comment.php プロジェクト: rlandas/UltradataHome
 /**
  * Initialise rules
  */
 public function init()
 {
     // name validator
     $this->rules['name'] = Validator::stringType()->setName('Your full name')->notEmpty()->length(1, 32);
     // email validator
     $this->rules['email'] = Validator::email()->setName('Email');
     // comment validator
     $this->rules['comment'] = Validator::stringType()->setName('Comment')->notEmpty();
 }
コード例 #13
0
ファイル: profile.php プロジェクト: slion0725/admin_ci303
 private function postValidator($post = array())
 {
     try {
         v::stringType()->notEmpty()->length(1, 32)->assert($post['name']);
         v::stringType()->notEmpty()->length(1, 32)->assert($post['password']);
     } catch (vn $exception) {
         $this->MSG->showmsg(nl2br($exception->getFullMessage()));
     }
 }
コード例 #14
0
 /**
  * Generates the next member in the look-and-say sequence
  * @param string $member the current member
  * @return string
  */
 public function nextMember($member)
 {
     Validator::stringType()->notEmpty()->check($member);
     $next = '';
     preg_match_all("/((\\d)\\2*)/", $member, $matches);
     foreach ($matches[0] as $match) {
         $next .= strval(strlen($match)) . substr($match, 0, 1);
     }
     return $next;
 }
コード例 #15
0
 public function defineLogin($login)
 {
     $loginValidador = Validator::stringType()->notEmpty()->noWhitespace()->length(8, 120);
     try {
         $loginValidador->check($login);
         $this->login = $login;
     } catch (ValidationException $exception) {
         print_r($exception->getMainMessage());
     }
 }
コード例 #16
0
 private static function validateParameters($app, $post)
 {
     if (v::key('email', v::email())->validate($post)) {
         return $app->render(400, array('msg' => 'Invalid email. Check your parameters and try again.'));
     } else {
         if (!v::key('name', v::stringType())->validate($post) || !v::key('subject', v::stringType())->validate($post) || !v::key('message', v::stringType())->validate($post)) {
             return $app->render(400, array('msg' => 'Invalid subject or message. Check your parameters and try again.'));
         }
     }
     return true;
 }
コード例 #17
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Check that user is authorized to edit this resource
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity'), 'edit', 'shifts');
     //Validate input
     $inputValidator = v::key('break', v::floatVal())->key('start_time', v::stringType())->key('end_time', v::stringType())->key('id', v::intVal());
     $inputValidator->assert($input);
     //Update shift data
     $shift = $this->commandBus->handle(new UpdateShiftCommand($input['id'], $input['break'], $input['start_time'], $input['end_time']));
     $shiftItem = new Item($shift, new ShiftTransformer());
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->createData($shiftItem)->toArray());
 }
コード例 #18
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Authorize user to be able to view shifts
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'view', 'shifts');
     //Validate input
     $inputValidator = v::key('startDateTime', v::stringType())->key('endDateTime', v::stringType());
     $inputValidator->assert($input);
     //Retrieve shifts between in time period
     $shifts = $this->shiftRepository->getShiftsBetween(Carbon::parse($input['startDateTime']), Carbon::parse($input['endDateTime']));
     $this->collection->setData($shifts)->setTransformer($this->shiftTransformer);
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->collection)->toArray());
 }
コード例 #19
0
 /**
  *  init valid rule
  */
 protected function initRule()
 {
     $this->validRule['uid'] = v::numeric();
     $this->validRule['eduid'] = v::numeric();
     $this->validRule['schoolName'] = v::stringType()->length(1, 32);
     $this->validRule['majorName'] = v::stringType()->length(1, 32);
     $this->validRule['majorCat'] = v::stringType()->length(1, 32);
     $this->validRule['area'] = v::stringType()->length(1, 32);
     $this->validRule['schoolCountry'] = v::stringType()->length(1, 32);
     $this->validRule['startDate'] = v::date('Y-m');
     $this->validRule['endDate'] = v::date('Y-m');
     $this->validRule['degreeStatus'] = v::intVal()->between(1, 3);
 }
コード例 #20
0
 /**
  * Handle notes validation, creation and update
  *
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function dispatch(Request $request, Response $response, $args)
 {
     $id = isset($args['id']) ? (int) $args['id'] : null;
     $input = $request->getParsedBody();
     $validator = v::key('body', v::stringType()->notEmpty()->length(5, null, true));
     $validator->assert($input);
     if ($id === null) {
         $note = $this->create($input);
     } else {
         $note = $this->update($input, $id);
     }
     return $response->write(json_encode([$note]));
 }
コード例 #21
0
 public function output($request, $response, $args)
 {
     $query = $request->getQueryParams();
     $validator = v::key('a', v::stringType()->length(1, 32))->key('b', v::alnum());
     list($ok, $message) = $this->validate($validator, $query);
     if (!$ok) {
         return $this->view->error('INPUT_ERROR', $message);
     }
     $ret = array();
     for ($i = 0; $i < 4; $i++) {
         $ret[] = array('data' => $i);
     }
     return $this->view->render($ret);
 }
コード例 #22
0
 private static function authorizeApiToken($app)
 {
     if (!v::key('apiKey', v::stringType())->validate($app->request->post()) || !v::key('apiToken', v::stringType())->validate($app->request->post())) {
         return false;
     }
     $user = AuthData::selectUserByIdentifierToken($app->request->post('apiKey'));
     if (!$user) {
         return "user";
     }
     if (!password_verify($app->request->post('apiToken'), $user->apiToken)) {
         return "password";
     }
     // Go now. Be free little brother.
     return $user->id;
 }
コード例 #23
0
ファイル: Conf.php プロジェクト: qinyuguang/libyaf
 public function __construct(array $options)
 {
     $options = ['baseUri' => Arr::get($options, 'baseUri', $this->baseUri), 'timeout' => Arr::get($options, 'timeout', $this->timeout), 'proxy' => Arr::get($options, 'proxy', $this->proxy), 'auth' => Arr::get($options, 'auth', $this->auth), 'logger' => Arr::get($options, 'logger')];
     try {
         V::arrayVal()->key('baseUri', V::url()->notEmpty())->key('timeout', V::floatVal()->min(0))->key('proxy', V::optional(V::url()))->key('auth', V::arrayVal()->key('user', V::stringType())->key('pass', V::stringType()))->key('logger', V::instance('\\Psr\\Log\\LoggerInterface'))->assert($options);
     } catch (\InvalidArgumentException $e) {
         $errors = array_filter($e->findMessages(['baseUri' => 'Required correct baseUri', 'timeout' => 'Required correct timeout', 'proxy' => 'Required correct proxy', 'auth' => 'Required correct authuser', 'logger' => 'Required a logger instance of psr\\log']));
         $errmsg = array_shift($errors);
         throw new Exception($errmsg);
     }
     $this->baseUri = $options['baseUri'];
     $this->timeout = $options['timeout'];
     $this->proxy = $options['proxy'];
     $this->auth = $options['auth'];
     $this->logger = $options['logger'];
 }
コード例 #24
0
 static function addAction($app)
 {
     $post = $app->request->post();
     // Validate parameters
     // Must have one or the other, or both 'action' and 'code'
     if (!v::key('action', v::stringType())->validate($post) && !v::key('code', v::stringType())->validate($post)) {
         // Validate input parameters
         return $app->render(400, array('msg' => 'Add action failed. Check your parameters and try again.'));
     }
     // Add the verifed action
     $newAction = array(":action" => v::key('action', v::stringType())->validate($post) ? $app->request->post('action') : '', ":code" => v::key('code', v::stringType())->validate($post) ? $app->request->post('code') : '', ":http_referer" => $app->request->getReferrer(), ":ip_address" => $app->request->getIp(), ":created_user_id" => APIAuth::getUserId());
     $actionId = ActionData::insertAction($newAction);
     if ($actionId) {
         return $app->render(200, array('msg' => 'Action recorded.', 'action' => $actionId));
     } else {
         return $app->render(400, array('msg' => 'Could not add new action.', 'action' => $newAction));
     }
 }
コード例 #25
0
 static function saveVariable($app, $variableId)
 {
     if (!v::intVal()->validate($variableId) || !v::key('name', v::stringType())->validate($app->request->post()) || !v::key('value', v::stringType())->validate($app->request->post())) {
         // Validate input parameters
         return $app->render(400, array('msg' => 'Update failed. Check your parameters and try again.'));
     }
     $savedConfig = ConfigData::getVariableById($variableId);
     if (!$savedConfig) {
         return $app->render(400, array('msg' => 'Variable doesnt seem to exist.'));
     } else {
         if ($savedConfig->locked) {
             return $app->render(400, array('msg' => 'This config variable is locked. It cannot be changed or deleted without special permissions.'));
         }
     }
     $disabled = $savedConfig->disabled;
     if (v::key('disabled')->validate($app->request->post())) {
         // TODO: Implement cusitom boolean Respect\Validator
         // Converting to boolean did not work well,
         // This allows a wider range of true false values
         $disabled = $app->request->post('disabled') === 1 || $app->request->post('disabled') === '1' || $app->request->post('disabled') === true || $app->request->post('disabled') === 'true' ? 1 : 0;
     }
     $indestructible = $savedConfig->indestructible;
     if (v::key('indestructible')->validate($app->request->post())) {
         // TODO: Implement cusitom boolean Respect\Validator
         // Converting to boolean did not work well,
         // This allows a wider range of true false values
         $indestructible = $app->request->post('indestructible') === 1 || $app->request->post('indestructible') === '1' || $app->request->post('indestructible') === true || $app->request->post('indestructible') === 'true' ? 1 : 0;
     }
     $locked = $savedConfig->locked;
     if (v::key('locked')->validate($app->request->post())) {
         // TODO: Implement cusitom boolean Respect\Validator
         // Converting to boolean did not work well,
         // This allows a wider range of true false values
         $locked = $app->request->post('locked') === 1 || $app->request->post('locked') === '1' || $app->request->post('locked') === true || $app->request->post('locked') === 'true' ? 1 : 0;
     }
     $data = array(":id" => $variableId, ":name" => $app->request->post('name'), ":value" => $app->request->post('value'), ":disabled" => $disabled, ":indestructible" => $indestructible, ":locked" => $locked, ":last_updated_by" => APIAuth::getUserId());
     $config = ConfigData::updateVariable($data);
     if ($config) {
         $config = ConfigData::getVariableById($variableId);
         return $app->render(200, array('variable' => $config));
     } else {
         return $app->render(400, array('msg' => 'Could not update system config variable.'));
     }
 }
コード例 #26
0
 static function quietlySaveAdditional($post, $userId = false)
 {
     $saved = false;
     $userId = !$userId && v::key('userId', v::stringType())->validate($post) ? $post['userId'] : $userId;
     if ($userId && v::key('referrer', v::stringType()->length(1, 255))->validate($post)) {
         $data = array(':user_id' => $userId, ':question' => "Where did you about from us?", ':answer' => $post['referrer']);
         $saved = InfoData::insertQuestion($data);
     }
     if ($userId && v::key('triviaLove', v::stringType()->length(1, 255))->validate($post)) {
         $data = array(':user_id' => $userId, ':question' => "How comitted are you?", ':answer' => $post['triviaLove']);
         $saved = InfoData::insertQuestion($data);
     }
     if ($userId && v::key('acceptTerms', v::stringType())->validate($post)) {
         $acceptTerms = $post['acceptTerms'] === 1 || $post['acceptTerms'] === '1' || $post['acceptTerms'] === true || $post['acceptTerms'] === 'true' ? 1 : 0;
         $data = array(':user_id' => $userId, ':accepted_terms' => $acceptTerms);
         $saved = InfoData::saveTerms($data);
     }
     return $saved;
 }
コード例 #27
0
 /**
  * Parses the elevator instructions
  *
  * @param string $instructions
  * @return ElevatorRideInstructions
  * @throws ElevatorInstructionsParserException
  */
 public static function parse($instructions)
 {
     Validator::stringType()->check($instructions);
     $parsedInstructions = [];
     if (strlen($instructions) > 0) {
         foreach (str_split($instructions) as $curr) {
             switch ($curr) {
                 case '(':
                     $parsedInstructions[] = 1;
                     break;
                 case ')':
                     $parsedInstructions[] = -1;
                     break;
                 default:
                     throw new ElevatorInstructionsParserException("Unsupported character: {$curr}");
             }
         }
     }
     return new ElevatorRideInstructions($parsedInstructions);
 }
コード例 #28
0
ファイル: Search.php プロジェクト: Anon215/movim
 function prepareSearch($key)
 {
     $view = $this->tpl();
     $validate_subject = Validator::stringType()->length(1, 15);
     if (!$validate_subject->validate($key)) {
         $view->assign('empty', true);
     } else {
         $view->assign('empty', false);
         $view->assign('presencestxt', getPresencesTxt());
         $pd = new PostnDAO();
         $posts = $pd->search($key);
         $view->assign('posts', $posts);
         $cd = new ContactDAO();
         $contacts = $cd->search($key);
         $view->assign('contacts', $contacts);
         if (!$posts && !$contacts) {
             $view->assign('empty', true);
         }
     }
     return $view->draw('_search_results', true);
 }
コード例 #29
0
ファイル: Validator.php プロジェクト: pagchen/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::stringType()->length($min)->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . ' must be at least ' . $min . ' characters long!';
                     }
                     break;
                 case 'email':
                     if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                         $errors[] = $name . ' must be a valid email address!';
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                         $errors[] = 'Value does not match the verification value';
                     }
                     break;
                 case 'unique':
                     $model = "Acme\\models\\" . $exploded[1];
                     $table = new $model();
                     $results = $table->where($name, '=', $_REQUEST[$name])->get();
                     foreach ($results as $result) {
                         $errors[] = $_REQUEST[$name] . " already exists in this system!";
                     }
                     break;
                 default:
                     $errors = 'No value found';
                     break;
             }
         }
     }
     return $errors;
 }
コード例 #30
0
 /**
  * @param $validation_data
  * @return array
  */
 public function check($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::stringType()->length($min)->Validate($this->request->input($name)) == false) {
                         $errors[] = $name . " must be at least " . $min . " characters long!";
                     }
                     break;
                 case 'email':
                     if (Valid::email()->Validate($this->request->input($name)) == false) {
                         $errors[] = $name . " must be a valid email!";
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($this->request->input($name))->Validate($this->request->input($exploded[1])) == false) {
                         $errors[] = "Value does not match verification value!";
                     }
                     break;
                 case 'unique':
                     $model = "Acme\\models\\" . $exploded[1];
                     $table = new $model();
                     $results = $this->getRows($table, $name);
                     foreach ($results as $item) {
                         $errors[] = $this->request->input($name) . " already exists in this system!";
                     }
                     break;
                 default:
                     $errors[] = "No value found!";
             }
         }
     }
     return $errors;
 }