You are here

class WebformContentCreatorUtilities in Webform Content Creator 8

Same name and namespace in other branches
  1. 3.x src/WebformContentCreatorUtilities.php \Drupal\webform_content_creator\WebformContentCreatorUtilities
  2. 2.x src/WebformContentCreatorUtilities.php \Drupal\webform_content_creator\WebformContentCreatorUtilities

Provides useful functions required in Webform content creator module.

Hierarchy

Expanded class hierarchy of WebformContentCreatorUtilities

3 files declare their use of WebformContentCreatorUtilities
WebformContentCreatorEntity.php in src/Entity/WebformContentCreatorEntity.php
WebformContentCreatorForm.php in src/Form/WebformContentCreatorForm.php
WebformContentCreatorManageFieldsForm.php in src/Form/WebformContentCreatorManageFieldsForm.php

File

src/WebformContentCreatorUtilities.php, line 11

Namespace

Drupal\webform_content_creator
View source
class WebformContentCreatorUtilities {
  const WEBFORM = 'webform';
  const WEBFORM_SUBMISSION = 'webform_submission';
  const ENTITY_TYPE_MANAGER = 'entity_type.manager';
  const ENTITY_MANAGER = 'entity_field.manager';
  const CONTENT_BASIC_FIELDS = [
    'body',
    'status',
    'uid',
  ];

  /**
   * Function to check whether an Webform content creator entity exists.
   *
   * @param string $id
   *   Webform Content Creator id.
   *
   * @return bool
   *   True, if the entity already exists.
   */
  public static function existsWebformContentCreatorEntity($id) {
    $entity = \Drupal::entityQuery('webform_content_creator')
      ->condition('id', $id)
      ->execute();
    return (bool) $entity;
  }

  /**
   * Contructs a tree with webform elements which can be used in Selects.
   *
   * @param array $elements
   *   Webform elements.
   *
   * @return array
   *   Tree with webform elements
   */
  private static function buildTree(array $elements) {
    $elementsDefinitions = \Drupal::service('plugin.manager.webform.element')
      ->getDefinitions();
    $layoutElements = [
      'webform_wizard_page',
      'container',
      'details',
      'fieldset',
      'webform_flexbox',
    ];
    $result = [];
    $webformFieldIds = array_keys($elements);

    // Default value, only used if there are no wizard pages in webform.
    $wizardPage = t('Webform elements');

    // Check which element is the first wizard page (in case it exists)
    $flag = 0;
    $aux = [];
    foreach ($webformFieldIds as $v) {
      if ($v === 'actions') {
        continue;
      }
      $title = 'Section';
      if (isset($elements[$v]['#title'])) {
        $title = $elements[$v]['#title'];
      }
      else {
        if (isset($elements[$v]['#markup'])) {
          $title = $elements[$v]['#markup'];
        }
      }
      if (in_array($elements[$v]["#type"], $layoutElements, TRUE)) {
        if ($elements[$v]["#webform_parent_key"] !== '') {
          continue;
        }

        // Executes only for the first wizard page (first optgroup in select)
        if ($flag === 0) {
          $wizardPage = html_entity_decode($title);
          unset($aux);
          $flag++;
          continue;
        }
        if (!empty($aux)) {
          foreach ($aux as $k2 => $v2) {
            $result[$wizardPage][$k2] = $v2;
          }
        }
        $wizardPage = html_entity_decode($title);
        unset($aux);
      }
      elseif ($elements[$v]["#webform_parent_key"] === '') {
        $result['0,' . $v] = html_entity_decode($title) . ' (' . $v . ') - ' . $elementsDefinitions[$elements[$v]["#type"]]['label'];
      }
      elseif ($elements[$v]["#type"] !== "webform_section") {
        $aux['0,' . $v] = html_entity_decode($title) . ' (' . $v . ') - ' . $elementsDefinitions[$elements[$v]["#type"]]['label'];
      }
    }

    // Organize webform elements as a tree (wizard pages as optgroups)
    foreach ($aux as $k2 => $v2) {
      $result[$wizardPage][$k2] = $v2;
    }
    return $result;
  }

  /**
   * Get webform elements and properties structured as a tree.
   *
   * @param string $webform_id
   *   Webform id.
   *
   * @return array
   *   Tree with webform elements and basic attributes.
   */
  public static function getWebformElements($webform_id) {
    $webform = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM)
      ->load($webform_id);
    $options = [];
    $submission_storage = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM_SUBMISSION);
    $field_definitions = $submission_storage
      ->checkFieldDefinitionAccess($webform, $submission_storage
      ->getFieldDefinitions());

    // Basic webform properties (sid, token, serial number ..)
    foreach ($field_definitions as $key => $field_definition) {
      if (isset($field_definition['type']) && !empty($field_definition['type'])) {
        $options['1,' . $key] = $field_definition['title'] . ' (' . $key . ') - ' . $field_definition['type'];
      }
    }

    // Webform elements.
    $elements = $webform
      ->getElementsInitializedAndFlattened();

    // Webform elements organized in a structured tree.
    $webformOptions = self::buildTree($elements);

    // Join with basic webform properties.
    $webformOptions[t('Webform properties')
      ->render()] = $options;
    return $webformOptions;
  }

  /**
   * Return array with all webform elements types.
   *
   * @param mixed $webform_id
   *   Webform id.
   *
   * @return array
   *   Webform basic attributes and element types
   */
  public static function getWebformElementsTypes($webform_id) {
    if (!isset($webform_id) || empty($webform_id)) {
      return NULL;
    }

    // Get webform entity.
    $webform = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM)
      ->load($webform_id);
    if (empty($webform)) {
      return NULL;
    }

    // Get webform submission storage.
    $submissionStorage = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM_SUBMISSION);
    $submissionStorageDefinitions = $submissionStorage
      ->getFieldDefinitions();
    if (empty($submissionStorageDefinitions)) {
      return NULL;
    }

    // Get webform basic attributes definitions.
    $fieldDefinitions = $submissionStorage
      ->checkFieldDefinitionAccess($webform, $submissionStorageDefinitions);
    if (empty($fieldDefinitions)) {
      return NULL;
    }

    // Get webform elements and merge with the webform basic attributes.
    $elements = $webform
      ->getElementsInitializedAndFlattened();
    if (is_array($elements)) {
      $webformFieldIds = array_keys($elements);
      foreach ($webformFieldIds as $v) {
        if (!isset($elements[$v]) || empty($elements[$v])) {
          continue;
        }
        $fieldDefinitions[$v] = $elements[$v]['#type'];
      }
    }
    return $fieldDefinitions;
  }

  /**
   * Return the content type fields.
   *
   * @param Drupal\node\Entity\NodeType $contentType
   *   Content type entity.
   *
   * @return array
   *   Content type fields
   */
  public static function contentTypeFields(NodeType $contentType) {
    $entityManager = \Drupal::service(self::ENTITY_MANAGER);
    $fields = [];
    if (!empty($contentType)) {
      $fields = $entityManager
        ->getFieldDefinitions('node', $contentType
        ->getOriginalId());
    }
    return $fields;
  }

  /**
   * Get content type fields, except the basic fields from node type entity.
   *
   * @param Drupal\node\Entity\NodeType $contentType
   *   Content type entity.
   *
   * @return array
   *   Associative array Content type fields
   */
  public static function getContentFieldsIds(NodeType $contentType) {
    $nodeFields = self::contentTypeFields($contentType);
    $nodeFieldIds = array_keys($nodeFields);
    return array_filter($nodeFieldIds, function ($fid) {
      return strpos($fid, 'field_') === 0 || in_array($fid, self::CONTENT_BASIC_FIELDS);
    });
  }

  /**
   * Get all content type ids.
   *
   * @return array
   *   Array with all content type ids.
   */
  public static function getAllContentTypeIds() {
    return \Drupal::service(self::ENTITY_TYPE_MANAGER)
      ->getStorage('node_type')
      ->getQuery()
      ->execute();
  }

  /**
   * Get all content type entities.
   *
   * @return array
   *   All content type entities.
   */
  public static function getAllContentTypes() {
    $ids = self::getAllContentTypeIds();
    return \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->loadMultiple(array_keys($ids));
  }

  /**
   * Get an associative array with content type ids and respective labels.
   *
   * @return array
   *   Associative array with content type ids and labels.
   */
  public static function getFormattedContentTypes() {
    $contentTypes = self::getAllContentTypes();
    $contentTypes_formatted = [];
    foreach ($contentTypes as $k => $v) {
      $contentTypes_formatted[$k] = $v
        ->label();
    }
    return $contentTypes_formatted;
  }

  /**
   * Get all webform ids.
   *
   * @return array
   *   Array with all webform ids.
   */
  public static function getAllWebformIds() {
    $ids = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM)
      ->getQuery()
      ->condition('template', FALSE)
      ->execute();
    return $ids;
  }

  /**
   * Get all webform entities.
   *
   * @return array
   *   All webform entities.
   */
  public static function getAllWebforms() {
    $ids = self::getAllWebformIds();
    $webforms = \Drupal::entityTypeManager()
      ->getStorage(self::WEBFORM)
      ->loadMultiple(array_keys($ids));
    return $webforms;
  }

  /**
   * Get an associative array with webform ids and respective labels.
   *
   * @return array
   *   Associative array with webform ids and labels.
   */
  public static function getFormattedWebforms() {
    $webforms = self::getAllWebforms();
    $webforms_formatted = [];
    foreach ($webforms as $k => $v) {
      $category = $v
        ->get('category');
      if (empty($category)) {
        $webforms_formatted[$k] = $v
          ->label();
      }
      else {
        $webforms_formatted[$category][$k] = $v
          ->label();
      }
    }
    return $webforms_formatted;
  }

  /**
   * Get an associative array with encryption profiles and respective labels.
   *
   * @return array
   *   Associative array with encryption profiles ids and labels.
   */
  public static function getFormattedEncryptionProfiles() {
    $encryption_profiles = [];
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler
      ->moduleExists('encrypt')) {
      $encryption_profiles = \Drupal::service(self::ENTITY_TYPE_MANAGER)
        ->getStorage('encryption_profile')
        ->loadMultiple();
    }
    $encryption_profiles_formatted = [];
    foreach ($encryption_profiles as $k => $v) {
      $encryption_profiles_formatted[$k] = $v
        ->label();
    }
    return $encryption_profiles_formatted;
  }

  /**
   * Get decrypted value.
   *
   * @param string $value
   *   Encrypted value.
   * @param string $encryption_profile
   *   Encryption profile.
   *
   * @return string
   *   Decrypted value
   */
  public static function getDecryptedValue($value, $encryption_profile) {
    if (empty($value) || empty($encryption_profile)) {
      return '';
    }
    $dec_value = \Drupal::service('encryption')
      ->decrypt($value, $encryption_profile);
    if ($dec_value === FALSE) {
      $dec_value = $value;
    }
    return $dec_value;
  }

  /**
   * Get decrypted values inside text with tokens.
   *
   * @param string $value
   *   String with tokens.
   * @param string $encryption_profile
   *   Encryption profile.
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   *   Webform submission.
   * @param string $type
   *   Token type.
   *
   * @return string
   *   Token value.
   */
  public static function getDecryptedTokenValue($value, $encryption_profile, WebformSubmissionInterface $webform_submission, $type = self::WEBFORM_SUBMISSION) {
    if (empty($value) || empty($webform_submission)) {
      return '';
    }

    // Get tokens in string.
    $tokens = \Drupal::token()
      ->scan($value);
    $token_keys = [];
    $token_values = [];
    if (empty($tokens)) {
      return $value;
    }
    foreach ($tokens[$type] as $val) {
      $token_value = \Drupal::token()
        ->replace($val, [
        self::WEBFORM_SUBMISSION => $webform_submission,
      ]);
      if (!empty($encryption_profile)) {

        // Decrypt single token value.
        $dec_token_value = self::getDecryptedValue($token_value, $encryption_profile);
      }
      else {
        $dec_token_value = $token_value;
      }
      $token_keys[] = $val;
      $token_values[] = $dec_token_value;
    }
    if (empty($token_values)) {
      return $value;
    }

    // Replace all token values in string.
    $dec_value = str_replace($token_keys, $token_values, $value);
    return $dec_value;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
WebformContentCreatorUtilities::buildTree private static function Contructs a tree with webform elements which can be used in Selects.
WebformContentCreatorUtilities::contentTypeFields public static function Return the content type fields.
WebformContentCreatorUtilities::CONTENT_BASIC_FIELDS constant
WebformContentCreatorUtilities::ENTITY_MANAGER constant
WebformContentCreatorUtilities::ENTITY_TYPE_MANAGER constant
WebformContentCreatorUtilities::existsWebformContentCreatorEntity public static function Function to check whether an Webform content creator entity exists.
WebformContentCreatorUtilities::getAllContentTypeIds public static function Get all content type ids.
WebformContentCreatorUtilities::getAllContentTypes public static function Get all content type entities.
WebformContentCreatorUtilities::getAllWebformIds public static function Get all webform ids.
WebformContentCreatorUtilities::getAllWebforms public static function Get all webform entities.
WebformContentCreatorUtilities::getContentFieldsIds public static function Get content type fields, except the basic fields from node type entity.
WebformContentCreatorUtilities::getDecryptedTokenValue public static function Get decrypted values inside text with tokens.
WebformContentCreatorUtilities::getDecryptedValue public static function Get decrypted value.
WebformContentCreatorUtilities::getFormattedContentTypes public static function Get an associative array with content type ids and respective labels.
WebformContentCreatorUtilities::getFormattedEncryptionProfiles public static function Get an associative array with encryption profiles and respective labels.
WebformContentCreatorUtilities::getFormattedWebforms public static function Get an associative array with webform ids and respective labels.
WebformContentCreatorUtilities::getWebformElements public static function Get webform elements and properties structured as a tree.
WebformContentCreatorUtilities::getWebformElementsTypes public static function Return array with all webform elements types.
WebformContentCreatorUtilities::WEBFORM constant
WebformContentCreatorUtilities::WEBFORM_SUBMISSION constant