WizardFactory.php in Chaos Tool Suite (ctools) 8.3
File
src/Wizard/WizardFactory.php
View source
<?php
namespace Drupal\ctools\Wizard;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Drupal\Core\Render\RendererInterface;
class WizardFactory implements WizardFactoryInterface {
protected $builder;
protected $dispatcher;
protected $renderer;
public function __construct(FormBuilderInterface $form_builder, EventDispatcherInterface $event_dispatcher, RendererInterface $renderer) {
$this->builder = $form_builder;
$this->dispatcher = $event_dispatcher;
$this->renderer = $renderer;
}
public function getWizardForm(FormWizardInterface $wizard, array $parameters = [], $ajax = FALSE) {
$form_state = $this
->getFormState($wizard, $parameters, $ajax);
$form = $this->builder
->buildForm($wizard, $form_state);
if ($ajax) {
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';
$status_messages = [
'#type' => 'status_messages',
];
if ($messages = $this->renderer
->renderRoot($status_messages)) {
if (!empty($form['#prefix'])) {
$form['#prefix'] = '<div class="wizard-messages">' . $messages . '</div>' . $form['#prefix'];
}
}
}
return $form;
}
public function createWizard($class, array $parameters) {
$arguments = [];
$reflection = new \ReflectionClass($class);
$constructor = $reflection
->getMethod('__construct');
foreach ($constructor
->getParameters() as $parameter) {
if (array_key_exists($parameter->name, $parameters)) {
$arguments[] = $parameters[$parameter->name];
}
elseif ($parameter
->isDefaultValueAvailable()) {
$arguments[] = $parameter
->getDefaultValue();
}
}
$wizard = $reflection
->newInstanceArgs($arguments);
return $wizard;
}
public function getFormState(FormWizardInterface $wizard, array $parameters, $ajax = FALSE) {
$form_state = new FormState();
if (!$wizard
->getMachineName() || !$wizard
->getTempstore()
->get($wizard
->getMachineName())) {
$cached_values = $wizard
->initValues();
if ($wizard
->getMachineName()) {
$wizard
->getTempstore()
->set($wizard
->getMachineName(), $cached_values);
}
}
else {
$cached_values = $wizard
->getTempstore()
->get($wizard
->getMachineName());
}
$form_state
->setTemporaryValue('wizard', $cached_values);
$form_state
->set('ajax', $ajax);
$parameters['form'] = [];
$parameters['form_state'] = $form_state;
$method = new \ReflectionMethod($wizard, 'buildForm');
$arguments = [];
foreach ($method
->getParameters() as $parameter) {
if (array_key_exists($parameter->name, $parameters)) {
$arguments[] = $parameters[$parameter->name];
}
elseif ($parameter
->isDefaultValueAvailable()) {
$arguments[] = $parameter
->getDefaultValue();
}
}
unset($parameters['form'], $parameters['form_state']);
unset($arguments[0], $arguments[1]);
$form_state
->addBuildInfo('args', array_values($arguments));
return $form_state;
}
}