本文整理汇总了PHP中Nette\Utils\Validators类的典型用法代码示例。如果您正苦于以下问题:PHP Validators类的具体用法?PHP Validators怎么用?PHP Validators使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Validators类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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.');
}
}
开发者ID:newPOPE,项目名称:web-addons.nette.org,代码行数:10,代码来源:UrlsHelper.php
示例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]);
}
}
开发者ID:joseki,项目名称:migration,代码行数:26,代码来源:MigrationExtension.php
示例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;
}
开发者ID:venne,项目名称:newsletter-module,代码行数:11,代码来源:UserEntity.php
示例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);
}
}
开发者ID:NetteCamp,项目名称:2015-nextras-orm-twitter,代码行数:33,代码来源:ConsoleExtension.php
示例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']));
}
开发者ID:rixxi,项目名称:calculator,代码行数:7,代码来源:CalculatorExtension.php
示例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);
}
开发者ID:dtforce,项目名称:nette-doctrine,代码行数:32,代码来源:DoctrineExtension.php
示例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'));
}
开发者ID:Richmond77,项目名称:learning-nette,代码行数:11,代码来源:LatteExtension.php
示例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!');
}
开发者ID:wodcz,项目名称:sandbox,代码行数:29,代码来源:CreateUser.php
示例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);
}
开发者ID:rixxi,项目名称:env,代码行数:29,代码来源:EnvExtension.php
示例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;
}
开发者ID:claryaldringen,项目名称:Backend,代码行数:38,代码来源:EmailModel.php
示例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);
}
开发者ID:caloriscz,项目名称:caloriscms,代码行数:29,代码来源:LostPassControl.php
示例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));
}
}
开发者ID:duskohu,项目名称:Cronner,代码行数:28,代码来源:CronnerExtension.php
示例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
}
}
开发者ID:blitzik,项目名称:CMS,代码行数:35,代码来源:Authorizator.php
示例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)));
}
}
开发者ID:blitzik,项目名称:CMS,代码行数:31,代码来源:AppEventLogger.php
示例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;
}
开发者ID:Achse,项目名称:cargo-client,代码行数:34,代码来源:LogisticsExtension.php
示例16: setupTemplating
/**
* @param \Nette\DI\ContainerBuilder $container
* @param array $config
*/
private function setupTemplating(ContainerBuilder $container, array $config)
{
$def = $container->addDefinition($this->prefix('templateFilesFormatter'))->setClass('Lohini\\Templating\\TemplateFilesFormatter')->addSetup('$skin', [$config['skin']]);
foreach ($config['dirs'] as $dir => $priority) {
$def->addSetup('addDir', Validators::isNumericInt($dir) ? [$priority] : [$container->expand($dir), $priority]);
}
}
开发者ID:lohini,项目名称:framework,代码行数:11,代码来源:LohiniExtension.php
示例17: buildClient
/**
* @param string $name
* @param array $config
* @return Nette\DI\ServiceDefinition
*/
protected function buildClient($name, $config)
{
$builder = $this->getContainerBuilder();
$defaultConfig = $this->getConfig($this->clientDefaults);
if ($parentName = Config\Helpers::takeParent($config)) {
Nette\Utils\Validators::assertField($this->configuredClients, $parentName, 'array', "parent configuration '%', are you sure it's defined?");
$defaultConfig = Config\Helpers::merge($this->configuredClients[$parentName], $defaultConfig);
}
$config = Config\Helpers::merge($config, $defaultConfig);
$config = array_intersect_key(self::fixClientConfig($config), $this->clientDefaults);
$client = $builder->addDefinition($clientName = $this->prefix(($name ? $name . '_' : '') . 'client'))->setClass('Kdyby\\Redis\\RedisClient', ['host' => $config['host'], 'port' => $config['port'], 'database' => $config['database'], 'timeout' => $config['timeout'], 'auth' => $config['auth'], 'persistent' => $config['persistent']]);
if (empty($builder->parameters[$this->name]['defaultClient'])) {
$builder->parameters[$this->name]['defaultClient'] = $clientName;
$this->configuredClients['default'] = $config;
$builder->addDefinition($this->prefix('default_client'))->setClass('Kdyby\\Redis\\RedisClient')->setFactory('@' . $clientName)->setAutowired(FALSE);
} else {
$client->setAutowired(FALSE);
}
$this->configuredClients[$name] = $config;
$client->addSetup('setupLockDuration', [$config['lockDuration'], $config['lockAcquireTimeout']]);
$client->addSetup('setConnectionAttempts', [$config['connectionAttempts']]);
$client->addTag('redis.client');
if (array_key_exists('debugger', $config) && $config['debugger']) {
$builder->addDefinition($panelName = $clientName . '.panel')->setClass('Kdyby\\Redis\\Diagnostics\\Panel')->setFactory('Kdyby\\Redis\\Diagnostics\\Panel::register')->addSetup('$renderPanel', [$config['debugger'] !== self::PANEL_COUNT_MODE])->addSetup('$name', [$name ?: 'default']);
$client->addSetup('setPanel', ['@' . $panelName]);
}
return $client;
}
开发者ID:kdyby,项目名称:redis,代码行数:33,代码来源:RedisExtension.php
示例18: loadConfiguration
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
$builder->addDefinition($this->prefix('helperSet'))->setClass('Symfony\\Component\\Console\\Helper\\HelperSet', array(array(new Nette\DI\Statement('Symfony\\Component\\Console\\Helper\\DialogHelper'), new Nette\DI\Statement('Symfony\\Component\\Console\\Helper\\FormatterHelper'), new Nette\DI\Statement('Symfony\\Component\\Console\\Helper\\ProgressHelper'), new Nette\DI\Statement('Kdyby\\Console\\Helpers\\PresenterHelper'))))->setInject(FALSE);
$builder->addDefinition($this->prefix('application'))->setClass('Kdyby\\Console\\Application', array($config['name'], $config['version']))->addSetup('setHelperSet', array($this->prefix('@helperSet')))->setInject(FALSE);
$builder->addDefinition($this->prefix('router'))->setClass('Kdyby\\Console\\CliRouter')->setAutowired(FALSE)->setInject(FALSE);
$builder->getDefinition('router')->addSetup('Kdyby\\Console\\CliRouter::prependTo($service, ?)', array($this->prefix('@router')));
$builder->getDefinition('nette.presenterFactory')->addSetup('if (method_exists($service, ?)) { $service->setMapping(array(? => ?)); } ' . 'elseif (property_exists($service, ?)) { $service->mapping[?] = ?; }', array('setMapping', 'Kdyby', 'KdybyModule\\*\\*Presenter', 'mapping', 'Kdyby', 'KdybyModule\\*\\*Presenter'));
if (!empty($config['url'])) {
if (!preg_match('~^https?://[^/]+\\.[a-z]+(/.*)?$~', $config['url'])) {
throw new Nette\Utils\AssertionException("The url '{$config['url']}' is not valid, please use this format: 'http://domain.tld/path'.");
}
$builder->getDefinition('nette.httpRequestFactory')->setClass('Kdyby\\Console\\HttpRequestFactory')->addSetup('setFakeRequestUrl', array($config['url']));
}
$builder->addDefinition($this->prefix('dicHelper'))->setClass('Kdyby\\Console\\ContainerHelper')->addTag(self::HELPER_TAG, 'dic');
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::COMMAND_TAG);
}
}
开发者ID:pixuin,项目名称:console,代码行数:28,代码来源:ConsoleExtension.php
示例19: loadConfiguration
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
Validators::assertField($config, 'merchantId', 'string');
Validators::assertField($config, 'shopName', 'string');
Validators::assertField($config, 'productionMode', 'bool');
Validators::assertField($config, 'returnMethod', 'string|pattern:(GET|POST)');
$envConfig = $config['productionMode'] ? $config['production'] : $config['sandbox'];
if (is_string($envConfig['privateKey'])) {
$envConfig['privateKey'] = ['path' => $envConfig['privateKey'], 'password' => NULL];
}
if (empty($envConfig['privateKey']['path']) || !file_exists($envConfig['privateKey']['path'])) {
throw new InvalidConfigException('Private key for not provided.');
}
$builder->addDefinition($this->prefix('config'))->setClass('Kdyby\\CsobPaymentGateway\\Configuration', [$config['merchantId'], $config['shopName']])->addSetup('setUrl', [$envConfig['url']])->addSetup('setReturnUrl', [$config['returnUrl']])->addSetup('setReturnMethod', [$config['returnMethod']]);
$builder->addDefinition($this->prefix('httpClient'))->setClass('Kdyby\\CsobPaymentGateway\\IHttpClient')->setFactory('Kdyby\\CsobPaymentGateway\\Http\\GuzzleClient')->setAutowired(FALSE);
$builder->addDefinition($this->prefix('signature'))->setClass('Kdyby\\CsobPaymentGateway\\Message\\Signature', [new Statement('Kdyby\\CsobPaymentGateway\\Certificate\\PrivateKey', [$envConfig['privateKey']['path'], $envConfig['privateKey']['password']]), new Statement('Kdyby\\CsobPaymentGateway\\Certificate\\PublicKey', [$envConfig['publicKey']])])->setAutowired(FALSE);
$client = $builder->addDefinition($this->prefix('client'))->setClass('Kdyby\\CsobPaymentGateway\\Client', [$this->prefix('@config'), $this->prefix('@signature'), $this->prefix('@httpClient')]);
if ($config['logging']) {
if (!is_bool($config['logging']) && class_exists('Kdyby\\Monolog\\Logger')) {
$client->addSetup('setLogger', [new Statement('@Kdyby\\Monolog\\Logger::channel', [$config['logging']])]);
} else {
$client->addSetup('setLogger');
// autowire
}
}
$builder->addDefinition($this->prefix('control'))->setImplement('Kdyby\\CsobPaygateNette\\UI\\ICsobControlFactory')->setArguments([$this->prefix('@client')]);
}
开发者ID:jiripudil,项目名称:CsobPaygateNette,代码行数:29,代码来源:CsobPaygateExtension.php
示例20: createSchema
private function createSchema($name, $command)
{
$variables = $this->variables;
$defaults = $this->variables;
Validators::assert($command['variables'], 'array');
Validators::assert($command['templates'], 'array');
if (isset($command['defaults'])) {
Validators::assert($command['defaults'], 'array');
$defaults = array_merge($defaults, $command['defaults']);
}
foreach ($command['variables'] as $var) {
$variables[$var] = null;
}
foreach ($defaults as $varName => $value) {
$variables[$varName] = $value;
}
foreach ($command['templates'] as $templateVar => $template) {
if (!file_exists($template)) {
throw new InvalidArgumentException("Template file '{$template}' used in FileTemplate command '{$name}' not found.");
}
if (!array_key_exists($templateVar, $variables)) {
throw new InvalidArgumentException("Missing variable '{$templateVar}' in FileTemplate command '{$name}'. Templates must be in 'FILE_NAME_VAR: path/to/template' notation.");
}
}
return new Schema($variables, $command['templates']);
}
开发者ID:Joseki,项目名称:FileTemplate,代码行数:26,代码来源:FileTemplateExtension.php
注:本文中的Nette\Utils\Validators类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论