3 namespace Drupal\Component\Plugin\Factory;
6 * A plugin factory that maps instance configuration to constructor arguments.
8 * Provides logic for any basic plugin type that needs to provide individual
9 * plugins based upon some basic logic.
11 class ReflectionFactory extends DefaultFactory {
16 public function createInstance($plugin_id, array $configuration = []) {
17 $plugin_definition = $this->discovery->getDefinition($plugin_id);
18 $plugin_class = static::getPluginClass($plugin_id, $plugin_definition, $this->interface);
20 // Lets figure out of there's a constructor for this class and pull
21 // arguments from the $options array if so to populate it.
22 $reflector = new \ReflectionClass($plugin_class);
23 if ($reflector->hasMethod('__construct')) {
24 $arguments = $this->getInstanceArguments($reflector, $plugin_id, $plugin_definition, $configuration);
25 $instance = $reflector->newInstanceArgs($arguments);
28 $instance = new $plugin_class();
35 * Inspects the plugin class and build a list of arguments for the constructor.
37 * This is provided as a helper method so factories extending this class can
38 * replace this and insert their own reflection logic.
40 * @param \ReflectionClass $reflector
41 * The reflector object being used to inspect the plugin class.
42 * @param string $plugin_id
43 * The identifier of the plugin implementation.
44 * @param mixed $plugin_definition
45 * The definition associated with the plugin_id.
46 * @param array $configuration
47 * An array of configuration that may be passed to the instance.
50 * An array of arguments to be passed to the constructor.
52 protected function getInstanceArguments(\ReflectionClass $reflector, $plugin_id, $plugin_definition, array $configuration) {
55 foreach ($reflector->getMethod('__construct')->getParameters() as $param) {
56 $param_name = $param->getName();
58 if ($param_name == 'plugin_id') {
59 $arguments[] = $plugin_id;
61 elseif ($param_name == 'plugin_definition') {
62 $arguments[] = $plugin_definition;
64 elseif ($param_name == 'configuration') {
65 $arguments[] = $configuration;
67 elseif (isset($configuration[$param_name]) || array_key_exists($param_name, $configuration)) {
68 $arguments[] = $configuration[$param_name];
70 elseif ($param->isDefaultValueAvailable()) {
71 $arguments[] = $param->getDefaultValue();