3 namespace Drupal\advagg\Asset;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Asset\AssetCollectionRendererInterface;
7 use Drupal\Core\Asset\CssCollectionRenderer as CoreCssCollectionRenderer;
8 use Drupal\Core\Config\ConfigFactoryInterface;
9 use Drupal\Core\State\StateInterface;
14 class CssCollectionRenderer extends CoreCssCollectionRenderer implements AssetCollectionRendererInterface {
17 * A config object for the advagg configuration.
19 * @var \Drupal\Core\Config\Config
26 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
27 * A config factory for retrieving required config objects.
29 public function __construct(StateInterface $state, ConfigFactoryInterface $config_factory) {
30 $this->state = $state;
31 $this->config = $config_factory->get('advagg.settings');
37 public function render(array $css_assets) {
38 $elements = ['prefetch' => []];
39 $prefetch = $this->config->get('dns_prefetch');
41 // A dummy query-string is added to filenames, to gain control over
42 // browser-caching. The string changes on every update or full cache
43 // flush, forcing browsers to load a new copy of the files, as the
45 $query_string = $this->state->get('system.css_js_query_string') ?: '0';
47 // Defaults skeleton for elements.
48 $link_element_defaults = [
49 '#type' => 'html_tag',
52 'rel' => 'stylesheet',
55 $style_element_defaults = [
56 '#type' => 'html_tag',
59 $prefetch_element_defaults = [
60 '#type' => 'html_tag',
63 'rel' => 'dns-prefetch',
67 // For filthy IE hack.
68 $current_ie_group_key = NULL;
69 $get_ie_group_key = function ($css_asset) {
72 $css_asset['preprocess'],
75 $css_asset['browsers'],
79 // Loop through all CSS assets, by key, to allow for the special IE
81 $css_assets_keys = array_keys($css_assets);
82 for ($i = 0; $i < count($css_assets_keys); $i++) {
83 $css_asset = $css_assets[$css_assets_keys[$i]];
84 switch ($css_asset['type']) {
85 // For file items, there are three possibilities.
86 // - There are up to 31 CSS assets on the page (some of which may be
87 // aggregated). In this case, output a LINK tag for file CSS assets.
88 // - There are more than 31 CSS assets on the page, yet we must stay
89 // below IE<10's limit of 31 total CSS inclusion tags, we handle this
91 // - file CSS assets that are not eligible for aggregation (their
92 // 'preprocess' flag has been set to FALSE): in this case, output a
94 // - file CSS assets that can be aggregated (and possibly have been):
95 // in this case, figure out which subsequent file CSS assets share
96 // the same key properties ('group', 'inline', 'browsers' and if
97 // set also 'media') and output this group into as few STYLE tags
98 // as possible (each STYLE tag must have less than 31 @import
101 // Prefetch contained domains (ie calls to url()).
102 if ($prefetch && !empty($css_asset['dns_prefetch'])) {
103 foreach ($css_asset['dns_prefetch'] as $domain) {
104 $element = $prefetch_element_defaults;
105 $element['#attributes']['href'] = '//' . $domain;
106 $elements['prefetch'][] = $element;
107 if ($domain == 'fonts.googleapis.com') {
108 // Add fonts.gstatic.com when fonts.googleapis.com is added.
109 $element['#attributes']['href'] = 'https://fonts.gstatic.com';
110 array_unshift($elements, $element);
115 // The dummy query string needs to be added to the URL to control
117 $query_string_separator = (strpos($css_asset['data'], '?') !== FALSE) ? '&' : '?';
119 // As long as the current page will not run into IE's limit for CSS
120 // assets: output a LINK tag for a file CSS asset.
121 if (count($css_assets) <= 31) {
122 $element = $link_element_defaults;
123 $element['#attributes']['href'] = file_url_transform_relative(file_create_url($css_asset['data'])) . $query_string_separator . $query_string;
124 $element['#browsers'] = $css_asset['browsers'];
125 if (isset($css_asset['media'])) {
126 $element['#attributes']['media'] = $css_asset['media'];
128 $element['#inline'] = !empty($css_asset['inline']) ? TRUE : FALSE;
129 $elements[] = $element;
131 // The current page will run into IE's limits for CSS assets: work
132 // around these limits by performing a light form of grouping.
133 // Once Drupal only needs to support IE10 and later, we can drop this.
135 // The file CSS asset is ineligible for aggregation: output it in a
137 if (!$css_asset['preprocess']) {
138 $element = $link_element_defaults;
139 $element['#attributes']['href'] = file_url_transform_relative(file_create_url($css_asset['data'])) . $query_string_separator . $query_string;
140 $element['#attributes']['media'] = $css_asset['media'];
141 $element['#browsers'] = $css_asset['browsers'];
142 $element['#inline'] = !empty($css_asset['inline']) ? TRUE : FALSE;
143 $elements[] = $element;
145 // The file CSS asset can be aggregated, but hasn't been: combine
146 // multiple items into as few STYLE tags as possible.
149 // Start with the current CSS asset, iterate over subsequent CSS
150 // assets and find which ones have the same 'type', 'group',
151 // 'preprocess', 'inline', 'browsers' properties and depending on
152 // settings, also 'media'.
154 $next_css_asset = $css_asset;
155 $current_ie_group_key = $get_ie_group_key($css_asset);
157 // The dummy query string needs to be added to the URL to
158 // control browser-caching. IE7 does not support a media type on
159 // the @import statement, so we instead specify the media for
160 // the group on the STYLE tag.
161 $import[] = '@import url("' . Html::escape(file_url_transform_relative(file_create_url($next_css_asset['data'])) . '?' . $query_string) . '");';
162 // Move the outer for loop skip the next item, since we
163 // processed it here.
165 // Retrieve next CSS asset, unless there is none: then break.
166 if ($j + 1 < count($css_assets_keys)) {
168 $next_css_asset = $css_assets[$css_assets_keys[$j]];
173 } while ($get_ie_group_key($next_css_asset) == $current_ie_group_key);
175 // In addition to IE's limit of 31 total CSS inclusion tags, it
176 // also has a limit of 31 @import statements per STYLE tag.
177 while (!empty($import)) {
178 $import_batch = array_slice($import, 0, 31);
179 $import = array_slice($import, 31);
180 $element = $style_element_defaults;
181 // This simplifies the JavaScript regex, allowing each line
182 // (separated by \n) to be treated as a completely different
183 // string. This means that we can use ^ and $ on one line at a
184 // time, and not worry about style tags since they'll never
186 $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
187 if (isset($css_asset['media'])) {
188 $element['#attributes']['media'] = $css_asset['media'];
190 $element['#browsers'] = $css_asset['browsers'];
191 $elements[] = $element;
197 // Output a LINK tag for an external CSS asset. The asset's 'data'
198 // property contains the full URL.
200 $element = $link_element_defaults;
201 $element['#attributes']['href'] = $css_asset['data'];
202 $element['#attributes']['media'] = $css_asset['media'];
203 $element['#browsers'] = $css_asset['browsers'];
204 $elements[] = $element;
206 $element = $prefetch_element_defaults;
207 $element['#attributes']['href'] = '//' . parse_url($css_asset['data'], PHP_URL_HOST);
208 $elements['prefetch'][] = $element;
209 if ($element['#attributes']['href'] == 'fonts.googleapis.com') {
210 // Add fonts.gstatic.com when fonts.googleapis.com is added.
211 $element['#attributes']['href'] = 'https://fonts.gstatic.com';
212 $elements['prefetch'][] = $element;
218 throw new \Exception('Invalid CSS asset type.');
221 if (empty($elements['prefetch'])) {
222 unset($elements['prefetch']);