/** * @param string $role * @param IResource|string $resource * @param $privilege * @return bool */ public function isAllowed($role, $resource, $privilege) { $roles = []; if ($role instanceof User) { $roles = $role->getRoles(); } elseif ($role instanceof \Nette\Security\User) { $userIdentity = $role->getIdentity(); if ($userIdentity !== null) { $roles = $role->getIdentity()->getRoles(); } } elseif ($role instanceof Role) { $roles[] = $role->getName(); } elseif (Validators::is($role, 'unicode:1..')) { $roles[] = $role; } else { return false; } try { foreach ($roles as $role) { if ($this->acl->isAllowed($role, $resource, $privilege) === true) { return true; } } return false; } catch (InvalidStateException $e) { return false; // role does not exists } }
/** * @param array $eventsToSkip * or [logType => *] or [logType1 => [event1, event2, ...], logType2 => ...] */ public function addEventsToSkip($eventsToSkip) { if ($eventsToSkip === '*') { $this->eventsToSkip = $eventsToSkip; } elseif (is_array($eventsToSkip)) { foreach ($eventsToSkip as $type => $events) { if (!Validators::is($type, 'unicode:1..')) { $this->logger->addWarning(sprintf('The keys of array $eventsToSkip must be non-empty strings. "%s" given', gettype($type))); continue; } if ($events === '*') { $this->eventsToSkip[$type] = $events; } elseif (is_array($events)) { foreach ($events as $event) { if (Validators::is($event, 'unicode:1..')) { $this->eventsToSkip[$type][$event] = $event; } else { $this->logger->addWarning(sprintf('The values of array $eventsToSkip[%s] must be non-empty string. "%s" given', $type, gettype($event))); } } } else { $this->logger->addWarning(sprintf('The values of array $eventsToSkip must be an ARRAY or * (a star). "%s" given', gettype($events))); } } } else { $this->logger->addWarning(sprintf('Argument $eventsToSkip must be an ARRAY or * (a star). "%s" given', gettype($eventsToSkip))); } }
public function loadState(array $params) { if (isset($params['page']) and !Validators::is($params['page'], 'numericint')) { $params['page'] = 1; } parent::loadState($params); $this->getPaginator()->setPage($this->page); $this->page = $this->getPaginator()->getPage(); }
/** * @param $user */ public function setUser($user) { if ($user instanceof User and !$user->isDetached()) { $this->assignEntityToProperty($user, 'user'); } else { if (Validators::is($user, 'numericint')) { $this->row->userID = $user; $this->row->cleanReferencedRowsCache('user', 'userID'); } else { throw new InvalidArgumentException('Argument $user can by only attached instance of App\\Entities\\User or integer number.'); } } }
public function actionRegistration($email, $token) { if (!Validators::is($email, 'email')) { $this->flashMessage('E-mailová adresa nemá platný formát.', 'warning'); $this->redirect('Login:default'); } try { $this->invitation = $this->invitationsFacade->checkInvitation($email, $token); } catch (\Exceptions\Runtime\InvitationValidityException $t) { $this->flashMessage('Registrovat se může pouze uživatel s platnou pozvánkou.', 'warning'); $this->redirect('Login:default'); } $this['registrationForm']['email']->setDefaultValue($this->invitation->email); }
/** * @param User|int $recipient */ private function setRecipient($recipient) { if ($recipient instanceof User and !$recipient->isDetached()) { $this->assignEntityToProperty($recipient, 'recipient'); } else { if (Validators::is($recipient, 'numericint')) { $this->row->recipient = $recipient; $this->row->cleanReferencedRowsCache('user', 'recipient'); } else { throw new InvalidArgumentException('Argument $recipient can by only instance of App\\Entities\\User or integer number.'); } } }
/** * @param string $author */ private function setAuthor($author) { if ($author instanceof User and !$author->isDetached()) { $this->assignEntityToProperty($author, 'author'); } else { if (Validators::is($author, 'numericint')) { $this->row->author = $author; $this->row->cleanReferencedRowsCache('user', 'author'); } else { throw new InvalidArgumentException('Argument $author can by only instance of App\\Entities\\User or integer number.'); } } }
/** * @param \App\Model\Entities\User|int $user * @return int */ protected function getUserID($user) { $id = null; if ($user instanceof User and !$user->isDetached()) { $id = $user->userID; } else { if (Validators::is($user, 'numericint')) { $id = $user; } else { throw new InvalidArgumentException('Argument $user must be instance of ' . User::class . ' or integer number.'); } } return $id; }
/** * Validate value for this rule * @param mixed $value * @param Rule $rule * @return bool * * @throws ValidationException * @throws InvalidStateException */ public function validate($value, Rule $rule) { if (isset($this->handle[$rule->expression])) { $callback = $this->handle[$rule->expression]; if (!is_callable($callback)) { throw new InvalidStateException('Handle for expression ' . $rule->expression . ' not found or is not callable'); } $params = array($value, $rule); call_user_func_array($callback, $params); return TRUE; } $expression = $this->parseExpression($rule); if (!Validators::is($value, $expression)) { throw ValidationException::createFromRule($rule, $value); } return TRUE; }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->hasOption('password') && $input->getOption('password') === NULL) { $output->writeln('<error>Please enable interactive mode to set password.</error>'); return 1; } if ($input->hasOption('password') && $input->getOption('generate-password')) { $output->writeln('<error>Cannot set and generate password at once.</error>'); return 1; } if (!$input->hasOption('password') && !$input->getOption('generate-password')) { $output->writeln('<error>Cannot create user without password.</error>'); return 1; } $name = $input->getArgument('name'); if ($this->model->getByNameOrEmail($name)) { $output->writeln('<error>User with same name already exists.</error>'); return 1; } $email = $input->getArgument('email'); if (!Validators::is($email, 'email')) { $output->writeln('<error>Invalid email</error>'); return 1; } if ($this->model->getByNameOrEmail($email)) { $output->writeln('<error>User with same email already exists.</error>'); return 1; } $printPassword = FALSE; if ($input->getOption('password') !== NULL) { $password = $input->getOption('password'); } elseif ($this->getOption('generate-password')) { $password = Strings::random(); $printPassword = TRUE; } $roles = $input->getOption('role'); $this->factory->create($name, $email, $password, $roles); if ($printPassword) { $verbosity = $output->getVerbosity(); $output->setVerbosity(OutputInterface::VERBOSITY_NORMAL); $output->write('<info>'); $output->write($password, OutputInterface::OUTPUT_RAW); $output->writeln('</info>'); $output->setVerbosity($verbosity); } }
/** * @param string $message * @param string $type * @param string|null $index * @param string|null $errorImportance */ public function addError($message, $type, $index = null, $errorImportance = null) { $error = new ValidationError($message, $type); if (Validators::is($errorImportance, 'unicode:1..')) { if (Validators::is($this->loggerChannel, 'unicode:1..')) { $error->setAsLoggable($errorImportance, $this->loggerChannel); } } if (Validators::is($index, 'unicode:1..')) { $error->setIndex($index); if (isset($this->errors[$index])) { throw new ValidationErrorIndexAlreadyExistsException(sprintf('Validation Object already contains an Error with index "%s"', $index)); } $this->errors[$index] = $error; } else { $this->errors[] = $error; } }
protected function createComponentOptionsForm() { $form = new Form(); $form->setTranslator($this->translator->domain('options.form')); $form->addText('blog_title', 'blogTitle.label', null, 255)->setRequired('blogTitle.messages.required'); $form->addText('blog_subtitle', 'blogSubtitle.label', null, 255); $form->addText('copyright', 'copyright.label', null, 255)->setRequired('copyright.messages.required'); $form->addText('articles_per_page', 'articlesPerPage.label', null, 2)->setRequired('articlesPerPage.messages.required')->addRule(function ($input) { if (Validators::is($input->value, 'numericint:1..')) { return true; } return false; }, 'articlesPerPage.messages.wrongInput'); $form->addText('google_analytics_measure_code', 'gaMeasureCode.label'); $form->addSubmit('save', 'save.caption'); $form->onSuccess[] = [$this, 'processForm']; $form->addProtection(); if (!$this->authorizator->isAllowed($this->user, 'options', 'edit')) { $form['save']->setDisabled(); } $form->setDefaults($this->optionFacade->loadOptions()); return $form; }
private function askInternalID(QuestionHelper $helper, InputInterface $input, OutputInterface $output) { $question = new Question('Internal ID: '); $question->setValidator(function ($answer) { if (!Validators::is(trim($answer), 'numericint:1..')) { throw new \RuntimeException('The Internal ID must be positive integer number.'); } return $answer; }); $question->setMaxAttempts(null); // unlimited number of attempts return $helper->ask($input, $output, $question); }
/** * Constructs absolute URL from Request object. * @param \Nette\Application\Request $appRequest * @param \Nette\Http\Url $refUrl * @throws \Nette\InvalidStateException * @return string|NULL */ public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return NULL; } $parameters = $appRequest->getParameters(); $url = $refUrl->getBaseUrl(); $urlStack = []; // Module prefix. $moduleFrags = explode(":", $appRequest->getPresenterName()); $moduleFrags = array_map('\\AdamStipak\\Support\\Inflector::spinalCase', $moduleFrags); $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; // Associations. if (isset($parameters['associations']) && Validators::is($parameters['associations'], 'array')) { $associations = $parameters['associations']; unset($parameters['associations']); foreach ($associations as $key => $value) { $urlStack[] = $key; $urlStack[] = $value; } } // Resource. $urlStack[] = $resourceName; // Id. if (isset($parameters['id']) && Validators::is($parameters['id'], 'scalar')) { $urlStack[] = $parameters['id']; unset($parameters['id']); } $url = $url . implode('/', $urlStack); $sep = ini_get('arg_separator.input'); if (isset($parameters['query'])) { $query = http_build_query($parameters['query'], '', $sep ? $sep[0] : '&'); if ($query != '') { $url .= '?' . $query; } } return $url; }
/** * Check value of quality * * @param int|string $quality * @param string $type */ private function checkQuality($quality) { // quality must be number or percent if (Validators::is($quality, 'string') && !Validators::isNumeric($quality)) { $msg = sprintf('Quality has unexpected format, "%s" given.', $quality); throw new InvalidArgumentException($msg); } // quality cannot be negative number if ((int) $quality < 0) { $msg = sprintf('Quality must be greater than 0, "%s" given.', $quality); throw new InvalidArgumentException($msg); } }
/** * Constructs absolute URL from Request object. * @param \Nette\Application\Request $appRequest * @param \Nette\Http\Url $refUrl * @throws \Nette\InvalidStateException * @return string|NULL */ public function constructUrl(Request $appRequest, Url $refUrl) { // Module prefix not match. if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) { return NULL; } $parameters = $appRequest->getParameters(); $url = $refUrl->getBaseUrl(); $urlStack = array(); // Module prefix. $moduleFrags = explode(":", Strings::lower($appRequest->getPresenterName())); $resourceName = array_pop($moduleFrags); $urlStack += $moduleFrags; // Associations. if (isset($parameters['associations']) && Validators::is($parameters['associations'], 'array')) { $associations =& $parameters['associations']; if (count($associations) % 2 !== 0) { throw new InvalidStateException("Number of associations is not even"); } foreach ($associations as $key => $value) { $urlStack[] = $key; $urlStack[] = $value; } } // Resource. $urlStack[] = Strings::lower($resourceName); // Id. if (isset($parameters['id']) && Validators::is($parameters['id'], 'scalar')) { $urlStack[] = $parameters['id']; } return $url . implode('/', $urlStack); }
private function askPassword(QuestionHelper $helper, InputInterface $input, OutputInterface $output) { $question = new Question('New user password: '******'unicode:1..')) { throw new \RuntimeException('The password must be non-empty string'); } return $answer; }); $question->setMaxAttempts(null); // unlimited number of attempts return $helper->ask($input, $output, $question); }
/** * @param Invitation|string $invitation * @throws InvitationNotFoundException * @throws InvitationExpiredException * @throws SendException * @return void */ public function sendInvitation($invitation) { if (Validators::is($invitation, 'string')) { $invitation = $this->invitationsReader->getInvitationByEmail($invitation); } $this->checkInvitationState($invitation); $this->invitationsSender->sendInvitation($invitation); $this->onAfterInvitationSending($invitation); }
/** * * @param int $year * @param int $month * @param int|null $day * @return boolean|\DateTime Returns DateTime if the given date is valid, otherwise returns FALSE */ public static function getDateTimeFromParameters($year, $month, $day = null) { if (!Validators::is($year, 'numericint') or !Validators::is($month, 'numericint') or !Validators::is($day, 'null|numericint')) { return FALSE; } if ($day == null) { if (\checkdate($month, 1, $year)) { return new \DateTime($year . '-' . $month); } } if (\checkdate($month, $day, $year)) { return new \DateTime($year . '-' . $month . '-' . $day); } return FALSE; }
/** privates */ private function autowireProps() { $rc = $this->getReflection(); foreach ($rc->getProperties() as $property) { $annotation = $property->getAnnotation('prop'); if ($annotation) { $type = (string) $property->getAnnotation('var'); $propName = isset($annotation['name']) ? $annotation['name'] : $property->name; //todo: implement @prop(type=specifictype) $value = $this->props->get($propName); if (in_array($type, ['array', 'int', 'numeric', 'string'])) { if (!Validators::is($value, $type)) { throw new PropValidationException("Prop {$propName} is not of required type {$type}but " . $this->getObjectType($value)); } } else { $type = PhpReflection::expandClassName($type, $rc); if (!$value instanceof $type) { throw new PropValidationException("Prop {$propName} is not of required type {$type}, but " . $this->getObjectType($value)); } } $this->{$property->name} = $value; } } }
/** * @param SentMessage|int $message * @return $this */ public function byMessage($message) { if (!Validators::is($message, 'numericint') and !$message instanceof SentMessage) { throw new InvalidArgumentException('Argument $message must be integer number or instance of ' . SentMessage::class); } $this->message = $message; $this->filter[] = function (QueryBuilder $qb) use($message) { $qb->andWhere('rm.message = :message')->setParameter('message', $message); }; return $this; }
/** * @param string $introHtml * @throws PageIntroHtmlLengthException */ public function setIntroHtml($introHtml) { Validators::assert($introHtml, 'unicode'); if (!Validators::is($introHtml, 'unicode:1..3000')) { throw new PageIntroHtmlLengthException(); } $this->introHtml = $introHtml; }
/** * @param string $name * @param mixed $value * @return boolean */ private function isValueValid($name, $value) { $metadata = self::getMetadata(); if ($metadata[$name][self::META_TYPE] === null) { return true; } else { $types = explode('|', $metadata[$name][self::META_TYPE]); foreach ($types as $key => $type) { $typeLength = strlen($type); if ($typeLength > 2 && $type[$typeLength - 2] === '[' && $type[$typeLength - 1] === ']') { $types[$key] = 'array'; } } return Validators::is($value, implode('|', $types)); } }
/** * @param string $value * @param string $format * * @return bool */ private function checkType($value, $format) { if ($format == 'date') { return $this->isValidDateString($value); } return Validators::is($value, $format); }