getInstanceFromDefinition example

$this->classResolver = $this->prophesize(ClassResolverInterface::class);
    $this->manager = new PluginFormFactory($this->classResolver->reveal());
  }

  /** * @covers ::createInstance */
  public function testCreateInstance() {
    $plugin_form = $this->prophesize(PluginFormInterface::class);
    $expected = $plugin_form->reveal();

    $this->classResolver->getInstanceFromDefinition(get_class($expected))->willReturn($expected);

    $plugin = $this->prophesize(PluginWithFormsInterface::class);
    $plugin->hasFormClass('standard_class')->willReturn(TRUE);
    $plugin->getFormClass('standard_class')->willReturn(get_class($expected));

    $form_object = $this->manager->createInstance($plugin->reveal(), 'standard_class');
    $this->assertSame($expected$form_object);
  }

  /** * @covers ::createInstance */

  public function getControllerFromDefinition($controller$path = '') {
    if (is_array($controller) || (is_object($controller) && method_exists($controller, '__invoke'))) {
      return $controller;
    }

    if (!str_contains($controller, ':')) {
      if (function_exists($controller)) {
        return $controller;
      }
      return $this->classResolver->getInstanceFromDefinition($controller);
    }

    $callable = $this->createController($controller);

    if (!is_callable($callable)) {
      throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable.', $path));
    }

    return $callable;
  }

  
$this->setMockContainerService('class_resolver', $class_resolver->reveal());
    $this->assertInstanceOf(ClassResolverInterface::class, \Drupal::classResolver());
  }

  /** * Tests the classResolver method when called with a class. * * @covers ::classResolver */
  public function testClassResolverWithClass() {
    $class_resolver = $this->prophesize(ClassResolverInterface::class);
    $class_resolver->getInstanceFromDefinition(static::class)->willReturn($this);
    $this->setMockContainerService('class_resolver', $class_resolver->reveal());
    $this->assertSame($this, \Drupal::classResolver(static::class));
  }

  /** * Tests the keyValueExpirable() method. * * @covers ::keyValueExpirable */
  public function testKeyValueExpirable() {
    $keyvalue = $this->getMockBuilder('Drupal\Core\KeyValueStore\KeyValueExpirableFactory')
      

  public static function classResolver($class = NULL) {
    if ($class) {
      return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class);
    }
    return static::getContainer()->get('class_resolver');
  }

  /** * Returns an expirable key value store collection. * * @param string $collection * The name of the collection holding key and value pairs. * * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface * An expirable key value store collection. */
return $this->getHandler($entity_type_id, 'list_builder');
  }

  /** * {@inheritdoc} */
  public function getFormObject($entity_type_id$operation) {
    if (!$class = $this->getDefinition($entity_type_id, TRUE)->getFormClass($operation)) {
      throw new InvalidPluginDefinitionException($entity_type_idsprintf('The "%s" entity type did not specify a "%s" form class.', $entity_type_id$operation));
    }

    $form_object = $this->classResolver->getInstanceFromDefinition($class);

    return $form_object
      ->setStringTranslation($this->stringTranslation)
      ->setModuleHandler($this->moduleHandler)
      ->setEntityTypeManager($this)
      ->setOperation($operation);
  }

  /** * {@inheritdoc} */
  
/** * {@inheritdoc} */
  public function getInstance(Constraint $constraint): ConstraintValidatorInterface {
    $class_name = $constraint->validatedBy();
    // Constraint validator instances should always be initialized newly and     // never shared, because the current validation context is getting injected     // into them through setter injection and in a case of a recursive     // validation where a validator triggers a validation chain leading to the     // same validator the context of the first call would be exchanged with the     // one of the subsequent validation chain.     return $this->classResolver->getInstanceFromDefinition($class_name);
  }

}
parent::setUp();

    $namespaces = new \ArrayObject([
      'Drupal\\Core\\TypedData' => $this->root . '/core/lib/Drupal/Core/TypedData',
      'Drupal\\Core\\Validation' => $this->root . '/core/lib/Drupal/Core/Validation',
      'Drupal\\Tests\\Core\\Plugin\\Fixtures' => $this->root . '/core/tests/Drupal/Tests/Core/Plugin/Fixtures',
    ]);
    $cache_backend = new NullBackend('cache');
    $module_handler = $this->prophesize(ModuleHandlerInterface::class);

    $class_resolver = $this->prophesize(ClassResolverInterface::class);
    $class_resolver->getInstanceFromDefinition(Argument::type('string'))->will(function D$arguments) {
      $class_name = $arguments[0];
      return new $class_name();
    });

    $type_data_manager = new TypedDataManager($namespaces$cache_backend$module_handler->reveal()$class_resolver->reveal());
    $type_data_manager->setValidationConstraintManager(new ConstraintManager($namespaces$cache_backend$module_handler->reveal()));

    $string_translation = new TranslationManager(new LanguageDefault([]));

    $container = new ContainerBuilder();
    $container->set('typed_data_manager', $type_data_manager);
    
public function hasActiveWorkspace() {
    return $this->getActiveWorkspace() !== FALSE;
  }

  /** * {@inheritdoc} */
  public function getActiveWorkspace() {
    if (!isset($this->activeWorkspace)) {
      $request = $this->requestStack->getCurrentRequest();
      foreach ($this->negotiatorIds as $negotiator_id) {
        $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);
        if ($negotiator->applies($request)) {
          // By default, 'view' access is checked when a workspace is activated,           // but it should also be checked when retrieving the currently active           // workspace.           if (($negotiated_workspace = $negotiator->getActiveWorkspace($request)) && $negotiated_workspace->access('view')) {
            $active_workspace = $negotiated_workspace;
            break;
          }
        }
      }

      

  public function buildForm(array $form, FormStateInterface $form_state, MenuLinkInterface $menu_link_plugin = NULL) {
    $form['menu_link_id'] = [
      '#type' => 'value',
      '#value' => $menu_link_plugin->getPluginId(),
    ];
    $class_name = $menu_link_plugin->getFormClass();
    $form['#plugin_form'] = $this->classResolver->getInstanceFromDefinition($class_name);
    $form['#plugin_form']->setMenuLinkInstance($menu_link_plugin);

    $form += $form['#plugin_form']->buildConfigurationForm($form$form_state);

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    ];
    return $form;
  }
    // be deleted.     $changed = $this->getRestResourceDependencies()->onDependencyRemoval($this$dependencies);
    return $parent || $changed;
  }

  /** * Returns the REST resource dependencies. * * @return \Drupal\rest\Entity\ConfigDependencies */
  protected function getRestResourceDependencies() {
    return \Drupal::service('class_resolver')->getInstanceFromDefinition(ConfigDependencies::class);
  }

  /** * Normalizes the method. * * @param string $method * The request method. * * @return string * The normalized request method. */
  
    $storage = $this->container->get('entity_type.manager')->getStorage('config_test');
    for ($i = 0; $i < 15; $i++) {
      $entity_id = 'config_test_' . $i;
      $storage->create(['id' => $entity_id, 'label' => $entity_id])->save();
    }

    // Set up the updater.     $sandbox = [];
    $settings = Settings::getInstance() ? Settings::getAll() : [];
    $settings['entity_update_batch_size'] = 10;
    new Settings($settings);
    $updater = $this->container->get('class_resolver')->getInstanceFromDefinition(ConfigEntityUpdater::class);

    $callback = function D$config_entity) {
      /** @var \Drupal\config_test\Entity\ConfigTest $config_entity */
      $number = (int) str_replace('config_test_', '', $config_entity->id());
      // Only update even numbered entities.       if ($number % 2 == 0) {
        $config_entity->set('label', $config_entity->label . ' (updated)');
        return TRUE;
      }
      return FALSE;
    };

    

  public function applies(RouteMatchInterface $route_match) {
    return TRUE;
  }

  /** * {@inheritdoc} */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    foreach ($this->negotiators as $negotiator_id) {
      $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);

      if ($negotiator->applies($route_match)) {
        $theme = $negotiator->determineActiveTheme($route_match);
        if ($theme !== NULL && $this->themeAccess->checkAccess($theme)) {
          return $theme;
        }
      }
    }
  }

}

  protected $entityFieldManager;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->entityTypeInfo = $this->container->get('class_resolver')->getInstanceFromDefinition(EntityTypeInfo::class);
    $this->entityTypeManager = $this->container->get('entity_type.manager');
    $this->entityFieldManager = $this->container->get('entity_field.manager');

    $this->installConfig(['content_moderation']);
  }

  /** * @covers ::entityBaseFieldInfo */
  public function testEntityBaseFieldInfo() {
    $definition = $this->entityTypeManager->getDefinition('entity_test');
    
/** * {@inheritdoc} */
  protected function getFormArgument(RouteMatchInterface $route_match) {
    return $route_match->getRouteObject()->getDefault('_form');
  }

  /** * {@inheritdoc} */
  protected function getFormObject(RouteMatchInterface $route_match$form_arg) {
    return $this->classResolver->getInstanceFromDefinition($form_arg);
  }

}
public function onViewRenderArray(ViewEvent $event) {
    $request = $event->getRequest();
    $result = $event->getControllerResult();

    // Render the controller result into a response if it's a render array.     if (is_array($result) && ($request->query->has(static::WRAPPER_FORMAT) || $request->getRequestFormat() == 'html')) {
      $wrapper = $request->query->get(static::WRAPPER_FORMAT, 'html');

      // Fall back to HTML if the requested wrapper envelope is not available.       $wrapper = isset($this->mainContentRenderers[$wrapper]) ? $wrapper : 'html';

      $renderer = $this->classResolver->getInstanceFromDefinition($this->mainContentRenderers[$wrapper]);
      $response = $renderer->renderResponse($result$request$this->routeMatch);
      // The main content render array is rendered into a different Response       // object, depending on the specified wrapper format.       if ($response instanceof CacheableResponseInterface) {
        $main_content_view_subscriber_cacheability = (new CacheableMetadata())->setCacheContexts(['url.query_args:' . static::WRAPPER_FORMAT]);
        $response->addCacheableDependency($main_content_view_subscriber_cacheability);
      }
      $event->setResponse($response);
    }
  }

  
Home | Imprint | This part of the site doesn't use cookies.