public function testProviderIsAdded() { $targetService = new Definition(); $targetService->setClass('Faker\\Generator'); $provider = $this->getMock('Acme\\Faker\\Provider\\CustomFakeDataProvider'); $providerService = new Definition(); $providerService->setClass(get_class($provider)); $providerService->addTag('bazinga_faker.provider'); $builder = new ContainerBuilder(); $builder->addDefinitions(array('faker.generator' => $targetService, 'acme.faker.provider.custom' => $providerService)); $builder->addCompilerPass(new AddProvidersPass()); $builder->compile(); $this->assertNotEmpty($builder->getServiceIds(), 'The services have been injected.'); $this->assertNotEmpty($builder->get('faker.generator'), 'The faker.generator service has been injected.'); $this->assertNotEmpty($builder->get('acme.faker.provider.custom'), 'The provider service has been injected.'); /* * Schema: * * [0] The list of methods. * [0] The name of the method to call. * [1] The arguments to pass into the method call. * [0] First argument to pass into the method call. * ... */ $targetMethodCalls = $builder->getDefinition('faker.generator')->getMethodCalls(); $this->assertNotEmpty($targetMethodCalls, 'The faker.generator service got method calls added.'); $this->assertEquals('addProvider', $targetMethodCalls[0][0], 'The faker.generator service got a provider added.'); $this->assertEquals('acme.faker.provider.custom', $targetMethodCalls[0][1][0], 'The faker.generator service got the correct provider added.'); }
/** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $configuration = $container->getParameter('knp_rad_auto_registration.configuration'); $enable = $configuration['enable']; $generator = $container->get('knp_rad_auto_registration.service_name_generator.bundle_service_name_generator'); foreach ($container->findTaggedServiceIds('knp_rad_auto_registration.definition_builder') as $id => $tags) { $builder = $container->get($id); if (false === $builder->isActive()) { continue; } if (false === in_array($builder->getName(), $this->sections)) { continue; } if (false === array_key_exists($builder->getName(), $enable)) { continue; } $definitions = $builder->buildDefinitions($enable[$builder->getName()]); foreach ($definitions as $class => $definition) { $serviceId = $generator->generateFromClassname($class); if (true === $container->hasDefinition($serviceId)) { continue; } if (true === $container->hasAlias($serviceId)) { continue; } $container->setDefinition($serviceId, $definition); } } }
/** * @param null $configPath * @param array $configFilenames */ function __construct($configPath = null, $configFilenames = array()) { $configPath = $configPath == null ? __DIR__ . '/../../../../../../app/config' : $configPath; $this->container = new ContainerBuilder(); // Load app parameters and config files into container $loader = new YamlFileLoader($this->container, new FileLocator($configPath)); $loader->load('parameters.yml'); foreach ($configFilenames as $filename) { $loader->load($filename); } $appName = $this->container->getParameter('application_name'); $appVersion = $this->container->getParameter('application_version'); parent::__construct($appName, $appVersion); // Set dispatcher definition, register listeners and subscribers $dispatcherDef = $this->container->register('event_dispatcher', 'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher'); $dispatcherDef->addArgument($this->container); $this->registerEventListeners(); $this->container->compile(); // Once container is compiled we can get the event_dispatcher from dic $this->dispatcher = $this->container->get('event_dispatcher'); // Add console commands (services console.command tagged) foreach ($this->getTaggedCommands() as $id) { $command = $this->container->get($id); $this->add($command); } }
public function process(ContainerBuilder $container) { $enableCache = $container->getParameter('antares_accessible.cache.enable'); // Annotation reader $annotationsReader = $container->get('antares_accessible.annotations.reader'); if ($annotationsReader instanceof NullService) { if ($enableCache) { $debug = $container->getParameter('kernel.debug'); $annotationCacheDriver = $container->get('antares_accessible.annotations.cache_driver'); $annotationsCache = new ChainCache([new ArrayCache(), $annotationCacheDriver]); Configuration::setAnnotationReader(new CachedReader(new AnnotationReader(), $annotationsCache, $debug)); } } else { Configuration::setAnnotationReader($annotationsReader); } // Constraints validator $constraintsValidator = $container->get('antares_accessible.constraints_validation.validator'); if (!$constraintsValidator instanceof NullService) { Configuration::setConstraintsValidator($constraintsValidator); } // Cache driver if ($enableCache) { $cacheDriver = $container->get('antares_accessible.cache.driver'); Configuration::setCacheDriver($cacheDriver); } // Enable the constraints validation of Initialize annotations values $constraintsValidationEnabled = $container->getParameter('antares_accessible.constraints_validation.enable'); Configuration::setConstraintsValidationEnabled($constraintsValidationEnabled); // Enable the constraints validation of Initialize annotations values $validateInitializeValues = $container->getParameter('antares_accessible.constraints_validation.validate_initialize_values'); Configuration::setInitializeValuesValidationEnabled($validateInitializeValues); }
/** * @param ContainerBuilder $container * * @throws \InvalidArgumentException */ public function process(ContainerBuilder $container) { $config = $container->getExtensionConfig('elastica')[0]; $jsonLdFrameLoader = $container->get('nemrod.elastica.jsonld.frame.loader.filesystem'); $confManager = $container->getDefinition('nemrod.elastica.config_manager'); $filiationBuilder = $container->get('nemrod.filiation.builder'); $jsonLdFrameLoader->setFiliationBuilder($filiationBuilder); foreach ($config['indexes'] as $name => $index) { $indexName = isset($index['index_name']) ? $index['index_name'] : $name; foreach ($index['types'] as $typeName => $settings) { $jsonLdFrameLoader->setEsIndex($name); $frame = $jsonLdFrameLoader->load($settings['frame'], null, true, true, true); $type = !empty($frame['@type']) ? $frame['@type'] : $settings['type']; if (empty($type)) { throw \Exception("You must provide a RDF Type."); } //type $typeId = 'nemrod.elastica.type.' . $name . '.' . $typeName; $indexId = 'nemrod.elastica.index.' . $name; $typeDef = new DefinitionDecorator('nemrod.elastica.type.abstract'); $typeDef->replaceArgument(0, $type); $typeDef->setFactory(array(new Reference($indexId), 'getType')); $typeDef->addTag('nemrod.elastica.type', array('index' => $name, 'name' => $typeName, 'type' => $type)); $container->setDefinition($typeId, $typeDef); //registering config to configManager $confManager->addMethodCall('setTypeConfigurationArray', array($name, $typeName, $type, $frame)); } } }
protected function getAnalyzerCommand() { $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__)); $loader->load('Config/services.yml'); return new AnalyzerCommand($container->get('analyzer'), $container->get('logger')); }
public function testQueryService() { $this->loadConfiguration($this->container, 'xiti_analytics'); $this->container->compile(); $query = $this->container->get('request_lab_xiti_analytics.query'); $this->assertInstanceOf('RequestLab\\XitiAnalytics\\Query', $query); }
public function testReconnectConfiguration() { $this->initContainer(); $this->loadConfiguration($this->container, 'reconnect_config'); $this->container->compile(); $this->assert->boolean($this->container->has('m6_redis'))->isIdenticalTo(true)->and()->object($serviceRedis = $this->container->get('m6_redis'))->isInstanceOf('M6Web\\Bundle\\RedisBundle\\Redis\\Redis'); }
/** * {@inheritDoc} */ public function process(ContainerBuilder $container) { try { // We have the service fork.settings and it's not empty if ($container->has('fork.settings') && !is_a($container->get('fork.settings'), 'stdClass')) { // we must set these parameters to be usable $container->setParameter('mailmotor.mail_engine', $container->get('fork.settings')->get('Mailmotor', 'mail_engine')); $container->setParameter('mailmotor.api_key', $container->get('fork.settings')->get('Mailmotor', 'api_key')); $container->setParameter('mailmotor.list_id', $container->get('fork.settings')->get('Mailmotor', 'list_id')); // When in fork cms installer, we don't have the service fork.settings // but we must set the parameters } else { // we must set these parameters to be usable $container->setParameter('mailmotor.mail_engine', 'not_implemented'); $container->setParameter('mailmotor.api_key', null); $container->setParameter('mailmotor.list_id', null); } } catch (\Exception $e) { // this might fail in the test so we have this as fallback // we must set these parameters to be usable $container->setParameter('mailmotor.mail_engine', 'not_implemented'); $container->setParameter('mailmotor.api_key', null); $container->setParameter('mailmotor.list_id', null); } }
/** * Updates a user. * * @param UserInterface $user * @param Boolean $andFlush Whether to flush the changes (default true) */ public function updateUser(UserInterface $user, $andFlush = true) { parent::updateUser($user, $andFlush); if ($this->container->getParameter('ephp_acl.access_log.enable')) { $accessClassName = $this->accessClass; try { $request = $this->container->get('request'); // \Ephp\UtilityBundle\Utility\Debug::vd($request); $check_ip = $this->container->getParameter('ephp_acl.access_log.check_ip'); if ($check_ip) { $_access = $this->objectManager->getRepository($accessClassName); /* @var $_access Ephp\ACLBundle\Model\BaseAccessLogRepository */ $_access->checkIp($user, $request->server->get('REMOTE_ADDR')); } $access = new $accessClassName(); /* @var $access \Ephp\ACLBundle\Model\BaseAccessLog */ $access->setUser($user); /* @var $request \Symfony\Component\HttpFoundation\Request */ $access->setIp($request->server->get('REMOTE_ADDR')); foreach ($request->cookies as $name => $cookie) { $access->addCookie($name, $cookie); } $access->setLoggedAt(new \DateTime()); $access->addNote('user_agent', $request->server->get('HTTP_USER_AGENT')); $access->addNote('accept_language', $request->server->get('HTTP_ACCEPT_LANGUAGE')); $this->objectManager->persist($access); $this->objectManager->flush(); // \Ephp\UtilityBundle\Utility\Debug::pr($request->server); $request->getSession()->set('access.log', $access->getId()); } catch (CheckIpException $e) { throw $e; } catch (\Exception $e) { } } }
/** * Returns task * * @param string $alias name of the task * @param array $options configuration options for the task * @return Task */ public function get($alias, array $options = array()) { $serviceId = $this->tasks[$alias]; $task = $this->container->get($serviceId); $task->setOptions($options); return $task; }
public function process(ContainerBuilder $container) { $reader = $container->get('annotation_reader'); $factory = $container->get('jms_di_extra.metadata.metadata_factory'); $converter = $container->get('jms_di_extra.metadata.converter'); $directories = $this->getScanDirectories($container); if (!$directories) { $container->getCompiler()->addLogMessage('No directories configured for AnnotationConfigurationPass.'); return; } $files = $this->finder->findFiles($directories); $container->addResource(new ServiceFilesResource($files, $directories)); foreach ($files as $file) { $container->addResource(new FileResource($file)); require_once $file; $className = $this->getClassName($file); if (null === ($metadata = $factory->getMetadataForClass($className))) { continue; } if (null === $metadata->getOutsideClassMetadata()->id) { continue; } foreach ($converter->convert($metadata) as $id => $definition) { $container->setDefinition($id, $definition); } } }
/** * Set up application: */ public function __construct() { $this->filesystem = new Filesystem(); $this->container = $this->getContainer(); $this->setDispatcher($this->container->get('event_dispatcher')); parent::__construct(self::APP_NAME, self::APP_VERSION); }
/** * @throws NotFoundException * * @param string $serviceId * @return mixed */ public function get($serviceId) { if (!$this->has($serviceId)) { throw NotFoundException::constructWithThingNotFound($serviceId); } return $this->symfonyServiceContainer->get($serviceId); }
public function testTemplatingConfiguration() { $this->loadConfiguration($this->container, 'simple'); $this->container->compile(); $helper = $this->container->get('fm_tinymce.templating.helper'); $this->assertInstanceOf('FM\\TinyMCEBundle\\Templating\\TinyMCEHelper', $helper); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $file = $this->directory . '/.tl.yml'; if (file_exists($file)) { $config = Yaml::parse(file_get_contents($file)); $output->writeln(sprintf('<info>Found existing file %s</info>', $file)); } else { $output->writeln('<info>Creating new file</info>'); $config = []; } foreach ($this->configurableServiceIds as $service_id) { $service_definition = $this->container->getDefinition($service_id); /** @var ConfigurableService $service_class */ $service_class = $service_definition->getClass(); $config = $service_class::getDefaults($config); $config = $service_class::askPreBootQuestions($helper, $input, $output, $config); } $this->container->setParameter('config', $config); // Now we can attempt boot. foreach ($this->configurableServiceIds as $service_id) { /** @var ConfigurableService $service */ $service = $this->container->get($service_id); $config = $service->askPostBootQuestions($helper, $input, $output, $config); } $this->container->setParameter('config', $config); file_put_contents($file, Yaml::dump($config)); $output->writeln(sprintf('<info>Wrote configuration to file %s</info>', $file)); }
/** * Tests the rest client configuration * * @test * * @covers Ci\RestClientBundle\DependencyInjection\CiRestClientExtension::load * @covers Ci\RestClientBundle\DependencyInjection\Configuration::getConfigTreeBuilder */ public function restClientConfig() { $this->loadConfiguration($this->container); $this->container->compile(); $this->assertTrue($this->container->has('ci.restclient')); $this->assertInstanceOf('Ci\\RestClientBundle\\Services\\RestClient', $this->container->get('ci.restclient')); }
public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) { if (!in_array($id, $this->ownServiceIds)) { throw new \LogicException('forbidden'); } return $this->delegate->get($id, $invalidBehavior); }
public function process(ContainerBuilder $container) { if (!$container->hasDefinition('json_schema.registry') || !$container->has('annotation_reader') || !$container->has('json_schema.reflection_factory')) { return; } $registry = $container->getDefinition('json_schema.registry'); $reader = $container->get('annotation_reader'); $factory = $container->get('json_schema.reflection_factory'); $mappings = $container->getParameter('json_schema.mappings'); foreach ($mappings as $mapping) { if (isset($mapping['dir']) && isset($mapping['prefix'])) { /** @var \ReflectionClass[] $refClasses */ $refClasses = $factory->createFromDirectory($mapping['dir'], $mapping['prefix']); foreach ($refClasses as $refClass) { foreach ($reader->getClassAnnotations($refClass) as $annotation) { if ($annotation instanceof \Knp\JsonSchemaBundle\Annotations\Schema) { $alias = $annotation->name ?: strtolower($refClass->getShortName()); $registry->addMethodCall('register', [$alias, $refClass->getName()]); } } } } elseif (isset($mapping['class'])) { $refClass = new \ReflectionClass($mapping['class']); foreach ($reader->getClassAnnotations($refClass) as $annotation) { if ($annotation instanceof \Knp\JsonSchemaBundle\Annotations\Schema) { $alias = $annotation->name ?: strtolower($refClass->getShortName()); $registry->addMethodCall('register', [$alias, $refClass->getName()]); } } } else { throw new \RuntimeException("Invalid mapping configuration!"); } } }
public function process(ContainerBuilder $container) { $factory = $container->get('jms_di_extra.metadata.metadata_factory'); $converter = $container->get('jms_di_extra.metadata.converter'); $disableGrep = $container->getParameter('jms_di_extra.disable_grep'); $directories = $this->getScanDirectories($container); if (!$directories) { $container->getCompiler()->addLogMessage('No directories configured for AnnotationConfigurationPass.'); return; } $finder = new PatternFinder('JMS\\DiExtraBundle\\Annotation', '*.php', $disableGrep); $files = $finder->findFiles($directories); $container->addResource(new ServiceFilesResource($files, $directories, $disableGrep)); foreach ($files as $file) { $container->addResource(new FileResource($file)); require_once $file; $className = $this->getClassName($file); if (null === ($metadata = $factory->getMetadataForClass($className))) { continue; } if (null === $metadata->getOutsideClassMetadata()->id) { continue; } if (!$metadata->getOutsideClassMetadata()->isLoadedInEnvironment($container->getParameter('kernel.environment'))) { continue; } foreach ($converter->convert($metadata) as $id => $definition) { $container->setDefinition($id, $definition); } } }
public function testVimeoService() { $this->loadConfiguration($this->container, 'request_lab_vimeo'); $this->container->compile(); $vimeo = $this->container->get('vimeo'); $this->assertInstanceOf('RequestLab\\VimeoBundle\\Service\\VimeoService', $vimeo); }
public function testPredefinedDiscovery() { $this->container->setParameter('kernel.debug', false); $this->load(['service' => ['name' => 'phpunit'], 'discovery' => ['type' => 'predefined', 'endpoints' => ['name' => ['http://foo.com', 'https://foo.com']]]]); $driver = $this->container->get('seven_service_bus.discovery'); $this->assertInstanceOf(PredefinedDiscovery::class, $driver); }
public function testSharedService() { $this->loader->load(__DIR__ . '/Fixtures/sharedService.yml'); $this->container->compile(); $one = $this->container->get('foo'); $two = $this->container->get('foo'); $this->assertNotSame($one, $two); }
function it_does_not_crash_if_themes_not_found(ContainerBuilder $containerBuilder, Definition $themeRepositoryDefinition, LoaderInterface $themeLoader, FileLocatorInterface $themeLocator) { $themeLocator->locate("theme.json", Argument::any(), false)->shouldBeCalled()->willThrow(new \InvalidArgumentException()); $containerBuilder->findDefinition("sylius.theme.repository")->shouldBeCalled()->willReturn($themeRepositoryDefinition); $containerBuilder->get("sylius.theme.locator")->shouldBeCalled()->willReturn($themeLocator); $containerBuilder->get("sylius.theme.loader")->shouldBeCalled()->willReturn($themeLoader); $this->process($containerBuilder); }
public function testBasicConfiguration() { $this->initContainer('basic_config', true); $this->assert->boolean($this->container->has('m6_statsd'))->isIdenticalTo(true)->and()->object($serviceStatsd = $this->container->get('m6_statsd'))->isInstanceOf('M6Web\\Bundle\\StatsdBundle\\Client\\Client'); // @TODO : check the client more // check datacollector $this->assert->object($dataCollector = $this->container->get('m6.data_collector.statsd'))->isInstanceOf('M6Web\\Bundle\\StatsdBundle\\DataCollector\\StatsdDataCollector'); }
public function testWithVersion() { $configs = ['crowd_reactive_lob' => ['api_key' => 'abc123', 'version' => '1.6.0']]; $this->extension->load($configs, $this->container); /** @var Lob $lob */ $lob = $this->container->get('crowd_reactive_lob.lob'); $this->assertEquals('1.6.0', $lob->getVersion()); }
private function registerShortcodes(ContainerBuilder $container) { $shortcodeManager = $container->get('wordpress.shortcode_manager'); foreach ($container->findTaggedServiceIds('wordpress.shortcode') as $service => $tags) { $shortcodeManager->add($container->get($service)); } $shortcodeManager->registerShortcodes(); }
public function testMenu() { $definition = new DefinitionDecorator('lug.ui.menu.builder'); $definition->setClass($class = $this->createMenuBuilderClassMock()); $this->container->setDefinition($menuName = 'lug.ui.menu.test', $definition); $this->compileContainer(); $this->assertInstanceOf($class, $this->container->get($menuName)); }
public function setUp() { parent::setUp(); global $auth, $cache, $config, $db, $phpbb_container, $phpbb_dispatcher, $user, $request, $phpEx, $phpbb_root_path, $user_loader; // Database $this->db = $this->new_dbal(); $db = $this->db; // Auth $auth = $this->getMock('\\phpbb\\auth\\auth'); $auth->expects($this->any())->method('acl_get')->with($this->stringContains('_'), $this->anything())->will($this->returnValueMap(array(array('f_noapprove', 1, true), array('f_postcount', 1, true), array('m_edit', 1, false)))); // Config $config = new \phpbb\config\config(array('num_topics' => 1, 'num_posts' => 1, 'allow_board_notifications' => true)); $cache_driver = new \phpbb\cache\driver\dummy(); $cache = new \phpbb\cache\service($cache_driver, $config, $db, $phpbb_root_path, $phpEx); // Event dispatcher $phpbb_dispatcher = new phpbb_mock_event_dispatcher(); // User $user = $this->getMock('\\phpbb\\user', array(), array(new \phpbb\language\language(new \phpbb\language\language_file_loader($phpbb_root_path, $phpEx)), '\\phpbb\\datetime')); $user->ip = ''; $user->data = array('user_id' => 2, 'username' => 'user-name', 'is_registered' => true, 'user_colour' => ''); // Request $type_cast_helper = $this->getMock('\\phpbb\\request\\type_cast_helper_interface'); $request = $this->getMock('\\phpbb\\request\\request'); $phpbb_dispatcher = new phpbb_mock_event_dispatcher(); $user_loader = new \phpbb\user_loader($db, $phpbb_root_path, $phpEx, USERS_TABLE); // Container $phpbb_container = new ContainerBuilder(); $loader = new YamlFileLoader($phpbb_container, new FileLocator(__DIR__ . '/fixtures')); $loader->load('services_notification.yml'); $phpbb_container->set('user_loader', $user_loader); $phpbb_container->set('user', $user); $phpbb_container->set('config', $config); $phpbb_container->set('dbal.conn', $db); $phpbb_container->set('auth', $auth); $phpbb_container->set('cache.driver', $cache_driver); $phpbb_container->set('cache', $cache); $phpbb_container->set('text_formatter.utils', new \phpbb\textformatter\s9e\utils()); $phpbb_container->set('dispatcher', $phpbb_dispatcher); $phpbb_container->setParameter('core.root_path', $phpbb_root_path); $phpbb_container->setParameter('core.php_ext', $phpEx); $phpbb_container->setParameter('tables.notifications', 'phpbb_notifications'); $phpbb_container->setParameter('tables.user_notifications', 'phpbb_user_notifications'); $phpbb_container->setParameter('tables.notification_types', 'phpbb_notification_types'); $phpbb_container->set('content.visibility', new \phpbb\content_visibility($auth, $config, $phpbb_dispatcher, $db, $user, $phpbb_root_path, $phpEx, FORUMS_TABLE, POSTS_TABLE, TOPICS_TABLE, USERS_TABLE)); $phpbb_container->compile(); // Notification Types $notification_types = array('quote', 'bookmark', 'post', 'post_in_queue', 'topic', 'topic_in_queue', 'approve_topic', 'approve_post'); $notification_types_array = array(); foreach ($notification_types as $type) { $class = $phpbb_container->get('notification.type.' . $type); $notification_types_array['notification.type.' . $type] = $class; } // Methods Types $notification_methods_array = array('notification.method.board' => $phpbb_container->get('notification.method.board')); // Notification Manager $phpbb_notifications = new \phpbb\notification\manager($notification_types_array, $notification_methods_array, $phpbb_container, $user_loader, $phpbb_dispatcher, $db, $cache, $user, NOTIFICATION_TYPES_TABLE, USER_NOTIFICATIONS_TABLE); $phpbb_container->set('notification_manager', $phpbb_notifications); }
/** * */ public function run() { /** @var Slim $slim */ $slim = $this->dic->get('slim'); /** @var RouteLoader $router */ $router = $this->dic->get('router'); $router->load(); $slim->run(); }