LibraryDiscovery.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Core\Cache\CacheCollectorInterface;
  4. /**
  5. * Discovers available asset libraries in Drupal.
  6. */
  7. class LibraryDiscovery implements LibraryDiscoveryInterface {
  8. /**
  9. * The library discovery cache collector.
  10. *
  11. * @var \Drupal\Core\Cache\CacheCollectorInterface
  12. */
  13. protected $collector;
  14. /**
  15. * The final library definitions, statically cached.
  16. *
  17. * hook_library_info_alter() and hook_js_settings_alter() allows modules
  18. * and themes to dynamically alter a library definition (once per request).
  19. *
  20. * @var array
  21. */
  22. protected $libraryDefinitions = [];
  23. /**
  24. * Constructs a new LibraryDiscovery instance.
  25. *
  26. * @param \Drupal\Core\Cache\CacheCollectorInterface $library_discovery_collector
  27. * The library discovery cache collector.
  28. */
  29. public function __construct(CacheCollectorInterface $library_discovery_collector) {
  30. $this->collector = $library_discovery_collector;
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function getLibrariesByExtension($extension) {
  36. if (!isset($this->libraryDefinitions[$extension])) {
  37. $libraries = $this->collector->get($extension);
  38. $this->libraryDefinitions[$extension] = [];
  39. foreach ($libraries as $name => $definition) {
  40. $this->libraryDefinitions[$extension][$name] = $definition;
  41. }
  42. }
  43. return $this->libraryDefinitions[$extension];
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function getLibraryByName($extension, $name) {
  49. $extension = $this->getLibrariesByExtension($extension);
  50. return isset($extension[$name]) ? $extension[$name] : FALSE;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function clearCachedDefinitions() {
  56. $this->libraryDefinitions = [];
  57. $this->collector->clear();
  58. }
  59. }