You are here

class MaestroBatchFunctionTask in Maestro 3.x

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

Maestro Batch Function 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 = "MaestroBatchFunction",
  task_description = @Translation("The Maestro Engine's Batch Function task."),
)

Hierarchy

Expanded class hierarchy of MaestroBatchFunctionTask

File

src/Plugin/EngineTasks/MaestroBatchFunctionTask.php, line 26

Namespace

Drupal\maestro\Plugin\EngineTasks
View source
class MaestroBatchFunctionTask 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('Batch Function');
  }

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

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

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

  /**
   * Part of the ExecutableInterface
   * Execution of the Batch Function task will use the handler for this task as the executable function.
   * The handler must return TRUE in order for this function to be completed by the engine.
   * We simply pass the return boolean value back from the called handler to the engine for processing.
   * {@inheritdoc}.
   */
  public function execute() {
    $returnValue = FALSE;
    $returnStatus = FALSE;
    $queueRecord = MaestroEngine::getQueueEntryById($this->queueID);
    if ($queueRecord) {

      // Pick off the handler here and call the code via the user func array.
      if ($queueRecord->handler != NULL) {
        $handler = $queueRecord->handler
          ->getString();
        if (function_exists($handler)) {
          $returnStatus = call_user_func_array($handler, [
            $this->processID,
            $this->queueID,
          ]);

          // Lets see if the return status is an array.  if so, we will check if it has any established structure to set status codes.
          if (is_array($returnStatus)) {
            if (array_key_exists('completion_status', $returnStatus)) {
              $this->completionStatus = $returnStatus['completion_status'];
            }
            if (array_key_exists('execution_status', $returnStatus)) {
              $this->executionStatus = $returnStatus['execution_status'];
            }
            if (array_key_exists('status', $returnStatus)) {

              // On false, this holds the engine at this task.
              $returnValue = $returnStatus['status'];
            }
          }
          else {
            $returnValue = $returnStatus;
          }
        }
      }
      else {

        // Just do a NOOP here.
        $returnValue = TRUE;
      }
    }

    // True or false to complete the task.
    return $returnValue;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function getTaskEditForm(array $task, $templateMachineName) {
    $form = [
      '#markup' => t('Batch Function Edit'),
    ];

    // Let modules signal the handlers they wish to share.
    $handlers = \Drupal::moduleHandler()
      ->invokeAll('maestro_batch_handlers', []);
    $handler_desc = $this
      ->t('The batch function name you wish to call.');
    if (isset($task['handler']) && isset($handlers[$task['handler']])) {
      $handler_desc = $handlers[$task['handler']];
    }
    $form['handler'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Handler'),
      '#default_value' => isset($task['handler']) ? $task['handler'] : '',
      '#required' => TRUE,
      '#autocomplete_route_name' => 'maestro.autocomplete.batch_handlers',
      '#ajax' => [
        'callback' => [
          $this,
          'batchFunctionHandlerCallback',
        ],
        'event' => 'autocompleteclose',
        'wrapper' => 'handler-ajax-refresh-wrapper',
        'progress' => [
          'type' => 'throbber',
          'message' => NULL,
        ],
      ],
    ];
    $form['handler_help_text'] = [
      '#type' => 'html_tag',
      '#tag' => 'div',
      '#value' => $handler_desc,
      '#readonly' => TRUE,
      '#attributes' => [
        'class' => [
          'handler-help-message',
        ],
        'id' => [
          'handler-ajax-refresh-wrapper',
        ],
      ],
    ];
    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 batchFunctionHandlerCallback(array &$form, FormStateInterface $form_state) {
    $selected_handler = $new_objective_id = $form_state
      ->getValue('handler');

    // Let modules signal the handlers they wish to share.
    $handlers = \Drupal::moduleHandler()
      ->invokeAll('maestro_batch_handlers', []);
    if ($selected_handler != '' && !function_exists($selected_handler)) {
      $handler_desc = \Drupal::translation()
        ->translate('This handler form function does not exist.');
    }
    elseif (isset($handlers[$selected_handler])) {
      $handler_desc = $handlers[$selected_handler];
    }
    else {
      $handler_desc = \Drupal::translation()
        ->translate('The batch function name you wish to call.');
    }
    $form['handler_help_text'] = [
      '#type' => 'html_tag',
      '#tag' => 'div',
      '#value' => $handler_desc,
      '#readonly' => TRUE,
      '#attributes' => [
        'class' => [
          'handler-help-message',
        ],
        'id' => [
          'handler-ajax-refresh-wrapper',
        ],
      ],
    ];
    return $form['handler_help_text'];
  }

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

    // Let's validate the handler here to ensure that it actually exists.
    if (!function_exists($handler)) {
      $form_state
        ->setErrorByName('handler', $this
        ->t('This handler batch function does not exist.'));
    }
  }

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

  /**
   * {@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('handler', $task) && $task['handler'] == '' || !array_key_exists('handler', $task)) {
      $validation_failure_tasks[] = [
        'taskID' => $task['id'],
        'taskLabel' => $task['label'],
        'reason' => t('The handler for the task has not been set. This will cause a failure of the engine to execute'),
      ];
    }
  }

  /**
   * {@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
MaestroBatchFunctionTask::batchFunctionHandlerCallback public function Implements callback for Ajax event on objective selection.
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::execute public function Part of the ExecutableInterface Execution of the Batch Function task will use the handler for this task as the executable function. The handler must return TRUE in order for this function to be completed by the engine. We simply pass the return… Overrides ExecutableInterface::execute
MaestroBatchFunctionTask::getExecutableForm public function Gets the Maestro executable form for a task console. Overrides MaestroEngineTaskInterface::getExecutableForm
MaestroBatchFunctionTask::getPluginId public function Overrides PluginBase::getPluginId
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::getTaskEditForm public function Method to allow a task to add their own fields to the task edit form. Overrides MaestroEngineTaskInterface::getTaskEditForm
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::prepareTaskForSave public function The specific task's manipulation of the values to save for a template save. Overrides MaestroEngineTaskInterface::prepareTaskForSave
MaestroBatchFunctionTask::shortDescription public function Get the task's short description. Useful for things like labels. Overrides MaestroEngineTaskInterface::shortDescription
MaestroBatchFunctionTask::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
MaestroBatchFunctionTask::__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.