LibraryDiscoveryParser.php 19 KB

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