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