Completed
Push — master ( e38f08...c6681d )
by Nazar
04:49
created

Cache::rebuild_optimized()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 14
ccs 11
cts 11
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
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\Assets;
9
use
10
	cs\Event,
11
	cs\Page\Assets_processing;
12
13
class Cache {
14
	/**
15
	 * @param \cs\Config   $Config
16
	 * @param \cs\Language $L
17
	 * @param string       $theme
18
	 */
19 4
	public static function rebuild ($Config, $L, $theme) {
20 4
		if (!file_exists(PUBLIC_CACHE."/$theme.json")) {
21 4
			static::rebuild_normal($Config, $theme);
22 4
			Event::instance()->fire('System/Page/rebuild_cache');
23 4
			static::rebuild_optimized($theme);
24 4
			static::rebuild_webcomponents_polyfill();
25
		}
26
		/**
27
		 * We take hash of languages in order to take into account when list of active languages has changed (and generate cache for all acive languages)
28
		 */
29 4
		$languages_hash = md5(implode('', $Config->core['active_languages']));
30 4
		if (!file_exists(PUBLIC_CACHE."/languages-$languages_hash.json")) {
31 4
			static::rebuild_languages($Config, $L, $languages_hash);
32
		}
33 4
	}
34
	/**
35
	 * @param \cs\Config $Config
36
	 * @param string     $theme
37
	 */
38 4
	protected static function rebuild_normal ($Config, $theme) {
39 4
		list($dependencies, $assets_map) = Collecting::get_assets_dependencies_and_map($Config, $theme);
40 4
		$compressed_assets_map      = [];
41 4
		$not_embedded_resources_map = [];
42
		/** @noinspection ForeachSourceInspection */
43 4
		foreach ($assets_map as $filename_prefix => $local_assets) {
44 4
			$compressed_assets_map[$filename_prefix] = static::cache_compressed_assets_files(
45 4
				PUBLIC_CACHE."/$theme:".str_replace('/', '+', $filename_prefix),
46
				$local_assets,
47 4
				$Config->core['vulcanization'],
48
				$not_embedded_resources_map
49
			);
50
		}
51 4
		unset($assets_map, $filename_prefix, $local_assets);
52 4
		file_put_json(PUBLIC_CACHE."/$theme.json", [$dependencies, $compressed_assets_map, array_filter($not_embedded_resources_map)]);
53 4
	}
54
	/**
55
	 * @param string $theme
56
	 */
57 4
	protected static function rebuild_optimized ($theme) {
58 4
		list(, $compressed_assets_map, $preload_source) = file_get_json(PUBLIC_CACHE."/$theme.json");
59 4
		$preload = [array_values($compressed_assets_map['System'])];
60
		/** @noinspection ForeachSourceInspection */
61 4
		foreach ($compressed_assets_map['System'] as $path) {
62 4
			if (isset($preload_source[$path])) {
63 4
				$preload[] = $preload_source[$path];
64
			}
65
		}
66 4
		unset($compressed_assets_map['System']);
67 4
		$optimized_assets = array_merge(...array_values(array_map('array_values', $compressed_assets_map)));
68 4
		$preload          = array_merge(...$preload);
69 4
		file_put_json(PUBLIC_CACHE."/$theme.optimized.json", [$optimized_assets, $preload]);
70 4
	}
71 4
	protected static function rebuild_webcomponents_polyfill () {
72 4
		$webcomponents_js = file_get_contents(DIR.'/assets/js/WebComponents-polyfill/webcomponents-custom.min.js');
73 4
		$hash             = md5($webcomponents_js);
74 4
		file_put_contents(PUBLIC_CACHE."/$hash.js", $webcomponents_js, LOCK_EX | FILE_BINARY);
75 4
		file_put_contents(PUBLIC_CACHE.'/webcomponents.js.hash', $hash, LOCK_EX | FILE_BINARY);
76 4
	}
77
	/**
78
	 * @param \cs\Config   $Config
79
	 * @param \cs\Language $L
80
	 * @param string       $languages_hash
81
	 */
82 4
	protected static function rebuild_languages ($Config, $L, $languages_hash) {
83 4
		$current_language = $L->clanguage;
84 4
		$languages_map    = [];
85
		/** @noinspection ForeachSourceInspection */
86 4
		foreach ($Config->core['active_languages'] as $language) {
87 4
			$L->change($language);
88
			/** @noinspection DisconnectedForeachInstructionInspection */
89 4
			$translations             = _json_encode($L);
90 4
			$language_hash            = md5($translations);
91 4
			$languages_map[$language] = $language_hash;
92 4
			file_put_contents(PUBLIC_CACHE."/languages-$language-$language_hash.js", "define($translations);");
93
		}
94 4
		$L->change($current_language);
95 4
		file_put_json(PUBLIC_CACHE."/languages-$languages_hash.json", $languages_map);
96 4
	}
97
	/**
98
	 * Creates cached version of given HTML, JS and CSS files.
99
	 * Resulting files names consist of `$filename_prefix` and extension.
100
	 *
101
	 * @param string     $target_file_path
102
	 * @param string[][] $assets                     Array of paths to files, may have keys: `css` and/or `js` and/or `html`
103
	 * @param bool       $vulcanization              Whether to put combined files separately or to make included assets built-in (vulcanization)
104
	 * @param string[][] $not_embedded_resources_map Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because
105
	 *                                               of CSP
106
	 *
107
	 * @return array
108
	 */
109 4
	protected static function cache_compressed_assets_files ($target_file_path, $assets, $vulcanization, &$not_embedded_resources_map) {
110 4
		$local_assets = [];
111 4
		foreach ($assets as $extension => $files) {
112 4
			$not_embedded_resources = [];
113 4
			$content                = static::cache_compressed_assets_files_single(
114
				$extension,
115
				$target_file_path,
116
				$files,
117
				$vulcanization,
118
				$not_embedded_resources
119
			);
120 4
			foreach ($not_embedded_resources as &$resource) {
121
				if (strpos($resource, '/') !== 0) {
122
					$resource = "/storage/public_cache/$resource";
123
				}
124
			}
125 4
			$file_path = PUBLIC_CACHE.'/'.md5($content).'.'.$extension;
126 4
			file_put_contents($file_path, $content, LOCK_EX | FILE_BINARY);
127 4
			$relative_path                              = '/storage/public_cache/'.basename($file_path);
128 4
			$local_assets[$extension]                   = $relative_path;
129 4
			$not_embedded_resources_map[$relative_path] = $not_embedded_resources;
130
		}
131 4
		return $local_assets;
132
	}
133
	/**
134
	 * @param string   $extension
135
	 * @param string   $target_file_path
136
	 * @param string[] $files
137
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
138
	 * @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
139
	 *
140
	 * @return string
141
	 */
142 4
	protected static function cache_compressed_assets_files_single ($extension, $target_file_path, $files, $vulcanization, &$not_embedded_resources) {
143 4
		$content = '';
144
		switch ($extension) {
145
			/**
146
			 * Insert external elements into resulting css file.
147
			 * It is needed, because those files will not be copied into new destination of resulting css file.
148
			 */
149 4
			case 'css':
150
				/**
151
				 * @param string $content
152
				 * @param string $file
153
				 *
154
				 * @return string
155
				 */
156
				$callback = function ($content, $file) use (&$not_embedded_resources) {
157 4
					return $content.Assets_processing::css(file_get_contents($file), $file, $not_embedded_resources);
158 4
				};
159 4
				break;
160
			/**
161
			 * Combine css and js files for Web Component into resulting files in order to optimize loading process
162
			 */
163 4
			case 'html':
164
				/**
165
				 * For CSP-compatible HTML files we need to know destination to put there additional JS/CSS files
166
				 *
167
				 * @param string $content
168
				 * @param string $file
169
				 *
170
				 * @return string
171
				 */
172
				$callback = function ($content, $file) use (&$not_embedded_resources) {
173
					return
174
						$content.
175 4
						Assets_processing::html(
176
							file_get_contents($file),
177
							$file,
178 4
							'',
179 4
							true,
180
							$not_embedded_resources
181
						);
182 4
				};
183 4
				break;
184 4
			case 'js':
185
				/**
186
				 * @param string $content
187
				 * @param string $file
188
				 *
189
				 * @return string
190
				 */
191 4
				$callback = function ($content, $file) {
192 4
					return $content.Assets_processing::js(file_get_contents($file));
193 4
				};
194 4
				if (substr($target_file_path, -7) == ':System') {
195 4
					$content = 'window.cs={};window.requirejs='._json_encode(RequireJS::get_config()).';';
196
				}
197
		}
198
		/** @noinspection PhpUndefinedVariableInspection */
199 4
		$content .= array_reduce($files, $callback);
200 4
		if ($extension == 'html') {
201 4
			$file_path = "$target_file_path-$extension";
202 4
			$content   = Assets_processing::html($content, $file_path, $file_path, $vulcanization);
203
		}
204 4
		return $content;
205
	}
206
}
207