/**
  * Apply the default values required by the AdminInterface to the Admin service definition
  *
  * @param \Symfony\Component\DependencyInjection\Definition $definition
  * @param array $attributes
  * @return \Symfony\Component\DependencyInjection\Definition
  */
 public function applyDefaults(Definition $definition, array $attributes = array())
 {
     $definition->setScope(ContainerInterface::SCOPE_PROTOTYPE);
     $manager_type = $attributes[0]['manager_type'];
     if (!$definition->hasMethodCall('setModelManager')) {
         $definition->addMethodCall('setModelManager', array(new Reference(sprintf('sonata.admin.manager.%s', $manager_type))));
     }
     if (!$definition->hasMethodCall('setFormContractor')) {
         $definition->addMethodCall('setFormContractor', array(new Reference(sprintf('sonata.admin.builder.%s_form', $manager_type))));
     }
     if (!$definition->hasMethodCall('setListBuilder')) {
         $definition->addMethodCall('setListBuilder', array(new Reference(sprintf('sonata.admin.builder.%s_list', $manager_type))));
     }
     if (!$definition->hasMethodCall('setDatagridBuilder')) {
         $definition->addMethodCall('setDatagridBuilder', array(new Reference(sprintf('sonata.admin.builder.%s_datagrid', $manager_type))));
     }
     if (!$definition->hasMethodCall('setTranslator')) {
         $definition->addMethodCall('setTranslator', array(new Reference('translator')));
     }
     if (!$definition->hasMethodCall('setConfigurationPool')) {
         $definition->addMethodCall('setConfigurationPool', array(new Reference('sonata.admin.pool')));
     }
     if (!$definition->hasMethodCall('setRouter')) {
         $definition->addMethodCall('setRouter', array(new Reference('router')));
     }
     if (!$definition->hasMethodCall('setLabel')) {
         $label = isset($attributes[0]['label']) ? $attributes[0]['label'] : '-';
         $definition->addMethodCall('setLabel', array($label));
     }
     $definition->addMethodCall('configure');
     return $definition;
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function process(ContainerBuilder $container)
 {
     foreach ($container->findTaggedServiceIds('snc_redis.connection_parameters') as $id => $attr) {
         $parameterDefinition = $container->getDefinition($id);
         $parameters = $parameterDefinition->getArgument(0);
         if ($parameters['logging']) {
             if ('%kernel.debug%' === $parameters['logging'] && false === $container->getParameter('kernel.debug')) {
                 continue;
             }
             $optionId = sprintf('snc_redis.client.%s_options', $parameters['alias']);
             $option = $container->getDefinition($optionId);
             if (1 < count($option->getArguments())) {
                 throw new \RuntimeException('Please check the predis option arguments.');
             }
             $arguments = $option->getArgument(0);
             $connectionFactoryId = sprintf('snc_redis.%s_connectionfactory', $parameters['alias']);
             $connectionFactoryDef = new Definition($container->getParameter('snc_redis.connection_factory.class'));
             $connectionFactoryDef->setPublic(false);
             $connectionFactoryDef->setScope(ContainerInterface::SCOPE_CONTAINER);
             $connectionFactoryDef->addArgument(new Reference(sprintf('snc_redis.client.%s_profile', $parameters['alias'])));
             $connectionFactoryDef->addMethodCall('setConnectionWrapperClass', array($container->getParameter('snc_redis.connection_wrapper.class')));
             $connectionFactoryDef->addMethodCall('setLogger', array(new Reference('snc_redis.logger')));
             $container->setDefinition($connectionFactoryId, $connectionFactoryDef);
             $arguments['connections'] = new Reference($connectionFactoryId);
             $option->replaceArgument(0, $arguments);
         }
     }
 }
 /**
  * {@inheritDoc}
  */
 public function load(array $configs, ContainerBuilder $container)
 {
     $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
     $loader->load('services.xml');
     $config = $this->getConfiguration($configs, $container);
     $config = $this->processConfiguration($config, $configs);
     foreach ($config['services'] as $name => $settings) {
         // until we can use file attachments in Guzzle in php 5.5 we block use of the upload type
         if ('upload' === $settings['type']) {
             throw new \ConfigurationException('The "upload" type is currently disabled due to PHP 5.5 cURL issues.');
         }
         $def = new Definition($container->getParameter('pompdelux.kraken.service.class'));
         $def->setPublic(true);
         $def->setScope(ContainerInterface::SCOPE_CONTAINER);
         $def->addArgument(new Reference('pompdelux.kraken.guzzle.' . $settings['type'] . '.service'));
         $def->addArgument(new Reference('logger'));
         $def->addArgument(new Reference('router'));
         $def->addArgument($settings['api_key']);
         $def->addArgument($settings['api_secret']);
         $def->addArgument($settings['type']);
         $def->addArgument($settings['use_lossy']);
         $callback = $settings['callback'] ? $settings['callback_route'] : null;
         $def->addArgument($callback);
         $container->setDefinition(sprintf('pompdelux.kraken.%s', $name), $def);
     }
 }
 /**
  * @param Definition $definition
  * @param array $config
  */
 private function configureDefinition(Definition $definition, array $config)
 {
     foreach ($config['servers'] as $currentServer) {
         $currentServer = explode(':', $currentServer, 2);
         $definition->addMethodCall('addServer', $currentServer);
     }
     $definition->addMethodCall('setTimeout', array($config['timeout']));
     $definition->setScope('prototype');
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function load(array $configs, ContainerBuilder $container)
 {
     $this->defineParameters($container);
     $definition = new Definition('Scaffold\\Scaffolder');
     $definition->setArguments(array('%scaffold.template_path%', '%scaffold.tmp_path%'));
     $definition->setScope('prototype');
     $container->setDefinition('scaffold.scaffolder', $definition);
     $definition = new Definition('Scaffold\\Variable\\Model');
     $container->setDefinition('model.variable', $definition);
 }
Example #6
0
 /**
  * Transforms the Definition into one we can use for mocks
  *
  * @return Object
  * @author Dan Cox
  */
 public function transformDefinition($mockery)
 {
     $definition = new Definition();
     // Set the class to the mockery decorator
     $definition->setClass('Wasp\\DI\\ServiceMockeryDecorator');
     // Add the mockery name as a definition;
     $definition->setArguments([$mockery]);
     // Incase it is a prototype scoped class
     $definition->setScope('container');
     return $definition;
 }
 /** @dataProvider getScopesTests */
 public function testFindLowestScopeInNamedPackageWithDefinition($scope)
 {
     $container = new ContainerBuilder();
     $defaultPackage = new Definition('stdClass');
     $aPackage = new Definition('stdClass');
     $bPackage = new Definition('stdClass');
     $bPackage->setScope($scope);
     $cPackage = new Definition('stdClass');
     $definition = new Definition('stdClass', array($defaultPackage, array($aPackage, $bPackage, $cPackage)));
     $container->setDefinition('templating.helper.assets', $definition);
     $profilerPass = new TemplatingAssetHelperPass();
     $profilerPass->process($container);
     $this->assertSame($scope, $definition->getScope());
 }
 /**
  * {@inheritDoc}
  */
 public function load(array $configs, ContainerBuilder $container)
 {
     $configuration = new Configuration();
     $config = $this->processConfiguration($configuration, $configs);
     $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
     $loader->load('services.xml');
     //Compatibilidad con fos user 1.3
     if (!class_exists('FOS\\UserBundle\\FOSUserEvents')) {
         $registrationFormHandlerDefinition = new Definition("Tecnocreaciones\\Bundle\\AjaxFOSUserBundle\\Handler\\RegistrationFormHandler");
         $registrationFormHandlerDefinition->setScope("request");
         $registrationFormHandlerDefinition->setArguments(array(new Reference("fos_user.registration.form"), new Reference("request"), new Reference("fos_user.user_manager"), new Reference("fos_user.mailer"), new Reference("fos_user.util.token_generator"), new Reference("event_dispatcher")));
         $container->setDefinition("fos_user.registration.form.handler.default", $registrationFormHandlerDefinition);
     }
 }
 /**
  * Loads connections.
  *
  * @param array $config A connection config options.
  * @param ContainerBuilder $container The ContainerBuilder instance
  */
 protected function loadConnection(array $config, ContainerBuilder $container)
 {
     $connectionDef = new Definition('Lt\\Bundle\\RedisBundle\\Connection\\RedisClient');
     //TODO: Use configurable class.
     $connectionDef->setScope(ContainerInterface::SCOPE_CONTAINER);
     $parameters = array('host' => $config['host'], 'port' => $config['port'], 'database' => $config['database'], 'password' => $config['auth']);
     $connectionDef->addArgument($parameters);
     $connectionDef->addArgument($config['options']);
     if ($config['logging']) {
         $connectionDef->addArgument(new Reference('lt_redis.connection_factory'));
     }
     $container->setDefinition(sprintf('lt_redis.%s', $config['alias']), $connectionDef);
     $container->setAlias(sprintf('lt_redis.%s_connection', $config['alias']), sprintf('lt_redis.%s', $config['alias']));
 }
 /**
  * {@inheritDoc}
  */
 public function load(array $configs, ContainerBuilder $container)
 {
     $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
     $loader->load('services.xml');
     $config = $this->getConfiguration($configs, $container);
     $config = $this->processConfiguration($config, $configs);
     foreach ($config['class'] as $name => $settings) {
         $def = new Definition($container->getParameter('pdl.phpredis.class'));
         $def->setPublic(true);
         $def->setScope(ContainerInterface::SCOPE_CONTAINER);
         $def->addArgument($name);
         $def->addArgument($container->getParameter('kernel.environment'));
         $def->addArgument($settings);
         $def->addMethodCall('setLogger', [new Reference('pdl.phpredis.logger')]);
         $container->setDefinition(sprintf('pdl.phpredis.%s', $name), $def);
     }
 }
 /**
  * Loads the Doctrine configuration.
  *
  * @param array            $config    A configuration array
  * @param ContainerBuilder $container A ContainerBuilder instance
  */
 protected function loadDoctrine(array $config, ContainerBuilder $container)
 {
     foreach ($config['doctrine'] as $name => $cache) {
         $clusterConfig = $config['clusters'][$cache['cluster']];
         $client = new Reference(sprintf('memcached.%s', $cache['cluster']));
         foreach ($cache['entity_managers'] as $em) {
             $definition = new Definition($container->getParameter('memcached.doctrine_cache.class'));
             $definition->setScope(ContainerInterface::SCOPE_CONTAINER);
             $definition->addMethodCall('setMemcached', array($client));
             $container->setDefinition(sprintf('doctrine.orm.%s_%s_cache', $em, $name), $definition);
         }
         foreach ($cache['document_managers'] as $dm) {
             $definition = new Definition($container->getParameter('memcached.doctrine_cache.class'));
             $definition->setScope(ContainerInterface::SCOPE_CONTAINER);
             $definition->addMethodCall('setMemcached', array($client));
             $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_%s_cache', $dm, $name), $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);
 }
 public function load(array $configs, ContainerBuilder $container)
 {
     $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
     $loader->load('services.yml');
     $config = array();
     foreach ($configs as $subConfig) {
         $config = array_merge($config, $subConfig);
     }
     foreach ($config['email'] as $alias => $options) {
         $optionId = sprintf('rage_notification.email.%s.message', $alias);
         $optionDef = new Definition($container->getParameter('rage_notification.email_message.class'));
         $optionDef->setScope(ContainerInterface::SCOPE_PROTOTYPE);
         $optionDef->addArgument(new Reference('mailer'));
         $optionDef->addArgument(new Reference('templating'));
         $optionDef->addArgument(new Reference('service_container'));
         if (!empty($options['from'])) {
             $optionDef->addMethodCall('setFrom', [$options['from']]);
         }
         if (!empty($options['reply_to'])) {
             $optionDef->addMethodCall('setReplyTo', [$options['reply_to']]);
         }
         if (!empty($options['embed_images'])) {
             $optionDef->addMethodCall('setEmbedImages', [$options['embed_images']['url'], $options['embed_images']['path']]);
         }
         if (!empty($options['template_path'])) {
             $optionDef->addMethodCall('setTemplatePath', [$options['template_path']]);
         }
         if (!empty($options['css_file'])) {
             $optionDef->addMethodCall('setCssFile', [$options['css_file']]);
         }
         $container->setDefinition($optionId, $optionDef);
         if ($alias === 'default') {
             $container->setAlias('rage_notification.email.message', $optionId);
         }
     }
 }
Example #14
0
 /**
  * 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);
 }
Example #15
0
    /**
     * 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) || (Boolean) $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['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);
    }
 /**
  * Resolves the definition
  *
  * @param string              $id         The definition identifier
  * @param DefinitionDecorator $definition
  *
  * @return Definition
  */
 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->setFactoryClass($parentDef->getFactoryClass());
     $def->setFactoryMethod($parentDef->getFactoryMethod());
     $def->setFactoryService($parentDef->getFactoryService());
     $def->setConfigurator($parentDef->getConfigurator());
     $def->setFile($parentDef->getFile());
     $def->setPublic($parentDef->isPublic());
     // 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());
     }
     if (isset($changes['factory_method'])) {
         $def->setFactoryMethod($definition->getFactoryMethod());
     }
     if (isset($changes['factory_service'])) {
         $def->setFactoryService($definition->getFactoryService());
     }
     if (isset($changes['configurator'])) {
         $def->setConfigurator($definition->getConfigurator());
     }
     if (isset($changes['file'])) {
         $def->setFile($definition->getFile());
     }
     if (isset($changes['public'])) {
         $def->setPublic($definition->isPublic());
     }
     // 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;
 }
 /**
  * Parses an individual Definition.
  *
  * @param \DOMElement $service
  * @param string      $file
  *
  * @return Definition|null
  */
 private function parseDefinition(\DOMElement $service, $file)
 {
     if ($alias = $service->getAttribute('alias')) {
         $public = true;
         if ($publicAttr = $service->getAttribute('public')) {
             $public = XmlUtils::phpize($publicAttr);
         }
         $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public));
         return;
     }
     if ($parent = $service->getAttribute('parent')) {
         $definition = new DefinitionDecorator($parent);
     } else {
         $definition = new Definition();
     }
     foreach (array('class', 'shared', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'lazy', 'abstract') as $key) {
         if ($value = $service->getAttribute($key)) {
             if (in_array($key, array('factory-class', 'factory-method', 'factory-service'))) {
                 @trigger_error(sprintf('The "%s" attribute of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use the "factory" element instead.', $key, (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
             }
             $method = 'set' . str_replace('-', '', $key);
             $definition->{$method}(XmlUtils::phpize($value));
         }
     }
     if ($value = $service->getAttribute('autowire')) {
         $definition->setAutowired(XmlUtils::phpize($value));
     }
     if ($value = $service->getAttribute('scope')) {
         $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
         if ($triggerDeprecation) {
             @trigger_error(sprintf('The "scope" attribute of service "%s" in file "%s" is deprecated since version 2.8 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
         }
         $definition->setScope(XmlUtils::phpize($value), false);
     }
     if ($value = $service->getAttribute('synchronized')) {
         $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
         if ($triggerDeprecation) {
             @trigger_error(sprintf('The "synchronized" attribute of service "%s" in file "%s" is deprecated since version 2.7 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
         }
         $definition->setSynchronized(XmlUtils::phpize($value), $triggerDeprecation);
     }
     if ($files = $this->getChildren($service, 'file')) {
         $definition->setFile($files[0]->nodeValue);
     }
     if ($deprecated = $this->getChildren($service, 'deprecated')) {
         $definition->setDeprecated(true, $deprecated[0]->nodeValue);
     }
     $definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
     $definition->setProperties($this->getArgumentsAsPhp($service, 'property'));
     if ($factories = $this->getChildren($service, 'factory')) {
         $factory = $factories[0];
         if ($function = $factory->getAttribute('function')) {
             $definition->setFactory($function);
         } else {
             $factoryService = $this->getChildren($factory, 'service');
             if (isset($factoryService[0])) {
                 $class = $this->parseDefinition($factoryService[0], $file);
             } elseif ($childService = $factory->getAttribute('service')) {
                 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
             } else {
                 $class = $factory->getAttribute('class');
             }
             $definition->setFactory(array($class, $factory->getAttribute('method')));
         }
     }
     if ($configurators = $this->getChildren($service, 'configurator')) {
         $configurator = $configurators[0];
         if ($function = $configurator->getAttribute('function')) {
             $definition->setConfigurator($function);
         } else {
             $configuratorService = $this->getChildren($configurator, 'service');
             if (isset($configuratorService[0])) {
                 $class = $this->parseDefinition($configuratorService[0], $file);
             } elseif ($childService = $configurator->getAttribute('service')) {
                 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
             } else {
                 $class = $configurator->getAttribute('class');
             }
             $definition->setConfigurator(array($class, $configurator->getAttribute('method')));
         }
     }
     foreach ($this->getChildren($service, 'call') as $call) {
         $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument'));
     }
     foreach ($this->getChildren($service, 'tag') as $tag) {
         $parameters = array();
         foreach ($tag->attributes as $name => $node) {
             if ('name' === $name) {
                 continue;
             }
             if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
                 $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
             }
             // keep not normalized key for BC too
             $parameters[$name] = XmlUtils::phpize($node->nodeValue);
         }
         $definition->addTag($tag->getAttribute('name'), $parameters);
     }
     foreach ($this->getChildren($service, 'autowiring-type') as $type) {
         $definition->addAutowiringType($type->textContent);
     }
     if ($value = $service->getAttribute('decorates')) {
         $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
         $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
         $definition->setDecoratedService($value, $renameId, $priority);
     }
     return $definition;
 }
 /**
  * Load a client configuration as a service in the container. A client can use multiple servers
  *
  * @param ContainerInterface $container  The container
  * @param string             $alias      Alias of the client
  * @param array              $config     Base config of the client
  * @param array              $servers    List of available servers as describe in the config file
  * @param boolean            $baseEvents Register base events
  *
  * @throws InvalidConfigurationException
  * @return string the service name
  */
 protected function loadClient($container, $alias, array $config, array $servers, $baseEvents)
 {
     $usedServers = [];
     $events = $config['events'];
     $matchedServers = [];
     if ($config['servers'][0] == 'all') {
         // Use all servers
         $matchedServers = array_keys($servers);
     } else {
         // Use only declared servers
         foreach ($config['servers'] as $serverAlias) {
             // Named server
             if (array_key_exists($serverAlias, $servers)) {
                 $matchedServers[] = $serverAlias;
                 continue;
             }
             // Search matchning server config name
             $found = false;
             foreach (array_keys($servers) as $key) {
                 if (fnmatch($serverAlias, $key)) {
                     $matchedServers[] = $key;
                     $found = true;
                 }
             }
             // No server found
             if (!$found) {
                 throw new InvalidConfigurationException(sprintf('M6WebStatsd client %s used server %s which is not defined in the servers section', $alias, $serverAlias));
             }
         }
     }
     // Matched server congurations
     foreach ($matchedServers as $serverAlias) {
         $usedServers[] = ['address' => $servers[$serverAlias]['address'], 'port' => $servers[$serverAlias]['port']];
     }
     // Add the statsd client configured
     $serviceId = $alias == 'default' ? 'm6_statsd' : 'm6_statsd.' . $alias;
     $definition = new Definition('M6Web\\Bundle\\StatsdBundle\\Client\\Client');
     $definition->setScope(ContainerInterface::SCOPE_CONTAINER);
     $definition->addArgument($usedServers);
     if (isset($config['to_send_limit'])) {
         $definition->addMethodCall('setToSendLimit', array($config['to_send_limit']));
     }
     foreach ($events as $eventName => $eventConfig) {
         $definition->addTag('kernel.event_listener', ['event' => $eventName, 'method' => 'handleEvent']);
         $definition->addMethodCall('addEventToListen', [$eventName, $eventConfig]);
     }
     $container->setDefinition($serviceId, $definition);
     // Add the statsd client listener
     $serviceListenerId = $serviceId . '.listener';
     $definition = new Definition('M6Web\\Bundle\\StatsdBundle\\Statsd\\Listener');
     $definition->addArgument(new Reference($serviceId));
     $definition->addArgument(new Reference('event_dispatcher'));
     $definition->addTag('kernel.event_listener', ['event' => 'kernel.terminate', 'method' => 'onKernelTerminate', 'priority' => -100]);
     if ($baseEvents) {
         $definition->addTag('kernel.event_listener', ['event' => 'kernel.terminate', 'method' => 'onKernelTerminateEvents', 'priority' => 0]);
         $definition->addTag('kernel.event_listener', ['event' => 'kernel.exception', 'method' => 'onKernelException', 'priority' => 0]);
     }
     $container->setDefinition($serviceListenerId, $definition);
     return $serviceId;
 }
Example #19
0
 /**
  * @group legacy
  */
 public function testPrototypeScopedDefinitionAreNotShared()
 {
     $def = new Definition('stdClass');
     $def->setScope(ContainerInterface::SCOPE_PROTOTYPE);
     $this->assertFalse($def->isShared());
     $this->assertEquals(ContainerInterface::SCOPE_PROTOTYPE, $def->getScope());
 }
 /**
  * Loads the Doctrine configuration.
  *
  * @param array            $config    A configuration array
  * @param ContainerBuilder $container A ContainerBuilder instance
  */
 protected function loadDoctrine(array $config, ContainerBuilder $container)
 {
     foreach ($config['doctrine'] as $name => $cache) {
         $client = new Reference(sprintf('snc_redis.%s_client', $cache['client']));
         foreach ($cache['entity_managers'] as $em) {
             $def = new Definition($container->getParameter('snc_redis.doctrine_cache.class'));
             $def->setScope(ContainerInterface::SCOPE_CONTAINER);
             $def->addMethodCall('setRedis', array($client));
             if ($cache['namespace']) {
                 $def->addMethodCall('setNamespace', array($cache['namespace']));
             }
             $container->setDefinition(sprintf('doctrine.orm.%s_%s', $em, $name), $def);
         }
         foreach ($cache['document_managers'] as $dm) {
             $def = new Definition($container->getParameter('snc_redis.doctrine_cache.class'));
             $def->setScope(ContainerInterface::SCOPE_CONTAINER);
             $def->addMethodCall('setRedis', array($client));
             if ($cache['namespace']) {
                 $def->addMethodCall('setNamespace', array($cache['namespace']));
             }
             $container->setDefinition(sprintf('doctrine_mongodb.odm.%s_%s', $dm, $name), $def);
         }
     }
 }
 /**
  * Builds excel node definition.
  *
  * @param ContainerBuilder $container
  * @param $config
  */
 private function buildFormulaInterpreterExcelDefinition(ContainerBuilder $container, $config)
 {
     foreach ($config['scopes'] as $scopeName => $scope) {
         $functions = $config['functions'];
         if (!$scope['use_default_functions']) {
             $functions = array_merge($this->getDefaultExcelFunctions(), $functions);
         }
         foreach ($functions as $functionName => $function) {
             if (!in_array($functionName, $scope['functions'])) {
                 unset($functions[$functionName]);
             }
         }
         if ($scope['use_default_functions']) {
             $functions = array_merge($this->getDefaultExcelFunctions(), $functions);
         }
         if (0 < count($diffs = array_diff($scope['functions'], array_keys($functions)))) {
             throw new InvalidConfigurationException(sprintf("Unknown function(s) in '%s' scope : %s", $scopeName, implode(', ', $diffs)));
         }
         // Defines ExpressionFunction services.
         $functionDefinitions = array();
         foreach ($functions as $name => $function) {
             $functionClassParameter = sprintf('%s.%s.class', $this->excelFunctionBaseName, strtolower($name));
             $container->setParameter($functionClassParameter, $function['class']);
             foreach ($function['translations'] as $translation) {
                 $translation = strtoupper($translation);
                 $functionDefinition = new Definition();
                 $functionDefinition->setClass($container->getParameter($functionClassParameter));
                 $functionDefinition->setArguments(array($translation));
                 $functionDefinition->setPublic(false);
                 // SF >= 2.8
                 if (method_exists('Symfony\\Component\\DependencyInjection\\Definition', 'setShared')) {
                     $functionDefinition->setShared(false);
                 } else {
                     $functionDefinition->setScope(ContainerInterface::SCOPE_PROTOTYPE);
                 }
                 foreach ($function['services'] as $service) {
                     $parameters = array();
                     foreach ($service['parameters'] as $parameter) {
                         $parameters[] = new Reference(ltrim($parameter, '@'));
                     }
                     $functionDefinition->addMethodCall($service['method'], $parameters);
                 }
                 $functionService = sprintf('%s.%s', $this->excelFunctionBaseName, $translation);
                 $container->setDefinition($functionService, $functionDefinition);
                 $functionDefinitions[] = $container->getDefinition($functionService);
             }
         }
         // Defines ExpressionLanguageProvider service using a list of ExpressionFunction.
         $expressionLanguageProvider = new Definition();
         $expressionLanguageProvider->setClass($container->getParameter('profideo.formula_interpreter.excel.expression_language_provider.class'));
         $expressionLanguageProvider->setArguments([$functionDefinitions]);
         $expressionLanguageProvider->setPublic(false);
         $container->setDefinition("profideo.formula_interpreter.excel.expression_language_provider.{$scopeName}", $expressionLanguageProvider);
         $constantList = $config['constants'];
         if (!$scope['use_default_constants']) {
             $constantList = array_merge($this->getDefaultExcelConstants(), $constantList);
         }
         foreach ($constantList as $constantName => $constant) {
             if (!in_array($constantName, $scope['constants'])) {
                 unset($constantList[$constantName]);
             }
         }
         if ($scope['use_default_constants']) {
             $constantList = array_merge($this->getDefaultExcelConstants(), $constantList);
         }
         if (0 < count($diffs = array_diff($scope['constants'], array_keys($constantList)))) {
             throw new InvalidConfigurationException(sprintf("Unknown constant(s) in '%s' scope : %s", $scopeName, implode(', ', $diffs)));
         }
         $constants = array();
         foreach ($constantList as $constant) {
             foreach ($constant['translations'] as $translation) {
                 $translation = strtoupper($translation);
                 $constants[$translation] = $constant['value'];
             }
         }
         // Defines ExpressionLanguage service using:
         // - ExpressionLanguageProvider service
         // - a constant list
         // - start with equal configuration
         // - minimum number of functions configuration
         $expressionLanguage = new Definition();
         $expressionLanguage->setClass($container->getParameter('profideo.formula_interpreter.excel.expression_language.class'));
         $expressionLanguage->setArguments(array(null, [$container->getDefinition("profideo.formula_interpreter.excel.expression_language_provider.{$scopeName}")], $constants, $scope['start_with_equal'], $scope['minimum_number_of_functions']));
         $expressionLanguage->setPublic(false);
         $container->setDefinition("profideo.formula_interpreter.excel.expression_language.{$scopeName}", $expressionLanguage);
         // Defines FormulaInterpreter service using:
         // - ExpressionLanguage service
         $formulaInterpreter = new Definition();
         $formulaInterpreter->setClass($container->getParameter('profideo.formula_interpreter.excel.formula_interpreter.class'));
         $formulaInterpreter->setArguments(array($container->getDefinition("profideo.formula_interpreter.excel.expression_language.{$scopeName}")));
         $formulaInterpreter->setPublic(true);
         $container->setDefinition("profideo.formula_interpreter.excel.{$scopeName}", $formulaInterpreter);
     }
 }
Example #22
0
 /**
  * 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);
 }
 /**
  * Set the definition property (public/abstract/scope/file) into definition object if it exists.
  *
  * @param Definition $definition definition object to hydrate
  * @param array      $array      raw definition datas
  */
 private function setDefinitionProperties(Definition $definition, array $array)
 {
     if (isset($array['public'])) {
         $definition->setPublic($array['public']);
     }
     if (isset($array['abstract'])) {
         $definition->setAbstract($array['abstract']);
     }
     if (isset($array['scope'])) {
         $definition->setScope($array['scope']);
     }
     if (isset($array['file'])) {
         $definition->setFile($array['file']);
     }
 }
 /**
  * @param Bean $bean
  * @return mixed
  */
 public function create(Bean $bean)
 {
     $useConfigurator = true;
     $originalClass = $class = ltrim($bean->class, '\\');
     if ($bean->factoryMethod) {
         // We don't have a clue what what the real class is, fake it and hope nothing breaks;
         $class = "stdClass";
     } else {
         if (class_exists($class)) {
             $rClass = new \ReflectionClass($class);
             if (!$rClass->implementsInterface('MooDev\\Bounce\\Config\\Configurable')) {
                 // The class definitely doesn't need the configurator, so we can disable it.
                 $useConfigurator = false;
             }
         }
     }
     $usesLookupMethods = false;
     if ($bean->lookupMethods) {
         if (!$this->proxyGeneratorFactory) {
             throw new BounceException("Proxy generator not configured, cannot use lookup-method");
         }
         // If we have lookup methods then the class is actually a generated proxy.
         $class = ltrim($this->proxyGeneratorFactory->loadProxy($bean), '\\');
         $usesLookupMethods = true;
     }
     $def = new Definition($class);
     if ($usesLookupMethods) {
         // The proxy will take an additional, first, constructor arg which is expected to be a bean factory.
         $def->addArgument($this->getBeanFactory());
     }
     if ($useConfigurator) {
         // We use the configurator if we know the class of the bean and it implements Configurable
         // or if we have no idea what the class of the bean is (there's a factory method.)
         $def->setConfigurator($this->getConfigurator());
     }
     if ($bean->scope) {
         // This is getting killed off in Symfony 3. Sigh.
         // TODO: deal with Symfony 3.
         switch ($bean->scope) {
             case "singleton":
                 $def->setScope(ContainerBuilder::SCOPE_CONTAINER);
                 break;
             case "prototype":
                 $def->setScope(ContainerBuilder::SCOPE_PROTOTYPE);
                 break;
             default:
                 $def->setScope($bean->scope);
         }
     }
     foreach ($bean->constructorArguments as $constructorArgument) {
         $def->addArgument($this->convertValueProviderToValue($constructorArgument));
     }
     foreach ($bean->properties as $name => $property) {
         // TODO: Could support setter injection using Reflection here?
         $def->setProperty($name, $this->convertValueProviderToValue($property));
     }
     if ($bean->factoryBean) {
         $def->setFactoryService($bean->factoryBean);
         $def->setFactoryMethod($bean->factoryMethod);
     } elseif ($bean->factoryMethod) {
         $def->setFactoryClass($originalClass);
         $def->setFactoryMethod($bean->factoryMethod);
     }
     return $def;
 }
 /**
  * Tests that the correct InvalidArgumentException is thrown for getScope().
  *
  * @covers ::getServiceDefinition
  *
  * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  */
 public function testGetServiceDefinitionWithInvalidScope()
 {
     $bar_definition = new Definition('\\stdClass');
     $bar_definition->setScope('foo_scope');
     $services['bar'] = $bar_definition;
     $this->containerBuilder->getDefinitions()->willReturn($services);
     $this->dumper->getArray();
 }
Example #26
0
 protected function parseDefinition($id, $service, $file)
 {
     if (is_string($service) && 0 === strpos($service, '@')) {
         $this->container->setAlias($id, substr($service, 1));
         return;
     } else {
         if (isset($service['alias'])) {
             $public = !array_key_exists('public', $service) || (bool) $service['public'];
             $this->container->setAlias($id, new Alias($service['alias'], $public));
             return;
         }
     }
     $definition = new Definition();
     if (isset($service['class'])) {
         $definition->setClass($service['class']);
     }
     if (isset($service['scope'])) {
         $definition->setScope($service['scope']);
     }
     if (isset($service['public'])) {
         $definition->setPublic($service['public']);
     }
     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['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) {
             $definition->addMethodCall($call[0], $this->resolveServices($call[1]));
         }
     }
     if (isset($service['tags'])) {
         foreach ($service['tags'] as $tag) {
             $name = $tag['name'];
             unset($tag['name']);
             $definition->addTag($name, $tag);
         }
     }
     $this->container->setDefinition($id, $definition);
 }
Example #27
0
 /**
  * @param ContainerBuilder $container
  */
 private function declareKernelContainer(ContainerBuilder $container)
 {
     $containerDefinition = new Definition(Container::class);
     $containerDefinition->setFactory([new Reference(self::KERNEL_ID), 'getContainer']);
     $containerDefinition->setScope('scenario');
     $container->setDefinition(self::KERNEL_CONTAINER_ID, $containerDefinition);
 }
 /**
  * Loads the Doctrine configuration.
  *
  * @param array $config A configuration array
  * @param ContainerBuilder $container A ContainerBuilder instance
  */
 protected function loadDoctrine(array $config, ContainerBuilder $container)
 {
     foreach ($config['doctrine'] as $name => $cache) {
         $pool = new Reference(sprintf('memcache.%s', $cache['pool']));
         foreach ($cache['entity_managers'] as $em) {
             $def = new Definition($container->getParameter('memcache.doctrine_cache.class'));
             $def->setScope(ContainerInterface::SCOPE_CONTAINER);
             $def->addMethodCall('setMemcache', array($pool));
             if ($cache['prefix']) {
                 $def->addMethodCall('setPrefix', array($cache['prefix']));
             }
             $container->setDefinition(sprintf('doctrine.orm.%s_%s', $em, $name), $def);
         }
         foreach ($cache['document_managers'] as $dm) {
             $def = new Definition($container->getParameter('memcache.doctrine_cache.class'));
             $def->setScope(ContainerInterface::SCOPE_CONTAINER);
             $def->addMethodCall('setMemcache', array($pool));
             if ($cache['prefix']) {
                 $def->addMethodCall('setPrefix', array($cache['prefix']));
             }
             $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_%s', $dm, $name), $def);
         }
     }
 }
 /**
  * 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;
 }
Example #30
0
 /**
  * Register a persistent service handler.
  *
  * This will be loaded into ServiceManager at runtime.
  *
  * @param string     $id         Service ID.
  * @param Definition $definition Class definition.
  * @param boolean    $shared     Shared service or not.
  *
  * @return void
  */
 public static function registerPersistentService($id, Definition $definition, $shared = true)
 {
     $handlers = ModUtil::getVar(self::HANDLERS, 'definitions', array());
     if ($shared) {
         $definition->setScope(ContainerInterface::SCOPE_CONTAINER);
     } else {
         $definition->setScope(ContainerInterface::SCOPE_PROTOTYPE);
     }
     $handlers[$id] = array('definition' => $definition, 'shared' => $shared);
     ModUtil::setVar(self::HANDLERS, 'definitions', $handlers);
 }