1<?php
2
3namespace Drupal\Core\Asset;
4
5use Drupal\Component\Serialization\Json;
6use Drupal\Core\State\StateInterface;
7
8/**
9 * Renders JavaScript assets.
10 */
11class JsCollectionRenderer implements AssetCollectionRendererInterface {
12
13  /**
14   * The state key/value store.
15   *
16   * @var \Drupal\Core\State\StateInterface
17   */
18  protected $state;
19
20  /**
21   * Constructs a JsCollectionRenderer.
22   *
23   * @param \Drupal\Core\State\StateInterface $state
24   *   The state key/value store.
25   */
26  public function __construct(StateInterface $state) {
27    $this->state = $state;
28  }
29
30  /**
31   * {@inheritdoc}
32   *
33   * This class evaluates the aggregation enabled/disabled condition on a group
34   * by group basis by testing whether an aggregate file has been made for the
35   * group rather than by testing the site-wide aggregation setting. This allows
36   * this class to work correctly even if modules have implemented custom
37   * logic for grouping and aggregating files.
38   */
39  public function render(array $js_assets) {
40    $elements = [];
41
42    // A dummy query-string is added to filenames, to gain control over
43    // browser-caching. The string changes on every update or full cache
44    // flush, forcing browsers to load a new copy of the files, as the
45    // URL changed. Files that should not be cached get REQUEST_TIME as
46    // query-string instead, to enforce reload on every page request.
47    $default_query_string = $this->state->get('system.css_js_query_string', '0');
48
49    // Defaults for each SCRIPT element.
50    $element_defaults = [
51      '#type' => 'html_tag',
52      '#tag' => 'script',
53      '#value' => '',
54    ];
55
56    // Loop through all JS assets.
57    foreach ($js_assets as $js_asset) {
58      // Element properties that do not depend on JS asset type.
59      $element = $element_defaults;
60      $element['#browsers'] = $js_asset['browsers'];
61
62      // Element properties that depend on item type.
63      switch ($js_asset['type']) {
64        case 'setting':
65          $element['#attributes'] = [
66            // This type attribute prevents this from being parsed as an
67            // inline script.
68            'type' => 'application/json',
69            'data-drupal-selector' => 'drupal-settings-json',
70          ];
71          $element['#value'] = Json::encode($js_asset['data']);
72          break;
73
74        case 'file':
75          $query_string = $js_asset['version'] == -1 ? $default_query_string : 'v=' . $js_asset['version'];
76          $query_string_separator = (strpos($js_asset['data'], '?') !== FALSE) ? '&' : '?';
77          $element['#attributes']['src'] = file_url_transform_relative(file_create_url($js_asset['data']));
78          // Only add the cache-busting query string if this isn't an aggregate
79          // file.
80          if (!isset($js_asset['preprocessed'])) {
81            $element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : REQUEST_TIME);
82          }
83          break;
84
85        case 'external':
86          $element['#attributes']['src'] = $js_asset['data'];
87          break;
88
89        default:
90          throw new \Exception('Invalid JS asset type.');
91      }
92
93      // Attributes may only be set if this script is output independently.
94      if (!empty($element['#attributes']['src']) && !empty($js_asset['attributes'])) {
95        $element['#attributes'] += $js_asset['attributes'];
96      }
97
98      $elements[] = $element;
99    }
100
101    return $elements;
102  }
103
104}
105