Completed
Push — master ( 247f2f...fcbcfe )
by Nazar
03:56
created

Includes_processing::css()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 77
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 6.2163

Importance

Changes 0
Metric Value
cc 6
eloc 41
nc 1
nop 3
dl 0
loc 77
ccs 27
cts 33
cp 0.8182
crap 6.2163
rs 8.4456
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2014-2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Page;
9
10
/**
11
 * Class includes few methods used for processing CSS and HTML files before putting into cache.
12
 *
13
 * This is because CSS and HTML files may contain other includes of other CSS, JS files, images, fonts and so on with absolute and relative paths.
14
 * Methods of this class handles all this includes and put them into single resulting file compressed with gzip.
15
 * This allows to decrease number of HTTP requests on page and avoid breaking of relative paths for fonts, images and other includes
16
 * after putting them into cache directory.
17
 */
18
class Includes_processing {
19
	/**
20
	 * Do not inline files bigger than 4 KiB
21
	 */
22
	const MAX_EMBEDDING_SIZE = 4096;
23
	protected static $extension_to_mime = [
24
		'jpeg' => 'image/jpg',
25
		'jpe'  => 'image/jpg',
26
		'jpg'  => 'image/jpg',
27
		'gif'  => 'image/gif',
28
		'png'  => 'image/png',
29
		'svg'  => 'image/svg+xml',
30
		'svgz' => 'image/svg+xml',
31
		'woff' => 'application/font-woff',
32
		//'woff2' => 'application/font-woff2',
33
		'css'  => 'text/css'
34
	];
35
	/**
36
	 * Analyses file for images, fonts and css links and include they content into single resulting css file.
37
	 *
38
	 * Supports next file extensions for possible includes:
39
	 * jpeg, jpe, jpg, gif, png, ttf, ttc, svg, svgz, woff, eot, css
40
	 *
41
	 * @param string   $data                   Content of processed file
42
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
43
	 * @param string[] $not_embedded_resources Some resources like images and fonts might not be embedded into resulting CSS because of their size
44
	 *
45
	 * @return string    $data
46
	 */
47 4
	static function css ($data, $file, &$not_embedded_resources = []) {
48 4
		$dir = dirname($file);
49
		/**
50
		 * Remove comments, tabs and new lines
51
		 */
52 4
		$data = preg_replace('#(/\*.*?\*/)|\t|\n|\r#s', ' ', $data);
53
		/**
54
		 * Remove unnecessary spaces
55
		 */
56 4
		$data = preg_replace('/\s*([,;>{}(])\s*/', '$1', $data);
57 4
		$data = preg_replace('/\s+/', ' ', $data);
58
		/**
59
		 * Return spaces required in media queries
60
		 */
61 4
		$data = preg_replace('/\s(and|or)\(/', ' $1 (', $data);
62
		/**
63
		 * Duplicated semicolons
64
		 */
65 4
		$data = preg_replace('/;+/m', ';', $data);
66
		/**
67
		 * Minify repeated colors declarations
68
		 */
69 4
		$data = preg_replace('/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3/i', '#$1$2$3', $data);
70
		/**
71
		 * Minify rgb colors declarations
72
		 */
73 4
		$data = preg_replace_callback(
74 4
			'/rgb\(([0-9,.]+)\)/i',
75
			function ($rgb) {
76
				$rgb = explode(',', $rgb[1]);
77
				return
78
					'#'.
79
					str_pad(dechex($rgb[0]), 2, 0, STR_PAD_LEFT).
80
					str_pad(dechex($rgb[1]), 2, 0, STR_PAD_LEFT).
81
					str_pad(dechex($rgb[2]), 2, 0, STR_PAD_LEFT);
82 4
			},
83
			$data
84
		);
85
		/**
86
		 * Remove unnecessary zeros
87
		 */
88 4
		$data = preg_replace('/(\D)0\.(\d+)/i', '$1.$2', $data);
89
		/**
90
		 * Includes processing
91
		 */
92 4
		$data = preg_replace_callback(
93 4
			'/url\((.*?)\)|@import[\s\t\n\r]*[\'"](.*?)[\'"]/',
94
			function ($match) use ($dir, &$not_embedded_resources) {
95 4
				$link = trim($match[1], '\'" ');
96 4
				$link = explode('?', $link, 2)[0];
97 4
				if (!static::is_relative_path_and_exists($link, $dir)) {
98 4
					return $match[0];
99
				}
100 4
				$content   = file_get_contents("$dir/$link");
101 4
				$extension = file_extension($link);
102 4
				if (!isset(static::$extension_to_mime[$extension]) || filesize("$dir/$link") > static::MAX_EMBEDDING_SIZE) {
103 4
					$path_relatively_to_the_root = str_replace(getcwd(), '', realpath("$dir/$link"));
104 4
					$path_relatively_to_the_root .= '?'.substr(md5($content), 0, 5);
105 4
					if (strpos($match[1], '?') === false) {
106
						$not_embedded_resources[] = $path_relatively_to_the_root;
107
					}
108 4
					return str_replace($match[1], "'".str_replace("'", "\\'", $path_relatively_to_the_root)."'", $match[0]);
109
				}
110
				if ($extension == 'css') {
111
					/**
112
					 * For recursive includes processing, if CSS file includes others CSS files
113
					 */
114
					$content = static::css($content, $link, $not_embedded_resources);
115
				}
116
				$mime_type = static::$extension_to_mime[$extension];
117
				$content   = base64_encode($content);
118
				return str_replace($match[1], "data:$mime_type;charset=utf-8;base64,$content", $match[0]);
119 4
			},
120
			$data
121
		);
122 4
		return trim($data);
123
	}
124
	/**
125
	 * Simple and fast JS minification
126
	 *
127
	 * @param string $data
128
	 *
129
	 * @return string
130
	 */
131 4
	static function js ($data) {
132
		/**
133
		 * Split into array of lines
134
		 */
135 4
		$data = explode("\n", $data);
136
		/**
137
		 * Flag that is `true` when inside comment
138
		 */
139 4
		$comment = false;
140
		/**
141
		 * Set of symbols that are safe to be concatenated without new line with anything else
142
		 */
143
		$regexp = /** @lang PhpRegExp */
144 4
			'[:;,.+\-*/{}?><^\'"\[\]=&(]';
145 4
		foreach ($data as $index => &$d) {
146 4
			$next_line = isset($data[$index + 1]) ? trim($data[$index + 1]) : '';
147
			/**
148
			 * Remove starting and trailing spaces
149
			 */
150 4
			$d = trim($d);
151
			/**
152
			 * Remove single-line comments
153
			 */
154 4
			if (mb_strpos($d, '//') === 0) {
155 4
				$d = '';
156 4
				continue;
157
			}
158
			/**
159
			 * Starts with multi-line comment
160
			 */
161 4
			if (mb_strpos($d, '/*') === 0) {
162 4
				$comment = true;
163
			}
164
			/**
165
			 * Add new line at the end if only needed
166
			 */
167
			if (
168 4
				$d &&
169 4
				$next_line &&
170 4
				!$comment &&
171 4
				!preg_match("#$regexp\$#", $d) &&
172 4
				!preg_match("#^$regexp#", $next_line)
173
			) {
174 4
				$d .= "\n";
175
			}
176 4
			if ($comment) {
177
				/**
178
				 * End of multi-line comment
179
				 */
180 4
				if (strpos($d, '*/') !== false) {
181 4
					$d       = explode('*/', $d)[1];
182 4
					$comment = false;
183
				} else {
184 4
					$d = '';
185
				}
186
			} else {
187
				/**
188
				 * Single-line comment
189
				 */
190 4
				$d = preg_replace('#^\s*//[^\'"]+$#', '', $d);
191
				/**
192
				 * If we are not sure - just add new like afterwards
193
				 */
194 4
				$d = preg_replace('#//.*$#', "\\0\n", $d);
195
			}
196
		}
197 4
		$data = implode('', $data);
198 4
		$data = str_replace('</script>', '<\/script>', $data);
199 4
		return trim($data, ';').';';
200
	}
201
	/**
202
	 * Analyses file for scripts and styles, combines them into resulting files in order to optimize loading process
203
	 * (files with combined scripts and styles will be created)
204
	 *
205
	 * @param string   $data                   Content of processed file
206
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
207
	 * @param string   $base_target_file_path  Base filename for resulting combined files
208
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
209
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
210
	 *
211
	 * @return string
212
	 */
213 4
	static function html ($data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources = []) {
214 4
		static::html_process_scripts($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
215 4
		static::html_process_links_and_styles($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
216
		// Removing HTML comments (those that are mostly likely comments, to avoid problems)
217 4
		$data = preg_replace_callback(
218 4
			'/^\s*<!--([^>-].*[^-])?-->/Ums',
219 4
			function ($matches) {
220 4
				return mb_strpos('--', $matches[1]) === false ? '' : $matches[0];
221 4
			},
222
			$data
223
		);
224 4
		return preg_replace("/\n+/", "\n", $data);
225
	}
226
	/**
227
	 * @param string   $data                   Content of processed file
228
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
229
	 * @param string   $base_target_file_path  Base filename for resulting combined files
230
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
231
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
232
	 *
233
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
234
	 */
235 4
	protected static function html_process_scripts (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
236 4
		if (!preg_match_all('/<script(.*)<\/script>/Uims', $data, $scripts)) {
237 4
			return;
238
		}
239 4
		$scripts_content    = '';
240 4
		$scripts_to_replace = [];
241 4
		$dir                = dirname($file);
242 4
		foreach ($scripts[1] as $index => $script) {
243 4
			$script = explode('>', $script, 2);
244 4
			if (preg_match('/src\s*=\s*[\'"](.*)[\'"]/Uims', $script[0], $url)) {
245 4
				$url = $url[1];
246 4
				if (!static::is_relative_path_and_exists($url, $dir)) {
247
					continue;
248
				}
249 4
				$scripts_to_replace[] = $scripts[0][$index];
250 4
				$scripts_content .= file_get_contents("$dir/$url").";\n";
251
			} else {
252 4
				$scripts_to_replace[] = $scripts[0][$index];
253 4
				$scripts_content .= "$script[1];\n";
254
			}
255
		}
256 4
		$scripts_content = static::js($scripts_content);
257 4
		if (!$scripts_to_replace) {
258
			return;
259
		}
260
		// Remove all scripts
261 4
		$data = str_replace($scripts_to_replace, '', $data);
262
		/**
263
		 * If vulcanization is not used - put contents into separate file, and put link to it, otherwise put minified content back
264
		 */
265 4
		if (!$vulcanization) {
266
			/**
267
			 * md5 to distinguish modifications of the files
268
			 */
269
			$content_md5 = substr(md5($scripts_content), 0, 5);
270
			file_put_contents("$base_target_file_path.js", $scripts_content, LOCK_EX | FILE_BINARY);
271
			$base_target_file_name = basename($base_target_file_path);
272
			// Add script with combined content file to the end
273
			$data .= "<script src=\"$base_target_file_name.js?$content_md5\"></script>";
274
			$not_embedded_resources[] = "$base_target_file_name.js?$content_md5";
275
		} else {
276
			// Add combined content inline script to the end
277 4
			$data .= "<script>$scripts_content</script>";
278
		}
279 4
	}
280
	/**
281
	 * @param string   $data                   Content of processed file
282
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
283
	 * @param string   $base_target_file_path  Base filename for resulting combined files
284
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
285
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
286
	 *
287
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
288
	 */
289 4
	protected static function html_process_links_and_styles (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
290
		// Drop Polymer inclusion, since it is already present
291 4
		$data = str_replace('<link rel="import" href="../polymer/polymer.html">', '', $data);
292 4
		if (!preg_match_all('/<link(.*)>|<style(.*)<\/style>/Uims', $data, $links_and_styles)) {
293 4
			return;
294
		}
295 4
		$imports_content             = '';
296 4
		$links_and_styles_to_replace = [];
297 4
		$dir                         = dirname($file);
298 4
		foreach ($links_and_styles[1] as $index => $link) {
299
			/**
300
			 * Check for custom styles `is="custom-style"` or styles includes `include=".."` - we'll skip them
301
			 * Or if content is plain CSS
302
			 */
303
			if (
304 4
				preg_match('/^[^>]*(is="custom-style"|include=)[^>]*>/Uim', $links_and_styles[2][$index]) ||
305 4
				mb_strpos($links_and_styles[0][$index], '</style>') > 0
306
			) {
307 4
				$content = explode('>', $links_and_styles[2][$index], 2)[1];
308 4
				$data    = str_replace(
309
					$content,
310 4
					static::css($content, $file, $not_embedded_resources),
311
					$data
312
				);
313 4
				continue;
314
			}
315 4
			if (!static::has_relative_href($link, $url, $dir)) {
316
				continue;
317
			}
318 4
			$import = preg_match('/rel\s*=\s*[\'"]import[\'"]/Uim', $link);
319
			/**
320
			 * CSS imports are available in Polymer alongside with HTML imports
321
			 */
322 4
			$css_import = $import && preg_match('/type\s*=\s*[\'"]css[\'"]/Uim', $link);
323 4
			$stylesheet = preg_match('/rel\s*=\s*[\'"]stylesheet[\'"]/Uim', $link);
324
			// TODO: Polymer only supports `style[is=custom-style]`, but no `link`-based counterpart, so we can't provide CSP-compatibility for CSS anyway
325 4
			if ($css_import || $stylesheet) {
326
				/**
327
				 * If content is link to CSS file
328
				 */
329 4
				$css  = static::css(
330 4
					file_get_contents("$dir/$url"),
331 4
					"$dir/$url",
332
					$not_embedded_resources
333
				);
334 4
				$data = preg_replace(
335 4
					'/'.$links_and_styles[0][$index].'.*<template>/Uims',
336 4
					"<template><style>$css</style>",
337
					$data
338
				);
339
			} elseif ($import) {
340
				/**
341
				 * If content is HTML import
342
				 */
343
				$links_and_styles_to_replace[] = $links_and_styles[0][$index];
344
				$imports_content .= static::html(
345
					file_get_contents("$dir/$url"),
346
					"$dir/$url",
347 4
					"$base_target_file_path-".basename($url, '.html'),
348
					$vulcanization,
349
					$not_embedded_resources
350
				);
351
			}
352
		}
353 4
		if (!$links_and_styles_to_replace) {
354 4
			return;
355
		}
356
		// Add imports to the end
357
		$data .= $imports_content;
358
	}
359
	/**
360
	 * @param string $link
361
	 * @param string $url
362
	 * @param string $dir
363
	 *
364
	 * @return bool
365
	 */
366 4
	protected static function has_relative_href ($link, &$url, $dir) {
367
		$result =
368 4
			$link &&
369 4
			preg_match('/href\s*=\s*[\'"](.*)[\'"]/Uims', $link, $url);
370 4
		if ($result && static::is_relative_path_and_exists($url[1], $dir)) {
371 4
			$url = $url[1];
372 4
			return true;
373
		}
374
		return false;
375
	}
376
	/**
377
	 * Simple check for http[s], ftp and absolute links
378
	 *
379
	 * @param string $path
380
	 * @param string $dir
381
	 *
382
	 * @return bool
383
	 */
384 4
	protected static function is_relative_path_and_exists ($path, $dir) {
385 4
		return !preg_match('#^(http://|https://|ftp://|/)#i', $path) && file_exists("$dir/$path");
386
	}
387
}
388