niobi-8.x-2.0-alpha4/modules/niobi_form/modules/niobi_app/src/Plugin/WebformHandler/NiobiAppQueueEmailWebformHandler.php
modules/niobi_form/modules/niobi_app/src/Plugin/WebformHandler/NiobiAppQueueEmailWebformHandler.php
<?php
namespace Drupal\niobi_app\Plugin\WebformHandler;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\niobi_app\NiobiAppUtilities;
use Drupal\task\TaskUtilities;
use Drupal\webform\Element\WebformHtmlEditor;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionConditionsValidatorInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformTokenManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Webform submission action handler.
*
* @WebformHandler(
* id = "niobi_app_queue_email",
* label = @Translation("Niobi Applications: Queue Email"),
* category = @Translation("Niobi Applications"),
* description = @Translation("Queue an email to send."),
* cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
* tokens = TRUE,
* )
*/
class NiobiAppQueueEmailWebformHandler extends WebformHandlerBase {
/**
* The webform token manager.
*
* @var \Drupal\webform\WebformTokenManagerInterface
*/
protected $tokenManager;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerChannelFactoryInterface $logger_factory, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, WebformSubmissionConditionsValidatorInterface $conditions_validator, WebformTokenManagerInterface $token_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $logger_factory, $config_factory, $entity_type_manager, $conditions_validator);
$this->tokenManager = $token_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('logger.factory'),
$container->get('config.factory'),
$container->get('entity_type.manager'),
$container->get('webform_submission.conditions_validator'),
$container->get('webform.token_manager')
);
}
/**
* {@inheritdoc}
*/
public function getSummary() {
$configuration = $this->getConfiguration();
$settings = $configuration['settings'];
// Get state labels.
$states = [
NiobiAppUtilities::EVENT_APPLICATION_SUBMITTED => $this->t('Draft created'),
];
$settings['states'] = array_intersect_key($states, array_combine($settings['states'], $settings['states']));
// Get message type.
$message_types = [
'status' => t('Status'),
'error' => t('Error'),
'warning' => t('Warning'),
'info' => t('Info'),
];
$settings['message'] = $settings['message'] ? WebformHtmlEditor::checkMarkup($settings['message']) : NULL;
$settings['message_type'] = $message_types[$settings['message_type']];
// Get data element keys.
$data = Yaml::decode($settings['data']) ?: [];
$settings['data'] = array_keys($data);
return [
'#settings' => $settings,
] + parent::getSummary();
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'states' => NiobiAppUtilities::EVENT_APPLICATION_SUBMITTED,
'actions' => [],
'from_address' => '',
'to_address' => '',
'email_subject' => '',
'email_message' => '',
'debug' => FALSE,
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$results_disabled = $this->getWebform()->getSetting('results_disabled');
$form['trigger'] = [
'#type' => 'fieldset',
'#title' => $this->t('Trigger'),
];
$form['trigger']['states'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Execute'),
'#options' => [
NiobiAppUtilities::EVENT_APPLICATION_SUBMITTED => $this->t('When the application is submitted for review'),
],
'#required' => TRUE,
'#access' => $results_disabled ? FALSE : TRUE,
'#default_value' => $results_disabled ? NiobiAppUtilities::EVENT_APPLICATION_SUBMITTED : $this->configuration['states'],
];
$form['actions'] = [
'#type' => 'fieldset',
'#title' => $this->t('Actions'),
];
$form['actions']['from_address'] = [
'#type' => 'webform_codemirror',
'#mode' => 'text',
'#title' => $this->t('From Address'),
'#default_value' => $this->configuration['from_address'] ? $this->configuration['from_address'] : '[site:mail]',
];
$form['actions']['to_address'] = [
'#type' => 'webform_codemirror',
'#mode' => 'text',
'#title' => $this->t('To Address'),
'#default_value' => $this->configuration['to_address'],
];
$form['actions']['email_subject'] = [
'#type' => 'webform_codemirror',
'#mode' => 'text',
'#title' => $this->t('Email Subject'),
'#default_value' => $this->configuration['email_subject'],
];
$form['actions']['email_message'] = [
'#type' => 'webform_html_editor',
'#title' => $this->t('Email message'),
'#default_value' => $this->configuration['email_message'],
];
$elements_rows = [];
$elements = $this->getWebform()->getElementsInitializedFlattenedAndHasValue();
foreach ($elements as $element_key => $element) {
$elements_rows[] = [
$element_key,
(isset($element['#title']) ? $element['#title'] : ''),
];
}
$form['actions']['elements'] = [
'#type' => 'details',
'#title' => $this->t('Available element keys'),
'element_keys' => [
'#type' => 'table',
'#header' => [$this->t('Element key'), $this->t('Element title')],
'#rows' => $elements_rows,
],
];
$form['actions']['token_tree_link'] = $this->buildTokenTreeElement();
// Development.
$form['development'] = [
'#type' => 'details',
'#title' => $this->t('Development settings'),
];
$form['development']['debug'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable debugging'),
'#description' => $this->t('If checked, trigger actions will be displayed onscreen to all users.'),
'#return_value' => TRUE,
'#default_value' => $this->configuration['debug'],
];
$this->elementTokenValidate($form);
return $this->setSettingsParents($form);
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
if ($form_state->hasAnyErrors()) {
return;
}
// Validate data element keys.
$elements = $this->getWebform()->getElementsInitializedFlattenedAndHasValue();
$data = Yaml::decode($form_state->getValue('data')) ?: [];
foreach ($data as $key => $value) {
if (!isset($elements[$key])) {
$form_state->setErrorByName('data', $this->t('%key is not valid element key.', ['%key' => $key]));
}
}
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$this->applyFormStateToConfiguration($form_state);
// Set the actions array.
$values = $form_state->getValues();
foreach ($values['actions'] as $key => $value) {
if (array_key_exists($key, $this->configuration)) {
$this->configuration[$key] = $value;
}
}
}
/**
* {@inheritdoc}
*/
public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
// This handler always runs
$this->executeAction($webform_submission);
}
/****************************************************************************/
// Action helper methods.
/****************************************************************************/
/**
* Execute this action.
*
* @param \Drupal\webform\WebformSubmissionInterface $webform_submission
* A webform submission.
*/
protected function executeAction(WebformSubmissionInterface $webform_submission) {
if ($webform_submission->isCompleted()) {
$task_email_data = [];
foreach ($this->configuration as $key => $value) {
if ($value !== NULL) {
$task_email_data[$key] = $this->replaceTokens($value, $webform_submission);
}
}
$send = TRUE;
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$params['from'] = $task_email_data['from_address'];
$params['subject'] = $task_email_data['email_subject'];
$params['message'] = $task_email_data['email_message'];
$notification_task = [
'type' => 'niobi_notification_task',
'name' => t('Notification'),
'expire_date' => NULL, // Does not expire
'field_trigger_type' => 'niobi_app_submit_application',
'task_data' => [
'actions' => [
'trigger' => [
'send_mail' => [
'module' => 'task',
'key' => 'task_mail',
'to' => $task_email_data['to_address'],
'langcode' => $langcode,
'params' => $params,
'reply' => NULL,
'send' => $send,
],
],
],
],
];
TaskUtilities::createTask($notification_task);
}
}
}
