PluginFormFactory.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\Core\Plugin;
  3. use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
  4. use Drupal\Component\Plugin\PluginAwareInterface;
  5. use Drupal\Core\DependencyInjection\ClassResolverInterface;
  6. /**
  7. * Provides form discovery capabilities for plugins.
  8. */
  9. class PluginFormFactory implements PluginFormFactoryInterface {
  10. /**
  11. * The class resolver.
  12. *
  13. * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
  14. */
  15. protected $classResolver;
  16. /**
  17. * PluginFormFactory constructor.
  18. *
  19. * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
  20. * The class resolver.
  21. */
  22. public function __construct(ClassResolverInterface $class_resolver) {
  23. $this->classResolver = $class_resolver;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function createInstance(PluginWithFormsInterface $plugin, $operation, $fallback_operation = NULL) {
  29. if (!$plugin->hasFormClass($operation)) {
  30. // Use the default form class if no form is specified for this operation.
  31. if ($fallback_operation && $plugin->hasFormClass($fallback_operation)) {
  32. $operation = $fallback_operation;
  33. }
  34. else {
  35. throw new InvalidPluginDefinitionException($plugin->getPluginId(), sprintf('The "%s" plugin did not specify a "%s" form class', $plugin->getPluginId(), $operation));
  36. }
  37. }
  38. $form_class = $plugin->getFormClass($operation);
  39. // If the form specified is the plugin itself, use it directly.
  40. if (ltrim(get_class($plugin), '\\') === ltrim($form_class, '\\')) {
  41. $form_object = $plugin;
  42. }
  43. else {
  44. $form_object = $this->classResolver->getInstanceFromDefinition($form_class);
  45. }
  46. // Ensure the resulting object is a plugin form.
  47. if (!$form_object instanceof PluginFormInterface) {
  48. throw new InvalidPluginDefinitionException($plugin->getPluginId(), sprintf('The "%s" plugin did not specify a valid "%s" form class, must implement \Drupal\Core\Plugin\PluginFormInterface', $plugin->getPluginId(), $operation));
  49. }
  50. if ($form_object instanceof PluginAwareInterface) {
  51. $form_object->setPlugin($plugin);
  52. }
  53. return $form_object;
  54. }
  55. }