summaryrefslogtreecommitdiffstats
path: root/src/Plugin/Alter/ThemeSuggestions.php
blob: b4a4c63dc7b1c659094add8021024f85f3c884b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
<?php
/**
 * @file
 * Contains \Drupal\bootstrap\Plugin\Alter\ThemeSuggestions.
 */

namespace Drupal\bootstrap\Plugin\Alter;

use Drupal\bootstrap\Annotation\BootstrapAlter;
use Drupal\bootstrap\Bootstrap;
use Drupal\bootstrap\Plugin\PluginBase;
use Drupal\bootstrap\Utility\Unicode;
use Drupal\bootstrap\Utility\Variables;
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_theme_suggestions_alter().
 *
 * @ingroup plugins_alter
 *
 * @BootstrapAlter("theme_suggestions")
 */
class ThemeSuggestions extends PluginBase implements AlterInterface {

  /**
   * @var array
   */
  protected $bootstrapPanelTypes = ['details', 'fieldset'];

  /**
   * An element object provided in the variables array, may not be set.
   *
   * @var \Drupal\bootstrap\Utility\Element|false
   */
  protected $element;

  /**
   * The theme hook invoked.
   *
   * @var string
   */
  protected $hook;

  /**
   * The theme hook suggestions, exploded by the "__" delimiter.
   *
   * @var array
   */
  protected $hookSuggestions;

  /**
   * The types of elements to ignore for the "input__form_control" suggestion.
   *
   * @var array
   */
  protected $ignoreFormControlTypes = ['checkbox', 'hidden', 'radio'];

  /**
   * The original "hook" value passed via hook_theme_suggestions_alter().
   *
   * @var string
   */
  protected $originalHook;

  /**
   * The array of suggestions to return.
   *
   * @var array
   */
  protected $suggestions;

  /**
   * The variables array object passed via hook_theme_suggestions_alter().
   *
   * @var \Drupal\bootstrap\Utility\Variables
   */
  protected $variables;

  /**
   * {@inheritdoc}
   */
  public function alter(&$suggestions, &$variables = [], &$hook = NULL) {
    // This is intentionally backwards. The "original" theme hook is actually
    // the hook being invoked. The provided $hook (to the alter) is the watered
    // down version of said original hook.
    $this->hook = !empty($variables['theme_hook_original']) ? $variables['theme_hook_original'] : $hook;
    $this->hookSuggestions = explode('__', $this->hook);
    $this->originalHook = $hook;
    $this->suggestions = $suggestions;
    $this->variables = Variables::create($variables);
    $this->element = $this->variables->element;

    // Processes the necessary theme hook suggestions.
    $this->processSuggestions();

    // Ensure the list of suggestions is unique.
    $suggestions = array_unique($this->suggestions);
  }

  /***************************************************************************
   * Dynamic alter methods.
   ***************************************************************************/

  /**
   * Dynamic alter method for "input".
   */
  protected function alterInput() {
    if ($this->element && $this->element->isButton()) {
      $hook = 'input__button';
      if ($this->element->getProperty('split')) {
        $hook .= '__split';
      }
      $this->addSuggestion($hook);
    }
    elseif ($this->element && !$this->element->isType($this->ignoreFormControlTypes)) {
      $this->addSuggestion('input__form_control');
    }
  }

  /**
   * Dynamic alter method for "links__dropbutton".
   */
  protected function alterLinksDropbutton() {
    // Remove the 'dropbutton' suggestion.
    array_shift($this->hookSuggestions);

    $this->addSuggestion('bootstrap_dropdown');
  }

  /**
   * Dynamic alter method for "user".
   *
   * @see https://www.drupal.org/node/2828634
   * @see https://www.drupal.org/node/2808481
   * @todo Remove/refactor once core issue is resolved.
   */
  protected function alterUser() {
    $this->addSuggestionsForEntity('user');
  }

  /***************************************************************************
   * Protected methods.
   ***************************************************************************/

  /**
   * Adds suggestions based on an array of hooks.
   *
   * @param string|string[] $hook
   *   A single theme hook suggestion or an array of theme hook suggestions.
   */
  protected function addSuggestion($hook) {
    $hooks = (array) $hook;
    foreach ($hooks as $hook) {
      $suggestions = $this->buildSuggestions($hook);
      foreach ($suggestions as $suggestion) {
        $this->suggestions[] = $suggestion;
      }
    }
  }

  /**
   * Adds "bundle" and "view mode" suggestions for an entity.
   *
   * This is a helper method because core's implementation of theme hook
   * suggestions on entities is inconsistent.
   *
   * @see https://www.drupal.org/node/2808481
   *
   * @param string $entity_type
   *   Optional. A specific type of entity to look for.
   * @param string $prefix
   *   Optional. A prefix (like "entity") to use. It will automatically be
   *   appended with the "__" separator.
   *
   * @todo Remove/refactor once core issue is resolved.
   */
  protected function addSuggestionsForEntity($entity_type = 'entity', $prefix = '') {
    // Immediately return if there is no element.
    if (!$this->element) {
      return;
    }

    // Extract the entity.
    if ($entity = $this->getEntityObject($entity_type)) {
      $entity_type_id = $entity->getEntityTypeId();
      $suggestions = [];

      // Only add the entity type identifier if there's a prefix.
      if (!empty($prefix)) {
        $prefix .= '__';
        $suggestions[] = $prefix . '__' . $entity_type_id;
      }

      // View mode.
      if ($view_mode = preg_replace('/[^A-Za-z0-9]+/', '_', $this->element->getProperty('view_mode'))) {
        $suggestions[] = $prefix . $entity_type_id . '__' . $view_mode;

        // Bundle.
        if ($entity->getEntityType()->hasKey('bundle')) {
          $suggestions[] = $prefix . $entity_type_id . '__' . $entity->bundle();
          $suggestions[] = $prefix . $entity_type_id . '__' . $entity->bundle() . '__' . $view_mode;
        }
      }

      // Add suggestions.
      if ($suggestions) {
        $this->addSuggestion($suggestions);
      }
    }
  }

  /**
   * Builds a list of suggestions.
   *
   * @param string $hook
   *   The theme hook suggestion to build.
   *
   * @return array
   */
  protected function buildSuggestions($hook) {
    $suggestions = [];

    $hook_suggestions = $this->hookSuggestions;

    // Replace the first hook suggestion with $hook.
    array_shift($hook_suggestions);
    array_unshift($suggestions, $hook);

    $suggestions = [];
    while ($hook_suggestions) {
      $suggestions[] = $hook . '__' . implode('__', $hook_suggestions);
      array_pop($hook_suggestions);
    }

    // Append the base hook.
    $suggestions[] = $hook;

    // Return the suggestions, reversed.
    return array_reverse($suggestions);
  }

  /**
   * Retrieves the methods to invoke to process the theme hook suggestion.
   *
   * @return array
   *   An indexed array of methods to be invoked.
   */
  protected function getAlterMethods() {
    // Retrieve cached theme hook suggestion alter methods.
    $cache = $this->theme->getCache('theme_hook_suggestions');
    if ($cache->has($this->hook)) {
      return $cache->get($this->hook);
    }

    // Uppercase each theme hook suggestion to be used in the method name.
    $hook_suggestions = $this->hookSuggestions;
    foreach ($hook_suggestions as $key => $suggestion) {
      $hook_suggestions[$key] = Unicode::ucfirst($suggestion);
    }

    $methods = [];
    while ($hook_suggestions) {
      $method = 'alter' . implode('', $hook_suggestions);
      if (method_exists($this, $method)) {
        $methods[] = $method;
      }
      array_pop($hook_suggestions);
    }

    // Reverse the methods.
    $methods = array_reverse($methods);

    // Cache the methods.
    $cache->set($this->hook, $methods);

    return $methods;
  }

  /**
   * Extracts the entity from the element(s) passed in the Variables object.
   *
   * @param string $entity_type
   *   Optional. The entity type to attempt to retrieve.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The extracted entity, NULL if entity could not be found.
   */
  protected function getEntityObject($entity_type = 'entity') {
    // Immediately return if there is no element.
    if (!$this->element) {
      return NULL;
    }

    // Attempt to retrieve the provided element type.
    $entity = $this->element->getProperty($entity_type);

    // If the provided entity type doesn't exist, check to see if a generic
    // "entity" property was used instead.
    if ($entity_type !== 'entity' && (!$entity || !($entity instanceof EntityInterface))) {
      $entity = $this->element->getProperty('entity');
    }

    // Only return the entity if it's the proper object.
    return $entity instanceof EntityInterface ? $entity : NULL;
  }

  /**
   * Processes the necessary theme hook suggestions.
   */
  protected function processSuggestions() {
    // Add special hook suggestions for Bootstrap panels.
    if ((in_array($this->originalHook, $this->bootstrapPanelTypes)) && $this->element && $this->element->getProperty('bootstrap_panel', TRUE)) {
      $this->addSuggestion('bootstrap_panel');
    }

    // Retrieve any dynamic alter methods.
    $methods = $this->getAlterMethods();
    foreach ($methods as $method) {
      $this->$method();
    }
  }

  /***************************************************************************
   * Deprecated methods (DO NOT USE).
   ***************************************************************************/

  /**
   * Adds "bundle" and "view mode" suggestions for an entity.
   *
   * @param array $suggestions
   *   The suggestions array, this is ignored.
   * @param \Drupal\bootstrap\Utility\Variables $variables
   *   The variables object, this is ignored.
   * @param string $entity_type
   *   Optional. A specific type of entity to look for.
   * @param string $prefix
   *   Optional. A prefix (like "entity") to use. It will automatically be
   *   appended with the "__" separator.
   *
   * @deprecated Since 8.x-3.2. Will be removed in a future release.
   *
   * @see \Drupal\bootstrap\Plugin\Alter\ThemeSuggestions::addSuggestionsForEntity
   */
  public function addEntitySuggestions(array &$suggestions, Variables $variables, $entity_type = 'entity', $prefix = '') {
    Bootstrap::deprecated();
    $this->addSuggestionsForEntity($entity_type, $prefix);
  }

  /**
   * Extracts the entity from the element(s) passed in the Variables object.
   *
   * @param \Drupal\bootstrap\Utility\Variables $variables
   *   The Variables object, this is ignored.
   * @param string $entity_type
   *   Optional. The entity type to attempt to retrieve.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The extracted entity, NULL if entity could not be found.
   *
   * @deprecated Since 8.x-3.2. Will be removed in a future release.
   *
   * @see \Drupal\bootstrap\Plugin\Alter\ThemeSuggestions::getEntityObject
   */
  public function getEntity(Variables $variables, $entity_type = 'entity') {
    Bootstrap::deprecated();
    return $this->getEntityObject($entity_type);
  }

}