Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / advagg / src / Asset / CssCollectionRenderer.php
1 <?php
2
3 namespace Drupal\advagg\Asset;
4
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;
10
11 /**
12  * {@inheritdoc}
13  */
14 class CssCollectionRenderer extends CoreCssCollectionRenderer implements AssetCollectionRendererInterface {
15
16   /**
17    * A config object for the advagg configuration.
18    *
19    * @var \Drupal\Core\Config\Config
20    */
21   protected $config;
22
23   /**
24    * {@inheritdoc}
25    *
26    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
27    *   A config factory for retrieving required config objects.
28    */
29   public function __construct(StateInterface $state, ConfigFactoryInterface $config_factory) {
30     $this->state = $state;
31     $this->config = $config_factory->get('advagg.settings');
32   }
33
34   /**
35    * {@inheritdoc}
36    */
37   public function render(array $css_assets) {
38     $elements = ['prefetch' => []];
39     $prefetch = $this->config->get('dns_prefetch');
40
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
44     // URL changed.
45     $query_string = $this->state->get('system.css_js_query_string') ?: '0';
46
47     // Defaults skeleton for elements.
48     $link_element_defaults = [
49       '#type' => 'html_tag',
50       '#tag' => 'link',
51       '#attributes' => [
52         'rel' => 'stylesheet',
53       ],
54     ];
55     $style_element_defaults = [
56       '#type' => 'html_tag',
57       '#tag' => 'style',
58     ];
59     $prefetch_element_defaults = [
60       '#type' => 'html_tag',
61       '#tag' => 'link',
62       '#attributes' => [
63         'rel' => 'dns-prefetch',
64       ],
65     ];
66
67     // For filthy IE hack.
68     $current_ie_group_key = NULL;
69     $get_ie_group_key = function ($css_asset) {
70       return [
71         $css_asset['type'],
72         $css_asset['preprocess'],
73         $css_asset['group'],
74         $css_asset['media'],
75         $css_asset['browsers'],
76       ];
77     };
78
79     // Loop through all CSS assets, by key, to allow for the special IE
80     // workaround.
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
90         //   in two ways:
91         //   - file CSS assets that are not eligible for aggregation (their
92         //     'preprocess' flag has been set to FALSE): in this case, output a
93         //     LINK tag.
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
99         //     statements).
100         case 'file':
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);
111               }
112             }
113           }
114
115           // The dummy query string needs to be added to the URL to control
116           // browser-caching.
117           $query_string_separator = (strpos($css_asset['data'], '?') !== FALSE) ? '&' : '?';
118
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'];
127             }
128             $element['#inline'] = !empty($css_asset['inline']) ? TRUE : FALSE;
129             $elements[] = $element;
130           }
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.
134           else {
135             // The file CSS asset is ineligible for aggregation: output it in a
136             // LINK tag.
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;
144             }
145             // The file CSS asset can be aggregated, but hasn't been: combine
146             // multiple items into as few STYLE tags as possible.
147             else {
148               $import = [];
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'.
153               $j = $i;
154               $next_css_asset = $css_asset;
155               $current_ie_group_key = $get_ie_group_key($css_asset);
156               do {
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.
164                 $i = $j;
165                 // Retrieve next CSS asset, unless there is none: then break.
166                 if ($j + 1 < count($css_assets_keys)) {
167                   $j++;
168                   $next_css_asset = $css_assets[$css_assets_keys[$j]];
169                 }
170                 else {
171                   break;
172                 }
173               } while ($get_ie_group_key($next_css_asset) == $current_ie_group_key);
174
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
185                 // match the regex.
186                 $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
187                 if (isset($css_asset['media'])) {
188                   $element['#attributes']['media'] = $css_asset['media'];
189                 }
190                 $element['#browsers'] = $css_asset['browsers'];
191                 $elements[] = $element;
192               }
193             }
194           }
195           break;
196
197         // Output a LINK tag for an external CSS asset. The asset's 'data'
198         // property contains the full URL.
199         case 'external':
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;
205           if ($prefetch) {
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;
213             }
214           }
215           break;
216
217         default:
218           throw new \Exception('Invalid CSS asset type.');
219       }
220     }
221     if (empty($elements['prefetch'])) {
222       unset($elements['prefetch']);
223     }
224     return $elements;
225   }
226
227 }