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; }
/** * 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(); }
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; }
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; }
/** * 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); }
/** * 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)); }
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; }
/** * 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; }
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; }
/** * 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); }
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'])); }
/** * 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(); }
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())); } }
/** * 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; }
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()); } }
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; }
/** * 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()); }
/** * 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()); }
/** * 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); }
/** * 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])); }
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); }
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; }
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']; }
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)); } }
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.')); } }
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; }
/** * 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); }
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); }
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; }
/** * @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; }