本文整理汇总了PHP中Nette\Utils\Validators类的典型用法代码示例。如果您正苦于以下问题:PHP Validators类的具体用法?PHP Validators怎么用?PHP Validators使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Validators类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: assertGithubRepositoryUrl
/**
* @param string
*/
public static function assertGithubRepositoryUrl($url)
{
Validators::assert($url, 'string', 'url');
if (!static::isGithubRepositoryUrl($url)) {
throw new \Nette\Utils\AssertionException('The url is not valid GitHub repository URL.');
}
}
示例2: loadConfiguration
public function loadConfiguration()
{
$container = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
Validators::assert($config['migrationDir'], 'string', 'Migration location directory');
Validators::assert($config['migrationPrefix'], 'string', 'Migration name prefix');
Validators::assert($config['options'], 'array', 'Generated SQL options');
if (!$config['logFile']) {
$config['logFile'] = FileSystem::normalizePath(sprintf('%s/_schema.txt', $config['migrationDir']));
}
$container->addDefinition($this->prefix('repository'))->setClass('Joseki\\Migration\\Database\\Repository', [$config['migrationTable']]);
$manager = $container->addDefinition($this->prefix('manager'))->setClass('Joseki\\Migration\\Manager', [$config['migrationDir'], $config['migrationPrefix']]);
$container->addDefinition($this->prefix('command.schema'))->setClass('Joseki\\Migration\\Console\\Command\\Schema', [$config['logFile']])->addTag(self::TAG_JOSEKI_COMMAND)->addTag(self::TAG_KDYBY_COMMAND);
$container->addDefinition($this->prefix('command.create'))->setClass('Joseki\\Migration\\Console\\Command\\Create')->addTag(self::TAG_JOSEKI_COMMAND)->addTag(self::TAG_KDYBY_COMMAND);
$container->addDefinition($this->prefix('command.migrate'))->setClass('Joseki\\Migration\\Console\\Command\\Migrate')->addTag(self::TAG_JOSEKI_COMMAND)->addTag(self::TAG_KDYBY_COMMAND);
$container->addDefinition($this->prefix('platform'))->setClass('Doctrine\\DBAL\\Platforms\\MySqlPlatform');
$container->addDefinition($this->prefix('generator.lm'))->setClass('Joseki\\Migration\\Generator\\LeanMapperSchemaGenerator', [$config['options']]);
foreach ($this->getFiles($config['migrationDir']) as $index => $class) {
if (!($class = $this->resolveRealClassName($class))) {
continue;
}
$name = $this->prefix('migration.' . $index);
$container->addDefinition($name)->setClass($class)->setInject(false)->setAutowired(false);
$manager->addSetup('add', ['@' . $name]);
}
}
示例3: setEmail
/**
* @param $email
* @throws \Nette\InvalidArgumentException
*/
public function setEmail($email)
{
if (!Validators::isEmail($email)) {
throw new InvalidArgumentException("Email must be in correct format.");
}
$this->email = $email;
}
示例4: loadConfiguration
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
$helperClasses = array('Symfony\\Component\\Console\\Helper\\FormatterHelper', 'Symfony\\Component\\Console\\Helper\\QuestionHelper', 'Kdyby\\Console\\Helpers\\PresenterHelper');
$helperClasses = array_map(function ($class) {
return new Nette\DI\Statement($class);
}, $helperClasses);
if (class_exists('Symfony\\Component\\Console\\Helper\\ProgressHelper')) {
$helperClasses[] = new Nette\DI\Statement('Symfony\\Component\\Console\\Helper\\ProgressHelper', array(false));
}
if (class_exists('Symfony\\Component\\Console\\Helper\\DialogHelper')) {
$helperClasses[] = new Nette\DI\Statement('Symfony\\Component\\Console\\Helper\\DialogHelper', array(false));
}
$builder->addDefinition($this->prefix('helperSet'))->setClass('Symfony\\Component\\Console\\Helper\\HelperSet', array($helperClasses))->setInject(FALSE);
$builder->addDefinition($this->prefix('application'))->setClass('Kdyby\\Console\\Application', array($config['name'], $config['version']))->addSetup('setHelperSet', array($this->prefix('@helperSet')))->addSetup('injectServiceLocator')->setInject(FALSE);
$builder->addDefinition($this->prefix('dicHelper'))->setClass('Kdyby\\Console\\ContainerHelper')->addTag(self::TAG_HELPER, 'dic');
if ($config['disabled']) {
return;
}
$builder->addDefinition($this->prefix('router'))->setClass('Kdyby\\Console\\CliRouter')->setAutowired(FALSE)->setInject(FALSE);
Nette\Utils\Validators::assert($config, 'array');
foreach ($config['commands'] as $command) {
$def = $builder->addDefinition($this->prefix('command.' . md5(Nette\Utils\Json::encode($command))));
list($def->factory) = Nette\DI\Compiler::filterArguments(array(is_string($command) ? new Nette\DI\Statement($command) : $command));
if (class_exists($def->factory->entity)) {
$def->class = $def->factory->entity;
}
$def->setAutowired(FALSE);
$def->setInject(FALSE);
$def->addTag(self::TAG_COMMAND);
}
}
示例5: loadConfiguration
public function loadConfiguration()
{
$config = $this->getConfig($this->defaults);
Validators::assert($config['precision'], 'int:0..');
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('calculator'))->setClass(Calculator::class, array($config['precision']));
}
示例6: loadConfiguration
public function loadConfiguration()
{
$config = $this->getConfig(self::$defaults);
$this->classMappings = $config['targetEntityMappings'];
$this->entitySources = $config['metadata'];
foreach ($this->compiler->getExtensions() as $extension) {
if ($extension instanceof IEntitySourceProvider) {
$entitySource = $extension->getEntityFolderMappings();
Validators::assert($entitySource, 'array');
$this->entitySources = array_merge($this->entitySources, $entitySource);
}
if ($extension instanceof IClassMappingProvider) {
$entityMapping = $extension->getClassnameToClassnameMapping();
Validators::assert($entityMapping, 'array');
$this->classMappings = array_merge($this->classMappings, $entityMapping);
}
}
if ($config['sourceDir'] !== NULL) {
$this->entitySources[] = $config['sourceDir'];
}
$builder = $this->getContainerBuilder();
$name = $config['prefix'];
$builder->addDefinition($name . ".resolver")->setClass('\\Doctrine\\ORM\\Tools\\ResolveTargetEntityListener');
$builder->addDefinition($name . ".naming")->setClass('\\Doctrine\\ORM\\Mapping\\UnderscoreNamingStrategy');
$builder->addDefinition($name . ".config")->setClass('\\Doctrine\\ORM\\Configuration')->addSetup(new Statement('setFilterSchemaAssetsExpression', [$config['dbal']['schema_filter']]));
$builder->addDefinition($name . ".connection")->setClass('\\Doctrine\\DBAL\\Connection')->setFactory('@' . $name . '.entityManager::getConnection');
$builder->addDefinition($name . ".entityManager")->setClass('\\Doctrine\\ORM\\EntityManager')->setFactory('\\Doctrine\\ORM\\EntityManager::create', [$config['connection'], '@' . $name . '.config', '@Doctrine\\Common\\EventManager']);
if ($this->hasIBarPanelInterface()) {
$builder->addDefinition($this->prefix($name . '.diagnosticsPanel'))->setClass(self::DOCTRINE_SQL_PANEL_FQN);
}
$this->addHelpersToKdybyConsole($builder);
}
示例7: addMacro
/**
* @param callable
* @return void
*/
public function addMacro($macro)
{
Nette\Utils\Validators::assert($macro, 'callable');
$container = $this->getContainerBuilder();
$container->getDefinition('nette.latte')->addSetup('?->onCompile[] = function ($engine) { ' . $macro . '($engine->getCompiler()); }', array('@self'));
$container->getDefinition($this->prefix('latteFactory'))->addSetup('?->onCompile[] = function ($engine) { ' . $macro . '($engine->getCompiler()); }', array('@self'));
}
示例8: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var QuestionHelper $questionHelper */
$questionHelper = $this->getHelper('question');
$usernameQuestion = new Question('E-mail: ');
$usernameQuestion->setValidator(function ($value) {
if (trim($value) === '') {
throw new \Exception('E-mail can not be empty');
}
if (!Validators::isEmail($value)) {
throw new \Exception('E-mail is not valid');
}
return $value;
});
$passwordQuestion = new Question('Password: ');
$passwordQuestion->setValidator(function ($value) {
if (trim($value) === '') {
throw new \Exception('The password can not be empty');
}
return $value;
});
$passwordQuestion->setHidden(TRUE);
$passwordQuestion->setHiddenFallback(FALSE);
$username = $questionHelper->ask($input, $output, $usernameQuestion);
$password = $questionHelper->ask($input, $output, $passwordQuestion);
$name = $questionHelper->ask($input, $output, new Question('Name: '));
$user = $this->userFacade->add($username, $password, $name);
$output->writeln('User ' . $user->getEmail() . ' was successfully created!');
}
示例9: loadConfiguration
public function loadConfiguration()
{
$config = $this->getConfig($this->defaults);
Validators::assert($config['parameters'], 'array');
$parameters = array();
foreach ($config['parameters'] as $name => $value) {
self::assertEnvName($name);
self::assertEnvValue($value, $name);
$parameters[$name] = $value;
}
Validators::assert($config['whitelist'], 'bool');
if (strpos(ini_get('variables_order'), 'E') === TRUE) {
foreach ($_ENV as $name => $value) {
if ($config['whitelist'] && !isset($parameters[$name])) {
continue;
}
self::assertEnvName($name);
self::assertEnvValue($value, $name);
$parameters[$name] = $value;
}
} else {
foreach (array_keys($config['parameters']) as $name) {
if (($value = getenv($name)) !== FALSE) {
$parameters[$name] = $value;
}
}
}
$this->getContainerBuilder()->parameters += array(self::PARAMETER_CONTAINER => $parameters);
}
示例10: setEmails
/**
* @param array $emails
* @return $this
* @throws Exception
* @throws \Dibi\Exception
*/
public function setEmails(array $emails)
{
$this->dbPostfix->begin();
try {
foreach ($emails as $email) {
if (!empty($email->id)) {
$this->dbPostfix->query("UPDATE mailbox SET [user]=%s, password=%s WHERE id=%i", $email->username, $email->password, $email->id);
} else {
$this->dbPostfix->query("INSERT INTO mailbox", array('user' => $email->username, 'password' => $email->password, 'domain_id' => $this->getDomainId()));
}
if (!empty($email->alias)) {
$aliases = explode(',', str_replace(' ', '', $email->alias));
foreach ($aliases as $alias) {
if (!\Nette\Utils\Validators::isEmail($alias)) {
throw new CmsException($alias . ' není platný email.');
}
}
$aliasId = $this->dbPostfix->query("SELECT id FROM alias WHERE domain_id=%i AND [user]=%s", $this->getDomainId(), $email->username)->fetchSingle();
if (!empty($aliasId)) {
$this->dbPostfix->query("UPDATE alias SET target=%s WHERE id=%i", implode(',', $aliases), $aliasId);
} else {
$this->dbPostfix->query("INSERT INTO alias", array('domain_id' => $this->getDomainId(), 'user' => $email->username, 'target' => implode(',', $aliases)));
}
}
}
} catch (Exception $ex) {
$this->dbPostfix->rollback();
throw $ex;
}
$this->dbPostfix->commit();
return $this;
}
示例11: sendFormSucceeded
function sendFormSucceeded(\Nette\Forms\BootstrapUIForm $form)
{
$email = $form->getValues()->email;
if ($form->values->layer == 'admin') {
$lostPass = $this->database->table("helpdesk_emails")->where("template", "lostpass-admin")->fetch();
} else {
$lostPass = $this->database->table("helpdesk_emails")->where("template", "lostpass-member")->fetch();
}
if (!\Nette\Utils\Validators::isEmail($email)) {
$this->presenter->flashMessage("Adresa je neplatná");
$this->presenter->redirect(":Front:Sign:lostpass");
}
$passwordGenerate = \Nette\Utils\Random::generate(12, "987654321zyxwvutsrqponmlkjihgfedcba");
if ($this->database->table('users')->where(array('email' => $email))->count() == 0) {
$this->flashMessage("E-mail nenalezen");
$this->presenter->redirect(":Front:Sign:lostpass");
}
$member = new \App\Model\MemberModel($this->database);
$member->setActivation($email, $passwordGenerate);
$latte = new \Latte\Engine();
$latte->setLoader(new \Latte\Loaders\StringLoader());
$params = array('code' => $passwordGenerate, 'email' => $email, 'settings' => $this->presenter->template->settings);
$mail = new \Nette\Mail\Message();
$mail->setFrom($this->presenter->template->settings['contacts:email:hq'])->addTo($email)->setSubject("Informace o novém hesle")->setHTMLBody($latte->renderToString($lostPass->body, $params));
$mailer = new \Nette\Mail\SendmailMailer();
$mailer->send($mail);
$this->presenter->flashMessage('Informace o zapomenutém hesle odeslány', 'success');
$this->presenter->redirect(this);
}
示例12: loadConfiguration
public function loadConfiguration()
{
$container = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
Validators::assert($config['timestampStorage'], 'string|object|null', 'Timestamp storage definition');
Validators::assert($config['maxExecutionTime'], 'integer|null', 'Script max execution time');
Validators::assert($config['criticalSectionTempDir'], 'string', 'Critical section files directory path');
$storage = $container->addDefinition($this->prefix('timestampStorage'))->setAutowired(FALSE)->setInject(FALSE);
if ($config['timestampStorage'] === NULL) {
$storageServiceName = $container->getByType('stekycz\\Cronner\\ITimestampStorage');
if ($storageServiceName) {
$storage->setFactory('@' . $storageServiceName);
} else {
$storage->setClass(self::DEFAULT_STORAGE_CLASS, array(self::DEFAULT_STORAGE_DIRECTORY));
}
} else {
if (is_string($config['timestampStorage']) && $container->getServiceName($config['timestampStorage'])) {
$storage->setFactory($config['timestampStorage']);
} else {
$storage->setClass($config['timestampStorage']->entity, $config['timestampStorage']->arguments);
}
}
$criticalSection = $container->addDefinition($this->prefix("criticalSection"))->setClass('stekycz\\Cronner\\CriticalSection', array($config['criticalSectionTempDir']))->setAutowired(FALSE)->setInject(FALSE);
$runner = $container->addDefinition($this->prefix('runner'))->setClass('stekycz\\Cronner\\Cronner', array($storage, $criticalSection, $config['maxExecutionTime'], array_key_exists('debugMode', $config) ? !$config['debugMode'] : TRUE));
foreach (array_keys($container->findByTag(self::TASKS_TAG)) as $serviceName) {
$runner->addSetup('addTasks', array('@' . $serviceName));
}
}
示例13: isAllowed
/**
* @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
}
}
示例14: addEventsToSkip
/**
* @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)));
}
}
示例15: configureClient
/**
* @param array $config
* @param string $tokenStorageDefinition
* @param string|NULL $name
* @return ServiceDefinition
* @throws InvalidConfigException
*/
private function configureClient(array $config, $tokenStorageDefinition, $name = NULL)
{
$name = $name !== NULL ? ".{$name}" : '';
$builder = $this->getContainerBuilder();
$message = 'parameter % in LogisticsExtension configuration';
Validators::assertField($config, 'appId', 'string', $message);
Validators::assertField($config, 'secret', 'string', $message);
if (!$builder->parameters['debugMode']) {
Validators::assertField($config, 'apiBaseUrl', 'url', $message);
Validators::assertField($config, 'apiBaseUrl', 'pattern:https\\:\\/\\/.*', $message);
}
$consumerDefinition = $builder->addDefinition($this->prefix("consumer{$name}"))->setClass(Consumer::class, [$config['appId'], $config['secret']])->setAutowired(FALSE);
if (!array_key_exists('requestFactory', $config)) {
$requestFactoryDefinition = $builder->addDefinition($this->prefix("requestFactory{$name}"))->setClass(RequestFactory::class, [$config['apiBaseUrl']])->setAutowired(FALSE);
} else {
// touch reference to validate it
if (!$builder->getServiceName($requestFactoryDefinition = $config['requestFactory'])) {
throw new InvalidConfigException("Invalid reference to service implementing IRequestFactory given: {$config['requestFactory']}");
}
}
$connectorDefinition = $builder->addDefinition($this->prefix("connector{$name}"))->setClass(Connector::class, [$consumerDefinition, $tokenStorageDefinition, $requestFactoryDefinition])->setAutowired(FALSE);
$logisticsClientDefiniton = $builder->addDefinition($this->prefix("logisticsClient{$name}"))->setClass(LogisticsClient::class, [$connectorDefinition, $requestFactoryDefinition]);
if ($name !== '') {
$logisticsClientDefiniton->setAutowired(FALSE);
}
return $logisticsClientDefiniton;
}