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