getFactory example

if (0 !== $priority) {
                $code .= sprintf(" decoration_priority: %s\n", $priority);
            }

            $decorationOnInvalid = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
            if (\in_array($decorationOnInvalid[ContainerInterface::IGNORE_ON_INVALID_REFERENCE, ContainerInterface::NULL_ON_INVALID_REFERENCE])) {
                $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE === $decorationOnInvalid ? 'null' : 'ignore';
                $code .= sprintf(" decoration_on_invalid: %s\n", $invalidBehavior);
            }
        }

        if ($callable = $definition->getFactory()) {
            if (\is_array($callable) && ['Closure', 'fromCallable'] !== $callable && $definition->getClass() === $callable[0]) {
                $code .= sprintf(" constructor: %s\n", $callable[1]);
            } else {
                $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));
        }

        
throw new InvalidArgumentException(sprintf('Missing attribute "version" of the "deprecated" option in "%s".', $file));
            }

            $definition->setDeprecated($deprecation['package'] ?? '', $deprecation['version'] ?? '', $deprecation['message'] ?? '');
        }

        if (isset($service['factory'])) {
            $definition->setFactory($this->parseCallable($service['factory'], 'factory', $id$file));
        }

        if (isset($service['constructor'])) {
            if (null !== $definition->getFactory()) {
                throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $id));
            }

            $definition->setFactory([null, $service['constructor']]);
        }

        if (isset($service['file'])) {
            $definition->setFile($service['file']);
        }

        if (isset($service['arguments'])) {
            
return $this->getDiscovery()->getDefinitions();
  }

  /** * {@inheritdoc} */
  public function createInstance($plugin_id, array $configuration = []) {
    // If this PluginManager has fallback capabilities catch     // PluginNotFoundExceptions.     if ($this instanceof FallbackPluginManagerInterface) {
      try {
        return $this->getFactory()->createInstance($plugin_id$configuration);
      }
      catch (PluginNotFoundException $e) {
        return $this->handlePluginNotFound($plugin_id$configuration);
      }
    }
    else {
      return $this->getFactory()->createInstance($plugin_id$configuration);
    }
  }

  /** * Allows plugin managers to specify custom behavior if a plugin is not found. * * @param string $plugin_id * The ID of the missing requested plugin. * @param array $configuration * An array of configuration relevant to the plugin instance. * * @return object * A fallback plugin instance. * * @throws \BadMethodCallException * When ::getFallbackPluginId() is not implemented in the concrete plugin * manager class. */
if ($childService = $factory->getAttribute('service')) {
                    $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
                } else {
                    $class = $factory->hasAttribute('class') ? $factory->getAttribute('class') : null;
                }

                $definition->setFactory([$class$factory->getAttribute('method') ?: '__invoke']);
            }
        }

        if ($constructor = $service->getAttribute('constructor')) {
            if (null !== $definition->getFactory()) {
                throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $service->getAttribute('id')));
            }

            $definition->setFactory([null, $constructor]);
        }

        if ($configurators = $this->getChildren($service, 'configurator')) {
            $configurator = $configurators[0];
            if ($function = $configurator->getAttribute('function')) {
                $definition->setConfigurator($function);
            } else {
                
if ($definition->isSynthetic()) {
            throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
        }

        if ($definition->isDeprecated()) {
            $deprecation = $definition->getDeprecation($id);
            trigger_deprecation($deprecation['package']$deprecation['version']$deprecation['message']);
        }

        $parameterBag = $this->getParameterBag();
        $class = $parameterBag->resolveValue($definition->getClass()) ?: (['Closure', 'fromCallable'] === $definition->getFactory() ? 'Closure' : null);

        if (['Closure', 'fromCallable'] === $definition->getFactory() && ('Closure' !== $class || $definition->isLazy())) {
            $callable = $parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArgument(0)));

            if ($callable instanceof Reference || $callable instanceof Definition) {
                $callable = [$callable, '__invoke'];
            }

            if (\is_array($callable) && (
                $callable[0] instanceof Reference
                || $callable[0] instanceof Definition && !isset($inlineServices[spl_object_hash($callable[0])])
            ))
$this->currentDefinition = $value;
        } elseif ($this->currentDefinition === $value) {
            return $value;
        }
        $this->lazy = false;

        $byConstructor = $this->byConstructor;
        $this->byConstructor = $isRoot || $byConstructor;

        $byFactory = $this->byFactory;
        $this->byFactory = true;
        if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
            if (!class_exists(Expression::class)) {
                throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
            }

            $factory = new Expression(substr($factory, 2));
        }
        $this->processValue($factory);
        $this->byFactory = $byFactory;

        $this->processValue($value->getArguments());

        
$definition = (new Prophet())->prophesize('\Symfony\Component\DependencyInjection\Definition');
        $definition->getClass()->willReturn($service_definition['class']);
        $definition->isPublic()->willReturn($service_definition['public']);
        $definition->getFile()->willReturn($service_definition['file']);
        $definition->isSynthetic()->willReturn($service_definition['synthetic']);
        $definition->isLazy()->willReturn($service_definition['lazy']);
        $definition->getArguments()->willReturn($service_definition['arguments']);
        $definition->getProperties()->willReturn($service_definition['properties']);
        $definition->getMethodCalls()->willReturn($service_definition['calls']);
        $definition->isShared()->willReturn($service_definition['shared']);
        $definition->getDecoratedService()->willReturn(NULL);
        $definition->getFactory()->willReturn($service_definition['factory']);
        $definition->getConfigurator()->willReturn($service_definition['configurator']);

        // Preserve order.         $filtered_service_definition = [];
        foreach ($base_service_definition as $key => $value) {
          $filtered_service_definition[$key] = $service_definition[$key];
          unset($service_definition[$key]);

          if ($key == 'class' || $key == 'arguments_count') {
            continue;
          }

          
final public const NEWSLETTER_FORM = 'newsletter_form';

    final public const CART_ADD_LINE_ITEM = 'cart_add_line_item';

    /** * @var array<string, RateLimiterFactory> */
    private array $factories;

    public function reset(string $route, string $key): void
    {
        $this->getFactory($route)->create($key)->reset();
    }

    public function ensureAccepted(string $route, string $key): void
    {
        $limiter = $this->getFactory($route)->create($key)->consume();

        if (!$limiter->isAccepted()) {
            throw new RateLimitExceededException($limiter->getRetryAfter()->getTimestamp());
        }
    }

    
return $this->addNewInstance($definition, ' '.$return.$instantiation$id$asGhostObject);
    }

    private function isTrivialInstance(Definition $definition): bool
    {
        if ($definition->hasErrors()) {
            return true;
        }
        if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) {
            return false;
        }
        if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments())) {
            return false;
        }

        foreach ($definition->getArguments() as $arg) {
            if (!$arg || $arg instanceof Parameter) {
                continue;
            }
            if (\is_array($arg) && 3 >= \count($arg)) {
                foreach ($arg as $k => $v) {
                    if ($this->dumpValue($k) !== $this->dumpValue($k, false)) {
                        return false;
                    }
$this->assertArrayHasKey(DummyMessage::class$handlersMapping);
        $this->assertArrayHasKey(SecondMessage::class$handlersMapping);

        $dummyHandlerDescriptorReference = $handlersMapping[DummyMessage::class]->getValues()[0];
        $dummyHandlerDescriptorDefinition = $container->getDefinition($dummyHandlerDescriptorReference);

        $dummyHandlerReference = $dummyHandlerDescriptorDefinition->getArgument(0);
        $dummyHandlerDefinition = $container->getDefinition($dummyHandlerReference);

        $this->assertSame('Closure', $dummyHandlerDefinition->getClass());
        $this->assertEquals([new Reference(HandlerMappingMethods::class), 'dummyMethod']$dummyHandlerDefinition->getArgument(0));
        $this->assertSame(['Closure', 'fromCallable']$dummyHandlerDefinition->getFactory());

        $secondHandlerDescriptorReference = $handlersMapping[SecondMessage::class]->getValues()[1];
        $secondHandlerDescriptorDefinition = $container->getDefinition($secondHandlerDescriptorReference);

        $secondHandlerReference = $secondHandlerDescriptorDefinition->getArgument(0);
        $secondHandlerDefinition = $container->getDefinition($secondHandlerReference);
        $this->assertSame(PrioritizedHandler::class$secondHandlerDefinition->getClass());
    }

    public function testRegisterAbstractHandler()
    {
        
return $this->addNewInstance($definition, ' '.$return.$instantiation$id);
    }

    private function isTrivialInstance(Definition $definition): bool
    {
        if ($definition->hasErrors()) {
            return true;
        }
        if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) {
            return false;
        }
        if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments())) {
            return false;
        }

        foreach ($definition->getArguments() as $arg) {
            if (!$arg || $arg instanceof Parameter) {
                continue;
            }
            if (\is_array($arg) && 3 >= \count($arg)) {
                foreach ($arg as $k => $v) {
                    if ($this->dumpValue($k) !== $this->dumpValue($k, false)) {
                        return false;
                    }
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

/** * @author Maxime Steinhausser <maxime.steinhausser@gmail.com> */
class ResolveFactoryClassPass extends AbstractRecursivePass
{
    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof Definition && \is_array($factory = $value->getFactory()) && null === $factory[0]) {
            if (null === $class = $value->getClass()) {
                throw new RuntimeException(sprintf('The "%s" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?', $this->currentId));
            }

            $factory[0] = $class;
            $value->setFactory($factory);
        }

        return parent::processValue($value$isRoot);
    }
}
return parent::processValue($value$isRoot);
        }
        if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $value->getInvalidBehavior() || $this->container->has($id = (string) $value)) {
            return $value;
        }

        $currentId = $this->currentId;
        $graph = $this->container->getCompiler()->getServiceReferenceGraph();

        if (isset($this->serviceLocatorContextIds[$currentId])) {
            $currentId = $this->serviceLocatorContextIds[$currentId];
            $locator = $this->container->getDefinition($this->currentId)->getFactory()[0];

            foreach ($locator->getArgument(0) as $k => $v) {
                if ($v->getValues()[0] === $value) {
                    if ($k !== $id) {
                        $currentId = $k.'" in the container provided to "'.$currentId;
                    }
                    throw new ServiceNotFoundException($id$currentId, null, $this->getAlternatives($id));
                }
            }
        }

        
return parent::processValue($value$isRoot);
        }

        if ($constructor = $this->getConstructor($value, false)) {
            $this->checkTypeDeclarations($value$constructor$value->getArguments());
        }

        foreach ($value->getMethodCalls() as $methodCall) {
            try {
                $reflectionMethod = $this->getReflectionMethod($value$methodCall[0]);
            } catch (RuntimeException $e) {
                if ($value->getFactory()) {
                    continue;
                }

                throw $e;
            }

            $this->checkTypeDeclarations($value$reflectionMethod$methodCall[1]);
        }

        return parent::processValue($value$isRoot);
    }

    
return reset($instances);
  }

  /** * {@inheritdoc} */
  public function createInstances($migration_id, array $configuration = []) {
    if (empty($migration_id)) {
      $migration_id = array_keys($this->getDefinitions());
    }

    $factory = $this->getFactory();
    $migration_ids = (array) $migration_id;

    // We need to expand any derivative migrations. Derivative migrations are     // calculated by migration derivers such as D6NodeDeriver. This allows     // migrations to depend on the base id and then have a dependency on all     // derivative migrations. For example, d6_comment depends on d6_node but     // after we've expanded the dependencies it will depend on d6_node:page,     // d6_node:story and so on, for other derivative migrations.     $plugin_ids = $this->expandPluginIds($migration_ids);

    $instances = [];
    
Home | Imprint | This part of the site doesn't use cookies.