Forms.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Grav\Plugin\Form;
  3. use Grav\Common\Page\Interfaces\PageInterface;
  4. use Grav\Common\Page\Page;
  5. use Grav\Framework\Form\Interfaces\FormFactoryInterface;
  6. use Grav\Framework\Form\Interfaces\FormInterface;
  7. class Forms
  8. {
  9. /** @var array|FormFactoryInterface[] */
  10. private $types;
  11. /** @var FormInterface|null */
  12. private $form;
  13. public function __construct()
  14. {
  15. $this->registerType('form', new FormFactory());
  16. }
  17. public function registerType(string $type, FormFactoryInterface $factory): void
  18. {
  19. $this->types[$type] = $factory;
  20. }
  21. public function unregisterType($type): void
  22. {
  23. unset($this->types[$type]);
  24. }
  25. public function hasType(string $type): bool
  26. {
  27. return isset($this->types[$type]);
  28. }
  29. public function getTypes(): array
  30. {
  31. return array_keys($this->types);
  32. }
  33. public function createPageForm(PageInterface $page, string $name = null, array $form = null): ?FormInterface
  34. {
  35. if (null === $form) {
  36. [$name, $form] = $this->getPageParameters($page, $name);
  37. }
  38. if (null === $form) {
  39. return null;
  40. }
  41. $type = $form['type'] ?? 'form';
  42. $factory = $this->types[$type] ?? null;
  43. if ($factory) {
  44. if (method_exists($factory, 'createFormForPage')) {
  45. return $factory->createFormForPage($page, $name, $form);
  46. }
  47. if ($page instanceof Page) {
  48. return $factory->createPageForm($page, $name, $form);
  49. }
  50. }
  51. return null;
  52. }
  53. public function getActiveForm(): ?FormInterface
  54. {
  55. return $this->form;
  56. }
  57. public function setActiveForm(FormInterface $form): void
  58. {
  59. $this->form = $form;
  60. }
  61. protected function getPageParameters(PageInterface $page, ?string $name): array
  62. {
  63. $forms = $page->forms();
  64. if ($name) {
  65. // If form with given name was found, use that.
  66. $form = $forms[$name] ?? null;
  67. } else {
  68. // Otherwise pick up the first form.
  69. $form = reset($forms) ?: null;
  70. $name = (string)key($forms);
  71. }
  72. return [$name, $form];
  73. }
  74. }