Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Asset / CssCollectionRenderer.php
1 <?php
2
3 namespace Drupal\Core\Asset;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\State\StateInterface;
7
8 /**
9  * Renders CSS assets.
10  *
11  * For production websites, LINK tags are preferable to STYLE tags with @import
12  * statements, because:
13  * - They are the standard tag intended for linking to a resource.
14  * - On Firefox 2 and perhaps other browsers, CSS files included with @import
15  *   statements don't get saved when saving the complete web page for offline
16  *   use: https://www.drupal.org/node/145218.
17  * - On IE, if only LINK tags and no @import statements are used, all the CSS
18  *   files are downloaded in parallel, resulting in faster page load, but if
19  *   @import statements are used and span across multiple STYLE tags, all the
20  *   ones from one STYLE tag must be downloaded before downloading begins for
21  *   the next STYLE tag. Furthermore, IE7 does not support media declaration on
22  *   the @import statement, so multiple STYLE tags must be used when different
23  *   files are for different media types. Non-IE browsers always download in
24  *   parallel, so this is an IE-specific performance quirk:
25  *   http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
26  *
27  * However, IE has an annoying limit of 31 total CSS inclusion tags
28  * (https://www.drupal.org/node/228818) and LINK tags are limited to one file
29  * per tag, whereas STYLE tags can contain multiple @import statements allowing
30  * multiple files to be loaded per tag. When CSS aggregation is disabled, a
31  * Drupal site can easily have more than 31 CSS files that need to be loaded, so
32  * using LINK tags exclusively would result in a site that would display
33  * incorrectly in IE. Depending on different needs, different strategies can be
34  * employed to decide when to use LINK tags and when to use STYLE tags.
35  *
36  * The strategy employed by this class is to use LINK tags for all aggregate
37  * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
38  * set to FALSE or the type is 'external'), and to use STYLE tags for groups
39  * of files that could be aggregated together but aren't (e.g., if the site-wide
40  * aggregation setting is disabled). This results in all LINK tags when
41  * aggregation is enabled, a guarantee that as many or only slightly more tags
42  * are used with aggregation disabled than enabled (so that if the limit were to
43  * be crossed with aggregation enabled, the site developer would also notice the
44  * problem while aggregation is disabled), and an easy way for a developer to
45  * view HTML source while aggregation is disabled and know what files will be
46  * aggregated together when aggregation becomes enabled.
47  *
48  * This class evaluates the aggregation enabled/disabled condition on a group
49  * by group basis by testing whether an aggregate file has been made for the
50  * group rather than by testing the site-wide aggregation setting. This allows
51  * this class to work correctly even if modules have implemented custom
52  * logic for grouping and aggregating files.
53  */
54 class CssCollectionRenderer implements AssetCollectionRendererInterface {
55
56   /**
57    * The state key/value store.
58    *
59    * @var \Drupal\Core\State\StateInterface
60    */
61   protected $state;
62
63   /**
64    * Constructs a CssCollectionRenderer.
65    *
66    * @param \Drupal\Core\State\StateInterface $state
67    *   The state key/value store.
68    */
69   public function __construct(StateInterface $state) {
70     $this->state = $state;
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function render(array $css_assets) {
77     $elements = [];
78
79     // A dummy query-string is added to filenames, to gain control over
80     // browser-caching. The string changes on every update or full cache
81     // flush, forcing browsers to load a new copy of the files, as the
82     // URL changed.
83     $query_string = $this->state->get('system.css_js_query_string') ?: '0';
84
85     // Defaults for LINK and STYLE elements.
86     $link_element_defaults = [
87       '#type' => 'html_tag',
88       '#tag' => 'link',
89       '#attributes' => [
90         'rel' => 'stylesheet',
91       ],
92     ];
93     $style_element_defaults = [
94       '#type' => 'html_tag',
95       '#tag' => 'style',
96     ];
97
98     // For filthy IE hack.
99     $current_ie_group_keys = NULL;
100     $get_ie_group_key = function ($css_asset) {
101       return [$css_asset['type'], $css_asset['preprocess'], $css_asset['group'], $css_asset['media'], $css_asset['browsers']];
102     };
103
104     // Loop through all CSS assets, by key, to allow for the special IE
105     // workaround.
106     $css_assets_keys = array_keys($css_assets);
107     for ($i = 0; $i < count($css_assets_keys); $i++) {
108       $css_asset = $css_assets[$css_assets_keys[$i]];
109       switch ($css_asset['type']) {
110         // For file items, there are three possibilities.
111         // - There are up to 31 CSS assets on the page (some of which may be
112         //   aggregated). In this case, output a LINK tag for file CSS assets.
113         // - There are more than 31 CSS assets on the page, yet we must stay
114         //   below IE<10's limit of 31 total CSS inclusion tags, we handle this
115         //   in two ways:
116         //    - file CSS assets that are not eligible for aggregation (their
117         //      'preprocess' flag has been set to FALSE): in this case, output a
118         //      LINK tag.
119         //    - file CSS assets that can be aggregated (and possibly have been):
120         //      in this case, figure out which subsequent file CSS assets share
121         //      the same key properties ('group', 'media' and 'browsers') and
122         //      output this group into as few STYLE tags as possible (a STYLE
123         //      tag may contain only 31 @import statements).
124         case 'file':
125           // The dummy query string needs to be added to the URL to control
126           // browser-caching.
127           $query_string_separator = (strpos($css_asset['data'], '?') !== FALSE) ? '&' : '?';
128
129           // As long as the current page will not run into IE's limit for CSS
130           // assets: output a LINK tag for a file CSS asset.
131           if (count($css_assets) <= 31) {
132             $element = $link_element_defaults;
133             $element['#attributes']['href'] = file_url_transform_relative(file_create_url($css_asset['data'])) . $query_string_separator . $query_string;
134             $element['#attributes']['media'] = $css_asset['media'];
135             $element['#browsers'] = $css_asset['browsers'];
136             $elements[] = $element;
137           }
138           // The current page will run into IE's limits for CSS assets: work
139           // around these limits by performing a light form of grouping.
140           // Once Drupal only needs to support IE10 and later, we can drop this.
141           else {
142             // The file CSS asset is ineligible for aggregation: output it in a
143             // LINK tag.
144             if (!$css_asset['preprocess']) {
145               $element = $link_element_defaults;
146               $element['#attributes']['href'] = file_url_transform_relative(file_create_url($css_asset['data'])) . $query_string_separator . $query_string;
147               $element['#attributes']['media'] = $css_asset['media'];
148               $element['#browsers'] = $css_asset['browsers'];
149               $elements[] = $element;
150             }
151             // The file CSS asset can be aggregated, but hasn't been: combine
152             // multiple items into as few STYLE tags as possible.
153             else {
154               $import = [];
155               // Start with the current CSS asset, iterate over subsequent CSS
156               // assets and find which ones have the same 'type', 'group',
157               // 'preprocess', 'media' and 'browsers' properties.
158               $j = $i;
159               $next_css_asset = $css_asset;
160               $current_ie_group_key = $get_ie_group_key($css_asset);
161               do {
162                 // The dummy query string needs to be added to the URL to
163                 // control browser-caching. IE7 does not support a media type on
164                 // the @import statement, so we instead specify the media for
165                 // the group on the STYLE tag.
166                 $import[] = '@import url("' . Html::escape(file_url_transform_relative(file_create_url($next_css_asset['data'])) . '?' . $query_string) . '");';
167                 // Move the outer for loop skip the next item, since we
168                 // processed it here.
169                 $i = $j;
170                 // Retrieve next CSS asset, unless there is none: then break.
171                 if ($j + 1 < count($css_assets_keys)) {
172                   $j++;
173                   $next_css_asset = $css_assets[$css_assets_keys[$j]];
174                 }
175                 else {
176                   break;
177                 }
178               } while ($get_ie_group_key($next_css_asset) == $current_ie_group_key);
179
180               // In addition to IE's limit of 31 total CSS inclusion tags, it
181               // also has a limit of 31 @import statements per STYLE tag.
182               while (!empty($import)) {
183                 $import_batch = array_slice($import, 0, 31);
184                 $import = array_slice($import, 31);
185                 $element = $style_element_defaults;
186                 // This simplifies the JavaScript regex, allowing each line
187                 // (separated by \n) to be treated as a completely different
188                 // string. This means that we can use ^ and $ on one line at a
189                 // time, and not worry about style tags since they'll never
190                 // match the regex.
191                 $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
192                 $element['#attributes']['media'] = $css_asset['media'];
193                 $element['#browsers'] = $css_asset['browsers'];
194                 $elements[] = $element;
195               }
196             }
197           }
198           break;
199
200         // Output a LINK tag for an external CSS asset. The asset's 'data'
201         // property contains the full URL.
202         case 'external':
203           $element = $link_element_defaults;
204           $element['#attributes']['href'] = $css_asset['data'];
205           $element['#attributes']['media'] = $css_asset['media'];
206           $element['#browsers'] = $css_asset['browsers'];
207           $elements[] = $element;
208           break;
209
210         default:
211           throw new \Exception('Invalid CSS asset type.');
212       }
213     }
214
215     return $elements;
216   }
217
218 }