You are here

class MaestroSetProcessVariableTask in Maestro 8.2

Same name and namespace in other branches
  1. 3.x src/Plugin/EngineTasks/MaestroSetProcessVariableTask.php \Drupal\maestro\Plugin\EngineTasks\MaestroSetProcessVariableTask

Maestro Set Process Variable 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 = "MaestroSetProcessVariable",
  task_description = @Translation("The Maestro Engine's Set Process Variable task."),
)

Hierarchy

Expanded class hierarchy of MaestroSetProcessVariableTask

File

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

Namespace

Drupal\maestro\Plugin\EngineTasks
View source
class MaestroSetProcessVariableTask 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('Set Process Variable');
  }

  /**
   * {@inheritDoc}
   */
  public function description() {
    return $this
      ->t('Sets a process variable to the desired value.');
  }

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

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

  /**
   * Part of the ExecutableInterface
   * Execution of the set process variable task.  We will read the data in the template for what we should do with the process variable
   * {@inheritdoc}.
   */
  public function execute() {
    $templateMachineName = MaestroEngine::getTemplateIdFromProcessId($this->processID);
    $taskMachineName = MaestroEngine::getTaskIdFromQueueId($this->queueID);
    $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskMachineName);
    $spv = $task['data']['spv'];
    $variable = $spv['variable'];
    $variableValue = $spv['variable_value'];
    switch ($spv['method']) {
      case 'addsubtract':

        // Simple here.. our value is a floatval.  This can be negative or positive.  Just add it to the current process variable.
        $processVar = MaestroEngine::getProcessVariable($variable, $this->processID);
        $processVar = $processVar + $variableValue;
        MaestroEngine::setProcessVariable($variable, $processVar, $this->processID);
        return TRUE;

        // Completes the task here.
        break;
      case 'hardcoded':

        // As easy as just taking the variable's value and setting it to what the template tells us to do.
        MaestroEngine::setProcessVariable($variable, $variableValue, $this->processID);
        return TRUE;

        // Completes the task here.
        break;
      case 'bycontentfunction':

        // [0] is our function, the rest are arguments
        $arr = explode(':', $variableValue);
        $arguments = explode(',', $arr[1]);
        $arguments[] = $this->queueID;
        $arguments[] = $this->processID;
        $newValue = call_user_func_array($arr[0], $arguments);
        MaestroEngine::setProcessVariable($variable, $newValue, $this->processID);
        return TRUE;

        // Completes the task here.
        break;
    }

    // We are relying on the base trait's default values to set the execution and completion status.
  }

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

  //not interactive.. we do nothing

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

  //not interactive.. we do nothing.

  /**
   * {@inheritDoc}
   */
  public function getTaskEditForm(array $task, $templateMachineName) {
    $spv = $task['data']['spv'];
    $form = [
      '#markup' => $this
        ->t('Editing the Process Variable Task'),
    ];
    $form['spv'] = [
      '#tree' => TRUE,
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Choose which process variable you wish to set and how'),
      '#collapsed' => FALSE,
    ];
    $variables = MaestroEngine::getTemplateVariables($templateMachineName);
    $options = [];
    foreach ($variables as $variableName => $arr) {
      $options[$variableName] = $variableName;
    }
    $form['spv']['variable'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Choose the variable'),
      '#required' => TRUE,
      '#default_value' => isset($spv['variable']) ? $spv['variable'] : '',
      '#options' => $options,
    ];

    // TODO: add other options here such as the content field result
    // however, the content field result needs to be rethought on how we're leveraging content.
    $form['spv']['method'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Method to set variable'),
      '#options' => [
        'hardcoded' => $this
          ->t('Hardcoded Value'),
        'addsubtract' => $this
          ->t('Add or Subtract a Value'),
        'bycontentfunction' => $this
          ->t('By Function. Pass "function_name:parameter1,parameter2,..." in variable
                                          as comma separated list. e.g. maestro_spv_content_value_fetch:unique_identifier,field_your_field'),
      ],
      '#default_value' => isset($spv['method']) ? $spv['method'] : '',
      '#required' => TRUE,
    ];
    $form['spv']['variable_value'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Variable value'),
      '#description' => $this
        ->t('The value you wish to set the variable to based on your METHOD selection above'),
      '#default_value' => isset($spv['variable_value']) ? $spv['variable_value'] : '',
      '#required' => TRUE,
    ];
    return $form;
  }

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

    // These are the set process variable values.
    $spv = $form_state
      ->getValue('spv');
    switch ($spv['method']) {
      case 'addsubtract':
        $addSubValue = $spv['variable_value'];
        $float = floatval($addSubValue);
        if (strcmp($float, $addSubValue) != 0) {
          $form_state
            ->setErrorByName('spv][variable_value', $this
            ->t('The add or subtract mechanism requires numerical values only.'));
        }
        break;
      case 'hardcoded':

        // We don't care what they hard code a variable to quite frankly.  But we at least trap the case here
        // in the event we need to do some preprocessing on it in the future.  Hook?
        break;
      case 'bycontentfunction':

        // In here we use the variable value and parse out the function, content type and field we wish to fetch.
        $variable = $spv['variable_value'];

        // Remove spaces.
        $variable = str_replace(' ', '', $variable);
        $arr = explode(':', $variable);
        if (!function_exists($arr[0])) {

          // Bad function!
          $form_state
            ->setErrorByName('spv][variable_value', $this
            ->t("The function name you provided doesn't exist."));
        }
        break;
    }
  }

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

  /**
   * {@inheritDoc}
   */
  public function performValidityCheck(array &$validation_failure_tasks, array &$validation_information_tasks, array $task) {
    $data = $task['data']['spv'];
    if (array_key_exists('variable', $data) && $data['variable'] == '' || !array_key_exists('variable', $data)) {
      $validation_failure_tasks[] = [
        'taskID' => $task['id'],
        'taskLabel' => $task['label'],
        'reason' => t('The SPV Task has not been set up properly.  The variable you wish to set is missing and thus the engine will be unable to execute this task.'),
      ];
    }
    if (array_key_exists('method', $data) && $data['method'] == '' || !array_key_exists('method', $data)) {
      $validation_failure_tasks[] = [
        'taskID' => $task['id'],
        'taskLabel' => $task['label'],
        'reason' => t('The SPV Task has not been set up properly.  The method you wish to set the variable with is missing and thus the engine will be unable to execute this task.'),
      ];
    }

    // We can have a blank value.... perhaps not in the form, but certainly in code.
    if (!array_key_exists('variable_value', $data)) {
      $validation_failure_tasks[] = [
        'taskID' => $task['id'],
        'taskLabel' => $task['label'],
        'reason' => t('The SPV Task has not been set up properly.  The variable value you wish to set the variable to is missing and thus the engine will be unable to execute this task.'),
      ];
    }
  }

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

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::execute public function Part of the ExecutableInterface Execution of the set process variable task. We will read the data in the template for what we should do with the process variable . Overrides ExecutableInterface::execute
MaestroSetProcessVariableTask::getExecutableForm public function Gets the Maestro executable form for a task console. Overrides MaestroEngineTaskInterface::getExecutableForm
MaestroSetProcessVariableTask::getPluginId public function Overrides PluginBase::getPluginId
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::getTaskEditForm public function Method to allow a task to add their own fields to the task edit form. Overrides MaestroEngineTaskInterface::getTaskEditForm
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::prepareTaskForSave public function The specific task's manipulation of the values to save for a template save. Overrides MaestroEngineTaskInterface::prepareTaskForSave
MaestroSetProcessVariableTask::shortDescription public function Get the task's short description. Useful for things like labels. Overrides MaestroEngineTaskInterface::shortDescription
MaestroSetProcessVariableTask::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
MaestroSetProcessVariableTask::__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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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 3
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.