public function testGetProxyFactoryCode() { $definition = new Definition(__CLASS__); $definition->setLazy(true); $code = $this->dumper->getProxyFactoryCode($definition, 'foo'); $this->assertStringMatchesFormat('%wif ($lazyLoad) {%wreturn $this->services[\'foo\'] = new ' . 'SymfonyBridgeProxyManagerTestsLazyProxyPhpDumperProxyDumperTest_%s(%wfunction ' . '(&$wrappedInstance, \\ProxyManager\\Proxy\\LazyLoadingInterface $proxy) {' . '%w$wrappedInstance = $this->getFooService(false);%w$proxy->setProxyInitializer(null);' . '%wreturn true;%w}%w);%w}%w', $code); }
public function testProcess() { $container = new ContainerBuilder(); $simpleFactory = new Definition(); $simpleProcessor = new Definition('Test\\SimpleProcessor'); $simpleProcessor->addTag('processor'); $abstractProcessor = new Definition(); $abstractProcessor->setAbstract(true); $abstractProcessor->addTag('processor'); $lazyProcessor = new Definition('Test\\LazyProcessor'); $lazyProcessor->setLazy(true); $lazyProcessor->addTag('processor'); $withArgumentsProcessor = new Definition('Test\\WithArgumentsProcessor', ['test']); $withArgumentsProcessor->addTag('processor'); $container->addDefinitions(['simple_factory' => $simpleFactory, 'simple_processor' => $simpleProcessor, 'abstract_processor' => $abstractProcessor, 'lazy_processor' => $lazyProcessor, 'with_arguments_processor' => $withArgumentsProcessor]); $compilerPass = new CleanUpProcessorsCompilerPass('simple_factory', 'processor'); $compilerPass->process($container); $this->assertFalse($container->hasDefinition('simple_processor')); $this->assertTrue($container->hasDefinition('abstract_processor')); $this->assertTrue($container->hasDefinition('lazy_processor')); $this->assertTrue($container->hasDefinition('with_arguments_processor')); $methodCalls = $simpleFactory->getMethodCalls(); $this->assertCount(1, $methodCalls); $this->assertEquals(['addProcessor', ['simple_processor', 'Test\\SimpleProcessor']], $methodCalls[0]); }
/** * @param Definition $definition * @param string $id * @param array $tags */ protected function addConnection(Definition $definition, $id, $tags) { $definition->addMethodCall('setRequestFactory', [new Reference('ms.rpc.request_factory')]); $definition->addMethodCall('setResponseFactory', [new Reference('ms.rpc.response_factory')]); $definition->addMethodCall('setSerializer', [new Reference('serializer')]); $definition->setLazy(true); }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $reflection = new \ReflectionClass($metadata->getClass('model')); $translatableInterface = TranslatableInterface::class; $translatable = interface_exists($translatableInterface) && $reflection->implementsInterface($translatableInterface); $repositoryClassParameterName = sprintf('%s.repository.%s.class', $metadata->getApplicationName(), $metadata->getName()); $repositoryClass = $translatable ? TranslatableResourceRepository::class : EntityRepository::class; if ($container->hasParameter($repositoryClassParameterName)) { $repositoryClass = $container->getParameter($repositoryClassParameterName); } if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); if ($metadata->hasParameter('translation')) { $translatableRepositoryInterface = TranslatableResourceRepositoryInterface::class; $translationConfig = $metadata->getParameter('translation'); if (interface_exists($translatableRepositoryInterface) && $repositoryReflection->implementsInterface($translatableRepositoryInterface)) { if (isset($translationConfig['fields'])) { $definition->addMethodCall('setTranslatableFields', [$translationConfig['fields']]); } } } $container->setDefinition($metadata->getServiceId('repository'), $definition); }
protected function addProvider(ContainerBuilder $container, $providerClass, $modelName) { $providerReflection = new \ReflectionClass($providerClass); $definition = new Definition($providerClass); $definition->setArguments([new Reference(sprintf('%s.repository.%s', $this->applicationName, $modelName)), new Reference(sprintf('%s.factory.%s', $this->applicationName, $modelName))]); $definition->setLazy(!$providerReflection->isFinal()); $container->setDefinition(sprintf('%s.provider.%s', $this->applicationName, $modelName), $definition); }
/** * @param ContainerBuilder $container * @param $config */ private function setMappings(ContainerBuilder $container, $config) { $definition = new Definition(); $definition->setClass('NilPortugues\\Api\\Mapping\\Mapper'); $args = $this->resolveMappings($container, $config['mappings']); $definition->setArguments($args); $definition->setLazy(true); $container->setDefinition('nil_portugues.api.mapping.mapper', $definition); }
/** * @param ContainerBuilder $container * @param array $metadata */ private function registerService(ContainerBuilder $container, array $metadata) { $class = 'SupportYard\\FrameworkBundle\\Interceptor\\InputInterceptor'; $interceptorId = $metadata['interceptorId']; $alias = $metadata['alias']; $inputId = $metadata['inputId']; $definition = new Definition($class, [new Reference('validator'), new Reference($inputId)]); $definition->setLazy(true)->addTag('support_yard_framework.interceptor', ['alias' => $alias]); $container->setDefinition($interceptorId, $definition); }
private function createSncRedisBusCommandBus($commandBusServiceName, $config, ContainerBuilder $container) { $client = new Reference(sprintf('snc_redis.%s_client', $config['client'])); $serializer = new Reference($config['serializer']); $keyGenerator = new Reference($config['key_generator']); $service = new Definition('%rezzza_command_bus.snc_redis_bus.class%', [$client, $keyGenerator, $serializer]); $service->setLazy(true); // because snc redis will initiate connection, and we may not want it. $container->setDefinition($commandBusServiceName, $service); $defaultConsumerProvider = new Definition('%rezzza_command_bus.snc_redis_provider.class%', [$client, $keyGenerator, $serializer, $config['read_block_timeout']]); foreach ($config['consumers'] as $consumerName => $consumerConfig) { $this->createConsumerDefinition($consumerName, $defaultConsumerProvider, $consumerConfig, $commandBusServiceName, $container); } }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $modelClass = $metadata->getClass('model'); $repositoryClass = in_array(TranslatableInterface::class, class_implements($modelClass)) ? TranslatableRepository::class : new Parameter('sylius.mongodb.odm.repository.class'); if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $unitOfWorkDefinition = new Definition('Doctrine\\ODM\\MongoDB\\UnitOfWork'); $unitOfWorkDefinition->setFactory([new Reference($this->getManagerServiceId($metadata)), 'getUnitOfWork'])->setPublic(false); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $unitOfWorkDefinition, $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * return from local cache or make a new one and put it in cache and then return it. * @param ContainerBuilder $container * @param string $contextName * @returns Reference The service definition reference */ private function getServiceFactory(ContainerBuilder $container, $contextName) { if (!array_key_exists($contextName, $this->serviceDefinistions)) { $def = new Definition(); $def->setClass('TechData\\ContextDiBundle\\Models\\Context'); $def->setLazy(TRUE); $def->setFactoryService('tech_data_context_di.context_handler'); $def->setFactoryMethod('getContext'); $def->setArguments(array($contextName)); $id = 'tech_data_context_di.contexts.' . $contextName; $container->setDefinition($id, $def); $this->serviceDefinistions[$contextName] = new Reference($id); } return $this->serviceDefinistions[$contextName]; }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $repositoryClassParameterName = sprintf('%s.repository.%s.class', $metadata->getApplicationName(), $metadata->getName()); $repositoryClass = EntityRepository::class; if ($container->hasParameter($repositoryClassParameterName)) { $repositoryClass = $container->getParameter($repositoryClassParameterName); } if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * Adds an operation. * * @param ContainerBuilder $container * @param string $serviceId * @param string $method * @param bool $collection * * @return Reference */ private function createOperation(ContainerBuilder $container, $serviceId, $method, $collection) { if ($collection) { $factoryMethodName = 'createCollectionOperation'; $operationId = '.collection_operation.'; } else { $factoryMethodName = 'createItemOperation'; $operationId = '.item_operation.'; } $operation = new Definition('Dunglas\\ApiBundle\\Api\\Operation\\Operation', [new Reference($serviceId), $method]); $operation->setFactory([new Reference('api.operation_factory'), $factoryMethodName]); $operation->setLazy(true); $operationId = $serviceId . $operationId . $method; $container->setDefinition($operationId, $operation); return new Reference($operationId); }
/** * @param ContainerBuilder $container * @param $config */ private function setMappings(ContainerBuilder $container, $config) { if (true === \file_exists($config['mappings'])) { $finder = new Finder(); $finder->files()->in($config['mappings']); $loadedMappings = []; foreach ($finder as $file) { /* @var \Symfony\Component\Finder\SplFileInfo $file */ $mapping = \file_get_contents($file->getPathname()); $mapping = Yaml::parse($mapping); $loadedMappings[] = $mapping['mapping']; } $definition = new Definition(); $definition->setClass('NilPortugues\\Api\\Mapping\\Mapper'); $args = array($loadedMappings); $definition->setArguments($args); $definition->setLazy(true); $container->setDefinition('nil_portugues.api.mapping.mapper', $definition); } }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $repositoryClass = new Parameter('sylius.phpcr_odm.repository.class'); if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); if ($metadata->hasParameter('translation')) { $translationConfig = $metadata->getParameter('translation'); if (in_array(TranslatableRepositoryInterface::class, class_implements($repositoryClass))) { if (isset($translationConfig['fields'])) { $definition->addMethodCall('setTranslatableFields', [$translationConfig['fields']]); } } } $container->setDefinition($metadata->getServiceId('repository'), $definition); }
private function getAllParameters() { $service = new Definition(); $service->setClass('stdClass'); $service->setAbstract(true); $service->setFactoryClass('stdClass'); $service->setFactoryMethod('get'); $service->setFactoryService('service.fact'); $service->setFile('/file.php'); $service->setLazy(true); $service->addMethodCall('methodCall1'); $service->addMethodCall('methodCall2', array('arg1', 'arg2')); $service->addMethodCall('methodCall3', array(new Reference('arg.one'))); $service->setProperty('prop1', 'val1'); $service->setProperty('prop2', new Reference('prop.one')); $service->setPublic(false); $service->setScope('request'); $service->setSynchronized(true); $service->setSynthetic(true); return new ServiceElement('service.two', $service); }
/** * Resolves the definition. * * @param ContainerBuilder $container The ContainerBuilder * @param DefinitionDecorator $definition * * @return Definition * * @throws \RuntimeException When the definition is invalid */ private function resolveDefinition(ContainerBuilder $container, DefinitionDecorator $definition) { if (!$container->hasDefinition($parent = $definition->getParent())) { throw new RuntimeException(sprintf('The parent definition "%s" defined for definition "%s" does not exist.', $parent, $this->currentId)); } $parentDef = $container->getDefinition($parent); if ($parentDef instanceof DefinitionDecorator) { $id = $this->currentId; $this->currentId = $parent; $parentDef = $this->resolveDefinition($container, $parentDef); $container->setDefinition($parent, $parentDef); $this->currentId = $id; } $this->compiler->addLogMessage($this->formatter->formatResolveInheritance($this, $this->currentId, $parent)); $def = new Definition(); // merge in parent definition // purposely ignored attributes: scope, abstract, tags $def->setClass($parentDef->getClass()); $def->setArguments($parentDef->getArguments()); $def->setMethodCalls($parentDef->getMethodCalls()); $def->setProperties($parentDef->getProperties()); $def->setAutowiringTypes($parentDef->getAutowiringTypes()); if ($parentDef->getFactoryClass(false)) { $def->setFactoryClass($parentDef->getFactoryClass(false)); } if ($parentDef->getFactoryMethod(false)) { $def->setFactoryMethod($parentDef->getFactoryMethod(false)); } if ($parentDef->getFactoryService(false)) { $def->setFactoryService($parentDef->getFactoryService(false)); } if ($parentDef->isDeprecated()) { $def->setDeprecated(true, $parentDef->getDeprecationMessage('%service_id%')); } $def->setFactory($parentDef->getFactory()); $def->setConfigurator($parentDef->getConfigurator()); $def->setFile($parentDef->getFile()); $def->setPublic($parentDef->isPublic()); $def->setLazy($parentDef->isLazy()); // overwrite with values specified in the decorator $changes = $definition->getChanges(); if (isset($changes['class'])) { $def->setClass($definition->getClass()); } if (isset($changes['factory_class'])) { $def->setFactoryClass($definition->getFactoryClass(false)); } if (isset($changes['factory_method'])) { $def->setFactoryMethod($definition->getFactoryMethod(false)); } if (isset($changes['factory_service'])) { $def->setFactoryService($definition->getFactoryService(false)); } if (isset($changes['factory'])) { $def->setFactory($definition->getFactory()); } if (isset($changes['configurator'])) { $def->setConfigurator($definition->getConfigurator()); } if (isset($changes['file'])) { $def->setFile($definition->getFile()); } if (isset($changes['public'])) { $def->setPublic($definition->isPublic()); } if (isset($changes['lazy'])) { $def->setLazy($definition->isLazy()); } if (isset($changes['deprecated'])) { $def->setDeprecated($definition->isDeprecated(), $definition->getDeprecationMessage('%service_id%')); } if (isset($changes['decorated_service'])) { $decoratedService = $definition->getDecoratedService(); if (null === $decoratedService) { $def->setDecoratedService($decoratedService); } else { $def->setDecoratedService($decoratedService[0], $decoratedService[1], $decoratedService[2]); } } // merge arguments foreach ($definition->getArguments() as $k => $v) { if (is_numeric($k)) { $def->addArgument($v); continue; } if (0 !== strpos($k, 'index_')) { throw new RuntimeException(sprintf('Invalid argument key "%s" found.', $k)); } $index = (int) substr($k, strlen('index_')); $def->replaceArgument($index, $v); } // merge properties foreach ($definition->getProperties() as $k => $v) { $def->setProperty($k, $v); } // append method calls if (count($calls = $definition->getMethodCalls()) > 0) { $def->setMethodCalls(array_merge($def->getMethodCalls(), $calls)); } // merge autowiring types foreach ($definition->getAutowiringTypes() as $autowiringType) { $def->addAutowiringType($autowiringType); } // these attributes are always taken from the child $def->setAbstract($definition->isAbstract()); $def->setScope($definition->getScope(false), false); $def->setShared($definition->isShared()); $def->setTags($definition->getTags()); return $def; }
public function testLazyLoadedService() { $loader = new ClosureLoader($container = new ContainerBuilder()); $loader->load(function (ContainerBuilder $container) { $container->set('a', new \BazClass()); $definition = new Definition('BazClass'); $definition->setLazy(true); $container->setDefinition('a', $definition); }); $container->setResourceTracking(true); $container->compile(); $class = new \BazClass(); $reflectionClass = new \ReflectionClass($class); $r = new \ReflectionProperty($container, 'resources'); $r->setAccessible(true); $resources = $r->getValue($container); $classInList = false; foreach ($resources as $resource) { if ($resource->getResource() === $reflectionClass->getFileName()) { $classInList = true; break; } } $this->assertTrue($classInList); }
/** * Parses a definition. * * @param string $id * @param array $service * @param string $file * * @throws InvalidArgumentException When tags are invalid */ private function parseDefinition($id, $service, $file) { if (is_string($service) && 0 === strpos($service, '@')) { $this->container->setAlias($id, substr($service, 1)); return; } if (!is_array($service)) { throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file)); } if (isset($service['alias'])) { $public = !array_key_exists('public', $service) || (bool) $service['public']; $this->container->setAlias($id, new Alias($service['alias'], $public)); return; } if (isset($service['parent'])) { $definition = new DefinitionDecorator($service['parent']); } else { $definition = new Definition(); } if (isset($service['class'])) { $definition->setClass($service['class']); } if (isset($service['scope'])) { $definition->setScope($service['scope']); } if (isset($service['synthetic'])) { $definition->setSynthetic($service['synthetic']); } if (isset($service['synchronized'])) { $definition->setSynchronized($service['synchronized']); } if (isset($service['lazy'])) { $definition->setLazy($service['lazy']); } if (isset($service['public'])) { $definition->setPublic($service['public']); } if (isset($service['abstract'])) { $definition->setAbstract($service['abstract']); } if (isset($service['factory'])) { if (is_string($service['factory'])) { if (strpos($service['factory'], ':') !== false && strpos($service['factory'], '::') === false) { $parts = explode(':', $service['factory']); $definition->setFactory(array($this->resolveServices('@' . $parts[0]), $parts[1])); } else { $definition->setFactory($service['factory']); } } else { $definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1])); } } if (isset($service['factory_class'])) { $definition->setFactoryClass($service['factory_class']); } if (isset($service['factory_method'])) { $definition->setFactoryMethod($service['factory_method']); } if (isset($service['factory_service'])) { $definition->setFactoryService($service['factory_service']); } if (isset($service['file'])) { $definition->setFile($service['file']); } if (isset($service['arguments'])) { $definition->setArguments($this->resolveServices($service['arguments'])); } if (isset($service['properties'])) { $definition->setProperties($this->resolveServices($service['properties'])); } if (isset($service['configurator'])) { if (is_string($service['configurator'])) { $definition->setConfigurator($service['configurator']); } else { $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1])); } } if (isset($service['calls'])) { if (!is_array($service['calls'])) { throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['calls'] as $call) { $args = isset($call[1]) ? $this->resolveServices($call[1]) : array(); $definition->addMethodCall($call[0], $args); } } if (isset($service['tags'])) { if (!is_array($service['tags'])) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['tags'] as $tag) { if (!is_array($tag)) { throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } if (!isset($tag['name'])) { throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file)); } $name = $tag['name']; unset($tag['name']); foreach ($tag as $attribute => $value) { if (!is_scalar($value) && null !== $value) { throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file)); } } $definition->addTag($name, $tag); } } if (isset($service['decorates'])) { $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null; $definition->setDecoratedService($service['decorates'], $renameId); } $this->container->setDefinition($id, $definition); }
/** * {@inheritdoc} * * @api */ public function setLazy($boolean) { $this->changes['lazy'] = true; return parent::setLazy($boolean); }
/** * @covers ::getProxyCode */ public function testGetProxyCodeWithSameClassMultipleTimes() { $definition = new Definition('Drupal\\Tests\\Component\\ProxyBuilder\\TestService'); $definition->setLazy(TRUE); $class = 'class Drupal_Tests_Component_ProxyBuilder_TestService_Proxy {}'; $this->proxyBuilder->expects($this->once())->method('build')->with('Drupal\\Tests\\Component\\ProxyBuilder\\TestService')->willReturn($class); $result = $this->proxyDumper->getProxyCode($definition); $this->assertEquals($class, $result); $result = $this->proxyDumper->getProxyCode($definition); $this->assertEquals('', $result); }
protected function loadRpcClients() { foreach ($this->config['rpc_clients'] as $key => $client) { $definition = new Definition('%old_sound_rabbit_mq.rpc_client.class%'); $definition->setLazy($client['lazy']); $definition->addTag('old_sound_rabbit_mq.rpc_client')->addMethodCall('initClient', array($client['expect_serialized_response'])); $this->injectConnection($definition, $client['connection']); if ($this->collectorEnabled) { $this->injectLoggedChannel($definition, $key, $client['connection']); } if (array_key_exists('unserializer', $client)) { $definition->addMethodCall('setUnserializer', array($client['unserializer'])); } if (array_key_exists('direct_reply_to', $client)) { $definition->addMethodCall('setDirectReplyTo', array($client['direct_reply_to'])); } $this->container->setDefinition(sprintf('old_sound_rabbit_mq.%s_rpc', $key), $definition); } }
/** * Parses a definition. * * @param string $id * @param array $service * @param string $file * * @throws InvalidArgumentException When tags are invalid */ private function parseDefinition($id, $service, $file) { if (is_string($service) && 0 === strpos($service, '@')) { $this->container->setAlias($id, substr($service, 1)); return; } if (!is_array($service)) { throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file)); } static::checkDefinition($id, $service, $file); if (isset($service['alias'])) { $public = !array_key_exists('public', $service) || (bool) $service['public']; $this->container->setAlias($id, new Alias($service['alias'], $public)); foreach ($service as $key => $value) { if (!in_array($key, array('alias', 'public'))) { @trigger_error(sprintf('The configuration key "%s" is unsupported for alias definition "%s" in "%s". Allowed configuration keys are "alias" and "public". The YamlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.', $key, $id, $file), E_USER_DEPRECATED); } } return; } if (isset($service['parent'])) { $definition = new DefinitionDecorator($service['parent']); } else { $definition = new Definition(); } if (isset($service['class'])) { $definition->setClass($service['class']); } if (isset($service['shared'])) { $definition->setShared($service['shared']); } if (isset($service['synthetic'])) { $definition->setSynthetic($service['synthetic']); } if (isset($service['lazy'])) { $definition->setLazy($service['lazy']); } if (isset($service['public'])) { $definition->setPublic($service['public']); } if (isset($service['abstract'])) { $definition->setAbstract($service['abstract']); } if (array_key_exists('deprecated', $service)) { $definition->setDeprecated(true, $service['deprecated']); } if (isset($service['factory'])) { $definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file)); } if (isset($service['file'])) { $definition->setFile($service['file']); } if (isset($service['arguments'])) { $definition->setArguments($this->resolveServices($service['arguments'])); } if (isset($service['properties'])) { $definition->setProperties($this->resolveServices($service['properties'])); } if (isset($service['configurator'])) { $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file)); } if (isset($service['calls'])) { if (!is_array($service['calls'])) { throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['calls'] as $call) { if (isset($call['method'])) { $method = $call['method']; $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array(); } else { $method = $call[0]; $args = isset($call[1]) ? $this->resolveServices($call[1]) : array(); } $definition->addMethodCall($method, $args); } } if (isset($service['tags'])) { if (!is_array($service['tags'])) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['tags'] as $tag) { if (!is_array($tag)) { throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } if (!isset($tag['name'])) { throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file)); } if (!is_string($tag['name']) || '' === $tag['name']) { throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file)); } $name = $tag['name']; unset($tag['name']); foreach ($tag as $attribute => $value) { if (!is_scalar($value) && null !== $value) { throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file)); } } $definition->addTag($name, $tag); } } if (isset($service['decorates'])) { if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) { throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($service['decorates'], 1))); } $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null; $priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0; $definition->setDecoratedService($service['decorates'], $renameId, $priority); } if (isset($service['autowire'])) { $definition->setAutowired($service['autowire']); } if (isset($service['autowiring_types'])) { if (is_string($service['autowiring_types'])) { $definition->addAutowiringType($service['autowiring_types']); } else { if (!is_array($service['autowiring_types'])) { throw new InvalidArgumentException(sprintf('Parameter "autowiring_types" must be a string or an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['autowiring_types'] as $autowiringType) { if (!is_string($autowiringType)) { throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file)); } $definition->addAutowiringType($autowiringType); } } } $this->container->setDefinition($id, $definition); }
private function buildHandler(ContainerBuilder $container, $name, array $handler) { $handlerId = $this->getHandlerId($name); $definition = new Definition(sprintf('%%monolog.handler.%s.class%%', $handler['type'])); $handler['level'] = $this->levelToMonologConst($handler['level']); switch ($handler['type']) { case 'service': $container->setAlias($handlerId, $handler['id']); return $handlerId; case 'stream': $definition->setArguments(array($handler['path'], $handler['level'], $handler['bubble'], $handler['file_permission'])); break; case 'console': if (!class_exists('Symfony\\Bridge\\Monolog\\Handler\\ConsoleHandler')) { throw new \RuntimeException('The console handler requires symfony/monolog-bridge 2.4+'); } $definition->setArguments(array(null, $handler['bubble'], isset($handler['verbosity_levels']) ? $handler['verbosity_levels'] : array())); $definition->addTag('kernel.event_subscriber'); break; case 'firephp': $definition->setArguments(array($handler['level'], $handler['bubble'])); $definition->addTag('kernel.event_listener', array('event' => 'kernel.response', 'method' => 'onKernelResponse')); break; case 'gelf': if (isset($handler['publisher']['id'])) { $publisherId = $handler['publisher']['id']; } elseif (class_exists('Gelf\\Transport\\UdpTransport')) { $transport = new Definition("Gelf\\Transport\\UdpTransport", array($handler['publisher']['hostname'], $handler['publisher']['port'], $handler['publisher']['chunk_size'])); $transportId = uniqid('monolog.gelf.transport.'); $transport->setPublic(false); $container->setDefinition($transportId, $transport); $publisher = new Definition('%monolog.gelfphp.publisher.class%', array()); $publisher->addMethodCall('addTransport', array(new Reference($transportId))); $publisherId = uniqid('monolog.gelf.publisher.'); $publisher->setPublic(false); $container->setDefinition($publisherId, $publisher); } elseif (class_exists('Gelf\\MessagePublisher')) { $publisher = new Definition('%monolog.gelf.publisher.class%', array($handler['publisher']['hostname'], $handler['publisher']['port'], $handler['publisher']['chunk_size'])); $publisherId = uniqid('monolog.gelf.publisher.'); $publisher->setPublic(false); $container->setDefinition($publisherId, $publisher); } else { throw new \RuntimeException('The gelf handler requires the graylog2/gelf-php package to be installed'); } $definition->setArguments(array(new Reference($publisherId), $handler['level'], $handler['bubble'])); break; case 'mongo': if (isset($handler['mongo']['id'])) { $clientId = $handler['mongo']['id']; } else { $server = 'mongodb://'; if (isset($handler['mongo']['user'])) { $server .= $handler['mongo']['user'] . ':' . $handler['mongo']['pass'] . '@'; } $server .= $handler['mongo']['host'] . ':' . $handler['mongo']['port']; $client = new Definition('%monolog.mongo.client.class%', array($server)); $clientId = uniqid('monolog.mongo.client.'); $client->setPublic(false); $container->setDefinition($clientId, $client); } $definition->setArguments(array(new Reference($clientId), $handler['mongo']['database'], $handler['mongo']['collection'], $handler['level'], $handler['bubble'])); break; case 'elasticsearch': if (isset($handler['elasticsearch']['id'])) { $clientId = $handler['elasticsearch']['id']; } else { // elastica client new definition $elasticaClient = new Definition('%monolog.elastica.client.class%'); $elasticaClient->setArguments(array(array('host' => $handler['elasticsearch']['host'], 'port' => $handler['elasticsearch']['port']))); $clientId = uniqid('monolog.elastica.client.'); $elasticaClient->setPublic(false); $container->setDefinition($clientId, $elasticaClient); } // elastica handler definition $definition->setArguments(array(new Reference($clientId), array('index' => $handler['index'], 'type' => $handler['document_type'], 'ignore_error' => $handler['ignore_error']), $handler['level'], $handler['bubble'])); break; case 'chromephp': $definition->setArguments(array($handler['level'], $handler['bubble'])); $definition->addTag('kernel.event_listener', array('event' => 'kernel.response', 'method' => 'onKernelResponse')); break; case 'rotating_file': $definition->setArguments(array($handler['path'], $handler['max_files'], $handler['level'], $handler['bubble'], $handler['file_permission'])); break; case 'fingers_crossed': $handler['action_level'] = $this->levelToMonologConst($handler['action_level']); if (null !== $handler['passthru_level']) { $handler['passthru_level'] = $this->levelToMonologConst($handler['passthru_level']); } $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->nestedHandlers[] = $nestedHandlerId; if (isset($handler['activation_strategy'])) { $activation = new Reference($handler['activation_strategy']); } elseif (!empty($handler['excluded_404s'])) { $activationDef = new Definition('%monolog.activation_strategy.not_found.class%', array($handler['excluded_404s'], $handler['action_level'])); $activationDef->addMethodCall('setRequest', array(new Reference('request', ContainerInterface::NULL_ON_INVALID_REFERENCE, false))); $container->setDefinition($handlerId . '.not_found_strategy', $activationDef); $activation = new Reference($handlerId . '.not_found_strategy'); } else { $activation = $handler['action_level']; } $definition->setArguments(array(new Reference($nestedHandlerId), $activation, $handler['buffer_size'], $handler['bubble'], $handler['stop_buffering'], $handler['passthru_level'])); break; case 'filter': $handler['min_level'] = $this->levelToMonologConst($handler['min_level']); $handler['max_level'] = $this->levelToMonologConst($handler['max_level']); foreach (array_keys($handler['accepted_levels']) as $k) { $handler['accepted_levels'][$k] = $this->levelToMonologConst($handler['accepted_levels'][$k]); } $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->nestedHandlers[] = $nestedHandlerId; $minLevelOrList = !empty($handler['accepted_levels']) ? $handler['accepted_levels'] : $handler['min_level']; $definition->setArguments(array(new Reference($nestedHandlerId), $minLevelOrList, $handler['max_level'], $handler['bubble'])); break; case 'buffer': $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->nestedHandlers[] = $nestedHandlerId; $definition->setArguments(array(new Reference($nestedHandlerId), $handler['buffer_size'], $handler['level'], $handler['bubble'], $handler['flush_on_overflow'])); break; case 'group': case 'whatfailuregroup': $references = array(); foreach ($handler['members'] as $nestedHandler) { $nestedHandlerId = $this->getHandlerId($nestedHandler); $this->nestedHandlers[] = $nestedHandlerId; $references[] = new Reference($nestedHandlerId); } $definition->setArguments(array($references, $handler['bubble'])); break; case 'syslog': $definition->setArguments(array($handler['ident'], $handler['facility'], $handler['level'], $handler['bubble'], $handler['logopts'])); break; case 'syslogudp': $definition->setArguments(array($handler['host'], $handler['port'], $handler['facility'], $handler['level'], $handler['bubble'])); break; case 'swift_mailer': $oldHandler = false; // fallback for older symfony versions that don't have the new SwiftMailerHandler in the bridge $newHandlerClass = $container->getParameterBag()->resolveValue($definition->getClass()); if (!class_exists($newHandlerClass)) { $definition = new Definition('Monolog\\Handler\\SwiftMailerHandler'); $oldHandler = true; } if (isset($handler['email_prototype'])) { if (!empty($handler['email_prototype']['method'])) { $prototype = array(new Reference($handler['email_prototype']['id']), $handler['email_prototype']['method']); } else { $prototype = new Reference($handler['email_prototype']['id']); } } else { $messageFactory = new Definition('Symfony\\Bundle\\MonologBundle\\SwiftMailer\\MessageFactory'); $messageFactory->setLazy(true); $messageFactory->setPublic(false); $messageFactory->setArguments(array(new Reference($handler['mailer']), $handler['from_email'], $handler['to_email'], $handler['subject'], $handler['content_type'])); $messageFactoryId = sprintf('%s.mail_message_factory', $handlerId); $container->setDefinition($messageFactoryId, $messageFactory); // set the prototype as a callable $prototype = array(new Reference($messageFactoryId), 'createMessage'); } $definition->setArguments(array(new Reference($handler['mailer']), $prototype, $handler['level'], $handler['bubble'])); if (!$oldHandler) { $this->swiftMailerHandlers[] = $handlerId; $definition->addTag('kernel.event_listener', array('event' => 'kernel.terminate', 'method' => 'onKernelTerminate')); if (method_exists($newHandlerClass, 'onCliTerminate')) { $definition->addTag('kernel.event_listener', array('event' => 'console.terminate', 'method' => 'onCliTerminate')); } } break; case 'native_mailer': $definition->setArguments(array($handler['to_email'], $handler['subject'], $handler['from_email'], $handler['level'], $handler['bubble'])); break; case 'socket': $definition->setArguments(array($handler['connection_string'], $handler['level'], $handler['bubble'])); if (isset($handler['timeout'])) { $definition->addMethodCall('setTimeout', array($handler['timeout'])); } if (isset($handler['connection_timeout'])) { $definition->addMethodCall('setConnectionTimeout', array($handler['connection_timeout'])); } if (isset($handler['persistent'])) { $definition->addMethodCall('setPersistent', array($handler['persistent'])); } break; case 'pushover': $definition->setArguments(array($handler['token'], $handler['user'], $handler['title'], $handler['level'], $handler['bubble'])); break; case 'hipchat': $definition->setArguments(array($handler['token'], $handler['room'], $handler['nickname'], $handler['notify'], $handler['level'], $handler['bubble'], $handler['use_ssl'], $handler['message_format'])); break; case 'slack': $definition->setArguments(array($handler['token'], $handler['channel'], $handler['bot_name'], $handler['use_attachment'], $handler['icon_emoji'], $handler['level'], $handler['bubble'], $handler['use_short_attachment'], $handler['include_extra'])); break; case 'cube': $definition->setArguments(array($handler['url'], $handler['level'], $handler['bubble'])); break; case 'amqp': $definition->setArguments(array(new Reference($handler['exchange']), $handler['exchange_name'], $handler['level'], $handler['bubble'])); break; case 'error_log': $definition->setArguments(array($handler['message_type'], $handler['level'], $handler['bubble'])); break; case 'raven': if (null !== $handler['client_id']) { $clientId = $handler['client_id']; } else { $client = new Definition('Raven_Client', array($handler['dsn'])); $client->setPublic(false); $clientId = 'monolog.raven.client.' . sha1($handler['dsn']); $container->setDefinition($clientId, $client); } $definition->setArguments(array(new Reference($clientId), $handler['level'], $handler['bubble'])); break; case 'loggly': $definition->setArguments(array($handler['token'], $handler['level'], $handler['bubble'])); if (!empty($handler['tags'])) { $definition->addMethodCall('setTag', array(implode(',', $handler['tags']))); } break; case 'logentries': $definition->setArguments(array($handler['token'], $handler['use_ssl'], $handler['level'], $handler['bubble'])); break; case 'flowdock': $definition->setArguments(array($handler['token'], $handler['level'], $handler['bubble'])); if (empty($handler['formatter'])) { $formatter = new Definition("Monolog\\Formatter\\FlowdockFormatter", array($handler['source'], $handler['from_email'])); $formatterId = 'monolog.flowdock.formatter.' . sha1($handler['source'] . '|' . $handler['from_email']); $formatter->setPublic(false); $container->setDefinition($formatterId, $formatter); $definition->addMethodCall('setFormatter', array(new Reference($formatterId))); } break; case 'rollbar': if (!empty($handler['id'])) { $rollbarId = $handler['id']; } else { $config = $handler['config'] ?: array(); $config['access_token'] = $handler['token']; $rollbar = new Definition('RollbarNotifier', array($config)); $rollbarId = 'monolog.rollbar.notifier.' . sha1(json_encode($config)); $rollbar->setPublic(false); $container->setDefinition($rollbarId, $rollbar); } $definition->setArguments(array(new Reference($rollbarId), $handler['level'], $handler['bubble'])); break; // Handlers using the constructor of AbstractHandler without adding their own arguments // Handlers using the constructor of AbstractHandler without adding their own arguments case 'browser_console': case 'newrelic': case 'test': case 'null': case 'debug': $definition->setArguments(array($handler['level'], $handler['bubble'])); break; default: throw new \InvalidArgumentException(sprintf('Invalid handler type "%s" given for handler "%s"', $handler['type'], $name)); } if (!empty($handler['formatter'])) { $definition->addMethodCall('setFormatter', array(new Reference($handler['formatter']))); } $container->setDefinition($handlerId, $definition); return $handlerId; }
/** * Resolves the definition. * * @param string $id The definition identifier * @param DefinitionDecorator $definition * * @return Definition * * @throws \RuntimeException When the definition is invalid */ private function resolveDefinition($id, DefinitionDecorator $definition) { if (!$this->container->hasDefinition($parent = $definition->getParent())) { throw new RuntimeException(sprintf('The parent definition "%s" defined for definition "%s" does not exist.', $parent, $id)); } $parentDef = $this->container->getDefinition($parent); if ($parentDef instanceof DefinitionDecorator) { $parentDef = $this->resolveDefinition($parent, $parentDef); } $this->compiler->addLogMessage($this->formatter->formatResolveInheritance($this, $id, $parent)); $def = new Definition(); // merge in parent definition // purposely ignored attributes: scope, abstract, tags $def->setClass($parentDef->getClass()); $def->setArguments($parentDef->getArguments()); $def->setMethodCalls($parentDef->getMethodCalls()); $def->setProperties($parentDef->getProperties()); $def->setFactory($parentDef->getFactory()); $def->setConfigurator($parentDef->getConfigurator()); $def->setFile($parentDef->getFile()); $def->setPublic($parentDef->isPublic()); $def->setLazy($parentDef->isLazy()); // overwrite with values specified in the decorator $changes = $definition->getChanges(); if (isset($changes['class'])) { $def->setClass($definition->getClass()); } if (isset($changes['factory'])) { $def->setFactory($definition->getFactory()); } if (isset($changes['configurator'])) { $def->setConfigurator($definition->getConfigurator()); } if (isset($changes['file'])) { $def->setFile($definition->getFile()); } if (isset($changes['public'])) { $def->setPublic($definition->isPublic()); } if (isset($changes['lazy'])) { $def->setLazy($definition->isLazy()); } // merge arguments foreach ($definition->getArguments() as $k => $v) { if (is_numeric($k)) { $def->addArgument($v); continue; } if (0 !== strpos($k, 'index_')) { throw new RuntimeException(sprintf('Invalid argument key "%s" found.', $k)); } $index = (int) substr($k, strlen('index_')); $def->replaceArgument($index, $v); } // merge properties foreach ($definition->getProperties() as $k => $v) { $def->setProperty($k, $v); } // append method calls if (count($calls = $definition->getMethodCalls()) > 0) { $def->setMethodCalls(array_merge($def->getMethodCalls(), $calls)); } // these attributes are always taken from the child $def->setAbstract($definition->isAbstract()); $def->setScope($definition->getScope()); $def->setTags($definition->getTags()); // set new definition on container $this->container->setDefinition($id, $def); return $def; }
/** * @param Service $annotation * @param Definition $definition */ private function processService($annotation, Definition $definition) { $definition->setPublic($annotation->public); $definition->setLazy($annotation->lazy); $definition->setShared($annotation->shared); $this->processConfigurator($annotation, $definition); if (isset($annotation->factory)) { $definition->setFactory($annotation->factory); } }
private function processClientsConfiguration(array $config, ContainerBuilder $container, $debug) { foreach ($config['clients'] as $name => $options) { $client = new Definition($options['class']); $client->setLazy($options['lazy']); if (isset($options['config'])) { if (!is_array($options['config'])) { throw new InvalidArgumentException(sprintf('Config for "csa_guzzle.client.%s" should be an array, but got %s', $name, gettype($options['config']))); } $client->addArgument($this->buildGuzzleConfig($options['config'], $debug)); } $attributes = []; if (!empty($options['middleware'])) { if ($debug) { $options['middleware'][] = 'stopwatch'; $options['middleware'][] = 'history'; $options['middleware'][] = 'logger'; } $attributes['middleware'] = implode(' ', array_unique($options['middleware'])); } $client->addTag(MiddlewarePass::CLIENT_TAG, $attributes); $clientServiceId = sprintf('csa_guzzle.client.%s', $name); $container->setDefinition($clientServiceId, $client); if (isset($options['alias'])) { $container->setAlias($options['alias'], $clientServiceId); } } }
/** * Parses a definition. * * @param string $id * @param array $service * @param string $file * * @throws InvalidArgumentException When tags are invalid */ private function parseDefinition($id, $service, $file) { if (is_string($service) && 0 === strpos($service, '@')) { $this->container->setAlias($id, substr($service, 1)); return; } if (!is_array($service)) { throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file)); } if (isset($service['alias'])) { $public = !array_key_exists('public', $service) || (bool) $service['public']; $this->container->setAlias($id, new Alias($service['alias'], $public)); return; } if (isset($service['parent'])) { $definition = new DefinitionDecorator($service['parent']); } else { $definition = new Definition(); } if (isset($service['class'])) { $definition->setClass($service['class']); } if (isset($service['scope'])) { $definition->setScope($service['scope']); } if (isset($service['synthetic'])) { $definition->setSynthetic($service['synthetic']); } if (isset($service['synchronized'])) { @trigger_error(sprintf('The "synchronized" key of service "%s" in file "%s" is deprecated since version 2.7 and will be removed in 3.0.', $id, $file), E_USER_DEPRECATED); $definition->setSynchronized($service['synchronized'], 'request' !== $id); } if (isset($service['lazy'])) { $definition->setLazy($service['lazy']); } if (isset($service['public'])) { $definition->setPublic($service['public']); } if (isset($service['abstract'])) { $definition->setAbstract($service['abstract']); } if (isset($service['factory'])) { if (is_string($service['factory'])) { if (strpos($service['factory'], ':') !== false && strpos($service['factory'], '::') === false) { $parts = explode(':', $service['factory']); $definition->setFactory(array($this->resolveServices('@' . $parts[0]), $parts[1])); } else { $definition->setFactory($service['factory']); } } else { $definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1])); } } if (isset($service['factory_class'])) { @trigger_error(sprintf('The "factory_class" key of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED); $definition->setFactoryClass($service['factory_class']); } if (isset($service['factory_method'])) { @trigger_error(sprintf('The "factory_method" key of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED); $definition->setFactoryMethod($service['factory_method']); } if (isset($service['factory_service'])) { @trigger_error(sprintf('The "factory_service" key of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED); $definition->setFactoryService($service['factory_service']); } if (isset($service['file'])) { $definition->setFile($service['file']); } if (isset($service['arguments'])) { $definition->setArguments($this->resolveServices($service['arguments'])); } if (isset($service['properties'])) { $definition->setProperties($this->resolveServices($service['properties'])); } if (isset($service['configurator'])) { if (is_string($service['configurator'])) { $definition->setConfigurator($service['configurator']); } else { $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1])); } } if (isset($service['calls'])) { if (!is_array($service['calls'])) { throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['calls'] as $call) { if (isset($call['method'])) { $method = $call['method']; $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array(); } else { $method = $call[0]; $args = isset($call[1]) ? $this->resolveServices($call[1]) : array(); } $definition->addMethodCall($method, $args); } } if (isset($service['tags'])) { if (!is_array($service['tags'])) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } foreach ($service['tags'] as $tag) { if (!is_array($tag)) { throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } if (!isset($tag['name'])) { throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file)); } if (!is_string($tag['name']) || '' === $tag['name']) { throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file)); } $name = $tag['name']; unset($tag['name']); foreach ($tag as $attribute => $value) { if (!is_scalar($value) && null !== $value) { throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file)); } } $definition->addTag($name, $tag); } } if (isset($service['decorates'])) { if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) { throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($service['decorates'], 1))); } $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null; $definition->setDecoratedService($service['decorates'], $renameId); } $this->container->setDefinition($id, $definition); }
/** * Parses a definition. * * @param string $id * @param array $service * @param string $file * * @throws InvalidArgumentException When tags are invalid */ private function parseDefinition($id, $service, $file) { if (is_string($service) && 0 === strpos($service, '@')) { $this->container->setAlias($id, substr($service, 1)); return; } elseif (isset($service['alias'])) { $public = !array_key_exists('public', $service) || (bool) $service['public']; $this->container->setAlias($id, new Alias($service['alias'], $public)); return; } if (isset($service['parent'])) { $definition = new DefinitionDecorator($service['parent']); } else { $definition = new Definition(); } if (isset($service['class'])) { $definition->setClass($service['class']); } if (isset($service['scope'])) { $definition->setScope($service['scope']); } if (isset($service['synthetic'])) { $definition->setSynthetic($service['synthetic']); } if (isset($service['synchronized'])) { $definition->setSynchronized($service['synchronized']); } if (isset($service['lazy'])) { $definition->setLazy($service['lazy']); } if (isset($service['public'])) { $definition->setPublic($service['public']); } if (isset($service['abstract'])) { $definition->setAbstract($service['abstract']); } if (isset($service['factory_class'])) { $definition->setFactoryClass($service['factory_class']); } if (isset($service['factory_method'])) { $definition->setFactoryMethod($service['factory_method']); } if (isset($service['factory_service'])) { $definition->setFactoryService($service['factory_service']); } if (isset($service['file'])) { $definition->setFile($service['file']); } if (isset($service['arguments'])) { $definition->setArguments($this->resolveServices($service['arguments'])); } if (isset($service['properties'])) { $definition->setProperties($this->resolveServices($service['properties'])); } if (isset($service['configurator'])) { if (is_string($service['configurator'])) { $definition->setConfigurator($service['configurator']); } else { $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1])); } } if (isset($service['calls'])) { foreach ($service['calls'] as $call) { $args = isset($call[1]) ? $this->resolveServices($call[1]) : array(); $definition->addMethodCall($call[0], $args); } } if (isset($service['tags'])) { if (!is_array($service['tags'])) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s.', $id, $file)); } foreach ($service['tags'] as $tag) { if (!isset($tag['name'])) { throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file)); } $name = $tag['name']; unset($tag['name']); foreach ($tag as $attribute => $value) { if (!is_scalar($value)) { throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s" in %s.', $id, $name, $file)); } } $definition->addTag($name, $tag); } } $this->container->setDefinition($id, $definition); }
/** * @param string $userType * @param string $userModel * @param ContainerBuilder $container */ private function createProviders($userType, $userModel, ContainerBuilder $container) { $repositoryServiceId = sprintf('sylius.repository.%s_user', $userType); $abstractProviderServiceId = sprintf('sylius.%s_user.provider', $userType); $providerEmailBasedServiceId = sprintf('sylius.%s_user.provider.email_based', $userType); $providerNameBasedServiceId = sprintf('sylius.%s_user.provider.name_based', $userType); $providerEmailOrNameBasedServiceId = sprintf('sylius.%s_user.provider.email_or_name_based', $userType); $abstractProviderDefinition = new Definition(AbstractUserProvider::class); $abstractProviderDefinition->setAbstract(true); $abstractProviderDefinition->setLazy(true); $abstractProviderDefinition->addArgument($userModel); $abstractProviderDefinition->addArgument(new Reference($repositoryServiceId)); $abstractProviderDefinition->addArgument(new Reference('sylius.user.canonicalizer')); $container->setDefinition($abstractProviderServiceId, $abstractProviderDefinition); $providerEmailBasedDefinition = new DefinitionDecorator($abstractProviderServiceId); $providerEmailBasedDefinition->setClass(EmailProvider::class); $container->setDefinition($providerEmailBasedServiceId, $providerEmailBasedDefinition); $providerNameBasedDefinition = new DefinitionDecorator($abstractProviderServiceId); $providerNameBasedDefinition->setClass(UsernameProvider::class); $container->setDefinition($providerNameBasedServiceId, $providerNameBasedDefinition); $providerEmailOrNameBasedDefinition = new DefinitionDecorator($abstractProviderServiceId); $providerEmailOrNameBasedDefinition->setClass(UsernameOrEmailProvider::class); $container->setDefinition($providerEmailOrNameBasedServiceId, $providerEmailOrNameBasedDefinition); }
private function buildHandler(ContainerBuilder $container, $name, array $handler) { $handlerId = $this->getHandlerId($name); if ('service' === $handler['type']) { $container->setAlias($handlerId, $handler['id']); return $handlerId; } $definition = new Definition($this->getHandlerClassByType($handler['type'])); $handler['level'] = $this->levelToMonologConst($handler['level']); if ($handler['include_stacktraces']) { $definition->setConfigurator(array('Symfony\\Bundle\\MonologBundle\\MonologBundle', 'includeStacktraces')); } if ($handler['process_psr_3_messages']) { $processorId = 'monolog.processor.psr_log_message'; if (!$container->hasDefinition($processorId)) { $processor = new Definition('Monolog\\Processor\\PsrLogMessageProcessor'); $processor->setPublic(false); $container->setDefinition($processorId, $processor); } $definition->addMethodCall('pushProcessor', array(new Reference($processorId))); } switch ($handler['type']) { case 'stream': $definition->setArguments(array($handler['path'], $handler['level'], $handler['bubble'], $handler['file_permission'])); break; case 'console': $definition->setArguments(array(null, $handler['bubble'], isset($handler['verbosity_levels']) ? $handler['verbosity_levels'] : array())); $definition->addTag('kernel.event_subscriber'); break; case 'firephp': $definition->setArguments(array($handler['level'], $handler['bubble'])); $definition->addTag('kernel.event_listener', array('event' => 'kernel.response', 'method' => 'onKernelResponse')); break; case 'gelf': if (isset($handler['publisher']['id'])) { $publisherId = $handler['publisher']['id']; } elseif (class_exists('Gelf\\Transport\\UdpTransport')) { $transport = new Definition("Gelf\\Transport\\UdpTransport", array($handler['publisher']['hostname'], $handler['publisher']['port'], $handler['publisher']['chunk_size'])); $transportId = uniqid('monolog.gelf.transport.', true); $transport->setPublic(false); $container->setDefinition($transportId, $transport); $publisher = new Definition('Gelf\\Publisher', array()); $publisher->addMethodCall('addTransport', array(new Reference($transportId))); $publisherId = uniqid('monolog.gelf.publisher.', true); $publisher->setPublic(false); $container->setDefinition($publisherId, $publisher); } elseif (class_exists('Gelf\\MessagePublisher')) { $publisher = new Definition('Gelf\\MessagePublisher', array($handler['publisher']['hostname'], $handler['publisher']['port'], $handler['publisher']['chunk_size'])); $publisherId = uniqid('monolog.gelf.publisher.', true); $publisher->setPublic(false); $container->setDefinition($publisherId, $publisher); } else { throw new \RuntimeException('The gelf handler requires the graylog2/gelf-php package to be installed'); } $definition->setArguments(array(new Reference($publisherId), $handler['level'], $handler['bubble'])); break; case 'mongo': if (isset($handler['mongo']['id'])) { $clientId = $handler['mongo']['id']; } else { $server = 'mongodb://'; if (isset($handler['mongo']['user'])) { $server .= $handler['mongo']['user'] . ':' . $handler['mongo']['pass'] . '@'; } $server .= $handler['mongo']['host'] . ':' . $handler['mongo']['port']; $client = new Definition('MongoClient', array($server)); $clientId = uniqid('monolog.mongo.client.', true); $client->setPublic(false); $container->setDefinition($clientId, $client); } $definition->setArguments(array(new Reference($clientId), $handler['mongo']['database'], $handler['mongo']['collection'], $handler['level'], $handler['bubble'])); break; case 'elasticsearch': if (isset($handler['elasticsearch']['id'])) { $clientId = $handler['elasticsearch']['id']; } else { // elastica client new definition $elasticaClient = new Definition('Elastica\\Client'); $elasticaClientArguments = array('host' => $handler['elasticsearch']['host'], 'port' => $handler['elasticsearch']['port'], 'transport' => $handler['elasticsearch']['transport']); if (isset($handler['elasticsearch']['user']) && isset($handler['elasticsearch']['password'])) { $elasticaClientArguments = array_merge($elasticaClientArguments, array('headers' => array('Authorization ' => 'Basic ' . base64_encode($handler['elasticsearch']['user'] . ':' . $handler['elasticsearch']['password'])))); } $elasticaClient->setArguments(array($elasticaClientArguments)); $clientId = uniqid('monolog.elastica.client.', true); $elasticaClient->setPublic(false); $container->setDefinition($clientId, $elasticaClient); } // elastica handler definition $definition->setArguments(array(new Reference($clientId), array('index' => $handler['index'], 'type' => $handler['document_type'], 'ignore_error' => $handler['ignore_error']), $handler['level'], $handler['bubble'])); break; case 'chromephp': $definition->setArguments(array($handler['level'], $handler['bubble'])); $definition->addTag('kernel.event_listener', array('event' => 'kernel.response', 'method' => 'onKernelResponse')); break; case 'rotating_file': $definition->setArguments(array($handler['path'], $handler['max_files'], $handler['level'], $handler['bubble'], $handler['file_permission'])); $definition->addMethodCall('setFilenameFormat', array($handler['filename_format'], $handler['date_format'])); break; case 'fingers_crossed': $handler['action_level'] = $this->levelToMonologConst($handler['action_level']); if (null !== $handler['passthru_level']) { $handler['passthru_level'] = $this->levelToMonologConst($handler['passthru_level']); } $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->markNestedHandler($nestedHandlerId); if (isset($handler['activation_strategy'])) { $activation = new Reference($handler['activation_strategy']); } elseif (!empty($handler['excluded_404s'])) { $activationDef = new Definition('Symfony\\Bridge\\Monolog\\Handler\\FingersCrossed\\NotFoundActivationStrategy', array(new Reference('request_stack'), $handler['excluded_404s'], $handler['action_level'])); $container->setDefinition($handlerId . '.not_found_strategy', $activationDef); $activation = new Reference($handlerId . '.not_found_strategy'); } else { $activation = $handler['action_level']; } $definition->setArguments(array(new Reference($nestedHandlerId), $activation, $handler['buffer_size'], $handler['bubble'], $handler['stop_buffering'], $handler['passthru_level'])); break; case 'filter': $handler['min_level'] = $this->levelToMonologConst($handler['min_level']); $handler['max_level'] = $this->levelToMonologConst($handler['max_level']); foreach (array_keys($handler['accepted_levels']) as $k) { $handler['accepted_levels'][$k] = $this->levelToMonologConst($handler['accepted_levels'][$k]); } $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->markNestedHandler($nestedHandlerId); $minLevelOrList = !empty($handler['accepted_levels']) ? $handler['accepted_levels'] : $handler['min_level']; $definition->setArguments(array(new Reference($nestedHandlerId), $minLevelOrList, $handler['max_level'], $handler['bubble'])); break; case 'buffer': $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->markNestedHandler($nestedHandlerId); $definition->setArguments(array(new Reference($nestedHandlerId), $handler['buffer_size'], $handler['level'], $handler['bubble'], $handler['flush_on_overflow'])); break; case 'deduplication': $nestedHandlerId = $this->getHandlerId($handler['handler']); $this->markNestedHandler($nestedHandlerId); $defaultStore = '%kernel.cache_dir%/monolog_dedup_' . sha1($handlerId); $definition->setArguments(array(new Reference($nestedHandlerId), isset($handler['store']) ? $handler['store'] : $defaultStore, $handler['deduplication_level'], $handler['time'], $handler['bubble'])); break; case 'group': case 'whatfailuregroup': $references = array(); foreach ($handler['members'] as $nestedHandler) { $nestedHandlerId = $this->getHandlerId($nestedHandler); $this->markNestedHandler($nestedHandlerId); $references[] = new Reference($nestedHandlerId); } $definition->setArguments(array($references, $handler['bubble'])); break; case 'syslog': $definition->setArguments(array($handler['ident'], $handler['facility'], $handler['level'], $handler['bubble'], $handler['logopts'])); break; case 'syslogudp': $definition->setArguments(array($handler['host'], $handler['port'], $handler['facility'], $handler['level'], $handler['bubble'])); break; case 'swift_mailer': if (isset($handler['email_prototype'])) { if (!empty($handler['email_prototype']['method'])) { $prototype = array(new Reference($handler['email_prototype']['id']), $handler['email_prototype']['method']); } else { $prototype = new Reference($handler['email_prototype']['id']); } } else { $messageFactory = new Definition('Symfony\\Bundle\\MonologBundle\\SwiftMailer\\MessageFactory'); $messageFactory->setLazy(true); $messageFactory->setPublic(false); $messageFactory->setArguments(array(new Reference($handler['mailer']), $handler['from_email'], $handler['to_email'], $handler['subject'], $handler['content_type'])); $messageFactoryId = sprintf('%s.mail_message_factory', $handlerId); $container->setDefinition($messageFactoryId, $messageFactory); // set the prototype as a callable $prototype = array(new Reference($messageFactoryId), 'createMessage'); } $definition->setArguments(array(new Reference($handler['mailer']), $prototype, $handler['level'], $handler['bubble'])); $this->swiftMailerHandlers[] = $handlerId; $definition->addTag('kernel.event_listener', array('event' => 'kernel.terminate', 'method' => 'onKernelTerminate')); $definition->addTag('kernel.event_listener', array('event' => 'console.terminate', 'method' => 'onCliTerminate')); break; case 'native_mailer': $definition->setArguments(array($handler['to_email'], $handler['subject'], $handler['from_email'], $handler['level'], $handler['bubble'])); break; case 'socket': $definition->setArguments(array($handler['connection_string'], $handler['level'], $handler['bubble'])); if (isset($handler['timeout'])) { $definition->addMethodCall('setTimeout', array($handler['timeout'])); } if (isset($handler['connection_timeout'])) { $definition->addMethodCall('setConnectionTimeout', array($handler['connection_timeout'])); } if (isset($handler['persistent'])) { $definition->addMethodCall('setPersistent', array($handler['persistent'])); } break; case 'pushover': $definition->setArguments(array($handler['token'], $handler['user'], $handler['title'], $handler['level'], $handler['bubble'])); break; case 'hipchat': $definition->setArguments(array($handler['token'], $handler['room'], $handler['nickname'], $handler['notify'], $handler['level'], $handler['bubble'], $handler['use_ssl'], $handler['message_format'], !empty($handler['host']) ? $handler['host'] : 'api.hipchat.com', !empty($handler['api_version']) ? $handler['api_version'] : 'v1')); break; case 'slack': $definition->setArguments(array($handler['token'], $handler['channel'], $handler['bot_name'], $handler['use_attachment'], $handler['icon_emoji'], $handler['level'], $handler['bubble'], $handler['use_short_attachment'], $handler['include_extra'])); break; case 'cube': $definition->setArguments(array($handler['url'], $handler['level'], $handler['bubble'])); break; case 'amqp': $definition->setArguments(array(new Reference($handler['exchange']), $handler['exchange_name'], $handler['level'], $handler['bubble'])); break; case 'error_log': $definition->setArguments(array($handler['message_type'], $handler['level'], $handler['bubble'])); break; case 'raven': if (null !== $handler['client_id']) { $clientId = $handler['client_id']; } else { $client = new Definition('Raven_Client', array($handler['dsn'], array('auto_log_stacks' => $handler['auto_log_stacks']))); $client->setPublic(false); $clientId = 'monolog.raven.client.' . sha1($handler['dsn']); $container->setDefinition($clientId, $client); } $definition->setArguments(array(new Reference($clientId), $handler['level'], $handler['bubble'])); if (!empty($handler['release'])) { $definition->addMethodCall('setRelease', array($handler['release'])); } break; case 'loggly': $definition->setArguments(array($handler['token'], $handler['level'], $handler['bubble'])); if (!empty($handler['tags'])) { $definition->addMethodCall('setTag', array(implode(',', $handler['tags']))); } break; case 'logentries': $definition->setArguments(array($handler['token'], $handler['use_ssl'], $handler['level'], $handler['bubble'])); if (isset($handler['timeout'])) { $definition->addMethodCall('setTimeout', array($handler['timeout'])); } if (isset($handler['connection_timeout'])) { $definition->addMethodCall('setConnectionTimeout', array($handler['connection_timeout'])); } break; case 'flowdock': $definition->setArguments(array($handler['token'], $handler['level'], $handler['bubble'])); if (empty($handler['formatter'])) { $formatter = new Definition("Monolog\\Formatter\\FlowdockFormatter", array($handler['source'], $handler['from_email'])); $formatterId = 'monolog.flowdock.formatter.' . sha1($handler['source'] . '|' . $handler['from_email']); $formatter->setPublic(false); $container->setDefinition($formatterId, $formatter); $definition->addMethodCall('setFormatter', array(new Reference($formatterId))); } break; case 'rollbar': if (!empty($handler['id'])) { $rollbarId = $handler['id']; } else { $config = $handler['config'] ?: array(); $config['access_token'] = $handler['token']; $rollbar = new Definition('RollbarNotifier', array($config)); $rollbarId = 'monolog.rollbar.notifier.' . sha1(json_encode($config)); $rollbar->setPublic(false); $container->setDefinition($rollbarId, $rollbar); } $definition->setArguments(array(new Reference($rollbarId), $handler['level'], $handler['bubble'])); break; case 'newrelic': $definition->setArguments(array($handler['level'], $handler['bubble'], $handler['app_name'])); break; // Handlers using the constructor of AbstractHandler without adding their own arguments // Handlers using the constructor of AbstractHandler without adding their own arguments case 'browser_console': case 'test': case 'null': $definition->setArguments(array($handler['level'], $handler['bubble'])); break; default: throw new \InvalidArgumentException(sprintf('Invalid handler type "%s" given for handler "%s"', $handler['type'], $name)); } if (!empty($handler['nested']) && true === $handler['nested']) { $this->markNestedHandler($handlerId); } if (!empty($handler['formatter'])) { $definition->addMethodCall('setFormatter', array(new Reference($handler['formatter']))); } $container->setDefinition($handlerId, $definition); return $handlerId; }