You are here

class Schemas in Express 8

The "schemas" theme setting.

Plugin annotation


@BootstrapSetting(
  id = "schemas",
  type = "hidden",
  weight = -20,
  groups = false,
)

Hierarchy

Expanded class hierarchy of Schemas

File

themes/contrib/bootstrap/src/Plugin/Setting/Schemas.php, line 29
Contains \Drupal\bootstrap\Plugin\Setting\Schemas.

Namespace

Drupal\bootstrap\Plugin\Setting
View source
class Schemas extends SettingBase {

  /**
   * {@inheritdoc}
   */
  public function alterFormElement(Element $form, FormStateInterface $form_state, $form_id = NULL) {
    parent::alterFormElement($form, $form_state, $form_id);
    $updates = [];
    foreach ($this->theme
      ->getPendingUpdates() as $version => $update) {
      $row = [];
      $row[] = $update
        ->getSchema();
      $row[] = new FormattableMarkup('<strong>@title</strong><p class="help-block">@description</p>', [
        '@title' => $update
          ->getLabel(),
        '@description' => $update
          ->getDescription(),
      ]);
      $row[] = $update
        ->getTheme()
        ->getTitle();
      $updates[] = [
        'class' => [
          $update
            ->getSeverity() ?: 'default',
        ],
        'data' => $row,
      ];
    }
    $form['update'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Theme Updates'),
      '#panel_type' => !!$updates ? 'primary' : 'default',
      '#open' => !!$updates,
      '#weight' => -20,
    ];
    $form['update']['table'] = [
      '#type' => 'table',
      '#header' => [
        t('Schema'),
        t('Description'),
        t('Provider'),
      ],
      '#empty' => t('There are currently no pending updates for this theme.'),
      '#rows' => $updates,
    ];
    if ($updates) {
      $form['update']['actions'] = [
        '#type' => 'actions',
      ];
      $form['update']['actions']['update'] = [
        '#type' => 'submit',
        '#value' => t('Update theme'),
        '#icon' => Bootstrap::glyphicon('open'),
        // @todo Setting a class like this is undesirable, create a suggestion.
        '#attributes' => [
          'class' => [
            'btn-primary',
          ],
        ],
        '#submit' => [
          [
            get_class($this),
            'updateTheme',
          ],
        ],
      ];
    }
  }

  /**
   * Callback for updating a theme.
   *
   * @param array $form
   *   Nested array of form elements that comprise the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public static function updateTheme(array $form, FormStateInterface $form_state) {
    if ($theme = SystemThemeSettings::getTheme($form, $form_state)) {

      // Due to the fact that the batch API stores it's arguments in DB storage,
      // theme based objects cannot be passed as an operation argument here.
      // During _batch_page(), the DB item will attempt to restore the arguments
      // using unserialize() and the autoload fix include added below may not
      // yet have been invoked to register the theme namespaces. So instead,
      // we capture the relevant information needed to reconstruct these objects
      // in the batch processing callback.
      $theme_name = $theme
        ->getName();

      // Create an operation for each update.
      $operations = [];
      foreach ($theme
        ->getPendingUpdates() as $update) {
        $operations[] = [
          [
            __CLASS__,
            'batchProcessUpdate',
          ],
          [
            $theme_name,
            $update
              ->getProvider() . ':' . $update
              ->getSchema(),
          ],
        ];
      }
      if ($operations) {
        $variables = [
          '@theme_title' => $theme
            ->getTitle(),
        ];
        batch_set([
          'operations' => $operations,
          'finished' => [
            __CLASS__,
            'batchFinished',
          ],
          'title' => t('Updating @theme_title', $variables),
          'init_message' => \Drupal::translation()
            ->formatPlural(count($operations), 'Initializing 1 theme update for @theme_title...', 'Initializing @count theme updates for @theme_title...', $variables),
          'progress_message' => t('Processing update @current of @total...', $variables),
          'error_message' => t('An error was encountered while attempting to update the @theme_title theme.', $variables),
          'file' => Bootstrap::autoloadFixInclude(),
        ]);
      }
    }
  }

  /**
   * Processes an update in a batch operation.
   *
   * @param string $theme_name
   *  The machine name of the theme this update is being applied to.
   * @param string $update_id
   *   The combined identifier of the update being applied, e.g.
   *   provider:schema.
   * @param array $context
   *   The batch context.
   */
  public static function batchProcessUpdate($theme_name, $update_id, array &$context) {

    // Reconstruct the theme object this update is being applied to.
    $theme = Bootstrap::getTheme($theme_name);

    // Reconstruct the update plugin that is being applied.
    list($provider, $plugin_id) = explode(':', $update_id);
    $provider = Bootstrap::getTheme($provider);

    /** @type \Drupal\bootstrap\Plugin\Update\UpdateInterface $update */
    $update = $provider
      ->getUpdateManager()
      ->createInstance($plugin_id, [
      'theme' => $provider,
    ]);

    // Initialize results with theme name and installed schemas.
    if (!isset($context['results']['theme_name'])) {
      $context['results']['theme_name'] = $theme_name;
    }
    if (!isset($context['results']['schemas'])) {
      $context['results']['schemas'] = $theme
        ->getSetting('schemas', []);
    }
    $schemas =& $context['results']['schemas'];
    $variables = [
      '@theme' => $update
        ->getTheme()
        ->getName(),
      '@schema' => $update
        ->getSchema(),
      '@label' => $update
        ->getLabel(),
    ];

    // Perform the update.
    try {

      // Attempt to perform the update.
      if ($update
        ->update($theme, $context) === FALSE) {
        throw new \Exception(t('Update failed'));
      }

      // Store the results.
      $schemas[$update
        ->getTheme()
        ->getName()] = $update
        ->getSchema();
      $context['results']['success'][] = t('<strong>[@theme][@schema] @label</strong>', $variables);
    } catch (\Exception $e) {
      $variables['@message'] = $e
        ->getMessage();
      $context['results']['errors'][] = t('<strong>[@theme][@schema] @label</strong> - @message', $variables);
    }
  }

  /**
   * Batch 'finished' callback
   *
   * @param bool $success
   *   A boolean indicating whether the batch has completed successfully.
   * @param array $results
   *   The value(s) set in $context['results'] in
   *   \Drupal\bootstrap\Plugin\Setting\Update::batchProcess().
   * @param $operations
   *   If $success is FALSE, contains the operations that remained unprocessed.
   */
  public static function batchFinished($success, $results, $operations) {

    /** @type \Drupal\bootstrap\Theme $theme */

    // Reconstruct the theme object this update is being applied to.
    $theme = Bootstrap::getTheme($results['theme_name']);

    // Save the current state of the installed schemas.
    $theme
      ->setSetting('schemas', $results['schemas']);

    // Show successful updates.
    if (!empty($results['success'])) {
      $list = Element::createStandalone([
        '#theme' => 'item_list__theme_update',
        '#items' => $results['success'],
        '#context' => [
          'type' => 'success',
        ],
      ]);
      drupal_set_message(new FormattableMarkup('@message' . $list
        ->renderPlain(), [
        '@message' => t('Successfully completed the following theme updates:'),
      ]));
    }

    // Show failed errors.
    if (!empty($results['errors'])) {
      $list = Element::createStandalone([
        '#theme' => 'item_list__theme_update',
        '#items' => $results['errors'],
        '#context' => [
          'type' => 'errors',
        ],
      ]);
      drupal_set_message(new FormattableMarkup('@message' . $list
        ->renderPlain(), [
        '@message' => t('The following theme updates could not be completed:'),
      ]), 'error');
    }
  }

}

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
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::$theme protected property The currently set theme object.
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::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 1
Schemas::alterFormElement public function The alter method to store the code. Overrides SettingBase::alterFormElement
Schemas::batchFinished public static function Batch 'finished' callback
Schemas::batchProcessUpdate public static function Processes an update in a batch operation.
Schemas::updateTheme public static function Callback for updating a theme.
SettingBase::alterForm public function The alter method to store the code. Overrides FormInterface::alterForm
SettingBase::drupalSettings public function Determines whether a theme setting should added to drupalSettings. Overrides SettingInterface::drupalSettings 25
SettingBase::getCacheTags public function The cache tags associated with this object. Overrides SettingInterface::getCacheTags 6
SettingBase::getDefaultValue public function Retrieves the setting's default value. Overrides SettingInterface::getDefaultValue
SettingBase::getElement Deprecated public function Overrides SettingInterface::getElement
SettingBase::getElementProperties public function Retrieves all the form properties from the setting definition.
SettingBase::getGroup Deprecated public function Overrides SettingInterface::getGroup
SettingBase::getGroupElement public function Retrieves the group form element the setting belongs to. Overrides SettingInterface::getGroupElement
SettingBase::getGroups public function Retrieves the setting's groups. Overrides SettingInterface::getGroups
SettingBase::getOptions public function Retrieves the settings options, if set. Overrides SettingInterface::getOptions
SettingBase::getSettingElement public function Retrieves the form element for the setting. Overrides SettingInterface::getSettingElement
SettingBase::getTitle public function Retrieves the setting's human-readable title. Overrides SettingInterface::getTitle
SettingBase::submitForm public static function Form submission handler. Overrides FormInterface::submitForm
SettingBase::submitFormElement public static function Form submission handler. Overrides FormInterface::submitFormElement 1
SettingBase::validateForm public static function Form validation handler. Overrides FormInterface::validateForm
SettingBase::validateFormElement public static function Form validation handler. Overrides FormInterface::validateFormElement
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.