You are here

abstract class WebformDevelEntityFormApiBaseForm in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_devel/src/Form/WebformDevelEntityFormApiBaseForm.php \Drupal\webform_devel\Form\WebformDevelEntityFormApiBaseForm

Export a webform's element to Form API (FAPI).

Hierarchy

Expanded class hierarchy of WebformDevelEntityFormApiBaseForm

File

modules/webform_devel/src/Form/WebformDevelEntityFormApiBaseForm.php, line 12

Namespace

Drupal\webform_devel\Form
View source
abstract class WebformDevelEntityFormApiBaseForm extends EntityForm {

  /**
   * The archiver manager.
   *
   * @var \Drupal\Core\Archiver\ArchiverManager
   */
  protected $archiverManager;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The webform submission generator service.
   *
   * @var \Drupal\webform\WebformSubmissionGenerateInterface
   */
  protected $generate;

  /**
   * The webform token manager.
   *
   * @var \Drupal\webform\WebformTokenManagerInterface
   */
  protected $tokenManager;

  /**
   * The webform element plugin manager.
   *
   * @var \Drupal\webform\Plugin\WebformElementManagerInterface
   */
  protected $elementManager;

  /**
   * An array of translatable properties.
   *
   * @var array
   */
  protected $translatableProperties;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = new static();
    $instance->archiverManager = $container
      ->get('plugin.manager.archiver');
    $instance->renderer = $container
      ->get('renderer');
    $instance->generate = $container
      ->get('webform_submission.generate');
    $instance->tokenManager = $container
      ->get('webform.token_manager');
    $instance->elementManager = $container
      ->get('plugin.manager.webform.element');
    $instance
      ->initialize();
    return $instance;
  }

  /**
   * Initialize WebformDevelEntityFormApiBaseForm object.
   */
  protected function initialize() {
    $translatable_properties = $this->elementManager
      ->getTranslatableProperties();
    $translatable_properties = array_combine($translatable_properties, $translatable_properties);
    unset($translatable_properties['default_value']);
    $this->translatableProperties = $translatable_properties;
  }

  /****************************************************************************/

  // Helper functions.

  /****************************************************************************/

  /**
   * Cleanup webform elements.
   *
   * @param array $elements
   *   An render array representing elements.
   */
  protected function cleanupElements(array &$elements) {
    foreach ($elements as $element_key => $element) {
      if (isset($element['#type'])) {
        switch ($element['#type']) {

          // Remove unsupported element types.
          case 'webform_actions':
            unset($elements[$element_key]);
            break;

          // Convert wizard pages to fieldset.
          case 'webform_wizard':
            $element['#type'] = 'fieldset';
            break;
        }
      }

      // Recursively cleanup child elements.
      if (Element::child($element_key) && is_array($element)) {
        $this
          ->cleanupElements($element);
      }
    }
  }

  /**
   * Export a PHP render array.
   *
   * @param array $form
   *   A form.
   * @param string $prefix
   *   The render arrays prefix.
   *
   * @return string
   *   Returns the variable representation of the render array.
   */
  protected function renderExport(array $form, $prefix = '$form') {
    $output = '';
    foreach ($form as $element_key => $element) {
      $element_prefix = $prefix . "['" . $element_key . "']";
      if (!is_array($element)) {
        $output .= $element_prefix . '[' . $element_key . '] = ' . var_export($element, TRUE) . ';' . PHP_EOL;
      }
      elseif ($prefix === '$form' && !Element::child($element_key)) {
        $output .= $element_prefix . ' = ' . $this
          ->varExport($element, TRUE) . ';' . PHP_EOL;
      }
      else {
        $element_plugin = is_array($element) ? $this->elementManager
          ->getElementInstance($element) : NULL;
        $element_children = [];
        $element_export = [];
        foreach ($element as $property => $value) {
          if (Element::child($property)) {
            $element_children[$property] = $value;
          }
          elseif ($this
            ->isPropertyTranslatable($property)) {
            $element_export[$property] = $this
              ->wrapTranslatableValue($value);
          }
          else {
            $element_export[$property] = $value;
          }
        }

        // Add comment for main container element.
        if ($prefix === '$form' && $element_plugin && $element_plugin
          ->isContainer($element)) {
          $output .= PHP_EOL . '// ' . $element_plugin
            ->getAdminLabel($element) . '.' . PHP_EOL;
        }
        $output .= $element_prefix . ' = ' . $this
          ->varExport($element_export, TRUE) . ';' . PHP_EOL;
        $output .= $this
          ->renderExport($element_children, $element_prefix);
      }
    }
    $output = str_replace("'<T>", "\$this->t('", $output);
    $output = str_replace("</T>'", "')", $output);
    return $output;
  }

  /**
   * Wrap translatable value in <T> tags.
   *
   * @param mixed $value
   *   A translatable value.
   *
   * @return array|string
   *   A translatable value in <T> tags.
   */
  protected function wrapTranslatableValue($value) {
    if (is_array($value)) {
      foreach ($value as $key => $item) {
        $value[$key] = $this
          ->wrapTranslatableValue($item);
      }
      return $value;
    }
    else {
      return '<T>' . $value . '</T>';
    }
  }

  /**
   * Determine if an element property is translatable.
   *
   * @param string $property
   *   An element property.
   *
   * @return bool
   *   TRUE if an element property is translatable.
   */
  protected function isPropertyTranslatable($property) {
    $property = str_replace('#', '', $property);
    if (strpos($property, '__') !== FALSE) {
      list(, $child_property) = explode('__', $property);
      return isset($this->translatableProperties[$child_property]);
    }
    else {
      return isset($this->translatableProperties[$property]);
    }
  }

  /**
   * Outputs string representation of a variable using array short syntax.
   *
   * @param mixed $expression
   *   The variable you want to export.
   * @param bool $return
   *   If used and set to TRUE, var_export() will return the variable
   *   representation instead of outputting it.
   *
   * @return string
   *   Returns the variable representation when the return parameter is used and
   *   evaluates to TRUE. Otherwise, this function will return NULL.
   */
  protected function varExport($expression, $return = FALSE) {

    // Export variable using array short syntax.
    // @see https://gist.github.com/Bogdaan/ffa287f77568fcbb4cffa0082e954022
    $export = var_export($expression, TRUE);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace([
      "/\\s*array\\s\\(\$/",
      "/\\)(,)?\$/",
      "/\\s=>\\s\$/",
    ], [
      NULL,
      ']$1',
      ' => [',
    ], $array);
    $export = implode(PHP_EOL, array_filter([
      "[",
    ] + $array));

    // Clean up output to match Drupal coding guidelines.
    $export = str_replace('    ', '  ', $export);
    $export = str_replace('=> true,', '=> TRUE,', $export);
    $export = str_replace('=> false,', '=> FALSE,', $export);
    $export = preg_replace('/\\d+ => /', '', $export);
    if ($return) {
      return $export;
    }
    else {
      echo $export;
    }
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 11
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 35
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 3
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 9
EntityForm::form public function Gets the actual form array to be built. 36
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 47
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 20
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
WebformDevelEntityFormApiBaseForm::$archiverManager protected property The archiver manager.
WebformDevelEntityFormApiBaseForm::$elementManager protected property The webform element plugin manager.
WebformDevelEntityFormApiBaseForm::$generate protected property The webform submission generator service.
WebformDevelEntityFormApiBaseForm::$renderer protected property The renderer.
WebformDevelEntityFormApiBaseForm::$tokenManager protected property The webform token manager.
WebformDevelEntityFormApiBaseForm::$translatableProperties protected property An array of translatable properties.
WebformDevelEntityFormApiBaseForm::cleanupElements protected function Cleanup webform elements.
WebformDevelEntityFormApiBaseForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformDevelEntityFormApiBaseForm::initialize protected function Initialize WebformDevelEntityFormApiBaseForm object.
WebformDevelEntityFormApiBaseForm::isPropertyTranslatable protected function Determine if an element property is translatable.
WebformDevelEntityFormApiBaseForm::renderExport protected function Export a PHP render array.
WebformDevelEntityFormApiBaseForm::varExport protected function Outputs string representation of a variable using array short syntax.
WebformDevelEntityFormApiBaseForm::wrapTranslatableValue protected function Wrap translatable value in <T> tags.