This repository was archived by the owner on Jun 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComponentBase.php
More file actions
484 lines (430 loc) · 13.6 KB
/
ComponentBase.php
File metadata and controls
484 lines (430 loc) · 13.6 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
<?php
namespace Drupal\ambientimpact_core;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Serialization\SerializationInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base class for implementing Ambient.Impact Component plug-ins.
*/
class ComponentBase extends PluginBase implements
ContainerFactoryPluginInterface, ConfigurableInterface, ComponentInterface {
use StringTranslationTrait;
/**
* The Drupal module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The Drupal language manager service.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The Drupal renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The Drupal YAML serialization class.
*
* @var \Drupal\Component\Serialization\SerializationInterface
*/
protected $yamlSerialization;
/**
* The Drupal string translation service.
*
* @var \Drupal\Core\StringTranslation\TranslationInterface
*/
protected $stringTranslation;
/**
* The Component HTML cache service.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $htmlCacheService;
/**
* The directory in which component directories are located.
*
* This is relative to the implementing module's directory.
*
* @var string
*/
protected $componentsDirectory = 'components';
/**
* The path to this component's directory.
*
* This is relative to the implementing module's directory.
*
* If empty, will be built in $this->__construct() with
* $this->componentsDirectory and the plug-in ID.
*
* @var string
*
* @see $this->componentsDirectory
* The directory in which this component's directory is found, relative to
* the implementing module's directory.
*/
protected $path = '';
/**
* Whether this Component has any HTML cached.
*
* @var null|bool
*/
protected $hasCachedHTML = null;
/**
* This Component's HTML cache ID.
*
* @var null|string
*/
protected $htmlCacheID = null;
/**
* Constructs an Ambient.Impact Component object.
*
* This calls the parent PluginBase::__construct(), and then calls
* $this->setConfiguration() to ensure settings are merged over defaults.
*
* @param array $configuration
* A configuration array containing information about the plug-in instance.
*
* @param string $pluginID
* The plugin_id for the plug-in instance.
*
* @param array $pluginDefinition
* The plug-in implementation definition. PluginBase defines this as mixed,
* but we should always have an array so the type is set. This can be
* changed in the future if need be.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
* The Drupal module handler service.
*
* @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
* The Drupal language manager service.
*
* @param \Drupal\Core\Render\RendererInterface $renderer
* The Drupal renderer service.
*
* @param \Drupal\Component\Serialization\SerializationInterface $yamlSerialization
* The Drupal YAML serialization class.
*
* @param \Drupal\Core\StringTranslation\TranslationInterface $stringTranslation
* The Drupal string translation service.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $htmlCacheService
* The Component HTML cache service.
*/
public function __construct(
array $configuration, string $pluginID, array $pluginDefinition,
ModuleHandlerInterface $moduleHandler,
LanguageManagerInterface $languageManager,
RendererInterface $renderer,
SerializationInterface $yamlSerialization,
TranslationInterface $stringTranslation,
CacheBackendInterface $htmlCacheService
) {
parent::__construct($configuration, $pluginID, $pluginDefinition);
// Save dependencies.
$this->moduleHandler = $moduleHandler;
$this->languageManager = $languageManager;
$this->renderer = $renderer;
$this->yamlSerialization = $yamlSerialization;
$this->stringTranslation = $stringTranslation;
$this->htmlCacheService = $htmlCacheService;
$this->setConfiguration($configuration);
// Build the path if it hasn't been built/specified.
if (empty($this->path)) {
$this->path = $this->componentsDirectory . '/' . $pluginID;
}
}
/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration, $pluginID, $pluginDefinition
) {
return new static(
$configuration, $pluginID, $pluginDefinition,
$container->get('module_handler'),
$container->get('language_manager'),
$container->get('renderer'),
$container->get('serialization.yaml'),
$container->get('string_translation'),
$container->get('cache.ambientimpact_component_html')
);
}
/**
* {@inheritdoc}
*/
public function getPath(bool $absolute = false): string {
if ($absolute === true) {
return $this->moduleHandler->getModule(
$this->pluginDefinition['provider']
)->getPath() . '/' . $this->path;
}
return $this->path;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* {@inheritdoc}
*
* @see \Drupal\Core\Block\BlockBase::setConfiguration()
* Copied from this.
*/
public function setConfiguration(array $configuration) {
$this->configuration = NestedArray::mergeDeep(
$this->baseConfigurationDefaults(),
$this->defaultConfiguration(),
$configuration
);
}
/**
* Returns generic default configuration for Component plug-ins.
*
* @return array
* An associative array with the default configuration.
*
* @todo Is there a point to including the plug-in ID in this?
*/
protected function baseConfigurationDefaults() {
return [
'id' => $this->getPluginId(),
];
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [];
}
/**
* {@inheritdoc}
*/
public function getLibraries(): array {
// This component's libraries, if any are found.
$libraries = [];
// An array of file array references for ease of manipulation: one index for
// each 'css' group found, and the 'js' array, if present. At that level
// they're structured the same, so this avoids repeating code.
$files = [];
// This is the full file system path to the file, including the file name
// and extension.
$filePath =
DRUPAL_ROOT . '/' . $this->getPath(true) . '/' .
$this->pluginDefinition['id'] . '.libraries.yml';
// Don't proceed if the file doesn't exist.
if (!file_exists($filePath)) {
return $libraries;
}
// Parse the YAML file.
$libraries = $this->yamlSerialization::decode(file_get_contents($filePath));
foreach ($libraries as &$library) {
// Save references to each 'css' group array found.
if (isset($library['css'])) {
foreach ($library['css'] as &$category) {
$files[] = &$category;
}
}
if (isset($library['js'])) {
// Save a reference to the 'js' array, if found.
$files[] = &$library['js'];
// Add the JavaScript framework as a dependency if:
if (
// This library isn't to be attached in the header. The reason for
// this is that this would cause Drupal to place the framework in the
// header as well, which would contribute to a page that's slower to
// render. If a library attaches itself to the header, it must not
// expect the framework to be available.
(
!isset($library['header']) ||
$library['header'] === false
) && (
// The library either doesn't have any dependencies defined, or it
// does but does not have the framework listed as a dependency.
!isset($library['dependencies']) ||
is_array($library['dependencies']) &&
!in_array(
'ambientimpact_core/framework',
$library['dependencies']
)
)
) {
$library['dependencies'][] = 'ambientimpact_core/framework';
}
// If no 'defer' attribute is set, default to true to delay component
// JavaScript until most other stuff is done executing. This helps the
// page feel a bit faster to load.
foreach ($library['js'] as $file => &$fileSettings) {
if (!isset($fileSettings['attributes']['defer'])) {
$fileSettings['attributes']['defer'] = true;
}
}
}
}
// Prepend the component path to make it relative to the module's directory
// as opposed to the component's.
foreach ($files as &$category) {
foreach (array_keys($category) as $key) {
// New key.
$category[$this->getPath() . '/' . $key] = $category[$key];
// Delete the old key.
unset($category[$key]);
}
}
return $libraries;
}
/**
* {@inheritdoc}
*/
public function getJSSettings(): array {
return [];
}
/**
* Get the Component HTML cache settings.
*
* This can be overridden on a per-Component basis to set custom cache
* invalidation.
*
* This supports 'max-age' and 'tags', but 'contexts' is not yet supported.
*
* @return array
* The Component HTML cache settings with 'max-age' set to permanent, i.e.
* only rebuilt on a cache rebuild.
*
* @see https://api.drupal.org/api/drupal/core!core.api.php/group/cache
* Drupal Cache API documentation.
*
* @todo Add support for cache contexts?
*
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Renderer.php/function/Renderer%3A%3AdoRender
* Cache contexts used in the rendering process.
*/
protected static function getHTMLCacheSettings(): array {
return [
'max-age' => Cache::PERMANENT,
];
}
/**
* Get this Component's HTML cache ID.
*
* This is only built once and stored for subsequent use.
*
* @return string
* The value of $this->htmlCacheID.
*
* @see $this->htmlCacheID
* The HTML cache ID is stored here.
*/
protected function getHTMLCacheID(): string {
if ($this->htmlCacheID === null) {
$this->htmlCacheID =
$this->pluginDefinition['provider'] . ':' .
$this->pluginDefinition['id'] . ':' .
$this->languageManager->getCurrentLanguage()->getId();
}
return $this->htmlCacheID;
}
/**
* Determine if this Component has any cached HTML available.
*
* @return boolean
* The value of $this->hasCachedHTML.
*
* @see $this->hasCachedHTML
* Stores whether this Component has cached HTML.
*/
protected function hasCachedHTML(): bool {
if ($this->hasCachedHTML === null) {
$this->hasCachedHTML = !empty(
$this->htmlCacheService->get($this->getHTMLCacheID())->data
);
}
return $this->hasCachedHTML;
}
/**
* Get the file system path to this Component's HTML file.
*
* @return string
* The Component's <component name>.html.twig file path.
*/
protected function getHTMLPath() {
// This is the full file system path to the file, including the file name
// and extension.
return DRUPAL_ROOT . '/' . $this->getPath(true) . '/' .
$this->pluginDefinition['id'] . '.html.twig';
}
/**
* {@inheritdoc}
*/
public function hasHTML(): bool {
return file_exists($this->getHTMLPath());
}
/**
* {@inheritdoc}
*/
public function getHTML() {
// Don't proceed if a Twig template doesn't exist.
if (!$this->hasHTML()) {
return false;
}
// If cached HTML is available, grab that without doing any rendering.
if ($this->hasCachedHTML()) {
$html = $this->htmlCacheService->get($this->getHTMLCacheID())->data;
// If no cached HTML is found, render and cache the HTML.
} else {
// Render array containing the file contents as an inline template.
$renderArray = [
'#type' => 'inline_template',
'#template' => file_get_contents($this->getHTMLPath()),
];
// Render the inline template.
$html = $this->renderer->renderPlain($renderArray);
$cacheSettings = static::getHTMLCacheSettings();
// Set the 'max-age' and 'tags' keys if they're not set.
if (!isset($cacheSettings['max-age'])) {
$cacheSettings['max-age'] = Cache::PERMANENT;
}
if (!isset($cacheSettings['tags'])) {
$cacheSettings['tags'] = [];
}
// Save the rendered template HTML to the cache.
$this->htmlCacheService->set(
$this->getHTMLCacheID(),
$html,
$cacheSettings['max-age'],
$cacheSettings['tags']
);
}
return $html;
}
/**
* {@inheritdoc}
*/
public function hasDemo(): bool {
$reflection = new \ReflectionMethod($this, 'getDemo');
return get_class() !== $reflection->getDeclaringClass()->getName();
}
/**
* {@inheritdoc}
*/
public function getDemo(): array {
return [];
}
}