BlockBase.php 10 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\block\BlockBase.
 */

namespace Drupal\block;

10
use Drupal\Core\Plugin\ContextAwarePluginBase;
11
use Drupal\block\BlockInterface;
12
use Drupal\Component\Utility\Unicode;
13
use Drupal\Component\Utility\NestedArray;
14
use Drupal\Core\Language\Language;
15 16
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableInterface;
17
use Drupal\Core\Session\AccountInterface;
18 19 20 21 22 23 24

/**
 * Defines a base block implementation that most blocks plugins will extend.
 *
 * This abstract class provides the generic block configuration form, default
 * block settings, and handling for general user-defined block visibility
 * settings.
25 26
 *
 * @ingroup block_api
27
 */
28
abstract class BlockBase extends ContextAwarePluginBase implements BlockPluginInterface {
29

30 31 32 33 34 35 36 37 38
  /**
   * {@inheritdoc}
   */
  public function label() {
    if (!empty($this->configuration['label'])) {
      return $this->configuration['label'];
    }

    $definition = $this->getPluginDefinition();
39 40 41
    // Cast the admin label to a string since it is an object.
    // @see \Drupal\Core\StringTranslation\TranslationWrapper
    return (string) $definition['admin_label'];
42 43
  }

44
  /**
45
   * {@inheritdoc}
46
   */
47
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
48
    parent::__construct($configuration, $plugin_id, $plugin_definition);
49

50
    $this->setConfiguration($configuration);
51 52 53
  }

  /**
54
   * {@inheritdoc}
55
   */
56
  public function getConfiguration() {
57 58 59 60
    return $this->configuration;
  }

  /**
61 62 63
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    $this->configuration = NestedArray::mergeDeep(
      $this->baseConfigurationDefaults(),
      $this->defaultConfiguration(),
      $configuration
    );
  }

  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return array(
79
      'id' => $this->getPluginId(),
80
      'label' => '',
81
      'provider' => $this->pluginDefinition['provider'],
82 83 84 85 86 87
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
        'contexts' => array(),
      ),
    );
88 89
  }

90 91 92 93 94 95 96
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array();
  }

97 98
  /**
   * {@inheritdoc}
99
   */
100
  public function setConfigurationValue($key, $value) {
101 102 103
    $this->configuration[$key] = $value;
  }

104 105 106 107 108 109 110
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return array();
  }

111
  /**
112
   * {@inheritdoc}
113
   */
114
  public function access(AccountInterface $account) {
115 116
    // By default, the block is visible unless user-configured rules indicate
    // that it should be hidden.
117 118 119 120
    return TRUE;
  }

  /**
121
   * {@inheritdoc}
122 123 124 125 126 127 128 129
   *
   * Creates a generic configuration form for all block types. Individual
   * block plugins can add elements to this form by overriding
   * BlockBase::blockForm(). Most block plugins should not override this
   * method unless they need to alter the generic form elements.
   *
   * @see \Drupal\block\BlockBase::blockForm()
   */
130
  public function buildConfigurationForm(array $form, array &$form_state) {
131
    $definition = $this->getPluginDefinition();
132
    $form['provider'] = array(
133
      '#type' => 'value',
134
      '#value' => $definition['provider'],
135 136
    );

137 138 139 140 141
    $form['admin_label'] = array(
      '#type' => 'item',
      '#title' => t('Block description'),
      '#markup' => $definition['admin_label'],
    );
142
    $form['label'] = array(
143
      '#type' => 'textfield',
144
      '#title' => $this->t('Title'),
145
      '#maxlength' => 255,
146
      '#default_value' => $this->label(),
147 148 149 150
      '#required' => TRUE,
    );
    $form['label_display'] = array(
      '#type' => 'checkbox',
151
      '#title' => $this->t('Display title'),
152
      '#default_value' => ($this->configuration['label_display'] === BlockInterface::BLOCK_LABEL_VISIBLE),
153
      '#return_value' => BlockInterface::BLOCK_LABEL_VISIBLE,
154
    );
155 156 157 158 159 160
    // Identical options to the ones for page caching.
    // @see \Drupal\system\Form\PerformanceForm::buildForm()
    $period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
    $period = array_map('format_interval', array_combine($period, $period));
    $period[0] = '<' . t('no caching') . '>';
    $period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever');
161
    $form['cache'] = array(
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      '#type' => 'details',
      '#title' => t('Cache settings'),
    );
    $form['cache']['max_age'] = array(
      '#type' => 'select',
      '#title' => t('Maximum age'),
      '#description' => t('The maximum time this block may be cached.'),
      '#default_value' => $this->configuration['cache']['max_age'],
      '#options' => $period,
    );
    $contexts = \Drupal::service("cache_contexts")->getLabels();
    // Blocks are always rendered in a "per theme" cache context. No need to
    // show that option to the end user.
    unset($contexts['cache_context.theme']);
    $form['cache']['contexts'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Vary by context'),
      '#description' => t('The contexts this cached block must be varied by.'),
      '#default_value' => $this->configuration['cache']['contexts'],
      '#options' => $contexts,
      '#states' => array(
        'disabled' => array(
          ':input[name="settings[cache][max_age]"]' => array('value' => (string) 0),
        ),
      ),
187
    );
188 189 190 191 192 193 194 195 196 197 198
    if (count($this->getRequiredCacheContexts()) > 0) {
      // Remove the required cache contexts from the list of contexts a user can
      // choose to modify by: they must always be applied.
      $context_labels = array();
      foreach ($this->getRequiredCacheContexts() as $context) {
        $context_labels[] = $form['cache']['contexts']['#options'][$context];
        unset($form['cache']['contexts']['#options'][$context]);
      }
      $required_context_list = implode(', ', $context_labels);
      $form['cache']['contexts']['#description'] .= ' ' . t('This block is <em>always</em> varied by the following contexts: %required-context-list.', array('%required-context-list' => $required_context_list));
    }
199

200
    // Add plugin-specific settings for this block type.
201
    $form += $this->blockForm($form, $form_state);
202 203 204 205
    return $form;
  }

  /**
206
   * {@inheritdoc}
207 208 209 210 211 212
   */
  public function blockForm($form, &$form_state) {
    return array();
  }

  /**
213
   * {@inheritdoc}
214 215 216 217 218 219
   *
   * Most block plugins should not override this method. To add validation
   * for a specific block type, override BlockBase::blockValdiate().
   *
   * @see \Drupal\block\BlockBase::blockValidate()
   */
220
  public function validateConfigurationForm(array &$form, array &$form_state) {
221 222 223
    // Transform the #type = checkboxes value to a numerically indexed array.
    $form_state['values']['cache']['contexts'] = array_values(array_filter($form_state['values']['cache']['contexts']));

224 225 226 227
    $this->blockValidate($form, $form_state);
  }

  /**
228
   * {@inheritdoc}
229 230 231 232
   */
  public function blockValidate($form, &$form_state) {}

  /**
233
   * {@inheritdoc}
234 235 236 237 238 239
   *
   * Most block plugins should not override this method. To add submission
   * handling for a specific block type, override BlockBase::blockSubmit().
   *
   * @see \Drupal\block\BlockBase::blockSubmit()
   */
240
  public function submitConfigurationForm(array &$form, array &$form_state) {
241
    // Process the block's submission handling if no errors occurred only.
242
    if (!form_get_errors($form_state)) {
243 244
      $this->configuration['label'] = $form_state['values']['label'];
      $this->configuration['label_display'] = $form_state['values']['label_display'];
245
      $this->configuration['provider'] = $form_state['values']['provider'];
246
      $this->configuration['cache'] = $form_state['values']['cache'];
247 248 249 250 251
      $this->blockSubmit($form, $form_state);
    }
  }

  /**
252
   * {@inheritdoc}
253 254
   */
  public function blockSubmit($form, &$form_state) {}
255

256 257 258 259 260 261 262 263 264 265
  /**
   * {@inheritdoc}
   */
  public function getMachineNameSuggestion() {
    $definition = $this->getPluginDefinition();
    $admin_label = $definition['admin_label'];

    // @todo This is basically the same as what is done in
    //   \Drupal\system\MachineNameController::transliterate(), so it might make
    //   sense to provide a common service for the two.
266
    $transliteration_service = \Drupal::transliteration();
267 268 269 270 271 272 273 274 275 276 277 278 279
    $transliterated = $transliteration_service->transliterate($admin_label, Language::LANGCODE_DEFAULT, '_');

    $replace_pattern = '[^a-z0-9_.]+';

    $transliterated = Unicode::strtolower($transliterated);

    if (isset($replace_pattern)) {
      $transliterated = preg_replace('@' . $replace_pattern . '@', '', $transliterated);
    }

    return $transliterated;
  }

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  /**
   * Returns the cache contexts required for this block.
   *
   * @return array
   *   The required cache contexts IDs.
   */
  protected function getRequiredCacheContexts() {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheKeys() {
    // Return the required cache contexts, merged with the user-configured cache
    // contexts, if any.
    return array_merge($this->getRequiredCacheContexts(), $this->configuration['cache']['contexts']);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // If a block plugin's output changes, then it must be able to invalidate a
    // cache tag that affects all instances of this block: across themes and
    // across regions.
    $block_plugin_cache_tag = str_replace(':', '__', $this->getPluginID());
    return array('block_plugin' => array($block_plugin_cache_tag));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheBin() {
314
    return 'render';
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return (int)$this->configuration['cache']['max_age'];
  }

  /**
   * {@inheritdoc}
   */
  public function isCacheable() {
    // Similar to the page cache, a block is cacheable if it has a max age.
    // Blocks that should never be cached can override this method to simply
    // return FALSE.
    $max_age = $this->getCacheMaxAge();
    return $max_age === Cache::PERMANENT || $max_age > 0;
  }

335
}