Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Asset / LibraryDiscoveryParser.php
1 <?php
2
3 namespace Drupal\Core\Asset;
4
5 use Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException;
6 use Drupal\Core\Asset\Exception\InvalidLibrariesOverrideSpecificationException;
7 use Drupal\Core\Asset\Exception\InvalidLibraryFileException;
8 use Drupal\Core\Asset\Exception\LibraryDefinitionMissingLicenseException;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Serialization\Yaml;
11 use Drupal\Core\Theme\ThemeManagerInterface;
12 use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
13 use Drupal\Component\Utility\NestedArray;
14
15 /**
16  * Parses library files to get extension data.
17  */
18 class LibraryDiscoveryParser {
19
20   /**
21    * The module handler.
22    *
23    * @var \Drupal\Core\Extension\ModuleHandlerInterface
24    */
25   protected $moduleHandler;
26
27   /**
28    * The theme manager.
29    *
30    * @var \Drupal\Core\Theme\ThemeManagerInterface
31    */
32   protected $themeManager;
33
34   /**
35    * The app root.
36    *
37    * @var string
38    */
39   protected $root;
40
41   /**
42    * Constructs a new LibraryDiscoveryParser instance.
43    *
44    * @param string $root
45    *   The app root.
46    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
47    *   The module handler.
48    * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
49    *   The theme manager.
50    */
51   public function __construct($root, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager) {
52     $this->root = $root;
53     $this->moduleHandler = $module_handler;
54     $this->themeManager = $theme_manager;
55   }
56
57   /**
58    * Parses and builds up all the libraries information of an extension.
59    *
60    * @param string $extension
61    *   The name of the extension that registered a library.
62    *
63    * @return array
64    *   All library definitions of the passed extension.
65    *
66    * @throws \Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException
67    *   Thrown when a library has no js/css/setting.
68    * @throws \UnexpectedValueException
69    *   Thrown when a js file defines a positive weight.
70    */
71   public function buildByExtension($extension) {
72     $libraries = [];
73
74     if ($extension === 'core') {
75       $path = 'core';
76       $extension_type = 'core';
77     }
78     else {
79       if ($this->moduleHandler->moduleExists($extension)) {
80         $extension_type = 'module';
81       }
82       else {
83         $extension_type = 'theme';
84       }
85       $path = $this->drupalGetPath($extension_type, $extension);
86     }
87
88     $libraries = $this->parseLibraryInfo($extension, $path);
89     $libraries = $this->applyLibrariesOverride($libraries, $extension);
90
91     foreach ($libraries as $id => &$library) {
92       if (!isset($library['js']) && !isset($library['css']) && !isset($library['drupalSettings'])) {
93         throw new IncompleteLibraryDefinitionException(sprintf("Incomplete library definition for definition '%s' in extension '%s'", $id, $extension));
94       }
95       $library += ['dependencies' => [], 'js' => [], 'css' => []];
96
97       if (isset($library['header']) && !is_bool($library['header'])) {
98         throw new \LogicException(sprintf("The 'header' key in the library definition '%s' in extension '%s' is invalid: it must be a boolean.", $id, $extension));
99       }
100
101       if (isset($library['version'])) {
102         // @todo Retrieve version of a non-core extension.
103         if ($library['version'] === 'VERSION') {
104           $library['version'] = \Drupal::VERSION;
105         }
106         // Remove 'v' prefix from external library versions.
107         elseif ($library['version'][0] === 'v') {
108           $library['version'] = substr($library['version'], 1);
109         }
110       }
111
112       // If this is a 3rd party library, the license info is required.
113       if (isset($library['remote']) && !isset($library['license'])) {
114         throw new LibraryDefinitionMissingLicenseException(sprintf("Missing license information in library definition for definition '%s' extension '%s': it has a remote, but no license.", $id, $extension));
115       }
116
117       // Assign Drupal's license to libraries that don't have license info.
118       if (!isset($library['license'])) {
119         $library['license'] = [
120           'name' => 'GNU-GPL-2.0-or-later',
121           'url' => 'https://www.drupal.org/licensing/faq',
122           'gpl-compatible' => TRUE,
123         ];
124       }
125
126       foreach (['js', 'css'] as $type) {
127         // Prepare (flatten) the SMACSS-categorized definitions.
128         // @todo After Asset(ic) changes, retain the definitions as-is and
129         //   properly resolve dependencies for all (css) libraries per category,
130         //   and only once prior to rendering out an HTML page.
131         if ($type == 'css' && !empty($library[$type])) {
132           foreach ($library[$type] as $category => $files) {
133             foreach ($files as $source => $options) {
134               if (!isset($options['weight'])) {
135                 $options['weight'] = 0;
136               }
137               // Apply the corresponding weight defined by CSS_* constants.
138               $options['weight'] += constant('CSS_' . strtoupper($category));
139               $library[$type][$source] = $options;
140             }
141             unset($library[$type][$category]);
142           }
143         }
144         foreach ($library[$type] as $source => $options) {
145           unset($library[$type][$source]);
146           // Allow to omit the options hashmap in YAML declarations.
147           if (!is_array($options)) {
148             $options = [];
149           }
150           if ($type == 'js' && isset($options['weight']) && $options['weight'] > 0) {
151             throw new \UnexpectedValueException("The $extension/$id library defines a positive weight for '$source'. Only negative weights are allowed (but should be avoided). Instead of a positive weight, specify accurate dependencies for this library.");
152           }
153           // Unconditionally apply default groups for the defined asset files.
154           // The library system is a dependency management system. Each library
155           // properly specifies its dependencies instead of relying on a custom
156           // processing order.
157           if ($type == 'js') {
158             $options['group'] = JS_LIBRARY;
159           }
160           elseif ($type == 'css') {
161             $options['group'] = $extension_type == 'theme' ? CSS_AGGREGATE_THEME : CSS_AGGREGATE_DEFAULT;
162           }
163           // By default, all library assets are files.
164           if (!isset($options['type'])) {
165             $options['type'] = 'file';
166           }
167           if ($options['type'] == 'external') {
168             $options['data'] = $source;
169           }
170           // Determine the file asset URI.
171           else {
172             if ($source[0] === '/') {
173               // An absolute path maps to DRUPAL_ROOT / base_path().
174               if ($source[1] !== '/') {
175                 $options['data'] = substr($source, 1);
176               }
177               // A protocol-free URI (e.g., //cdn.com/example.js) is external.
178               else {
179                 $options['type'] = 'external';
180                 $options['data'] = $source;
181               }
182             }
183             // A stream wrapper URI (e.g., public://generated_js/example.js).
184             elseif ($this->fileValidUri($source)) {
185               $options['data'] = $source;
186             }
187             // A regular URI (e.g., http://example.com/example.js) without
188             // 'external' explicitly specified, which may happen if, e.g.
189             // libraries-override is used.
190             elseif ($this->isValidUri($source)) {
191               $options['type'] = 'external';
192               $options['data'] = $source;
193             }
194             // By default, file paths are relative to the registering extension.
195             else {
196               $options['data'] = $path . '/' . $source;
197             }
198           }
199
200           if (!isset($library['version'])) {
201             // @todo Get the information from the extension.
202             $options['version'] = -1;
203           }
204           else {
205             $options['version'] = $library['version'];
206           }
207
208           // Set the 'minified' flag on JS file assets, default to FALSE.
209           if ($type == 'js' && $options['type'] == 'file') {
210             $options['minified'] = isset($options['minified']) ? $options['minified'] : FALSE;
211           }
212
213           $library[$type][] = $options;
214         }
215       }
216     }
217
218     return $libraries;
219   }
220
221   /**
222    * Parses a given library file and allows modules and themes to alter it.
223    *
224    * This method sets the parsed information onto the library property.
225    *
226    * Library information is parsed from *.libraries.yml files; see
227    * editor.library.yml for an example. Every library must have at least one js
228    * or css entry. Each entry starts with a machine name and defines the
229    * following elements:
230    * - js: A list of JavaScript files to include. Each file is keyed by the file
231    *   path. An item can have several attributes (like HTML
232    *   attributes). For example:
233    *   @code
234    *   js:
235    *     path/js/file.js: { attributes: { defer: true } }
236    *   @endcode
237    *   If the file has no special attributes, just use an empty object:
238    *   @code
239    *   js:
240    *     path/js/file.js: {}
241    *   @endcode
242    *   The path of the file is relative to the module or theme directory, unless
243    *   it starts with a /, in which case it is relative to the Drupal root. If
244    *   the file path starts with //, it will be treated as a protocol-free,
245    *   external resource (e.g., //cdn.com/library.js). Full URLs
246    *   (e.g., http://cdn.com/library.js) as well as URLs that use a valid
247    *   stream wrapper (e.g., public://path/to/file.js) are also supported.
248    * - css: A list of categories for which the library provides CSS files. The
249    *   available categories are:
250    *   - base
251    *   - layout
252    *   - component
253    *   - state
254    *   - theme
255    *   Each category is itself a key for a sub-list of CSS files to include:
256    *   @code
257    *   css:
258    *     component:
259    *       css/file.css: {}
260    *   @endcode
261    *   Just like with JavaScript files, each CSS file is the key of an object
262    *   that can define specific attributes. The format of the file path is the
263    *   same as for the JavaScript files.
264    * - dependencies: A list of libraries this library depends on.
265    * - version: The library version. The string "VERSION" can be used to mean
266    *   the current Drupal core version.
267    * - header: By default, JavaScript files are included in the footer. If the
268    *   script must be included in the header (along with all its dependencies),
269    *   set this to true. Defaults to false.
270    * - minified: If the file is already minified, set this to true to avoid
271    *   minifying it again. Defaults to false.
272    * - remote: If the library is a third-party script, this provides the
273    *   repository URL for reference.
274    * - license: If the remote property is set, the license information is
275    *   required. It has 3 properties:
276    *   - name: The human-readable name of the license.
277    *   - url: The URL of the license file/information for the version of the
278    *     library used.
279    *   - gpl-compatible: A Boolean for whether this library is GPL compatible.
280    *
281    * See https://www.drupal.org/node/2274843#define-library for more
282    * information.
283    *
284    * @param string $extension
285    *   The name of the extension that registered a library.
286    * @param string $path
287    *   The relative path to the extension.
288    *
289    * @return array
290    *   An array of parsed library data.
291    *
292    * @throws \Drupal\Core\Asset\Exception\InvalidLibraryFileException
293    *   Thrown when a parser exception got thrown.
294    */
295   protected function parseLibraryInfo($extension, $path) {
296     $libraries = [];
297
298     $library_file = $path . '/' . $extension . '.libraries.yml';
299     if (file_exists($this->root . '/' . $library_file)) {
300       try {
301         $libraries = Yaml::decode(file_get_contents($this->root . '/' . $library_file));
302       }
303       catch (InvalidDataTypeException $e) {
304         // Rethrow a more helpful exception to provide context.
305         throw new InvalidLibraryFileException(sprintf('Invalid library definition in %s: %s', $library_file, $e->getMessage()), 0, $e);
306       }
307     }
308
309     // Allow modules to add dynamic library definitions.
310     $hook = 'library_info_build';
311     if ($this->moduleHandler->implementsHook($extension, $hook)) {
312       $libraries = NestedArray::mergeDeep($libraries, $this->moduleHandler->invoke($extension, $hook));
313     }
314
315     // Allow modules to alter the module's registered libraries.
316     $this->moduleHandler->alter('library_info', $libraries, $extension);
317     $this->themeManager->alter('library_info', $libraries, $extension);
318
319     return $libraries;
320   }
321
322   /**
323    * Apply libraries overrides specified for the current active theme.
324    *
325    * @param array $libraries
326    *   The libraries definitions.
327    * @param string $extension
328    *   The extension in which these libraries are defined.
329    *
330    * @return array
331    *   The modified libraries definitions.
332    */
333   protected function applyLibrariesOverride($libraries, $extension) {
334     $active_theme = $this->themeManager->getActiveTheme();
335     // ActiveTheme::getLibrariesOverride() returns libraries-overrides for the
336     // current theme as well as all its base themes.
337     $all_libraries_overrides = $active_theme->getLibrariesOverride();
338     foreach ($all_libraries_overrides as $theme_path => $libraries_overrides) {
339       foreach ($libraries as $library_name => $library) {
340         // Process libraries overrides.
341         if (isset($libraries_overrides["$extension/$library_name"])) {
342           // Active theme defines an override for this library.
343           $override_definition = $libraries_overrides["$extension/$library_name"];
344           if (is_string($override_definition) || $override_definition === FALSE) {
345             // A string or boolean definition implies an override (or removal)
346             // for the whole library. Use the override key to specify that this
347             // library will be overridden when it is called.
348             // @see \Drupal\Core\Asset\LibraryDiscovery::getLibraryByName()
349             if ($override_definition) {
350               $libraries[$library_name]['override'] = $override_definition;
351             }
352             else {
353               $libraries[$library_name]['override'] = FALSE;
354             }
355           }
356           elseif (is_array($override_definition)) {
357             // An array definition implies an override for an asset within this
358             // library.
359             foreach ($override_definition as $sub_key => $value) {
360               // Throw an exception if the asset is not properly specified.
361               if (!is_array($value)) {
362                 throw new InvalidLibrariesOverrideSpecificationException(sprintf('Library asset %s is not correctly specified. It should be in the form "extension/library_name/sub_key/path/to/asset.js".', "$extension/$library_name/$sub_key"));
363               }
364               if ($sub_key === 'drupalSettings') {
365                 // drupalSettings may not be overridden.
366                 throw new InvalidLibrariesOverrideSpecificationException(sprintf('drupalSettings may not be overridden in libraries-override. Trying to override %s. Use hook_library_info_alter() instead.', "$extension/$library_name/$sub_key"));
367               }
368               elseif ($sub_key === 'css') {
369                 // SMACSS category should be incorporated into the asset name.
370                 foreach ($value as $category => $overrides) {
371                   $this->setOverrideValue($libraries[$library_name], [$sub_key, $category], $overrides, $theme_path);
372                 }
373               }
374               else {
375                 $this->setOverrideValue($libraries[$library_name], [$sub_key], $value, $theme_path);
376               }
377             }
378           }
379         }
380       }
381     }
382
383     return $libraries;
384   }
385
386   /**
387    * Wraps drupal_get_path().
388    */
389   protected function drupalGetPath($type, $name) {
390     return drupal_get_path($type, $name);
391   }
392
393   /**
394    * Wraps file_valid_uri().
395    */
396   protected function fileValidUri($source) {
397     return file_valid_uri($source);
398   }
399
400   /**
401    * Determines if the supplied string is a valid URI.
402    */
403   protected function isValidUri($string) {
404     return count(explode('://', $string)) === 2;
405   }
406
407   /**
408    * Overrides the specified library asset.
409    *
410    * @param array $library
411    *   The containing library definition.
412    * @param array $sub_key
413    *   An array containing the sub-keys specifying the library asset, e.g.
414    *   @code['js']@endcode or @code['css', 'component']@endcode
415    * @param array $overrides
416    *   Specifies the overrides, this is an array where the key is the asset to
417    *   be overridden while the value is overriding asset.
418    */
419   protected function setOverrideValue(array &$library, array $sub_key, array $overrides, $theme_path) {
420     foreach ($overrides as $original => $replacement) {
421       // Get the attributes of the asset to be overridden. If the key does
422       // not exist, then throw an exception.
423       $key_exists = NULL;
424       $parents = array_merge($sub_key, [$original]);
425       // Save the attributes of the library asset to be overridden.
426       $attributes = NestedArray::getValue($library, $parents, $key_exists);
427       if ($key_exists) {
428         // Remove asset to be overridden.
429         NestedArray::unsetValue($library, $parents);
430         // No need to replace if FALSE is specified, since that is a removal.
431         if ($replacement) {
432           // Ensure the replacement path is relative to drupal root.
433           $replacement = $this->resolveThemeAssetPath($theme_path, $replacement);
434           $new_parents = array_merge($sub_key, [$replacement]);
435           // Replace with an override if specified.
436           NestedArray::setValue($library, $new_parents, $attributes);
437         }
438       }
439     }
440   }
441
442   /**
443    * Ensures that a full path is returned for an overriding theme asset.
444    *
445    * @param string $theme_path
446    *   The theme or base theme.
447    * @param string $overriding_asset
448    *   The overriding library asset.
449    *
450    * @return string
451    *   A fully resolved theme asset path relative to the Drupal directory.
452    */
453   protected function resolveThemeAssetPath($theme_path, $overriding_asset) {
454     if ($overriding_asset[0] !== '/' && !$this->isValidUri($overriding_asset)) {
455       // The destination is not an absolute path and it's not a URI (e.g.
456       // public://generated_js/example.js or http://example.com/js/my_js.js), so
457       // it's relative to the theme.
458       return '/' . $theme_path . '/' . $overriding_asset;
459     }
460     return $overriding_asset;
461   }
462
463 }