/** * @param Definition $definition */ protected function processDefinition(Definition $definition) { if ($definition->isSynthetic()) { return; } if ($definition->getFactoryService() || $definition->getFactoryClass()) { return; } if ($file = $definition->getFile()) { require_once $file; } if (!class_exists($definition->getClass())) { return; } $class = new \ReflectionClass($definition->getClass()); if (!$class->implementsInterface(static::INTERFACE_CLASS)) { return; } $metadata = $this->getMetadataFactory()->getMetadataForClass($definition->getClass()); if (!$metadata instanceof ClassMetadata) { return; } $namespace = $metadata->getNamespace() ?: static::ROOT_NAMESPACE; $serviceName = static::PROVIDER_PREFIX . substr(sha1($namespace), 0, 10); if (!$this->container->hasDefinition($serviceName)) { $cacher = new Definition('Werkint\\Bundle\\CacheBundle\\Service\\CacheProvider', [$this->container->getParameter('kernel.cache_dir') . '/werkint_cache']); $cacher->setPublic(true); $cacher->addMethodCall('setNamespace', [$namespace]); $this->container->setDefinition($serviceName, $cacher); } $definition->addMethodCall('setCacheProvider', [new Reference($serviceName)]); }
/** * Adds a service * * @param string $id * @param Definition $definition * * @return string */ private function addService($id, $definition) { $code = " {$id}:\n"; if ($definition->getClass()) { $code .= sprintf(" class: %s\n", $definition->getClass()); } $tagsCode = ''; foreach ($definition->getTags() as $name => $tags) { foreach ($tags as $attributes) { $att = array(); foreach ($attributes as $key => $value) { $att[] = sprintf('%s: %s', $this->dumper->dump($key), $this->dumper->dump($value)); } $att = $att ? ', ' . implode(' ', $att) : ''; $tagsCode .= sprintf(" - { name: %s%s }\n", $this->dumper->dump($name), $att); } } if ($tagsCode) { $code .= " tags:\n" . $tagsCode; } if ($definition->getFile()) { $code .= sprintf(" file: %s\n", $definition->getFile()); } if ($definition->isSynthetic()) { $code .= sprintf(" synthetic: true\n"); } if ($definition->isSynchronized()) { $code .= sprintf(" synchronized: true\n"); } if ($definition->getFactoryMethod()) { $code .= sprintf(" factory_method: %s\n", $definition->getFactoryMethod()); } if ($definition->getFactoryService()) { $code .= sprintf(" factory_service: %s\n", $definition->getFactoryService()); } if ($definition->getArguments()) { $code .= sprintf(" arguments: %s\n", $this->dumper->dump($this->dumpValue($definition->getArguments()), 0)); } if ($definition->getProperties()) { $code .= sprintf(" properties: %s\n", $this->dumper->dump($this->dumpValue($definition->getProperties()), 0)); } if ($definition->getMethodCalls()) { $code .= sprintf(" calls:\n%s\n", $this->dumper->dump($this->dumpValue($definition->getMethodCalls()), 1, 12)); } if (ContainerInterface::SCOPE_CONTAINER !== ($scope = $definition->getScope())) { $code .= sprintf(" scope: %s\n", $scope); } if ($callable = $definition->getConfigurator()) { if (is_array($callable)) { if ($callable[0] instanceof Reference) { $callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]); } else { $callable = array($callable[0], $callable[1]); } } $code .= sprintf(" configurator: %s\n", $this->dumper->dump($callable, 0)); } return $code; }
/** * Adds a service. * * @param string $id * @param Definition $definition * * @return string */ private function addService($id, $definition) { $code = " {$id}:\n"; if ($definition->getClass()) { $code .= sprintf(" class: %s\n", $definition->getClass()); } if (!$definition->isPublic()) { $code .= " public: false\n"; } $tagsCode = ''; foreach ($definition->getTags() as $name => $tags) { foreach ($tags as $attributes) { $att = array(); foreach ($attributes as $key => $value) { $att[] = sprintf('%s: %s', $this->dumper->dump($key), $this->dumper->dump($value)); } $att = $att ? ', ' . implode(', ', $att) : ''; $tagsCode .= sprintf(" - { name: %s%s }\n", $this->dumper->dump($name), $att); } } if ($tagsCode) { $code .= " tags:\n" . $tagsCode; } if ($definition->getFile()) { $code .= sprintf(" file: %s\n", $definition->getFile()); } if ($definition->isSynthetic()) { $code .= sprintf(" synthetic: true\n"); } if ($definition->isLazy()) { $code .= sprintf(" lazy: true\n"); } if ($definition->getArguments()) { $code .= sprintf(" arguments: %s\n", $this->dumper->dump($this->dumpValue($definition->getArguments()), 0)); } if ($definition->getProperties()) { $code .= sprintf(" properties: %s\n", $this->dumper->dump($this->dumpValue($definition->getProperties()), 0)); } if ($definition->getMethodCalls()) { $code .= sprintf(" calls:\n%s\n", $this->dumper->dump($this->dumpValue($definition->getMethodCalls()), 1, 12)); } if (ContainerInterface::SCOPE_CONTAINER !== ($scope = $definition->getScope())) { $code .= sprintf(" scope: %s\n", $scope); } if (null !== ($decorated = $definition->getDecoratedService())) { list($decorated, $renamedId) = $decorated; $code .= sprintf(" decorates: %s\n", $decorated); if (null !== $renamedId) { $code .= sprintf(" decoration_inner_name: %s\n", $renamedId); } } if ($callable = $definition->getFactory()) { $code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0)); } if ($callable = $definition->getConfigurator()) { $code .= sprintf(" configurator: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0)); } return $code; }
private function assertProvider(ContainerBuilder $container, Definition $definition) { $class = $container->getParameterBag()->resolveValue($definition->getClass()); $refClass = new \ReflectionClass($class); if (!$refClass->implementsInterface('Hateoas\\Configuration\\Provider\\Resolver\\RelationProviderResolverInterface')) { throw new InvalidArgumentException(sprintf('Relation provider "%s" does not implement the ReleationProviderResolver interface', $definition->getClass())); } }
public function validate(Definition $definition) : bool { if (!$definition->isPublic() || $definition->isAbstract()) { return false; } if (null === $definition->getClass() || !class_exists($definition->getClass())) { return false; } return true; }
/** * {@inheritdoc} */ public function getProxyCode(Definition $definition) { // Maybe the same class is used in different services, which are both marked // as lazy (just think about 2 database connections). // In those cases we should not generate proxy code the second time. if (!isset($this->buildClasses[$definition->getClass()])) { $this->buildClasses[$definition->getClass()] = TRUE; return $this->builder->build($definition->getClass()); } else { return ''; } }
/** * @covers Symfony\Component\DependencyInjection\Definition::__construct */ public function testConstructor() { $def = new Definition('stdClass'); $this->assertEquals('stdClass', $def->getClass(), '__construct() takes the class name as its first argument'); $def = new Definition('stdClass', array('foo')); $this->assertEquals(array('foo'), $def->getArguments(), '__construct() takes an optional array of arguments as its second argument'); }
private function watchServiceClassForChanges(Definition $definition, ContainerBuilder $containerBuilder) { $classReflection = new ReflectionClass($definition->getClass()); do { $containerBuilder->addResource(new FileResource($classReflection->getFileName())); } while ($classReflection = $classReflection->getParentClass()); }
/** * @param Definition $definition * @param string $class * @param string $repository */ private function assertDefinition(Definition $definition, $class, $repository) { $this->assertSame($definition->getClass(), $repository); $factory = $definition->getFactory(); $this->assertSame($factory[1], "getRepository"); $this->assertSame($definition->getArgument(0), $class); }
/** * @param Definition $emitterService * @param string $expectedInterface * * @throws LogicException */ private function guardAgainstInvalidClass(Definition $emitterService, $expectedInterface) { $definedClass = $emitterService->getClass(); $reflection = new ReflectionClass($definedClass); if ($reflection->implementsInterface($expectedInterface) === false) { throw new LogicException(sprintf('Invalid class type registered, expected %s, got %s.', $expectedInterface, $definedClass)); } }
/** * @param Definition $definition * @param stdClass $dependables */ private function addDefinitionArguments(Definition $definition, stdClass $dependables) { $class = $definition->getClass(); $dependables->references[$class] = array(); for ($arg = 0; $arg < count($definition->getArguments()); $arg++) { $dependables->references[$class][$arg] = $definition->getArgument($arg); } }
/** * @param ContainerBuilder $container * @param Definition $definition * @param string $id */ private function assertClassImplementInterface(ContainerBuilder $container, Definition $definition, $id) { $class = $this->resolveClassName($container, $definition->getClass()); $refClass = new ReflectionClass($class); if (!$refClass->implementsInterface($this->interfaceToImplement)) { throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $this->interfaceToImplement)); } }
/** * {@inheritdoc} */ public function instantiateProxy(ContainerInterface $container, Definition $definition, $id, $realInstantiator) { return $this->factory->createProxy($definition->getClass(), function (&$wrappedInstance, LazyLoadingInterface $proxy) use($realInstantiator) { $wrappedInstance = call_user_func($realInstantiator); $proxy->setProxyInitializer(null); return true; }); }
/** * @param Definition $definition * @param Reference $container */ private function injectContainer(Definition $definition, Reference $container) { $class = $definition->getClass(); if (empty($class) || !is_subclass_of($class, ContainerAwareInterface::class)) { return; } $definition->addMethodCall('setContainer', [$container]); }
/** * Is the definition an interface template? * * @access private * @return boolean */ private function isDefinitionATemplate(Definition $definition) { try { $reflect = new \ReflectionClass($definition->getClass()); } catch (\ReflectionException $e) { return false; } return $reflect->isInterface(); }
/** * @param Definition $formDefinition * * @return string Form name */ private function getFormName(Definition $formDefinition) { $tags = $formDefinition->getTag('form.type'); $formName = isset($tags[0]['alias']) ? $tags[0]['alias'] : null; if (null === $formName) { throw new \InvalidArgumentException(sprintf('Definition "%s" tagged by "%s" should also be tagged by "%s" with attribute "%s"', $formDefinition->getClass(), 'sylius.metadata.dynamic_form', 'form.type', 'alias')); } return $formName; }
protected function assertDefinitionContainsMethodCall(Definition $serviceDefinition, $expectedMethod, $expectedFirstArgument) { foreach ($serviceDefinition->getMethodCalls() as $methodCall) { if ($expectedMethod == $methodCall[0] && $expectedFirstArgument == $methodCall[1][0]) { return; } } $this->fail(sprintf('Failed assert that service (Class: %s) has method %s been called with first argument %s', $serviceDefinition->getClass(), $expectedMethod, $expectedFirstArgument)); }
/** * Gets class of the given definition. * * @param ContainerBuilder $container * @param Definition $definition * * @return string|null */ private function getClass(ContainerBuilder $container, Definition $definition) { if ($class = $definition->getClass()) { return $class; } if ($definition instanceof DefinitionDecorator) { return $container->getDefinition($definition->getParent())->getClass(); } }
/** * @param Definition $definition * @param string $class * @param string $repository * @param bool $filterType */ private function assertDefinition(Definition $definition, $class, $repository, $filterType) { $this->assertSame($definition->getClass(), $repository); $factory = $definition->getFactory(); $this->assertSame($factory[1], "getRepository"); $this->assertSame($definition->getArgument(0), $class); if ($filterType) { $this->assertTrue($definition->hasMethodCall('setFilterTypeManager')); } }
/** * @param Definition $subscriberDef * * @return array */ private function getSubscribedPaths(Definition $subscriberDef) { $class = $subscriberDef->getClass(); if (!in_array('Iphp\\RedirectNotFoundBundle\\Observer\\NotFoundSubscriberInterface', class_implements($class))) { throw new InvalidArgumentException(sprintf('Class "%s" must implements interface "%s"', $class, 'Iphp\\RedirectNotFoundBundle\\Observer\\NotFoundSubscriberInterface')); } $paths = forward_static_call([$class, 'getPaths']); if (!is_array($paths)) { throw new RuntimeException(sprintf('Can\'t retrieve paths from subscriber class "%s".', $class)); } return $paths; }
private function extractEventNames(Definition $handlerDefinition) { $class = new \ReflectionClass($handlerDefinition->getClass()); $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); $events = []; foreach ($methods as $method) { if ($method->isStatic() || strpos($method->getName(), 'handle') !== 0) { continue; } $events[] = substr($method->getName(), 6); } return $events; }
/** * @return bool */ private function canBeAdded(Definition $definition) { if ($definition->isAbstract()) { return false; } if (!$definition->isPublic()) { return false; } if (!$definition->getClass()) { return false; } return true; }
private function validateClass(Definition $definition) { $class = $definition->getClass(); if ($class) { $class = $this->containerBuilder->getParameterBag()->resolveValue($class); // TODO only services created using a factory can have an interface if (!class_exists($class) && !interface_exists($class)) { throw new ClassNotFoundException($class); } } elseif ($this->shouldDefinitionHaveAClass($definition)) { throw new DefinitionHasNoClassException(); } }
protected function injectKnownDependencies(Definition $definition) { $class = $definition->getClass(); $r = new \ReflectionClass($class); if ($r->implementsInterface('RP\\CommonBundle\\CommandBus\\CommandHandler\\EntityManagerAwareInterface')) { $definition->addMethodCall('setEntityManager', [new Reference('doctrine.orm.default_entity_manager')]); } if ($r->implementsInterface('RP\\CommonBundle\\CommandBus\\CommandHandler\\CommandBusAwareInterface')) { $definition->addMethodCall('setCommandBus', [new Reference('rp.command_bus')]); } if ($r->implementsInterface('RP\\CommonBundle\\CommandBus\\CommandHandler\\EventDispatcherAwareInterface')) { $definition->addMethodCall('setEventDispatcher', [new Reference('event_dispatcher')]); } }
private function shouldClassDefinitionBeAutowired(Definition $definition) : bool { $classReflection = new ReflectionClass($definition->getClass()); if (!$classReflection->hasMethod('__construct') || !$this->hasMethodArguments($classReflection->getConstructor())) { return false; } $constructorReflection = $classReflection->getConstructor(); if ($this->areAllMethodArgumentsRequired($definition, $constructorReflection)) { return false; } if (!$this->haveMissingArgumentsTypehints($definition, $constructorReflection)) { return false; } return true; }
private function getReflectionClass($id, Definition $definition) { if (isset($this->reflectionClasses[$id])) { return $this->reflectionClasses[$id]; } if (!($class = $definition->getClass())) { return false; } $class = $this->container->getParameterBag()->resolveValue($class); try { $reflector = new \ReflectionClass($class); } catch (\ReflectionException $e) { $reflector = false; } return $this->reflectionClasses[$id] = $reflector; }
/** * Compiles the $id service's $definition with all the aspects provided. * * @param string $id * @param \Symfony\Component\DependencyInjection\Definition $definition */ protected function compileDefinition($id, Definition $definition) { $refClass = new ReflectionClass($definition->getClass()); $aspectGenerator = new AspectGenerator($this->annotationReader, $this->annotationClassName); if ($aspectGenerator->hasAnnotation($refClass)) { $pg = new ProxyGenerator($refClass, array($aspectGenerator)); $filename = $this->proxyDirectory . '/' . str_replace('\\', '-', $refClass->name) . '.php'; $pg->writeClass($filename); $definition->setClass($pg->getClassName($refClass)); $definition->setFile($filename); $definition->setClass($pg->getClassName($refClass)); foreach ($this->serviceNames as $serviceName) { $definition->addArgument(new Reference($serviceName)); } } }
function it_sets_services_to_array_of_controller_services_definitions(ContainerBuilder $container, Definition $definition1, Definition $definition2) { $container->findTaggedServiceIds(InjectableCompilerPass::TAG_NAME)->willReturn(['my.first.controller' => [InjectableCompilerPass::TAG_NAME], 'my.second.controller' => [InjectableCompilerPass::TAG_NAME]]); $controllersObject = (object) array('references' => array('My_First_Controller' => [0 => 'arg1', 1 => 'arg2'], 'My_Second_Controller' => [0 => 'arg1'])); $definition1->getClass()->willReturn('My_First_Controller'); $definition1->getArguments()->willReturn(['arg1', 'arg2']); $definition1->getArgument(0)->willReturn('arg1'); $definition1->getArgument(1)->willReturn('arg2'); $container->findDefinition('my.first.controller')->willReturn($definition1); $definition2->getClass()->willReturn('My_Second_Controller'); $definition2->getArguments()->willReturn(['arg1']); $definition2->getArgument(0)->willReturn('arg1'); $container->findDefinition('my.second.controller')->willReturn($definition2); $this->process($container); $container->set(InjectableCompilerPass::INJECTABLES_SERVICE_ID, $controllersObject)->shouldHaveBeenCalled(); }
private function updateDefinition(ContainerBuilder $container, $id, Definition $definition, array $previous = array()) { // circular reference if (isset($previous[$id])) { return; } $factory = $definition->getFactory(); if (null === $factory || null !== $definition->getClass()) { return; } $class = null; if (is_string($factory)) { try { $m = new \ReflectionFunction($factory); } catch (\ReflectionException $e) { return; } } else { if ($factory[0] instanceof Reference) { $previous[$id] = true; $factoryDefinition = $container->findDefinition((string) $factory[0]); $this->updateDefinition($container, (string) $factory[0], $factoryDefinition, $previous); $class = $factoryDefinition->getClass(); } else { $class = $factory[0]; } try { $m = new \ReflectionMethod($class, $factory[1]); } catch (\ReflectionException $e) { return; } } $returnType = $m->getReturnType(); if (null !== $returnType && !$returnType->isBuiltin()) { $returnType = (string) $returnType; if (null !== $class) { $declaringClass = $m->getDeclaringClass()->getName(); if ('self' === $returnType) { $returnType = $declaringClass; } elseif ('parent' === $returnType) { $returnType = get_parent_class($declaringClass) ?: null; } } $definition->setClass($returnType); } }
private function extractCommands(Definition $handlerDefinition) { $class = new \ReflectionClass($handlerDefinition->getClass()); $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); $commands = []; foreach ($methods as $method) { if ($method->isStatic() || strpos($method->getName(), 'handle') !== 0) { continue; } $parameters = $method->getParameters(); if (count($parameters) !== 1 || $parameters[0]->getClass() === null) { continue; } $commands[] = $parameters[0]->getClass()->name; } return $commands; }