You are here

function yamlform_update_8067 in YAML Form 8

Issue #2825410: Allow forms labels to be translatable.

See also

\Drupal\config_translation\Form\ConfigTranslationFormBase::submitForm

File

includes/yamlform.update.inc, line 1319
YAML Form module update hooks.

Code

function yamlform_update_8067(&$sandbox) {

  // Skip updates if the Configuration translation module is not enabled.
  if (!\Drupal::moduleHandler()
    ->moduleExists('config_translation')) {
    return;
  }
  $language_manager = \Drupal::languageManager();

  /** @var \Drupal\yamlform\YamlFormElementManagerInterface $element_manager */
  $element_manager = \Drupal::service('plugin.manager.yamlform.element');
  $languages = $language_manager
    ->getLanguages();
  unset($languages[$language_manager
    ->getDefaultLanguage()
    ->getId()]);
  foreach ($languages as $langcode => $language) {
    $config_factory = \Drupal::configFactory();
    foreach ($config_factory
      ->listAll('yamlform.yamlform.') as $yamlform_config_name) {

      /** @var Drupal\language\Config\LanguageConfigOverride $config_translation */
      $config_translation = $language_manager
        ->getLanguageConfigOverride($langcode, $yamlform_config_name);
      $config_elements = $config_translation
        ->get('elements');
      if (empty($config_elements)) {
        continue;
      }

      // Flatten and get any array containging translatable properties.
      // @see \Drupal\yamlform\YamlFormTranslationManager::getBaseElements()
      $elements = Yaml::decode($config_elements);
      $elements = YamlFormElementHelper::getFlattened($elements);
      $translatable_properties = YamlFormArrayHelper::addPrefix($element_manager
        ->getTranslatableProperties());
      foreach ($elements as $element_key => &$element) {
        foreach ($element as $property_key => $property_value) {
          $translatable_property_key = $property_key;
          if (preg_match('/^.*__(.*)$/', $translatable_property_key, $match)) {
            $translatable_property_key = '#' . $match[1];
          }
          if (in_array($translatable_property_key, [
            '#options',
            '#answers',
          ]) && is_string($property_value)) {
            unset($element[$property_key]);
          }
          elseif (!isset($translatable_properties[$translatable_property_key])) {
            unset($element[$property_key]);
          }
        }
        if (empty($element)) {
          unset($elements[$element_key]);
        }
      }

      // DEBUG:
      // drush_print($yamlform_config_name); drush_print($config_elements); drush_print(Yaml::encode($elements));
      $config_translation
        ->set('elements', Yaml::encode($elements))
        ->save();
    }
  }
}