Completed
Push — master ( 014d41...b96f05 )
by Nazar
04:05
created

Includes_processing::css()   C

Complexity

Conditions 7
Paths 1

Size

Total Lines 83
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 7

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 7
eloc 43
c 1
b 1
f 1
nc 1
nop 3
dl 0
loc 83
ccs 39
cts 39
cp 1
crap 7
rs 6.5439

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 6
	static function css ($data, $file, &$not_embedded_resources = []) {
48 6
		$dir = dirname($file);
49
		/**
50
		 * Remove comments, tabs and new lines
51
		 */
52 6
		$data = preg_replace('#(/\*.*?\*/)|\t|\n|\r#s', ' ', $data);
53
		/**
54
		 * Remove unnecessary spaces
55
		 */
56 6
		$data = preg_replace('/\s*([,;>{}(])\s*/', '$1', $data);
57 6
		$data = preg_replace('/\s+/', ' ', $data);
58
		/**
59
		 * Return spaces required in media queries
60
		 */
61 6
		$data = preg_replace('/\s(and|or)\(/', ' $1 (', $data);
62
		/**
63
		 * Duplicated semicolons
64
		 */
65 6
		$data = preg_replace('/;+/m', ';', $data);
66
		/**
67
		 * Minify rgb colors declarations
68
		 */
69 6
		$data = preg_replace_callback(
70 6
			'/rgb\(([0-9,.]+)\)/i',
71
			function ($rgb) {
72 2
				$rgb = explode(',', $rgb[1]);
73
				return
74
					'#'.
75 2
					str_pad(dechex($rgb[0]), 2, 0, STR_PAD_LEFT).
76 2
					str_pad(dechex($rgb[1]), 2, 0, STR_PAD_LEFT).
77 2
					str_pad(dechex($rgb[2]), 2, 0, STR_PAD_LEFT);
78 6
			},
79
			$data
80
		);
81
		/**
82
		 * Minify repeated colors declarations
83
		 */
84 6
		$data = preg_replace('/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3/i', '#$1$2$3', $data);
85
		/**
86
		 * Remove unnecessary zeros
87
		 */
88 6
		$data = preg_replace('/(\D)0\.(\d+)/i', '$1.$2', $data);
89
		/**
90
		 * Unnecessary spaces around colons (should have whitespace character after, otherwise might be `.c :disabled` and will be handled incorrectly)
91
		 */
92 6
		$data = preg_replace('/\s*:\s+/', ':', $data);
93
		/**
94
		 * Includes processing
95
		 */
96 6
		$data = preg_replace_callback(
97 6
			'/url\((.*?)\)|@import\s*[\'"](.*?)[\'"]\s*;/',
98
			function ($match) use ($dir, &$not_embedded_resources) {
99 6
				$path      = @$match[2] ?: $match[1];
100 6
				$path      = trim($path, '\'" ');
101 6
				$link      = explode('?', $path, 2)[0];
102 6
				$content   = file_get_contents("$dir/$link");
103 6
				$extension = file_extension($link);
104 6
				if ($extension == 'css') {
105
					/**
106
					 * For recursive includes processing, if CSS file includes others CSS files
107
					 * TODO: Support for `@import` with media queries
108
					 */
109 2
					return static::css($content, $link, $not_embedded_resources);
110
				}
111 6
				if (!static::is_relative_path_and_exists($link, $dir)) {
112 6
					return $match[0];
113
				}
114 6
				if (!isset(static::$extension_to_mime[$extension]) || filesize("$dir/$link") > static::MAX_EMBEDDING_SIZE) {
115 6
					$path_relatively_to_the_root = str_replace(getcwd(), '', realpath("$dir/$link"));
116 6
					$path_relatively_to_the_root .= '?'.substr(md5($content), 0, 5);
117 6
					if (strpos($path, '?') === false) {
118 2
						$not_embedded_resources[] = $path_relatively_to_the_root;
119
					}
120 6
					return str_replace($path, "'".str_replace("'", "\\'", $path_relatively_to_the_root)."'", $match[0]);
121
				}
122 2
				$mime_type = static::$extension_to_mime[$extension];
123 2
				$content   = base64_encode($content);
124 2
				return str_replace($path, "data:$mime_type;charset=utf-8;base64,$content", $match[0]);
125 6
			},
126
			$data
127
		);
128 6
		return trim($data);
129
	}
130
	/**
131
	 * Simple and fast JS minification
132
	 *
133
	 * @param string $data
134
	 *
135
	 * @return string
136
	 */
137 4
	static function js ($data) {
138
		/**
139
		 * Split into array of lines
140
		 */
141 4
		$data = explode("\n", $data);
142
		/**
143
		 * Flag that is `true` when inside comment
144
		 */
145 4
		$comment = false;
146
		/**
147
		 * Set of symbols that are safe to be concatenated without new line with anything else
148
		 */
149
		$regexp = /** @lang PhpRegExp */
150 4
			'[:;,.+\-*/{}?><^\'"\[\]=&(]';
151 4
		foreach ($data as $index => &$d) {
152 4
			$next_line = isset($data[$index + 1]) ? trim($data[$index + 1]) : '';
153
			/**
154
			 * Remove starting and trailing spaces
155
			 */
156 4
			$d = trim($d);
157
			/**
158
			 * Remove single-line comments
159
			 */
160 4
			if (mb_strpos($d, '//') === 0) {
161 4
				$d = '';
162 4
				continue;
163
			}
164
			/**
165
			 * Starts with multi-line comment
166
			 */
167 4
			if (mb_strpos($d, '/*') === 0) {
168 4
				$comment = true;
169
			}
170
			/**
171
			 * Add new line at the end if only needed
172
			 */
173
			if (
174 4
				$d &&
175 4
				$next_line &&
176 4
				!$comment &&
177 4
				!preg_match("#$regexp\$#", $d) &&
178 4
				!preg_match("#^$regexp#", $next_line)
179
			) {
180 4
				$d .= "\n";
181
			}
182 4
			if ($comment) {
183
				/**
184
				 * End of multi-line comment
185
				 */
186 4
				if (strpos($d, '*/') !== false) {
187 4
					$d       = explode('*/', $d)[1];
188 4
					$comment = false;
189
				} else {
190 4
					$d = '';
191
				}
192
			} else {
193
				/**
194
				 * Single-line comment
195
				 */
196 4
				$d = preg_replace('#^\s*//[^\'"]+$#', '', $d);
197
				/**
198
				 * If we are not sure - just add new like afterwards
199
				 */
200 4
				$d = preg_replace('#//.*$#', "\\0\n", $d);
201
			}
202
		}
203 4
		$data = implode('', $data);
204 4
		$data = str_replace('</script>', '<\/script>', $data);
205 4
		return trim($data, ';').';';
206
	}
207
	/**
208
	 * Analyses file for scripts and styles, combines them into resulting files in order to optimize loading process
209
	 * (files with combined scripts and styles will be created)
210
	 *
211
	 * @param string   $data                   Content of processed file
212
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
213
	 * @param string   $base_target_file_path  Base filename for resulting combined files
214
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
215
	 * @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
216
	 *
217
	 * @return string
218
	 */
219 4
	static function html ($data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources = []) {
220 4
		static::html_process_scripts($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
221 4
		static::html_process_links_and_styles($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
222
		// Removing HTML comments (those that are mostly likely comments, to avoid problems)
223 4
		$data = preg_replace_callback(
224 4
			'/^\s*<!--([^>-].*[^-])?-->/Ums',
225 4
			function ($matches) {
226
				return mb_strpos('--', $matches[1]) === false ? '' : $matches[0];
227 4
			},
228
			$data
229
		);
230 4
		return preg_replace("/\n+/", "\n", $data);
231
	}
232
	/**
233
	 * @param string   $data                   Content of processed file
234
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
235
	 * @param string   $base_target_file_path  Base filename for resulting combined files
236
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
237
	 * @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
238
	 *
239
	 * @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...
240
	 */
241 4
	protected static function html_process_scripts (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
242 4
		if (!preg_match_all('/<script(.*)<\/script>/Uims', $data, $scripts)) {
243 4
			return;
244
		}
245 4
		$scripts_content    = '';
246 4
		$scripts_to_replace = [];
247 4
		$dir                = dirname($file);
248 4
		foreach ($scripts[1] as $index => $script) {
249 4
			$script = explode('>', $script, 2);
250 4
			if (preg_match('/src\s*=\s*[\'"](.*)[\'"]/Uims', $script[0], $url)) {
251 4
				$url = $url[1];
252 4
				if (!static::is_relative_path_and_exists($url, $dir)) {
253
					continue;
254
				}
255 4
				$scripts_to_replace[] = $scripts[0][$index];
256 4
				$scripts_content .= file_get_contents("$dir/$url").";\n";
257
			} else {
258 4
				$scripts_to_replace[] = $scripts[0][$index];
259 4
				$scripts_content .= "$script[1];\n";
260
			}
261
		}
262 4
		$scripts_content = static::js($scripts_content);
263 4
		if (!$scripts_to_replace) {
264
			return;
265
		}
266
		// Remove all scripts
267 4
		$data = str_replace($scripts_to_replace, '', $data);
268
		/**
269
		 * If vulcanization is not used - put contents into separate file, and put link to it, otherwise put minified content back
270
		 */
271 4
		if (!$vulcanization) {
272
			/**
273
			 * md5 to distinguish modifications of the files
274
			 */
275
			$content_md5 = substr(md5($scripts_content), 0, 5);
276
			file_put_contents("$base_target_file_path.js", $scripts_content, LOCK_EX | FILE_BINARY);
277
			$base_target_file_name = basename($base_target_file_path);
278
			// Add script with combined content file to the end
279
			$data .= "<script src=\"$base_target_file_name.js?$content_md5\"></script>";
280
			$not_embedded_resources[] = "$base_target_file_name.js?$content_md5";
281
		} else {
282
			// Add combined content inline script to the end
283 4
			$data .= "<script>$scripts_content</script>";
284
		}
285 4
	}
286
	/**
287
	 * @param string   $data                   Content of processed file
288
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
289
	 * @param string   $base_target_file_path  Base filename for resulting combined files
290
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
291
	 * @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
292
	 *
293
	 * @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...
294
	 */
295 4
	protected static function html_process_links_and_styles (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
296
		// Drop Polymer inclusion, since it is already present
297 4
		$data = str_replace('<link rel="import" href="../polymer/polymer.html">', '', $data);
298 4
		if (!preg_match_all('/<link(.*)>|<style(.*)<\/style>/Uims', $data, $links_and_styles)) {
299 4
			return;
300
		}
301 4
		$imports_content             = '';
302 4
		$links_and_styles_to_replace = [];
303 4
		$dir                         = dirname($file);
304 4
		foreach ($links_and_styles[1] as $index => $link) {
305
			/**
306
			 * Check for custom styles `is="custom-style"` or styles includes `include=".."` - we'll skip them
307
			 * Or if content is plain CSS
308
			 */
309
			if (
310 4
				preg_match('/^[^>]*(is="custom-style"|include=)[^>]*>/Uim', $links_and_styles[2][$index]) ||
311 4
				mb_strpos($links_and_styles[0][$index], '</style>') > 0
312
			) {
313 4
				$content = explode('>', $links_and_styles[2][$index], 2)[1];
314 4
				$data    = str_replace(
315
					$content,
316 4
					static::css($content, $file, $not_embedded_resources),
317
					$data
318
				);
319 4
				continue;
320
			}
321 4
			if (!static::has_relative_href($link, $url, $dir)) {
322
				continue;
323
			}
324 4
			$import = preg_match('/rel\s*=\s*[\'"]import[\'"]/Uim', $link);
325
			/**
326
			 * CSS imports are available in Polymer alongside with HTML imports
327
			 */
328 4
			$css_import = $import && preg_match('/type\s*=\s*[\'"]css[\'"]/Uim', $link);
329 4
			$stylesheet = preg_match('/rel\s*=\s*[\'"]stylesheet[\'"]/Uim', $link);
330
			// TODO: Polymer only supports `style[is=custom-style]`, but no `link`-based counterpart, so we can't provide CSP-compatibility for CSS anyway
331 4
			if ($css_import || $stylesheet) {
332
				/**
333
				 * If content is link to CSS file
334
				 */
335 4
				$css  = static::css(
336 4
					file_get_contents("$dir/$url"),
337 4
					"$dir/$url",
338
					$not_embedded_resources
339
				);
340 4
				$data = preg_replace(
341 4
					'/'.$links_and_styles[0][$index].'.*<template>/Uims',
342 4
					"<template><style>$css</style>",
343
					$data
344
				);
345
			} elseif ($import) {
346
				/**
347
				 * If content is HTML import
348
				 */
349
				$links_and_styles_to_replace[] = $links_and_styles[0][$index];
350
				$imports_content .= static::html(
351
					file_get_contents("$dir/$url"),
352
					"$dir/$url",
353 4
					"$base_target_file_path-".basename($url, '.html'),
354
					$vulcanization,
355
					$not_embedded_resources
356
				);
357
			}
358
		}
359 4
		if (!$links_and_styles_to_replace) {
360 4
			return;
361
		}
362
		// Add imports to the end
363
		$data .= $imports_content;
364
	}
365
	/**
366
	 * @param string $link
367
	 * @param string $url
368
	 * @param string $dir
369
	 *
370
	 * @return bool
371
	 */
372 4
	protected static function has_relative_href ($link, &$url, $dir) {
373
		$result =
374 4
			$link &&
375 4
			preg_match('/href\s*=\s*[\'"](.*)[\'"]/Uims', $link, $url);
376 4
		if ($result && static::is_relative_path_and_exists($url[1], $dir)) {
377 4
			$url = $url[1];
378 4
			return true;
379
		}
380
		return false;
381
	}
382
	/**
383
	 * Simple check for http[s], ftp and absolute links
384
	 *
385
	 * @param string $path
386
	 * @param string $dir
387
	 *
388
	 * @return bool
389
	 */
390 6
	protected static function is_relative_path_and_exists ($path, $dir) {
391 6
		return !preg_match('#^(http://|https://|ftp://|/)#i', $path) && file_exists("$dir/$path");
392
	}
393
}
394