You are here

class MaestroSpawnSubFlowTask in Maestro 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/EngineTasks/MaestroSpawnSubFlowTask.php \Drupal\maestro\Plugin\EngineTasks\MaestroSpawnSubFlowTask

Maestro Spawn Sub Flow Task Plugin.

The plugin annotations below should include: id: The task type ID for this task. For Maestro tasks, this is Maestro[TaskType]. So for example, the start task shipped by Maestro is MaestroStart. The Maestro End task has an id of MaestroEnd Those task IDs are what's used in the engine when a task is injected into the queue.

Plugin annotation


@Plugin(
  id = "MaestroSpawnSubFlow",
  task_description = @Translation("The Maestro Engine's Spawn Sub Flow Task."),
)

Hierarchy

Expanded class hierarchy of MaestroSpawnSubFlowTask

File

src/Plugin/EngineTasks/MaestroSpawnSubFlowTask.php, line 28

Namespace

Drupal\maestro\Plugin\EngineTasks
View source
class MaestroSpawnSubFlowTask extends PluginBase implements MaestroEngineTaskInterface {
  use MaestroTaskTrait;

  /**
   * Constructor.
   */
  public function __construct($configuration = NULL) {
    if (is_array($configuration)) {
      $this->processID = $configuration[0];
      $this->queueID = $configuration[1];
    }
  }

  /**
   * {@inheritDoc}
   */
  public function isInteractive() {
    return FALSE;
  }

  /**
   * {@inheritDoc}
   */
  public function shortDescription() {
    return t('Spawn Sub Flow');
  }

  /**
   * {@inheritDoc}
   */
  public function description() {
    return $this
      ->t('Spawn Sub Flow.');
  }

  /**
   * {@inheritDoc}
   *
   * @see \Drupal\Component\Plugin\PluginBase::getPluginId()
   */
  public function getPluginId() {
    return 'MaestroSpawnSubFlow';
  }

  /**
   * {@inheritDoc}
   */
  public function getTaskColours() {
    return '#707070';
  }

  /**
   * {@inheritdoc}
   */
  public function getExecutableForm($modal, MaestroExecuteInteractive $parent) {
  }

  /**
   * {@inheritdoc}
   */
  public function handleExecuteSubmit(array &$form, FormStateInterface $form_state) {
  }

  /**
   * Part of the ExecutableInterface
   * Execution of the Sub Flow task will create a new process and push all selected parent variables to the newly spawned
   * sub process.  The variables pushed to the sub process will be prefixed with "maestro_parent_" and will also include a new
   * variable named "parent_process_id" which will store the process ID of the parent.
   * {@inheritdoc}.
   */
  public function execute() {
    $templateMachineName = MaestroEngine::getTemplateIdFromProcessId($this->processID);
    $taskMachineName = MaestroEngine::getTaskIdFromQueueId($this->queueID);
    $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskMachineName);
    $spawnTemplate = $task['data']['maestro_template'];
    $variables = [];
    if (isset($task['data']['variables'])) {
      $variables = $task['data']['variables'];
    }

    // Let's first start by adding in the new process ID.
    $maestro = new MaestroEngine();
    $newProcessID = $maestro
      ->newProcess($spawnTemplate);
    if ($newProcessID !== FALSE) {

      // first, create the parent process ID variable.
      $values = [
        'process_id' => $newProcessID,
        'variable_name' => 'maestro_parent_process_id',
        'variable_value' => $this->processID,
      ];
      $new_var = \Drupal::entityTypeManager()
        ->getStorage('maestro_process_variables')
        ->create($values);
      $new_var
        ->save();
      if (!$new_var
        ->id()) {

        // Throw a maestro exception
        // completion should technically end here for this initiation.
        throw new MaestroSaveEntityException('maestro_process_variable', $values['variable_name'] . ' failed saving during new process creation.');
      }
      foreach ($variables as $machine_name => $checked_value) {
        if ($machine_name != '') {

          // We now populate the new process with variables.
          $parent_value = MaestroEngine::getProcessVariable($machine_name, $this->processID);
          $values = [
            'process_id' => $newProcessID,
            'variable_name' => 'maestro_parent_' . $machine_name,
            'variable_value' => $parent_value,
          ];
          $new_var = \Drupal::entityTypeManager()
            ->getStorage('maestro_process_variables')
            ->create($values);
          $new_var
            ->save();
          if (!$new_var
            ->id()) {

            // Throw a maestro exception
            // completion should technically end here for this initiation.
            throw new MaestroSaveEntityException('maestro_process_variable', $values['variable_name'] . ' failed saving during new process creation.');
          }
          $parent_value = '';
        }
      }
      return TRUE;
    }
    else {
      \Drupal::logger('maestro')
        ->error('Unable to spawn sub process.  Process spawn returned an error.');
      return FALSE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getTaskEditForm(array $task, $templateMachineName) {
    $form = [
      '#markup' => t('Spawn Sub Flow Edit'),
    ];
    $maestro_templates = MaestroEngine::getTemplates();
    $templates = [];
    $templates['none'] = $this
      ->t('Please Select Template');
    foreach ($maestro_templates as $machine_name => $template) {
      $templates[$machine_name] = $template
        ->label();
    }
    $form['maestro_task_machine_name'] = [
      '#type' => 'hidden',
      '#value' => $task['id'],
    ];
    $form['maestro_template_machine_name'] = [
      '#type' => 'hidden',
      '#value' => $templateMachineName,
    ];
    $selected_template = '';
    if (isset($task['data']['maestro_template'])) {
      $selected_template = $task['data']['maestro_template'];
    }
    $form['maestro_template'] = [
      '#type' => 'select',
      '#options' => $templates,
      '#title' => $this
        ->t('Choose the Maestro Template'),
      '#default_value' => $selected_template,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => [
          $this,
          'subFlowChoiceHandlerCallback',
        ],
        'event' => 'change',
        'wrapper' => 'handler-ajax-refresh-wrapper',
        'progress' => [
          'type' => 'throbber',
          'message' => NULL,
        ],
      ],
    ];
    $template_machine_name = $selected_template;
    $form_state_template = $task['form_state']
      ->getValue('maestro_template');
    if (isset($form_state_template)) {
      $template_machine_name = $form_state_template;
    }
    if ($template_machine_name != 'none' && $template_machine_name != '') {
      $template = MaestroEngine::getTemplate($template_machine_name);
      $form['maestro_sub_flow_label'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Chosen Template') . ': ' . $template
          ->label(),
        '#url' => Url::fromRoute('maestro_template_builder', [
          'templateMachineName' => $template_machine_name,
        ]),
        '#attributes' => [
          'class' => [
            'handler-help-message',
          ],
          'target' => '_new',
          'id' => [
            'handler-ajax-refresh-wrapper',
          ],
        ],
      ];
    }
    else {
      $form['maestro_sub_flow_label'] = [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => $this
          ->t('Please choose a template.'),
        '#attributes' => [
          'class' => [
            'handler-help-message',
          ],
          'id' => [
            'handler-ajax-refresh-wrapper',
          ],
        ],
      ];
    }
    $form['maestro_sub_flow_settings'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#description' => $this
        ->t('Choose the variables you wish to send from the parent to the child. Variables will be prefixed with "maestro_parent_" when injected into the sub-process.'),
      '#title' => $this
        ->t('Variable Selection'),
    ];
    $template = MaestroEngine::getTemplate($templateMachineName);
    $form['maestro_sub_flow_settings']['variables'] = [];

    // Get all variables other than some of the exclusive Maestro variables.
    foreach ($template->variables as $var_name => $var_definition) {
      $form['maestro_sub_flow_settings']['variables']['variable_' . $var_name] = [
        '#type' => 'checkbox',
        '#title' => $var_name,
        '#default_value' => @array_key_exists($var_name, $task['data']['variables']) ? TRUE : FALSE,
        '#attributes' => [
          'autocomplete' => 'off',
        ],
      ];
    }
    $form['#cache'] = [
      'max-age' => 0,
    ];

    // Hi Firefox, I see you caching.
    $form['#attributes']['autocomplete'] = 'off';
    return $form;
  }

  /**
   * Implements callback for Ajax event on objective selection.
   *
   * @param array $form
   *   From render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Current state of form.
   *
   * @return array
   *   Objective selection section of the form.
   */
  public function subFlowChoiceHandlerCallback(array $form, FormStateInterface &$form_state) {
    return $form['maestro_sub_flow_label'];
  }

  /**
   * {@inheritDoc}
   */
  public function validateTaskEditForm(array &$form, FormStateInterface $form_state) {
    $template = $form_state
      ->getValue('maestro_template');

    // Let's validate the handler here to ensure that it actually exists.
    if ($template == 'none') {
      $form_state
        ->setErrorByName('maestro_template', $this
        ->t('You must choose a template.'));
    }
  }

  /**
   * {@inheritDoc}
   */
  public function prepareTaskForSave(array &$form, FormStateInterface $form_state, array &$task) {
    $task['data']['maestro_template'] = $form_state
      ->getValue('maestro_template');

    // Now handle the variables.
    unset($task['data']['variables']);
    $all_values = $form_state
      ->getValues();
    foreach ($all_values as $key => $var) {
      if (strpos($key, 'variable_') === 0) {

        // Starts with 'variable_',so we know this is our variables.
        $is_checked = $form_state
          ->getValue($key);
        if ($is_checked) {

          // Strip of "variable_".
          $varname = substr($key, 9);

          // Signal that it's checked.
          $task['data']['variables'][$varname] = 1;
        }
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function performValidityCheck(array &$validation_failure_tasks, array &$validation_information_tasks, array $task) {

    // So we know that we need a few keys in this $task array to even have a batch function run properly.
    // namely the handler.
    if (array_key_exists('maestro_template', $task['data']) && $task['data']['maestro_template'] == '' || !array_key_exists('maestro_template', $task['data'])) {
      $validation_failure_tasks[] = [
        'taskID' => $task['id'],
        'taskLabel' => $task['label'],
        'reason' => t('This task requires a Maestro Template to be chosen.'),
      ];
    }
  }

  /**
   * {@inheritDoc}
   */
  public function getTemplateBuilderCapabilities() {
    return [
      'edit',
      'drawlineto',
      'removelines',
      'remove',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MaestroSpawnSubFlowTask::description public function Longer description. This generally follows the short Description but can be used to be more descriptive if you wish to surface this description in a UI element. Overrides MaestroEngineTaskInterface::description
MaestroSpawnSubFlowTask::execute public function Part of the ExecutableInterface Execution of the Sub Flow task will create a new process and push all selected parent variables to the newly spawned sub process. The variables pushed to the sub process will be prefixed with… Overrides ExecutableInterface::execute
MaestroSpawnSubFlowTask::getExecutableForm public function Gets the Maestro executable form for a task console. Overrides MaestroEngineTaskInterface::getExecutableForm
MaestroSpawnSubFlowTask::getPluginId public function Overrides PluginBase::getPluginId
MaestroSpawnSubFlowTask::getTaskColours public function Returns the task's defined colours. This is useful if you want to let the tasks decide on what colours to paint themselves in the UI. Overrides MaestroEngineTaskInterface::getTaskColours
MaestroSpawnSubFlowTask::getTaskEditForm public function Method to allow a task to add their own fields to the task edit form. Overrides MaestroEngineTaskInterface::getTaskEditForm
MaestroSpawnSubFlowTask::getTemplateBuilderCapabilities public function Returns an array of consistenly keyed array elements that define what this task can do in the template builder. Elements are: edit, drawlineto, drawfalselineto, removelines, remove. Overrides MaestroEngineTaskInterface::getTemplateBuilderCapabilities
MaestroSpawnSubFlowTask::handleExecuteSubmit public function Interactive tasks, or tasks that signal themselves as requiring human interaction will have the resulting form submissions sent to their own handler for processing to determine if the task should be completed or not or to carry out any task processing… Overrides MaestroEngineTaskInterface::handleExecuteSubmit
MaestroSpawnSubFlowTask::isInteractive public function Returns TRUE or FALSE to denote if this task has an interactive interface that needs to be shown in the Task Console and for any other requirements of the task. Overrides MaestroEngineTaskInterface::isInteractive
MaestroSpawnSubFlowTask::performValidityCheck public function Lets the task perform validation on itself. If the task is missing any internal requirements, it can flag itself as having an issue. Return array MUST be in the format of array( 'taskID' => the task machine name, 'taskLabel'… Overrides MaestroEngineTaskInterface::performValidityCheck
MaestroSpawnSubFlowTask::prepareTaskForSave public function The specific task's manipulation of the values to save for a template save. Overrides MaestroEngineTaskInterface::prepareTaskForSave
MaestroSpawnSubFlowTask::shortDescription public function Get the task's short description. Useful for things like labels. Overrides MaestroEngineTaskInterface::shortDescription
MaestroSpawnSubFlowTask::subFlowChoiceHandlerCallback public function Implements callback for Ajax event on objective selection.
MaestroSpawnSubFlowTask::validateTaskEditForm public function This method must be called by the template builder in order to validate the form entry values before saving. Overrides MaestroEngineTaskInterface::validateTaskEditForm
MaestroSpawnSubFlowTask::__construct public function Constructor. Overrides PluginBase::__construct
MaestroTaskTrait::$completionStatus protected property Default will be that the task completed normally.
MaestroTaskTrait::$executionStatus protected property The default will be success for the execution status.
MaestroTaskTrait::$processID protected property The Maestro Process ID.
MaestroTaskTrait::$queueID protected property The Maestro queue ID.
MaestroTaskTrait::getAssignmentsAndNotificationsForm public function Retrieve the core Maestro form edit elements for Assignments and Notifications.
MaestroTaskTrait::getBaseEditForm public function Retrieve the core Maestro form edit elements that all tasks MUST adhere to.
MaestroTaskTrait::getCompletionStatus public function Returns the value of the completion status protected variable denoting any special completion status condition the task wishes to pass along.
MaestroTaskTrait::getExecutionStatus public function Returns the value of the execution status protected variable denoting if the execution of this task is complete.
MaestroTaskTrait::saveTask public function Available for all tasks -- this does the general task construction for us, ensuring we have sanity in the saved Config Entity for the task. Assignments and Notifications are the two main elements this method worries about.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.