3 namespace Drupal\Core\Asset;
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;
16 * Parses library files to get extension data.
18 class LibraryDiscoveryParser {
23 * @var \Drupal\Core\Extension\ModuleHandlerInterface
25 protected $moduleHandler;
30 * @var \Drupal\Core\Theme\ThemeManagerInterface
32 protected $themeManager;
42 * Constructs a new LibraryDiscoveryParser instance.
46 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
48 * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
51 public function __construct($root, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager) {
53 $this->moduleHandler = $module_handler;
54 $this->themeManager = $theme_manager;
58 * Parses and builds up all the libraries information of an extension.
60 * @param string $extension
61 * The name of the extension that registered a library.
64 * All library definitions of the passed extension.
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.
71 public function buildByExtension($extension) {
74 if ($extension === 'core') {
76 $extension_type = 'core';
79 if ($this->moduleHandler->moduleExists($extension)) {
80 $extension_type = 'module';
83 $extension_type = 'theme';
85 $path = $this->drupalGetPath($extension_type, $extension);
88 $libraries = $this->parseLibraryInfo($extension, $path);
89 $libraries = $this->applyLibrariesOverride($libraries, $extension);
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));
95 $library += ['dependencies' => [], 'js' => [], 'css' => []];
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));
101 if (isset($library['version'])) {
102 // @todo Retrieve version of a non-core extension.
103 if ($library['version'] === 'VERSION') {
104 $library['version'] = \Drupal::VERSION;
106 // Remove 'v' prefix from external library versions.
107 elseif ($library['version'][0] === 'v') {
108 $library['version'] = substr($library['version'], 1);
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));
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,
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;
137 // Apply the corresponding weight defined by CSS_* constants.
138 $options['weight'] += constant('CSS_' . strtoupper($category));
139 $library[$type][$source] = $options;
141 unset($library[$type][$category]);
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)) {
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.");
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
158 $options['group'] = JS_LIBRARY;
160 elseif ($type == 'css') {
161 $options['group'] = $extension_type == 'theme' ? CSS_AGGREGATE_THEME : CSS_AGGREGATE_DEFAULT;
163 // By default, all library assets are files.
164 if (!isset($options['type'])) {
165 $options['type'] = 'file';
167 if ($options['type'] == 'external') {
168 $options['data'] = $source;
170 // Determine the file asset URI.
172 if ($source[0] === '/') {
173 // An absolute path maps to DRUPAL_ROOT / base_path().
174 if ($source[1] !== '/') {
175 $options['data'] = substr($source, 1);
177 // A protocol-free URI (e.g., //cdn.com/example.js) is external.
179 $options['type'] = 'external';
180 $options['data'] = $source;
183 // A stream wrapper URI (e.g., public://generated_js/example.js).
184 elseif ($this->fileValidUri($source)) {
185 $options['data'] = $source;
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;
194 // By default, file paths are relative to the registering extension.
196 $options['data'] = $path . '/' . $source;
200 if (!isset($library['version'])) {
201 // @todo Get the information from the extension.
202 $options['version'] = -1;
205 $options['version'] = $library['version'];
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;
213 $library[$type][] = $options;
222 * Parses a given library file and allows modules and themes to alter it.
224 * This method sets the parsed information onto the library property.
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:
235 * path/js/file.js: { attributes: { defer: true } }
237 * If the file has no special attributes, just use an empty object:
240 * path/js/file.js: {}
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:
255 * Each category is itself a key for a sub-list of CSS files to include:
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
279 * - gpl-compatible: A Boolean for whether this library is GPL compatible.
281 * See https://www.drupal.org/node/2274843#define-library for more
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.
290 * An array of parsed library data.
292 * @throws \Drupal\Core\Asset\Exception\InvalidLibraryFileException
293 * Thrown when a parser exception got thrown.
295 protected function parseLibraryInfo($extension, $path) {
298 $library_file = $path . '/' . $extension . '.libraries.yml';
299 if (file_exists($this->root . '/' . $library_file)) {
301 $libraries = Yaml::decode(file_get_contents($this->root . '/' . $library_file));
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);
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));
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);
323 * Apply libraries overrides specified for the current active theme.
325 * @param array $libraries
326 * The libraries definitions.
327 * @param string $extension
328 * The extension in which these libraries are defined.
331 * The modified libraries definitions.
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;
353 $libraries[$library_name]['override'] = FALSE;
356 elseif (is_array($override_definition)) {
357 // An array definition implies an override for an asset within this
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"));
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"));
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);
375 $this->setOverrideValue($libraries[$library_name], [$sub_key], $value, $theme_path);
387 * Wraps drupal_get_path().
389 protected function drupalGetPath($type, $name) {
390 return drupal_get_path($type, $name);
394 * Wraps file_valid_uri().
396 protected function fileValidUri($source) {
397 return file_valid_uri($source);
401 * Determines if the supplied string is a valid URI.
403 protected function isValidUri($string) {
404 return count(explode('://', $string)) === 2;
408 * Overrides the specified library asset.
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.
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.
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);
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.
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);
443 * Ensures that a full path is returned for an overriding theme asset.
445 * @param string $theme_path
446 * The theme or base theme.
447 * @param string $overriding_asset
448 * The overriding library asset.
451 * A fully resolved theme asset path relative to the Drupal directory.
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;
460 return $overriding_asset;