ReflectionFactory.php 2.6 KB

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