AssetResolver.php 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
<?php
/**
 * @file
 * Contains \Drupal\Core\Asset\AssetResolver.
 */

namespace Drupal\Core\Asset;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Theme\ThemeManagerInterface;

/**
 * The default asset resolver.
 */
class AssetResolver implements AssetResolverInterface {

  /**
   * The library discovery service.
   *
   * @var \Drupal\Core\Asset\LibraryDiscoveryInterface
   */
  protected $libraryDiscovery;

  /**
   * The library dependency resolver.
   *
   * @var \Drupal\Core\Asset\LibraryDependencyResolverInterface
   */
  protected $libraryDependencyResolver;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme manager.
   *
   * @var \Drupal\Core\Theme\ThemeManagerInterface
   */
  protected $themeManager;

  /**
   * Constructs a new AssetResolver instance.
   *
   * @param \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery
   *   The library discovery service.
   * @param \Drupal\Core\Asset\LibraryDependencyResolverInterface $library_dependency_resolver
   *   The library dependency resolver.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager.
   */
  public function __construct(LibraryDiscoveryInterface $library_discovery, LibraryDependencyResolverInterface $library_dependency_resolver, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager) {
    $this->libraryDiscovery = $library_discovery;
    $this->libraryDependencyResolver = $library_dependency_resolver;
    $this->moduleHandler = $module_handler;
    $this->themeManager = $theme_manager;
  }

  /**
   * Returns the libraries that need to be loaded.
   *
   * For example, with core/a depending on core/c and core/b on core/d:
   * @code
   * $assets = new AttachedAssets();
   * $assets->setLibraries(['core/a', 'core/b', 'core/c']);
   * $assets->setAlreadyLoadedLibraries(['core/c']);
   * $resolver->getLibrariesToLoad($assets) === ['core/a', 'core/b', 'core/d']
   * @endcode
   *
   * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
   *   The assets attached to the current response.
   *
   * @return string[]
   *   A list of libraries and their dependencies, in the order they should be
   *   loaded, excluding any libraries that have already been loaded.
   */
  protected function getLibrariesToLoad(AttachedAssetsInterface $assets) {
    return array_diff(
      $this->libraryDependencyResolver->getLibrariesWithDependencies($assets->getLibraries()),
      $this->libraryDependencyResolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries())
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCssAssets(AttachedAssetsInterface $assets, $optimize) {
    $theme_info = $this->themeManager->getActiveTheme();

    $css = [];
97 98 99 100 101 102 103 104 105
    $default_options = [
      'type' => 'file',
      'group' => CSS_AGGREGATE_DEFAULT,
      'weight' => 0,
      'every_page' => FALSE,
      'media' => 'all',
      'preprocess' => TRUE,
      'browsers' => [],
    ];
106 107 108 109 110 111

    foreach ($this->getLibrariesToLoad($assets) as $library) {
      list($extension, $name) = explode('/', $library, 2);
      $definition = $this->libraryDiscovery->getLibraryByName($extension, $name);
      if (isset($definition['css'])) {
        foreach ($definition['css'] as $options) {
112 113
          $options += $default_options;
          $options['browsers'] += [
114 115
            'IE' => TRUE,
            '!IE' => TRUE,
116
          ];
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

          // Files with a query string cannot be preprocessed.
          if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
            $options['preprocess'] = FALSE;
          }

          // Always add a tiny value to the weight, to conserve the insertion
          // order.
          $options['weight'] += count($css) / 1000;

          // Add the data to the CSS array depending on the type.
          switch ($options['type']) {
            case 'file':
              // Local CSS files are keyed by basename; if a file with the same
              // basename is added more than once, it gets overridden.
              // By default, take over the filename as basename.
              if (!isset($options['basename'])) {
134
                $options['basename'] = \Drupal::service('file_system')->basename($options['data']);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
              }
              $css[$options['basename']] = $options;
              break;

            default:
              // External files are keyed by their full URI, so the same CSS
              // file is not added twice.
              $css[$options['data']] = $options;
          }
        }
      }
    }

    // Allow modules and themes to alter the CSS assets.
    $this->moduleHandler->alter('css', $css, $assets);
    $this->themeManager->alter('css', $css, $assets);

    // Sort CSS items, so that they appear in the correct order.
    uasort($css, 'static::sort');

    // Allow themes to remove CSS files by basename.
    if ($stylesheet_remove = $theme_info->getStyleSheetsRemove()) {
      foreach ($css as $key => $options) {
        if (isset($options['basename']) && isset($stylesheet_remove[$options['basename']])) {
          unset($css[$key]);
        }
      }
    }
    // Allow themes to conditionally override CSS files by basename.
    if ($stylesheet_override = $theme_info->getStyleSheetsOverride()) {
      foreach ($css as $key => $options) {
        if (isset($options['basename']) && isset($stylesheet_override[$options['basename']])) {
          $css[$key]['data'] = $stylesheet_override[$options['basename']];
        }
      }
    }

    if ($optimize) {
      $css = \Drupal::service('asset.css.collection_optimizer')->optimize($css);
    }

    return $css;
  }

  /**
   * Returns the JavaScript settings assets for this response's libraries.
   *
   * Gathers all drupalSettings from all libraries in the attached assets
   * collection and merges them, then it merges individual attached settings,
   * and finally invokes hook_js_settings_alter() to allow alterations of
   * JavaScript settings by modules and themes.
   *
   * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
   *   The assets attached to the current response.
   * @return array
   *   A (possibly optimized) collection of JavaScript assets.
   */
  protected function getJsSettingsAssets(AttachedAssetsInterface $assets) {
    $settings = [];

    foreach ($this->getLibrariesToLoad($assets) as $library) {
      list($extension, $name) = explode('/', $library, 2);
      $definition = $this->libraryDiscovery->getLibraryByName($extension, $name);
      if (isset($definition['drupalSettings'])) {
        $settings = NestedArray::mergeDeepArray([$settings, $definition['drupalSettings']], TRUE);
      }
    }

    // Attached settings win over settings in libraries.
    $settings = NestedArray::mergeDeepArray([$settings, $assets->getSettings()], TRUE);

    // Allow modules and themes to alter the JavaScript settings.
    $this->moduleHandler->alter('js_settings', $settings, $assets);
    $this->themeManager->alter('js_settings', $settings, $assets);

    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function getJsAssets(AttachedAssetsInterface $assets, $optimize) {
    $javascript = [];
218 219 220 221 222 223 224 225 226 227 228 229
    $default_options = [
      'type' => 'file',
      'group' => JS_DEFAULT,
      'every_page' => FALSE,
      'weight' => 0,
      'cache' => TRUE,
      'preprocess' => TRUE,
      'attributes' => [],
      'version' => NULL,
      'browsers' => [],
    ];

230
    $libraries_to_load = $this->getLibrariesToLoad($assets);
231

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    // Collect all libraries that contain JS assets and are in the header.
    $header_js_libraries = [];
    foreach ($libraries_to_load as $library) {
      list($extension, $name) = explode('/', $library, 2);
      $definition = $this->libraryDiscovery->getLibraryByName($extension, $name);
      if (isset($definition['js']) && !empty($definition['header'])) {
        $header_js_libraries[] = $library;
      }
    }
    // The current list of header JS libraries are only those libraries that are
    // in the header, but their dependencies must also be loaded for them to
    // function correctly, so update the list with those.
    $header_js_libraries = $this->libraryDependencyResolver->getLibrariesWithDependencies($header_js_libraries);

    foreach ($libraries_to_load as $library) {
247 248 249 250
      list($extension, $name) = explode('/', $library, 2);
      $definition = $this->libraryDiscovery->getLibraryByName($extension, $name);
      if (isset($definition['js'])) {
        foreach ($definition['js'] as $options) {
251
          $options += $default_options;
252

253 254 255 256
          // 'scope' is a calculated option, based on which libraries are marked
          // to be loaded from the header (see above).
          $options['scope'] = in_array($library, $header_js_libraries) ? 'header' : 'footer';

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
          // Preprocess can only be set if caching is enabled and no attributes
          // are set.
          $options['preprocess'] = $options['cache'] && empty($options['attributes']) ? $options['preprocess'] : FALSE;

          // Always add a tiny value to the weight, to conserve the insertion
          // order.
          $options['weight'] += count($javascript) / 1000;

          // Local and external files must keep their name as the associative
          // key so the same JavaScript file is not added twice.
          $javascript[$options['data']] = $options;
        }
      }
    }

    // Allow modules and themes to alter the JavaScript assets.
    $this->moduleHandler->alter('js', $javascript, $assets);
    $this->themeManager->alter('js', $javascript, $assets);

    // Sort JavaScript assets, so that they appear in the correct order.
    uasort($javascript, 'static::sort');

    // Prepare the return value: filter JavaScript assets per scope.
    $js_assets_header = [];
    $js_assets_footer = [];
    foreach ($javascript as $key => $item) {
      if ($item['scope'] == 'header') {
        $js_assets_header[$key] = $item;
      }
      elseif ($item['scope'] == 'footer') {
        $js_assets_footer[$key] = $item;
      }
    }

291 292 293 294 295 296
    if ($optimize) {
      $collection_optimizer = \Drupal::service('asset.js.collection_optimizer');
      $js_assets_header = $collection_optimizer->optimize($js_assets_header);
      $js_assets_footer = $collection_optimizer->optimize($js_assets_footer);
    }

297 298 299 300 301 302 303 304 305 306 307 308 309 310
    // If the core/drupalSettings library is being loaded or is already loaded,
    // get the JavaScript settings assets, and convert them into a single
    // "regular" JavaScript asset.
    $libraries_to_load = $this->getLibrariesToLoad($assets);
    $settings_needed = in_array('core/drupalSettings', $libraries_to_load) || in_array('core/drupalSettings', $this->libraryDependencyResolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()));
    $settings_have_changed = count($libraries_to_load) > 0 || count($assets->getSettings()) > 0;
    if ($settings_needed && $settings_have_changed) {
      $settings = $this->getJsSettingsAssets($assets);
      if (!empty($settings)) {
        $settings_as_inline_javascript = [
          'type' => 'setting',
          'group' => JS_SETTING,
          'every_page' => TRUE,
          'weight' => 0,
311
          'browsers' => [],
312 313
          'data' => $settings,
        ];
314 315 316 317 318 319 320 321 322
        $settings_js_asset = ['drupalSettings' => $settings_as_inline_javascript];
        // Prepend to the list of JS assets, to render it first. Preferably in
        // the footer, but in the header if necessary.
        if (in_array('core/drupalSettings', $header_js_libraries)) {
          $js_assets_header = $settings_js_asset + $js_assets_header;
        }
        else {
          $js_assets_footer = $settings_js_asset + $js_assets_footer;
        }
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
      }
    }

    return [
      $js_assets_header,
      $js_assets_footer,
    ];
  }

  /**
   * Sorts CSS and JavaScript resources.
   *
   * This sort order helps optimize front-end performance while providing
   * modules and themes with the necessary control for ordering the CSS and
   * JavaScript appearing on a page.
   *
   * @param $a
   *   First item for comparison. The compared items should be associative
   *   arrays of member items.
   * @param $b
   *   Second item for comparison.
   *
   * @return int
   */
  public static function sort($a, $b) {
    // First order by group, so that all items in the CSS_AGGREGATE_DEFAULT
    // group appear before items in the CSS_AGGREGATE_THEME group. Modules may
    // create additional groups by defining their own constants.
    if ($a['group'] < $b['group']) {
      return -1;
    }
    elseif ($a['group'] > $b['group']) {
      return 1;
    }
    // Within a group, order all infrequently needed, page-specific files after
    // common files needed throughout the website. Separating this way allows
    // for the aggregate file generated for all of the common files to be reused
    // across a site visit without being cut by a page using a less common file.
    elseif ($a['every_page'] && !$b['every_page']) {
      return -1;
    }
    elseif (!$a['every_page'] && $b['every_page']) {
      return 1;
    }
    // Finally, order by weight.
    elseif ($a['weight'] < $b['weight']) {
      return -1;
    }
    elseif ($a['weight'] > $b['weight']) {
      return 1;
    }
    else {
      return 0;
    }
  }

}