You are here

public function ReflectionFactory::createInstance in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Component/Plugin/Factory/ReflectionFactory.php \Drupal\Component\Plugin\Factory\ReflectionFactory::createInstance()
  2. 9 core/lib/Drupal/Component/Plugin/Factory/ReflectionFactory.php \Drupal\Component\Plugin\Factory\ReflectionFactory::createInstance()

Creates a pre-configured instance of a plugin.

Parameters

string $plugin_id: The ID of the plugin being instantiated.

array $configuration: An array of configuration relevant to the plugin instance.

Return value

object A fully configured plugin instance.

Throws

\Drupal\Component\Plugin\Exception\PluginException If the instance cannot be created, such as if the ID is invalid.

Overrides DefaultFactory::createInstance

File

core/lib/Drupal/Component/Plugin/Factory/ReflectionFactory.php, line 16

Class

ReflectionFactory
A plugin factory that maps instance configuration to constructor arguments.

Namespace

Drupal\Component\Plugin\Factory

Code

public function createInstance($plugin_id, array $configuration = []) {
  $plugin_definition = $this->discovery
    ->getDefinition($plugin_id);
  $plugin_class = static::getPluginClass($plugin_id, $plugin_definition, $this->interface);

  // Lets figure out of there's a constructor for this class and pull
  // arguments from the $options array if so to populate it.
  $reflector = new \ReflectionClass($plugin_class);
  if ($reflector
    ->hasMethod('__construct')) {
    $arguments = $this
      ->getInstanceArguments($reflector, $plugin_id, $plugin_definition, $configuration);
    $instance = $reflector
      ->newInstanceArgs($arguments);
  }
  else {
    $instance = new $plugin_class();
  }
  return $instance;
}