Inheritance: extends Nette\Object
Ejemplo n.º 1
0
 function getAssets()
 {
     $serviceDefinition = new ServiceDefinition();
     $serviceDefinition->setClass('Mike227\\NAssetic\\AssetCollection');
     $serviceDefinition->setArguments(array(array('test6.js'), array(new TestFilter('#FILTER')), __DIR__ . '/../sources/'));
     return array('js1' => new GlobAsset(__DIR__ . '/../sources/test1.*'), 'js2' => array(new GlobAsset(__DIR__ . '/../sources/test2.*'), __DIR__ . '/../sources/test3.js', array(__DIR__ . '/../sources/test4.js', new GlobAsset(__DIR__ . '/../sources/test5.*')), 'serviceDef' => $serviceDefinition));
 }
 /**
  * @param string $class
  * @return ServiceDefinition
  */
 public function createServiceDefinition($class)
 {
     $definition = new ServiceDefinition();
     $definition->setClass($class);
     $definition->addTag('kdyby.subscriber');
     return $definition;
 }
Ejemplo n.º 3
0
 private function updateDefinition(DI\ServiceDefinition $def)
 {
     $class = $def->getClass();
     $setups = $def->getSetup();
     foreach (self::getInjectProperties($class) as $property => $type) {
         $builder = $this->getContainerBuilder();
         $inject = new DI\Statement('$' . $property, ['@\\' . ltrim($type, '\\')]);
         foreach ($setups as $key => $setup) {
             if ($setup->getEntity() === $inject->getEntity()) {
                 $inject = $setup;
                 $builder = NULL;
                 unset($setups[$key]);
             }
         }
         self::checkType($class, $property, $type, $builder);
         array_unshift($setups, $inject);
     }
     foreach (array_reverse(self::getInjectMethods($def->getClass())) as $method) {
         $inject = new DI\Statement($method);
         foreach ($setups as $key => $setup) {
             if ($setup->getEntity() === $inject->getEntity()) {
                 $inject = $setup;
                 unset($setups[$key]);
             }
         }
         array_unshift($setups, $inject);
     }
     $def->setSetup($setups);
 }
Ejemplo n.º 4
0
 /**
  * @param ServiceDefinition $def
  */
 private function registerToLatte(ServiceDefinition $def)
 {
     $def->addSetup('?->onCompile[] = function (Latte\\Engine $engine) { (new Texy\\Bridges\\Latte\\TexyMacro($engine, ?))->install(); }', ['@self', $this->prefix('@texy')])->addSetup('addFilter', ['texy', [$this->prefix('@texy'), 'process']]);
     if (method_exists('Latte\\Engine', 'addProvider')) {
         $def->addSetup('addProvider', ['texy', $this->prefix('@texy')]);
     } else {
         $def->addSetup('?->addFilter(\'getTexy\', function () { return ?;})', ['@self', $this->prefix('@texy')]);
     }
 }
 /**
  * @param \Nette\DI\ServiceDefinition $configuration
  * @param string $namespace
  * @param array $config
  */
 private function applyNamespaceConfiguration(ServiceDefinition $configuration, $namespace, array $config)
 {
     $builder = $this->getContainerBuilder();
     $safeNamespace = str_replace('-', '_', Strings::webalize($namespace));
     if ($namespace === Configuration::DEFAULT_NAMESPACE_NAME || $config['nameResolver']['class']) {
         if (!class_exists($config['nameResolver']['class'])) {
             throw new ConfigurationException('Name resolver ' . $config['nameResolver']['class'] . ' for namespace ' . $namespace . ' does not exists.');
         }
         $nameResolver = $builder->addDefinition($this->prefix('nameResolver.' . $safeNamespace))->setClass($config['nameResolver']['class']);
         $configuration->addSetup('setNameResolver', [$namespace, $nameResolver]);
     }
     if ($config['default'] !== null) {
         $configuration->addSetup('setDefaultImage', [$namespace, $config['default']]);
     }
     if ($config['resizeFlag'] !== null) {
         $resizeFlag = Helpers::parseResizeFlags($config['resizeFlag']);
         $configuration->addSetup('setResizeFlag', [$namespace, $resizeFlag]);
     }
     if ($config['quality'] !== null) {
         $configuration->addSetup('setQuality', [$namespace, $config['quality']]);
     }
     if (isset($config['presets']) && count($config['presets'])) {
         foreach ($config['presets'] as $name => $preset) {
             if ($preset instanceof Statement) {
                 $size = Helpers::parseSize($preset->getEntity());
                 $resizeFlags = Helpers::parseResizeFlags($preset->arguments);
             } else {
                 $size = Helpers::parseSize($preset);
                 $resizeFlags = null;
             }
             $configuration->addSetup('addPreset', [$namespace, $name, $size[0], $size[1], $resizeFlags]);
         }
     }
     if ($config['dummy']['enabled'] !== null) {
         $configuration->addSetup('enableDummy', [$namespace, $config['dummy']['enabled']]);
     }
     if ($config['dummy']['class'] !== null) {
         if (!class_exists($config['dummy']['class'])) {
             throw new ConfigurationException('Dummy provider class ' . $config['dummy']['class'] . ' for namespace ' . $namespace . ' does not exists.');
         }
         $provider = $builder->addDefinition($this->prefix('dummy.' . $safeNamespace))->setClass($config['dummy']['class']);
         $configuration->addSetup('setDummyProvider', [$namespace, $provider]);
     }
     if ($config['dummy']['category'] !== null) {
         $configuration->addSetup('setDummyCategory', [$namespace, $config['dummy']['category']]);
     }
     if ($config['dummy']['fallbackSize'] !== null) {
         $size = $config['dummy']['fallbackSize'];
         $configuration->addSetup('setDummyFallbackSize', [$namespace, $size[0], $size[1]]);
     }
     if ($config['dummy']['chance'] !== null) {
         $configuration->addSetup('setDummyDisplayChance', [$namespace, $config['dummy']['chance']]);
     }
 }
Ejemplo n.º 6
0
 /**
  * @param ServiceDefinition $service
  * @return array
  */
 private function parseSubscriberTags(ServiceDefinition $service)
 {
     $tags = $service->getTags();
     // Array contains EVENT_TAG_NAME key
     if (isset($tags[self::EVENT_TAG_NAME]) && is_array($tags[self::EVENT_TAG_NAME])) {
         return $tags[self::EVENT_TAG_NAME];
     }
     // Array contains other tags
     $etags = [];
     foreach ($tags as $tag => $value) {
         if (strncmp($tag, self::EVENT_TAG_PREFIX, strlen(self::EVENT_TAG_PREFIX)) === 0) {
             $etags[] = trim(substr($tag, strlen(self::EVENT_TAG_PREFIX)), '.:');
         }
     }
     return $etags;
 }
Ejemplo n.º 7
0
 public function process(ServiceDefinition $definition, $tags)
 {
     if (is_string($tags)) {
         $tags = array($tags);
     }
     $currentTags = $definition->getTags();
     foreach ((array) $tags as $tag => $attrs) {
         if (is_int($tag) && is_string($attrs)) {
             $tag = $attrs;
             $attrs = TRUE;
         }
         if (!isset($currentTags[$tag])) {
             $definition->addTag($tag, $attrs);
         }
     }
 }
Ejemplo n.º 8
0
 /**
  * @param ServiceDefinition
  * @return string|null
  */
 protected static function detectClass(ServiceDefinition $def)
 {
     if ($def->getClass()) {
         return $def->getClass();
     } elseif ($interface = $def->getImplement()) {
         $rc = Reflection\ClassType::from($interface);
         $method = $rc->hasMethod('create') ? 'create' : ($rc->hasMethod('get') ? 'get' : NULL);
         if ($method === NULL) {
             return NULL;
         }
         if (!($returnType = $rc->getMethod($method)->getAnnotation('return'))) {
             return NULL;
         }
         return Reflection\AnnotationsParser::expandClassName(preg_replace('#[|\\s].*#', '', $returnType), $rc);
     }
     return NULL;
 }
Ejemplo n.º 9
0
 private function configureEndpoints($config, ServiceDefinition $solarium)
 {
     if (empty($config['endpoints'])) {
         $endpoints = ['default' => array_intersect_key($config, $this->endpointDefaults)];
     } else {
         $endpoints = $config['endpoints'];
     }
     $solarium->addSetup('clearEndpoints');
     $default = TRUE;
     foreach ($endpoints as $name => $options) {
         $options += $this->endpointDefaults;
         $options += ['key' => $name];
         $solarium->addSetup('addEndpoint', [array_diff_key($options, ['default' => TRUE])]);
         if ($default === TRUE && $options['default'] === NULL || $options['default'] === TRUE) {
             $solarium->addSetup('setDefaultEndpoint', [$name]);
         }
     }
 }
Ejemplo n.º 10
0
    private function decorateServiceDefinitionWithNetteEvent(ServiceDefinition $serviceDefinition, NetteEventItemInterface $netteEvent)
    {
        $propertyStatement = new Statement('function () {
			$class = ?;
			$event = new $class(...func_get_args());
			?->dispatch(?, $event);
		}', [$netteEvent->getEventClass(), '@' . EventDispatcherInterface::class, $netteEvent->getEventName()]);
        $serviceDefinition->addSetup('$service->?[] = ?;', [$netteEvent->getProperty(), $propertyStatement]);
    }
Ejemplo n.º 11
0
 public function process(ServiceDefinition $definition, $methods)
 {
     $currentSetupMethods = array_map(function (Statement $statement) {
         return $statement->getEntity();
     }, $definition->getSetup());
     Validators::assert($methods, 'array');
     foreach ($methods as $setup) {
         $method = $setup;
         $args = array();
         if ($method instanceof Statement) {
             $args = $method->arguments;
             $method = $method->getEntity();
         }
         if (!in_array($method, $currentSetupMethods)) {
             $definition->addSetup($method, $args);
         }
     }
 }
 /**
  * Configures BowerLoader instance.
  * @param ServiceDefinition
  * @return void
  */
 private function setupService(ServiceDefinition $service)
 {
     // Bower components directory
     $service->addSetup('setBowerDir', array($this->getBowerDir()));
     // Setup autoloading
     $service->addSetup('setAutoload', array(isset($this->config['autoload']) ? $this->config['autoload'] : TRUE));
     // Setup package files prepending
     $service->addSetup('setPrepend', array(isset($this->config['prepend']) ? $this->config['prepend'] : TRUE));
     // Set cache storage
     $service->addSetup('setCacheStorage', array('@cacheStorage'));
 }
Ejemplo n.º 13
0
 private function registerExtension($extension)
 {
     $builder = $this->containerBuilder;
     // Statement
     if ($extension instanceof Statement) {
         $class = $extension->getEntity();
     } elseif (is_string($extension) && Strings::startsWith($extension, '@')) {
         $class = $builder->getDefinition($builder->getServiceName($extension))->getClass();
     } elseif (is_string($extension)) {
         $class = $extension;
         $extension = new Statement($extension);
     } else {
         throw new UnexpectedTypeException("Extension has to be string or Statement, given " . (is_object($extension) ? get_class($extension) : gettype($extension)) . ".");
     }
     if (!class_exists($class)) {
         throw new InvalidArgumentException("Form extension class {$class} not found.");
     }
     $reflection = new ClassType($class);
     $matched = FALSE;
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IBeforeCreateContainer')) {
         $this->beforeCreateContainerOpSet->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IContainerFactory')) {
         $this->containerFactories->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IAfterCreateContainer')) {
         $this->afterCreateContainerOpSet->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IBeforeCreateControl')) {
         $this->beforeCreateControlOpSet->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IControlFactory')) {
         $this->controlFactories->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Builder\\Components\\IAfterCreateControl')) {
         $this->afterCreateControlOpSet->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if ($reflection->implementsInterface('NForms\\Mapping\\IControlMapper')) {
         $this->controlMapperSet->addSetup('add', array($extension));
         $matched = TRUE;
     }
     if (!$matched) {
         throw new UnexpectedTypeException("Extension does not implement any of the expected interface. Given: '" . get_class($extension) . "'." . "Expected interfaces: IBeforeCreateContainer, IContainerFactory, IAfterCreateContainer, IBeforeCreateControl, IControlFactory, IAfterCreateControl, IControlMapper.");
     }
     return $this;
 }
Ejemplo n.º 14
0
 /**
  * Create definition statement for method
  * @param ServiceDefinition $definition
  * @param \Nette\Reflection\Method $method
  */
 protected function autowireParams(ServiceDefinition $definition, \Nette\Reflection\Method $method)
 {
     $parameters = $method->getParameters();
     foreach ($parameters as $num => $param) {
         /** @var \Nette\Reflection\Parameter $param */
         if ($targetClass = $param->getClass()) {
             if ($targetClass->getName() === 'Kdyby\\Doctrine\\EntityDao' && !isset($definition->factory->arguments[$num])) {
                 $annotations = $method->getAnnotations();
                 $entity = $this->getEntityName($param, $annotations);
                 if ($definition->factory === NULL) {
                     $definition->setFactory($definition->class);
                 }
                 $definition->factory->arguments[$num] = new \Nette\DI\Statement('@doctrine.dao', array($entity));
             }
         }
     }
 }
Ejemplo n.º 15
0
 /**
  * Parses single service from configuration file.
  * @return void
  */
 public static function parseService(ServiceDefinition $definition, $config)
 {
     if ($config === NULL) {
         return;
     } elseif (is_string($config) && interface_exists($config)) {
         $config = ['class' => NULL, 'implement' => $config];
     } elseif ($config instanceof Statement && is_string($config->getEntity()) && interface_exists($config->getEntity())) {
         $config = ['class' => NULL, 'implement' => $config->getEntity(), 'factory' => array_shift($config->arguments)];
     } elseif (!is_array($config) || isset($config[0], $config[1])) {
         $config = ['class' => NULL, 'create' => $config];
     }
     if (array_key_exists('factory', $config)) {
         $config['create'] = $config['factory'];
         unset($config['factory']);
     }
     $known = ['class', 'create', 'arguments', 'setup', 'autowired', 'dynamic', 'inject', 'parameters', 'implement', 'run', 'tags'];
     if ($error = array_diff(array_keys($config), $known)) {
         throw new Nette\InvalidStateException(sprintf("Unknown or deprecated key '%s' in definition of service.", implode("', '", $error)));
     }
     $config = Helpers::filterArguments($config);
     $arguments = [];
     if (array_key_exists('arguments', $config)) {
         Validators::assertField($config, 'arguments', 'array');
         $arguments = $config['arguments'];
         $definition->setArguments($arguments);
     }
     if (array_key_exists('class', $config) || array_key_exists('create', $config)) {
         $definition->setClass(NULL);
         $definition->setFactory(NULL);
     }
     if (array_key_exists('class', $config)) {
         Validators::assertField($config, 'class', 'string|Nette\\DI\\Statement|null');
         if (!$config['class'] instanceof Statement) {
             $definition->setClass($config['class']);
         }
         $definition->setFactory($config['class'], $arguments);
     }
     if (array_key_exists('create', $config)) {
         Validators::assertField($config, 'create', 'callable|Nette\\DI\\Statement|null');
         $definition->setFactory($config['create'], $arguments);
     }
     if (isset($config['setup'])) {
         if (Config\Helpers::takeParent($config['setup'])) {
             $definition->setSetup([]);
         }
         Validators::assertField($config, 'setup', 'list');
         foreach ($config['setup'] as $id => $setup) {
             Validators::assert($setup, 'callable|Nette\\DI\\Statement', "setup item #{$id}");
             $definition->addSetup($setup);
         }
     }
     if (isset($config['parameters'])) {
         Validators::assertField($config, 'parameters', 'array');
         $definition->setParameters($config['parameters']);
     }
     if (isset($config['implement'])) {
         Validators::assertField($config, 'implement', 'string');
         $definition->setImplement($config['implement']);
         $definition->setAutowired(TRUE);
     }
     if (isset($config['autowired'])) {
         Validators::assertField($config, 'autowired', 'bool');
         $definition->setAutowired($config['autowired']);
     }
     if (isset($config['dynamic'])) {
         Validators::assertField($config, 'dynamic', 'bool');
         $definition->setDynamic($config['dynamic']);
     }
     if (isset($config['inject'])) {
         Validators::assertField($config, 'inject', 'bool');
         $definition->addTag(Extensions\InjectExtension::TAG_INJECT, $config['inject']);
     }
     if (isset($config['run'])) {
         $config['tags']['run'] = (bool) $config['run'];
     }
     if (isset($config['tags'])) {
         Validators::assertField($config, 'tags', 'array');
         if (Config\Helpers::takeParent($config['tags'])) {
             $definition->setTags([]);
         }
         foreach ($config['tags'] as $tag => $attrs) {
             if (is_int($tag) && is_string($attrs)) {
                 $definition->addTag($attrs);
             } else {
                 $definition->addTag($tag, $attrs);
             }
         }
     }
 }
 /**
  * @param ServiceDefinition $definition
  * @param ClassType $class
  * @param array $methodMapping
  */
 public function injectToDefinition(ServiceDefinition $definition, ClassType $class, array $methodMapping)
 {
     $injectionProperties = $this->getInjectionByNameProperties($class, $methodMapping);
     // Copy original setup method to be able to place them after injection
     $setupSave = $definition->setup;
     $definition->setup = [];
     foreach ($injectionProperties as $injectionProperty => $injectedServiceName) {
         $definition->addSetup($methodMapping[self::IIS_INJECT_SERVICE_METHOD], [$injectionProperty, '@' . $injectedServiceName]);
     }
     $injectionProperties = $this->getInjectionByTypeProperties($class, $methodMapping);
     foreach ($injectionProperties as $injectionProperty => $injectedServiceType) {
         $definition->addSetup($methodMapping[self::IIS_INJECT_SERVICE_METHOD], [$injectionProperty, '@' . $injectedServiceType]);
     }
     $definition->addSetup($methodMapping[self::IIS_INJECT_PARAMETERS_METHOD], ['@container']);
     $definition->addSetup($methodMapping[self::IIS_INJECTION_COMPLETED_METHOD], []);
     // Add original setup statements after injection completed method call
     foreach ($setupSave as $originalSetup) {
         $definition->addSetup($originalSetup);
     }
 }
Ejemplo n.º 17
0
 public function process(ServiceDefinition $definition, $args)
 {
     if ($args === TRUE) {
         $definition->setInject(TRUE);
     }
 }
Ejemplo n.º 18
0
 /**
  * @param \Nette\DI\ServiceDefinition $def
  */
 private function registerMacros(ServiceDefinition $def)
 {
     $def->addSetup('Ark8\\Security\\Latte\\AuthorizatorMacros::install(?->getCompiler())', ['@self']);
 }
Ejemplo n.º 19
0
 /**
  * @param Nette\DI\ServiceDefinition $def
  * @return string[]
  */
 protected function getServiceBoundManagers(Nette\DI\ServiceDefinition $def)
 {
     $builder = $this->getContainerBuilder();
     $boundManagers = $def->getTag(self::TAG_BIND_TO_MANAGER);
     return is_array($boundManagers) ? $boundManagers : array($builder->parameters[$this->name]['orm']['defaultEntityManager']);
 }
 /**
  * @param string $class
  * @return ServiceDefinition
  */
 public function createServiceDefinition($class)
 {
     $definition = new ServiceDefinition();
     $definition->setClass($class);
     return $definition;
 }
 /**
  * Registers new entity in mapper
  * @param  ServiceDefinition
  * @param  array  [table => '', primaryKey => '', entity => '', repository => '']
  * @return void
  */
 protected function registerInMapper(ServiceDefinition $mapper, array $mapping = NULL)
 {
     if ($mapping === NULL) {
         return;
     }
     if (!isset($mapping['table']) || !is_string($mapping['table'])) {
         throw new \InvalidArgumentException('Table name missing or it\'s not string');
     }
     if (!isset($mapping['entity']) || !is_string($mapping['entity'])) {
         throw new \InvalidArgumentException('Entity class missing or it\'s not string');
     }
     $repositoryClass = isset($mapping['repository']) ? $mapping['repository'] : NULL;
     $primaryKey = isset($mapping['primaryKey']) ? $mapping['primaryKey'] : NULL;
     if (!is_string($repositoryClass) && !is_null($repositoryClass)) {
         throw new \InvalidArgumentException('Repository class must be string or NULL, ' . gettype($repositoryClass) . ' given');
     }
     if (!is_string($primaryKey) && !is_null($primaryKey)) {
         throw new \InvalidArgumentException('Primary key must be string or NULL, ' . gettype($primaryKey) . ' given');
     }
     $mapper->addSetup('register', array($mapping['table'], $mapping['entity'], $repositoryClass, $primaryKey));
 }
Ejemplo n.º 22
0
 /**
  * @param ServiceDefinition $filterManager
  * @param array $aliases
  * @throws \Mike227\NAssetic\Exceptions\UnexpectedValueException
  */
 private static function setupFilters(ServiceDefinition $filterManager, array $aliases)
 {
     foreach ($aliases as $name => $filter) {
         if (is_object($filter)) {
             $statement = $filter instanceof Statement ? $filter : new Statement($filter->value, $filter->attributes);
             $filterManager->addSetup('set', array($name, $statement));
         } else {
             if (class_exists($filter)) {
                 $filterManager->addSetup('set', array($name, new Statement($filter)));
             } else {
                 if (Strings::startsWith($filter, '@')) {
                     $filterManager->addSetup('set', array($name, $filter));
                 } else {
                     if (is_string($filter)) {
                         throw new UnexpectedValueException("Filter \"{$name}: {$filter}\" class not found.");
                     } else {
                         throw new UnexpectedValueException("Invalid filter definition \"{$name}: {$filter}\".");
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 23
0
 /**
  * @param $interface
  * @return mixed|ServiceDefinition
  */
 public function createFactoryDefinition($interface)
 {
     $definition = new ServiceDefinition();
     $definition->setImplement($interface);
     return $definition;
 }
Ejemplo n.º 24
0
 /**
  * @param string $class
  * @return ServiceDefinition
  * @throws \Nette\InvalidArgumentException
  */
 public function createServiceDefinition($class)
 {
     // Validate annotation attributes
     if (count($this->parameters) === 0) {
         throw new InvalidArgumentException("Annotation  @" . get_class() . " of class {$class} expects one or more parameters.");
     }
     // Create service definition
     $definition = new ServiceDefinition();
     $definition->setClass($class);
     $definition->setInject(TRUE);
     // Parameters for service's constructor
     $serviceParameters = array();
     // One parameter - @DaoManager("Name\Space\EntityClass")
     if (count($this->parameters) === 1 && isset($this->parameters[0])) {
         $entityName = $this->parameters[0];
         $daoParameters = $this->findConstructorDaoParameters($class);
         if (count($daoParameters) === 0) {
             throw new InvalidArgumentException("Annotation  @" . get_class() . ": {$class}::__construct() does not contain attribute with type hint " . self::DAO_CLASS);
         } else {
             if (count($daoParameters) > 1) {
                 throw new InvalidArgumentException("Annotation  @" . get_class() . ": {$class}::__construct() contains multiple attributes with type hint " . self::DAO_CLASS);
             }
         }
         $serviceParameters = array($daoParameters[0] => $this->createDaoStatement($entityName));
     } else {
         foreach ($this->parameters as $attributeName => $entityName) {
             $serviceParameters[$attributeName] = $this->createDaoStatement($entityName);
         }
     }
     $definition->setArguments($serviceParameters);
     return $definition;
 }
Ejemplo n.º 25
0
 protected function bindEventProperties(Nette\DI\ServiceDefinition $def, Nette\Reflection\ClassType $class)
 {
     foreach ($class->getProperties(Nette\Reflection\Property::IS_PUBLIC) as $property) {
         if (!preg_match('#^on[A-Z]#', $name = $property->getName())) {
             continue;
         }
         if ($property->hasAnnotation('persistent') || $property->hasAnnotation('inject')) {
             // definitely not an event
             continue;
         }
         $def->addSetup('$' . $name, array(new Nette\DI\Statement($this->prefix('@manager') . '::createEvent', array(array($class->getName(), $name), new Code\PhpLiteral('$service->' . $name)))));
     }
 }
Ejemplo n.º 26
0
 /**
  * @param \Nette\DI\ServiceDefinition $metadataDriver
  * @param string $namespace
  * @param string|object $driver
  * @param string $prefix
  * @throws \Nette\Utils\AssertionException
  * @return string
  */
 protected function processMetadataDriver(Nette\DI\ServiceDefinition $metadataDriver, $namespace, $driver, $prefix)
 {
     if (!is_string($namespace) || !Strings::match($namespace, '#^' . self::PHP_NAMESPACE . '\\z#')) {
         throw new Nette\Utils\AssertionException("The metadata namespace expects to be valid namespace, {$namespace} given.");
     }
     $namespace = ltrim($namespace, '\\');
     if (is_string($driver) || is_array($driver)) {
         $paths = is_array($driver) ? $driver : array($driver);
         foreach ($paths as $path) {
             if (($pos = strrpos($path, '*')) !== FALSE) {
                 $path = substr($path, 0, $pos);
             }
             if (!file_exists($path)) {
                 throw new Nette\Utils\AssertionException("The metadata path expects to be an existing directory, {$path} given.");
             }
         }
         $driver = new Statement(self::ANNOTATION_DRIVER, is_array($paths) ? $paths : array($paths));
     }
     $impl = $driver instanceof \stdClass ? $driver->value : ($driver instanceof Statement ? $driver->entity : (string) $driver);
     list($driver) = CacheHelpers::filterArgs($driver);
     /** @var Statement $driver */
     if (isset($this->metadataDriverClasses[$impl])) {
         $driver->entity = $this->metadataDriverClasses[$impl];
     }
     if (is_string($driver->entity) && substr($driver->entity, 0, 1) === '@') {
         $metadataDriver->addSetup('addDriver', array($driver->entity, $namespace));
         return $driver->entity;
     }
     if ($impl === self::ANNOTATION_DRIVER) {
         $driver->arguments = array(Nette\Utils\Arrays::flatten($driver->arguments), 2 => $this->prefix('@cache.' . $prefix . '.metadata'));
     }
     $serviceName = $this->prefix($prefix . '.driver.' . str_replace('\\', '_', $namespace) . '.' . $impl . 'Impl');
     $this->getContainerBuilder()->addDefinition($serviceName)->setClass('Doctrine\\Common\\Persistence\\Mapping\\Driver\\MappingDriver')->setFactory($driver->entity, $driver->arguments)->setAutowired(FALSE)->setInject(FALSE);
     $metadataDriver->addSetup('addDriver', array('@' . $serviceName, $namespace));
     return '@' . $serviceName;
 }
Ejemplo n.º 27
0
 private function resolveImplement(ServiceDefinition $def, $name)
 {
     $interface = $def->getImplement();
     if (!interface_exists($interface)) {
         throw new ServiceCreationException("Interface {$interface} used in service '{$name}' not found.");
     }
     self::checkCase($interface);
     $rc = new ReflectionClass($interface);
     $method = $rc->hasMethod('create') ? $rc->getMethod('create') : ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL);
     if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) {
         throw new ServiceCreationException("Interface {$interface} used in service '{$name}' must have just one non-static method create() or get().");
     }
     $def->setImplementType($methodName = $rc->hasMethod('create') ? 'create' : 'get');
     if (!$def->getClass() && !$def->getEntity()) {
         $returnType = PhpReflection::getReturnType($method);
         if (!$returnType) {
             throw new ServiceCreationException("Method {$interface}::{$methodName}() used in service '{$name}' has no @return annotation.");
         } elseif (!class_exists($returnType)) {
             throw new ServiceCreationException("Check a @return annotation of the {$interface}::{$methodName}() method used in service '{$name}', class '{$returnType}' cannot be found.");
         }
         $def->setClass($returnType);
     }
     if ($methodName === 'get') {
         if ($method->getParameters()) {
             throw new ServiceCreationException("Method {$interface}::get() used in service '{$name}' must have no arguments.");
         }
         if (!$def->getEntity()) {
             $def->setFactory('@\\' . ltrim($def->getClass(), '\\'));
         } elseif (!$this->getServiceName($def->getFactory()->getEntity())) {
             throw new ServiceCreationException("Invalid factory in service '{$name}' definition.");
         }
     }
     if (!$def->parameters) {
         $ctorParams = [];
         if (!$def->getEntity()) {
             $def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : []);
         }
         if (($class = $this->resolveEntityClass($def->getFactory(), [$name => 1])) && ($ctor = (new ReflectionClass($class))->getConstructor())) {
             foreach ($ctor->getParameters() as $param) {
                 $ctorParams[$param->getName()] = $param;
             }
         }
         foreach ($method->getParameters() as $param) {
             $hint = PhpReflection::getParameterType($param);
             if (isset($ctorParams[$param->getName()])) {
                 $arg = $ctorParams[$param->getName()];
                 if ($hint !== PhpReflection::getParameterType($arg)) {
                     throw new ServiceCreationException("Type hint for \${$param->getName()} in {$interface}::{$methodName}() doesn't match type hint in {$class} constructor.");
                 }
                 $def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName());
             }
             $paramDef = $hint . ' ' . $param->getName();
             if ($param->isOptional()) {
                 $def->parameters[$paramDef] = $param->getDefaultValue();
             } else {
                 $def->parameters[] = $paramDef;
             }
         }
     }
 }
Ejemplo n.º 28
0
 /**
  * Parses single service definition from configuration.
  * @return void
  */
 public static function loadDefinition(ServiceDefinition $definition, $config)
 {
     if ($config === NULL) {
         return;
     } elseif (is_string($config) && interface_exists($config)) {
         $config = ['class' => NULL, 'implement' => $config];
     } elseif ($config instanceof Statement && is_string($config->getEntity()) && interface_exists($config->getEntity())) {
         $config = ['class' => NULL, 'implement' => $config->getEntity(), 'factory' => array_shift($config->arguments)];
     } elseif (!is_array($config) || isset($config[0], $config[1])) {
         $config = ['class' => NULL, 'factory' => $config];
     }
     if (array_key_exists('create', $config)) {
         trigger_error("Key 'create' is deprecated, use 'factory' or 'class' in configuration.", E_USER_DEPRECATED);
         $config['factory'] = $config['create'];
         unset($config['create']);
     }
     $known = ['class', 'factory', 'arguments', 'setup', 'autowired', 'dynamic', 'inject', 'parameters', 'implement', 'run', 'tags'];
     if ($error = array_diff(array_keys($config), $known)) {
         $hints = array_filter(array_map(function ($error) use($known) {
             return Nette\Utils\ObjectMixin::getSuggestion($known, $error);
         }, $error));
         $hint = $hints ? ", did you mean '" . implode("', '", $hints) . "'?" : '.';
         throw new Nette\InvalidStateException(sprintf("Unknown key '%s' in definition of service{$hint}", implode("', '", $error)));
     }
     $config = Helpers::filterArguments($config);
     if (array_key_exists('class', $config) || array_key_exists('factory', $config)) {
         $definition->setClass(NULL);
         $definition->setFactory(NULL);
     }
     if (array_key_exists('class', $config)) {
         Validators::assertField($config, 'class', 'string|Nette\\DI\\Statement|null');
         if (!$config['class'] instanceof Statement) {
             $definition->setClass($config['class']);
         }
         $definition->setFactory($config['class']);
     }
     if (array_key_exists('factory', $config)) {
         Validators::assertField($config, 'factory', 'callable|Nette\\DI\\Statement|null');
         $definition->setFactory($config['factory']);
     }
     if (array_key_exists('arguments', $config)) {
         Validators::assertField($config, 'arguments', 'array');
         $arguments = $config['arguments'];
         if (!Config\Helpers::takeParent($arguments) && !Nette\Utils\Arrays::isList($arguments) && $definition->getFactory()) {
             $arguments += $definition->getFactory()->arguments;
         }
         $definition->setArguments($arguments);
     }
     if (isset($config['setup'])) {
         if (Config\Helpers::takeParent($config['setup'])) {
             $definition->setSetup([]);
         }
         Validators::assertField($config, 'setup', 'list');
         foreach ($config['setup'] as $id => $setup) {
             Validators::assert($setup, 'callable|Nette\\DI\\Statement|array:1', "setup item #{$id}");
             if (is_array($setup)) {
                 $setup = new Statement(key($setup), array_values($setup));
             }
             $definition->addSetup($setup);
         }
     }
     if (isset($config['parameters'])) {
         Validators::assertField($config, 'parameters', 'array');
         $definition->setParameters($config['parameters']);
     }
     if (isset($config['implement'])) {
         Validators::assertField($config, 'implement', 'string');
         $definition->setImplement($config['implement']);
         $definition->setAutowired(TRUE);
     }
     if (isset($config['autowired'])) {
         Validators::assertField($config, 'autowired', 'bool|string|array');
         $definition->setAutowired($config['autowired']);
     }
     if (isset($config['dynamic'])) {
         Validators::assertField($config, 'dynamic', 'bool');
         $definition->setDynamic($config['dynamic']);
     }
     if (isset($config['inject'])) {
         Validators::assertField($config, 'inject', 'bool');
         $definition->addTag(Extensions\InjectExtension::TAG_INJECT, $config['inject']);
     }
     if (isset($config['run'])) {
         trigger_error("Option 'run' is deprecated, use 'run' as tag.", E_USER_DEPRECATED);
         $config['tags']['run'] = (bool) $config['run'];
     }
     if (isset($config['tags'])) {
         Validators::assertField($config, 'tags', 'array');
         if (Config\Helpers::takeParent($config['tags'])) {
             $definition->setTags([]);
         }
         foreach ($config['tags'] as $tag => $attrs) {
             if (is_int($tag) && is_string($attrs)) {
                 $definition->addTag($attrs);
             } else {
                 $definition->addTag($tag, $attrs);
             }
         }
     }
 }
Ejemplo n.º 29
0
 /**
  * Parses single service from configuration file.
  * @return void
  */
 public static function parseService(Nette\DI\ServiceDefinition $definition, $config, $shared = TRUE)
 {
     if ($config === NULL) {
         return;
     } elseif (!is_array($config)) {
         $config = array('class' => NULL, 'factory' => $config);
     }
     $known = $shared ? array('class', 'factory', 'arguments', 'setup', 'autowired', 'run', 'tags') : array('class', 'factory', 'arguments', 'setup', 'autowired', 'tags', 'internal', 'parameters');
     if ($error = array_diff(array_keys($config), $known)) {
         throw new Nette\InvalidStateException("Unknown key '" . implode("', '", $error) . "' in definition of service.");
     }
     $arguments = array();
     if (array_key_exists('arguments', $config)) {
         Validators::assertField($config, 'arguments', 'array');
         $arguments = self::filterArguments($config['arguments']);
         $definition->setArguments($arguments);
     }
     if (array_key_exists('class', $config) || array_key_exists('factory', $config)) {
         $definition->class = NULL;
         $definition->factory = NULL;
     }
     if (array_key_exists('class', $config)) {
         Validators::assertField($config, 'class', 'string|stdClass|null');
         if ($config['class'] instanceof \stdClass) {
             $definition->setClass($config['class']->value, self::filterArguments($config['class']->attributes));
         } else {
             $definition->setClass($config['class'], $arguments);
         }
     }
     if (array_key_exists('factory', $config)) {
         Validators::assertField($config, 'factory', 'callable|stdClass|null');
         if ($config['factory'] instanceof \stdClass) {
             $definition->setFactory($config['factory']->value, self::filterArguments($config['factory']->attributes));
         } else {
             $definition->setFactory($config['factory'], $arguments);
         }
     }
     if (isset($config['setup'])) {
         if (Helpers::takeParent($config['setup'])) {
             $definition->setup = array();
         }
         Validators::assertField($config, 'setup', 'list');
         foreach ($config['setup'] as $id => $setup) {
             Validators::assert($setup, 'callable|stdClass', "setup item #{$id}");
             if ($setup instanceof \stdClass) {
                 Validators::assert($setup->value, 'callable', "setup item #{$id}");
                 $definition->addSetup($setup->value, self::filterArguments($setup->attributes));
             } else {
                 $definition->addSetup($setup);
             }
         }
     }
     $definition->setShared($shared);
     if (isset($config['parameters'])) {
         Validators::assertField($config, 'parameters', 'array');
         $definition->setParameters($config['parameters']);
     }
     if (isset($config['autowired'])) {
         Validators::assertField($config, 'autowired', 'bool');
         $definition->setAutowired($config['autowired']);
     }
     if (isset($config['internal'])) {
         Validators::assertField($config, 'internal', 'bool');
         $definition->setInternal($config['internal']);
     }
     if (isset($config['run'])) {
         $config['tags']['run'] = (bool) $config['run'];
     }
     if (isset($config['tags'])) {
         Validators::assertField($config, 'tags', 'array');
         if (Helpers::takeParent($config['tags'])) {
             $definition->tags = array();
         }
         foreach ($config['tags'] as $tag => $attrs) {
             if (is_int($tag) && is_string($attrs)) {
                 $definition->addTag($attrs);
             } else {
                 $definition->addTag($tag, $attrs);
             }
         }
     }
 }
Ejemplo n.º 30
0
	/**
	 * Parses single service from configuration file.
	 * @return void
	 */
	public static function parseService(ServiceDefinition $definition, $config)
	{
		if ($config === NULL) {
			return;

		} elseif (is_string($config) && interface_exists($config)) {
			$config = array('class' => NULL, 'implement' => $config);

		} elseif ($config instanceof \stdClass && interface_exists($config->value)) {
			$config = array('class' => NULL, 'implement' => $config->value, 'factory' => array_shift($config->attributes));

		} elseif (!is_array($config)) {
			$config = array('class' => NULL, 'create' => $config);
		}

		if (array_key_exists('factory', $config)) {
			$config['create'] = $config['factory'];
			unset($config['factory']);
		};

		$known = array('class', 'create', 'arguments', 'setup', 'autowired', 'inject', 'parameters', 'implement', 'run', 'tags');
		if ($error = array_diff(array_keys($config), $known)) {
			throw new Nette\InvalidStateException(sprintf("Unknown or deprecated key '%s' in definition of service.", implode("', '", $error)));
		}

		$arguments = array();
		if (array_key_exists('arguments', $config)) {
			Validators::assertField($config, 'arguments', 'array');
			$arguments = self::filterArguments($config['arguments']);
			$definition->setArguments($arguments);
		}

		if (array_key_exists('class', $config) || array_key_exists('create', $config)) {
			$definition->class = NULL;
			$definition->factory = NULL;
		}

		if (array_key_exists('class', $config)) {
			Validators::assertField($config, 'class', 'string|stdClass|null');
			if ($config['class'] instanceof \stdClass) {
				$definition->setClass($config['class']->value, self::filterArguments($config['class']->attributes));
			} else {
				$definition->setClass($config['class'], $arguments);
			}
		}

		if (array_key_exists('create', $config)) {
			Validators::assertField($config, 'create', 'callable|stdClass|null');
			if ($config['create'] instanceof \stdClass) {
				$definition->setFactory($config['create']->value, self::filterArguments($config['create']->attributes));
			} else {
				$definition->setFactory($config['create'], $arguments);
			}
		}

		if (isset($config['setup'])) {
			if (Config\Helpers::takeParent($config['setup'])) {
				$definition->setup = array();
			}
			Validators::assertField($config, 'setup', 'list');
			foreach ($config['setup'] as $id => $setup) {
				Validators::assert($setup, 'callable|stdClass', "setup item #$id");
				if ($setup instanceof \stdClass) {
					Validators::assert($setup->value, 'callable', "setup item #$id");
					$definition->addSetup($setup->value, self::filterArguments($setup->attributes));
				} else {
					$definition->addSetup($setup);
				}
			}
		}

		if (isset($config['parameters'])) {
			Validators::assertField($config, 'parameters', 'array');
			$definition->setParameters($config['parameters']);
		}

		if (isset($config['implement'])) {
			Validators::assertField($config, 'implement', 'string');
			$definition->setImplement($config['implement']);
			$definition->setAutowired(TRUE);
		}

		if (isset($config['autowired'])) {
			Validators::assertField($config, 'autowired', 'bool');
			$definition->setAutowired($config['autowired']);
		}

		if (isset($config['inject'])) {
			Validators::assertField($config, 'inject', 'bool');
			$definition->setInject($config['inject']);
		}

		if (isset($config['run'])) {
			$config['tags']['run'] = (bool) $config['run'];
		}

		if (isset($config['tags'])) {
			Validators::assertField($config, 'tags', 'array');
			if (Config\Helpers::takeParent($config['tags'])) {
				$definition->tags = array();
			}
			foreach ($config['tags'] as $tag => $attrs) {
				if (is_int($tag) && is_string($attrs)) {
					$definition->addTag($attrs);
				} else {
					$definition->addTag($tag, $attrs);
				}
			}
		}
	}