Completed
Push — master ( 59aee7...54e8e0 )
by Nazar
04:11
created

Includes::get_includes_prepare()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 17
rs 9.4285
cc 3
eloc 9
nc 2
nop 2
1
<?php
2
/**
3
 * @package   CleverStyle CMS
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
use
10
	cs\App,
11
	cs\Core,
12
	cs\Config,
13
	cs\Event,
14
	cs\Language,
15
	cs\Request,
16
	cs\User,
17
	h,
18
	cs\Page\Includes\RequireJS;
19
20
/**
21
 * Includes management for `cs\Page` class
22
 *
23
 * @property string $Title
24
 * @property string $Description
25
 * @property string $canonical_url
26
 * @property string $Head
27
 * @property string $post_Body
28
 * @property string $theme
29
 */
30
trait Includes {
31
	use
32
		RequireJS;
33
	/**
34
	 * @var array
35
	 */
36
	protected $core_html;
37
	/**
38
	 * @var array
39
	 */
40
	protected $core_js;
41
	/**
42
	 * @var array
43
	 */
44
	protected $core_css;
45
	/**
46
	 * @var string
47
	 */
48
	protected $core_config;
49
	/**
50
	 * @var array
51
	 */
52
	protected $html;
53
	/**
54
	 * @var array
55
	 */
56
	protected $js;
57
	/**
58
	 * @var array
59
	 */
60
	protected $css;
61
	/**
62
	 * @var string
63
	 */
64
	protected $config;
65
	/**
66
	 * Base name is used as prefix when creating CSS/JS/HTML cache files in order to avoid collisions when having several themes and languages
67
	 * @var string
68
	 */
69
	protected $pcache_basename;
70
	protected function init_includes () {
71
		$this->core_html       = ['path' => [], 'plain' => ''];
72
		$this->core_js         = ['path' => [], 'plain' => ''];
73
		$this->core_css        = ['path' => [], 'plain' => ''];
74
		$this->core_config     = '';
75
		$this->html            = ['path' => [], 'plain' => ''];
76
		$this->js              = ['path' => [], 'plain' => ''];
77
		$this->css             = ['path' => [], 'plain' => ''];
78
		$this->config          = '';
79
		$this->pcache_basename = '';
80
	}
81
	/**
82
	 * Including of Web Components
83
	 *
84
	 * @param string|string[] $add  Path to including file, or code
85
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
86
	 *
87
	 * @return \cs\Page
88
	 */
89
	function html ($add, $mode = 'file') {
90
		return $this->html_internal($add, $mode);
91
	}
92
	/**
93
	 * @param string|string[] $add
94
	 * @param string          $mode
95
	 * @param bool            $core
96
	 *
97
	 * @return \cs\Page
98
	 */
99
	protected function html_internal ($add, $mode = 'file', $core = false) {
100
		return $this->include_common('html', $add, $mode, $core);
101
	}
102
	/**
103
	 * Including of JavaScript
104
	 *
105
	 * @param string|string[] $add  Path to including file, or code
106
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
107
	 *
108
	 * @return \cs\Page
109
	 */
110
	function js ($add, $mode = 'file') {
111
		return $this->js_internal($add, $mode);
112
	}
113
	/**
114
	 * @param string|string[] $add
115
	 * @param string          $mode
116
	 * @param bool            $core
117
	 *
118
	 * @return \cs\Page
119
	 */
120
	protected function js_internal ($add, $mode = 'file', $core = false) {
121
		return $this->include_common('js', $add, $mode, $core);
122
	}
123
	/**
124
	 * Including of CSS
125
	 *
126
	 * @param string|string[] $add  Path to including file, or code
127
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
128
	 *
129
	 * @return \cs\Page
130
	 */
131
	function css ($add, $mode = 'file') {
132
		return $this->css_internal($add, $mode);
133
	}
134
	/**
135
	 * @param string|string[] $add
136
	 * @param string          $mode
137
	 * @param bool            $core
138
	 *
139
	 * @return \cs\Page
140
	 */
141
	protected function css_internal ($add, $mode = 'file', $core = false) {
142
		return $this->include_common('css', $add, $mode, $core);
143
	}
144
	/**
145
	 * @param string          $what
146
	 * @param string|string[] $add
147
	 * @param string          $mode
148
	 * @param bool            $core
149
	 *
150
	 * @return \cs\Page
151
	 */
152
	protected function include_common ($what, $add, $mode, $core) {
153
		if (!$add) {
154
			return $this;
155
		}
156
		if (is_array($add)) {
157
			foreach (array_filter($add) as $style) {
158
				$this->include_common($what, $style, $mode, $core);
159
			}
160
		} else {
161
			if ($core) {
162
				$what = "core_$what";
163
			}
164
			$target = &$this->$what;
165
			if ($mode == 'file') {
166
				$target['path'][] = $add;
167
			} elseif ($mode == 'code') {
168
				$target['plain'] .= "$add\n";
169
			}
170
		}
171
		return $this;
172
	}
173
	/**
174
	 * Add config on page to make it available on frontend
175
	 *
176
	 * @param mixed  $config_structure        Any scalar type or array
177
	 * @param string $target                  Target is property of `window` object where config will be inserted as value, nested properties like `cs.sub.prop`
178
	 *                                        are supported and all nested properties are created on demand. It is recommended to use sub-properties of `cs`
179
	 *
180
	 * @return \cs\Page
181
	 */
182
	function config ($config_structure, $target) {
183
		return $this->config_internal($config_structure, $target);
184
	}
185
	/**
186
	 * @param mixed  $config_structure
187
	 * @param string $target
188
	 * @param bool   $core
189
	 *
190
	 * @return \cs\Page
191
	 */
192
	protected function config_internal ($config_structure, $target, $core = false) {
193
		$config = h::script(
194
			json_encode($config_structure, JSON_UNESCAPED_UNICODE),
195
			[
196
				'target' => $target,
197
				'class'  => 'cs-config',
198
				'type'   => 'application/json'
199
			]
200
		);
201
		if ($core) {
202
			$this->core_config .= $config;
203
		} else {
204
			$this->config .= $config;
205
		}
206
		return $this;
207
	}
208
	/**
209
	 * Getting of HTML, JS and CSS includes
210
	 *
211
	 * @return \cs\Page
212
	 */
213
	protected function add_includes_on_page () {
214
		$Config = Config::instance(true);
215
		if (!$Config) {
216
			return $this;
217
		}
218
		/**
219
		 * Base name for cache files
220
		 */
221
		$this->pcache_basename = $this->theme.'_'.Language::instance()->clang;
222
		/**
223
		 * Some JS configs required by system
224
		 */
225
		$this->add_system_configs();
226
		// TODO: I hope some day we'll get rid of this sh*t :(
227
		$this->ie_edge();
228
		$Request = Request::instance();
229
		/**
230
		 * If CSS and JavaScript compression enabled
231
		 */
232
		if ($Config->core['cache_compress_js_css'] && !($Request->admin_path && isset($Request->query['debug']))) {
233
			$this->webcomponents_polyfill($Request, true);
234
			$includes = $this->get_includes_for_page_with_compression();
235
		} else {
236
			$this->webcomponents_polyfill($Request, false);
237
			/**
238
			 * Language translation is added explicitly only when compression is disabled, otherwise it will be in compressed JS file
239
			 */
240
			$this->config_internal(Language::instance(), 'cs.Language', true);
241
			$this->config_internal($this->get_requirejs_paths(), 'requirejs.paths', true);
242
			$includes = $this->get_includes_for_page_without_compression($Config);
243
		}
244
		$this->css_internal($includes['css'], 'file', true);
245
		$this->js_internal($includes['js'], 'file', true);
246
		$this->html_internal($includes['html'], 'file', true);
247
		$this->add_includes_on_page_manually_added($Config);
248
		return $this;
249
	}
250
	/**
251
	 * @param string[]|string[][] $path
252
	 *
253
	 * @return string[]|string[][]
254
	 */
255
	protected function absolute_path_to_relative ($path) {
256
		return _substr($path, strlen(DIR) + 1);
257
	}
258
	/**
259
	 * Add JS polyfills for IE/Edge
260
	 */
261
	protected function ie_edge () {
262
		if (!preg_match('/Trident|Edge/', Request::instance()->header('user-agent'))) {
263
			return;
264
		}
265
		$this->js_internal(
266
			get_files_list(DIR."/includes/js/microsoft_sh*t", "/.*\\.js$/i", 'f', "includes/js/microsoft_sh*t", true),
267
			'file',
268
			true
269
		);
270
	}
271
	/**
272
	 * Hack: Add WebComponents Polyfill for browsers without native Shadow DOM support
273
	 *
274
	 * @param Request $Request
275
	 * @param bool    $with_compression
276
	 */
277
	protected function webcomponents_polyfill ($Request, $with_compression) {
278
		if ($Request->cookie('shadow_dom') == 1) {
279
			return;
280
		}
281
		$file = 'includes/js/WebComponents-polyfill/webcomponents-custom.min.js';
282
		if ($with_compression) {
283
			$compressed_file = PUBLIC_CACHE.'/webcomponents.js';
284
			if (!file_exists($compressed_file)) {
285
				$content = file_get_contents(DIR."/$file");
286
				file_put_contents($compressed_file, gzencode($content, 9), LOCK_EX | FILE_BINARY);
287
				file_put_contents("$compressed_file.hash", substr(md5($content), 0, 5));
288
			}
289
			$hash = file_get_contents("$compressed_file.hash");
290
			$this->js_internal("storage/pcache/webcomponents.js?$hash", 'file', true);
291
		} else {
292
			$this->js_internal($file, 'file', true);
293
		}
294
	}
295
	protected function add_system_configs () {
296
		$Config         = Config::instance();
297
		$Request        = Request::instance();
298
		$User           = User::instance();
299
		$current_module = $Request->current_module;
300
		$this->config_internal(
301
			[
302
				'base_url'              => $Config->base_url(),
303
				'current_base_url'      => $Config->base_url().'/'.($Request->admin_path ? 'admin/' : '').$current_module,
304
				'public_key'            => Core::instance()->public_key,
305
				'module'                => $current_module,
306
				'in_admin'              => (int)$Request->admin_path,
307
				'is_admin'              => (int)$User->admin(),
308
				'is_user'               => (int)$User->user(),
309
				'is_guest'              => (int)$User->guest(),
310
				'password_min_length'   => (int)$Config->core['password_min_length'],
311
				'password_min_strength' => (int)$Config->core['password_min_strength'],
312
				'debug'                 => (int)DEBUG,
313
				'route'                 => $Request->route,
314
				'route_path'            => $Request->route_path,
315
				'route_ids'             => $Request->route_ids
316
			],
317
			'cs',
318
			true
319
		);
320
		if ($User->admin()) {
321
			$this->config_internal((int)$Config->core['simple_admin_mode'], 'cs.simple_admin_mode', true);
322
		}
323
	}
324
	/**
325
	 * @return array[]
326
	 */
327
	protected function get_includes_for_page_with_compression () {
328
		/**
329
		 * Rebuilding HTML, JS and CSS cache if necessary
330
		 */
331
		if (file_exists(PUBLIC_CACHE."/$this->pcache_basename.json")) {
332
			list($dependencies, $compressed_includes_map) = file_get_json(PUBLIC_CACHE."/$this->pcache_basename.json");
333
		} else {
334
			list($dependencies, $includes_map) = $this->includes_dependencies_and_map();
335
			$compressed_includes_map = [];
336
			foreach ($includes_map as $filename_prefix => $local_includes) {
337
				// We replace `/` by `+` to make it suitable for filename
338
				$filename_prefix                           = str_replace('/', '+', $filename_prefix);
339
				$compressed_includes_map[$filename_prefix] = $this->create_cached_includes_files($filename_prefix, $local_includes);
340
			}
341
			unset($includes_map, $filename_prefix, $local_includes);
342
			file_put_json(PUBLIC_CACHE."/$this->pcache_basename.json", [$dependencies, $compressed_includes_map]);
343
			Event::instance()->fire('System/Page/rebuild_cache');
344
		}
345
		return $this->get_normalized_includes($dependencies, $compressed_includes_map, '+');
346
	}
347
	/**
348
	 * @param array      $dependencies
349
	 * @param string[][] $includes_map
350
	 * @param string     $separator `+` or `/`
351
	 *
352
	 * @return array
353
	 */
354
	protected function get_normalized_includes ($dependencies, $includes_map, $separator) {
355
		$Request        = Request::instance();
356
		$current_module = $Request->current_module;
357
		/**
358
		 * Current URL based on controller path (it better represents how page was rendered)
359
		 */
360
		$current_url = array_slice(App::instance()->controller_path, 1);
361
		$current_url = ($Request->admin_path ? "admin$separator" : '')."$current_module$separator".implode($separator, $current_url);
362
		/**
363
		 * Narrow the dependencies to current module only
364
		 */
365
		$dependencies          = array_merge(
366
			isset($dependencies[$current_module]) ? $dependencies[$current_module] : [],
367
			$dependencies['System']
368
		);
369
		$system_includes       = [];
370
		$dependencies_includes = [];
371
		$includes              = [];
372
		foreach ($includes_map as $path => $local_includes) {
373
			if ($path == 'System') {
374
				$system_includes = $local_includes;
375
			} elseif ($this->get_includes_is_dependency($dependencies, $path, '/')) {
376
				$dependencies_includes[] = $local_includes;
377
			} elseif (mb_strpos($current_url, $path) === 0) {
378
				$includes[] = $local_includes;
379
			}
380
		}
381
		return array_merge_recursive($system_includes, ...$dependencies_includes, ...$includes);
382
	}
383
	/**
384
	 * Creates cached version of given HTML, JS and CSS files.
385
	 * Resulting file name consists of `$filename_prefix` and `$this->pcache_basename`
386
	 *
387
	 * @param string $filename_prefix
388
	 * @param array  $includes Array of paths to files, may have keys: `css` and/or `js` and/or `html`
389
	 *
390
	 * @return array
391
	 */
392
	protected function create_cached_includes_files ($filename_prefix, $includes) {
393
		$local_includes = [];
394
		foreach ($includes as $extension => $files) {
395
			$content  = $this->create_cached_includes_files_process_files($extension, $filename_prefix, $files);
396
			$filename = "$this->pcache_basename:$filename_prefix.$extension";
397
			file_put_contents(PUBLIC_CACHE."/$filename", gzencode($content, 9), LOCK_EX | FILE_BINARY);
398
			$local_includes[$extension] = "storage/pcache/$filename?".substr(md5($content), 0, 5);
399
		}
400
		return $local_includes;
401
	}
402
	protected function create_cached_includes_files_process_files ($extension, $filename_prefix, $files) {
403
		$content = '';
404
		switch ($extension) {
405
			/**
406
			 * Insert external elements into resulting css file.
407
			 * It is needed, because those files will not be copied into new destination of resulting css file.
408
			 */
409
			case 'css':
410
				$callback = function ($content, $file) {
411
					return $content.Includes_processing::css(file_get_contents($file), $file);
412
				};
413
				break;
414
			/**
415
			 * Combine css and js files for Web Component into resulting files in order to optimize loading process
416
			 */
417
			case 'html':
418
				/**
419
				 * For CSP-compatible HTML files we need to know destination to put there additional JS/CSS files
420
				 */
421
				$destination = Config::instance()->core['vulcanization'] ? false : PUBLIC_CACHE;
422
				$callback    = function ($content, $file) use ($filename_prefix, $destination) {
423
					$base_filename = "$this->pcache_basename:$filename_prefix-".basename($file).'+'.substr(md5($file), 0, 5);
424
					return $content.Includes_processing::html(file_get_contents($file), $file, $base_filename, $destination);
425
				};
426
				break;
427
			case 'js':
428
				$callback = function ($content, $file) {
429
					return $content.Includes_processing::js(file_get_contents($file));
430
				};
431
				if ($filename_prefix == 'System') {
432
					$content = 'window.cs={Language:'._json_encode(Language::instance()).'};';
433
					$content .= 'window.requirejs={paths:'._json_encode($this->get_requirejs_paths()).'};';
434
				}
435
		}
436
		/** @noinspection PhpUndefinedVariableInspection */
437
		return array_reduce($files, $callback, $content);
438
	}
439
	/**
440
	 * @param Config $Config
441
	 *
442
	 * @return array[]
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string[][].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
443
	 */
444
	protected function get_includes_for_page_without_compression ($Config) {
445
		// To determine all dependencies and stuff we need `$Config` object to be already created
446
		if ($Config) {
447
			list($dependencies, $includes_map) = $this->includes_dependencies_and_map();
448
			$includes = $this->get_normalized_includes($dependencies, $includes_map, '/');
449
		} else {
450
			$includes = $this->get_includes_list();
451
		}
452
		return $this->add_versions_hash($this->absolute_path_to_relative($includes));
1 ignored issue
show
Documentation introduced by
$this->absolute_path_to_relative($includes) is of type array<integer,string|array<integer,string>>, but the function expects a array<integer,array<integer,string>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
453
	}
454
	/**
455
	 * @param array  $dependencies
456
	 * @param string $url
457
	 * @param string $separator `+` or `/`
458
	 *
459
	 * @return bool
460
	 */
461
	protected function get_includes_is_dependency ($dependencies, $url, $separator) {
462
		$url_exploded = explode($separator, $url);
463
		/** @noinspection NestedTernaryOperatorInspection */
464
		$url_module = $url_exploded[0] != 'admin' ? $url_exploded[0] : (@$url_exploded[1] ?: '');
465
		$Request    = Request::instance();
466
		return
467
			$url_module !== Config::SYSTEM_MODULE &&
468
			in_array($url_module, $dependencies) &&
469
			(
470
				$Request->admin_path || $Request->admin_path == ($url_exploded[0] == 'admin')
471
			);
472
	}
473
	/**
474
	 * @param string[][] $includes
475
	 *
476
	 * @return string[][]
477
	 */
478
	protected function add_versions_hash ($includes) {
479
		$content = array_map('file_get_contents', get_files_list(DIR.'/components', '/^meta\.json$/', 'f', true, true));
480
		$content = implode('', $content);
481
		$hash    = substr(md5($content), 0, 5);
482
		foreach ($includes as &$files) {
483
			foreach ($files as &$file) {
484
				$file .= "?$hash";
485
			}
486
			unset($file);
487
		}
488
		return $includes;
489
	}
490
	/**
491
	 * @param Config $Config
492
	 */
493
	protected function add_includes_on_page_manually_added ($Config) {
494
		$configs = $this->core_config.$this->config;
495
		/** @noinspection NestedTernaryOperatorInspection */
496
		$styles =
497
			array_reduce(
498
				array_merge($this->core_css['path'], $this->css['path']),
499
				function ($content, $href) {
500
					return "$content<link href=\"/$href\" rel=\"stylesheet\" shim-shadowdom>\n";
501
				}
502
			).
503
			h::style($this->core_css['plain'].$this->css['plain'] ?: false);
504
		/** @noinspection NestedTernaryOperatorInspection */
505
		$scripts      =
506
			array_reduce(
507
				array_merge($this->core_js['path'], $this->js['path']),
508
				function ($content, $src) {
509
					return "$content<script src=\"/$src\"></script>\n";
510
				}
511
			).
512
			h::script($this->core_js['plain'].$this->js['plain'] ?: false);
513
		$html_imports =
514
			array_reduce(
515
				array_merge($this->core_html['path'], $this->html['path']),
516
				function ($content, $href) {
517
					return "$content<link href=\"/$href\" rel=\"import\">\n";
518
				}
519
			).
520
			$this->core_html['plain'].$this->html['plain'];
521
		$this->Head .= $configs.$styles;
522
		if ($Config->core['put_js_after_body']) {
523
			$this->post_Body .= $scripts.$html_imports;
524
		} else {
525
			$this->Head .= $scripts.$html_imports;
526
		}
527
	}
528
	/**
529
	 * Getting of HTML, JS and CSS files list to be included
530
	 *
531
	 * @return string[][]
532
	 */
533
	protected function get_includes_list () {
534
		$includes = [];
535
		/**
536
		 * Get includes of system and theme
537
		 */
538
		$this->get_includes_list_add_includes(DIR.'/includes', $includes);
539
		$this->get_includes_list_add_includes(THEMES."/$this->theme", $includes);
540
		$Config = Config::instance();
541
		foreach ($Config->components['modules'] as $module_name => $module_data) {
542
			if ($module_data['active'] == Config\Module_Properties::UNINSTALLED) {
543
				continue;
544
			}
545
			$this->get_includes_list_add_includes(MODULES."/$module_name/includes", $includes);
546
		}
547
		foreach ($Config->components['plugins'] as $plugin_name) {
548
			$this->get_includes_list_add_includes(PLUGINS."/$plugin_name/includes", $includes);
549
		}
550
		return [
551
			'html' => array_merge(...$includes['html']),
552
			'js'   => array_merge(...$includes['js']),
553
			'css'  => array_merge(...$includes['css'])
554
		];
555
	}
556
	/**
557
	 * @param string     $base_dir
558
	 * @param string[][] $includes
559
	 */
560
	protected function get_includes_list_add_includes ($base_dir, &$includes) {
561
		$includes['html'][] = $this->get_includes_list_add_includes_internal($base_dir, 'html');
562
		$includes['js'][]   = $this->get_includes_list_add_includes_internal($base_dir, 'js');
563
		$includes['css'][]  = $this->get_includes_list_add_includes_internal($base_dir, 'css');
564
	}
565
	/**
566
	 * @param string $base_dir
567
	 * @param string $ext
568
	 *
569
	 * @return array
570
	 */
571
	protected function get_includes_list_add_includes_internal ($base_dir, $ext) {
572
		return get_files_list("$base_dir/$ext", "/.*\\.$ext\$/i", 'f', true, true, 'name', '!include') ?: [];
573
	}
574
	/**
575
	 * Get dependencies of components between each other (only that contains some HTML, JS and CSS files) and mapping HTML, JS and CSS files to URL paths
576
	 *
577
	 * @return array[] [$dependencies, $includes_map]
578
	 */
579
	protected function includes_dependencies_and_map () {
580
		/**
581
		 * Get all includes
582
		 */
583
		$all_includes = $this->get_includes_list();
584
		$includes_map = [];
585
		/**
586
		 * Array [package => [list of packages it depends on]]
587
		 */
588
		$dependencies    = [];
589
		$functionalities = [];
590
		/**
591
		 * According to components's maps some files should be included only on specific pages.
592
		 * Here we read this rules, and remove from whole includes list such items, that should be included only on specific pages.
593
		 * Also collect dependencies.
594
		 */
595
		$Config = Config::instance();
596
		foreach ($Config->components['modules'] as $module_name => $module_data) {
597
			if ($module_data['active'] == Config\Module_Properties::UNINSTALLED) {
598
				continue;
599
			}
600
			$this->process_meta(MODULES."/$module_name", $dependencies, $functionalities);
601
			$this->process_map(MODULES."/$module_name", $includes_map, $all_includes);
602
		}
603
		unset($module_name, $module_data);
604
		foreach ($Config->components['plugins'] as $plugin_name) {
605
			$this->process_meta(PLUGINS."/$plugin_name", $dependencies, $functionalities);
606
			$this->process_map(PLUGINS."/$plugin_name", $includes_map, $all_includes);
607
		}
608
		unset($plugin_name);
609
		/**
610
		 * For consistency
611
		 */
612
		$includes_map['System'] = $all_includes;
613
		Event::instance()->fire(
614
			'System/Page/includes_dependencies_and_map',
615
			[
616
				'dependencies' => &$dependencies,
617
				'includes_map' => &$includes_map
618
			]
619
		);
620
		$dependencies = $this->normalize_dependencies($dependencies, $functionalities);
621
		$includes_map = $this->clean_includes_arrays_without_files($dependencies, $includes_map);
622
		$dependencies = array_map('array_values', $dependencies);
623
		$dependencies = array_filter($dependencies);
624
		return [$dependencies, $includes_map];
625
	}
626
	/**
627
	 * Process meta information and corresponding entries to dependencies and functionalities
628
	 *
629
	 * @param string $base_dir
630
	 * @param array  $dependencies
631
	 * @param array  $functionalities
632
	 */
633
	protected function process_meta ($base_dir, &$dependencies, &$functionalities) {
634
		if (!file_exists("$base_dir/meta.json")) {
635
			return;
636
		}
637
		$meta = file_get_json("$base_dir/meta.json");
638
		$meta += [
639
			'require'  => [],
640
			'optional' => [],
641
			'provide'  => []
642
		];
643
		$package = $meta['package'];
644
		foreach ((array)$meta['require'] as $r) {
645
			/**
646
			 * Get only name of package or functionality
647
			 */
648
			$r                        = preg_split('/[=<>]/', $r, 2)[0];
649
			$dependencies[$package][] = $r;
650
		}
651
		foreach ((array)$meta['optional'] as $o) {
652
			/**
653
			 * Get only name of package or functionality
654
			 */
655
			$o                        = preg_split('/[=<>]/', $o, 2)[0];
656
			$dependencies[$package][] = $o;
657
		}
658
		foreach ((array)$meta['provide'] as $p) {
659
			/**
660
			 * If provides sub-functionality for other component (for instance, `Blog/post_patch`) - inverse "providing" to "dependency"
661
			 * Otherwise it is just functionality alias to package name
662
			 */
663
			if (strpos($p, '/') !== false) {
664
				/**
665
				 * Get name of package or functionality
666
				 */
667
				$p                  = explode('/', $p)[0];
668
				$dependencies[$p][] = $package;
669
			} else {
670
				$functionalities[$p] = $package;
671
			}
672
		}
673
	}
674
	/**
675
	 * Process map structure, fill includes map and remove files from list of all includes (remaining files will be included on all pages)
676
	 *
677
	 * @param string $base_dir
678
	 * @param array  $includes_map
679
	 * @param array  $all_includes
680
	 */
681
	protected function process_map ($base_dir, &$includes_map, &$all_includes) {
682
		if (!file_exists("$base_dir/includes/map.json")) {
683
			return;
684
		}
685
		$this->process_map_internal(file_get_json("$base_dir/includes/map.json"), "$base_dir/includes", $includes_map, $all_includes);
686
	}
687
	/**
688
	 * Process map structure, fill includes map and remove files from list of all includes (remaining files will be included on all pages)
689
	 *
690
	 * @param array  $map
691
	 * @param string $includes_dir
692
	 * @param array  $includes_map
693
	 * @param array  $all_includes
694
	 */
695
	protected function process_map_internal ($map, $includes_dir, &$includes_map, &$all_includes) {
696
		foreach ($map as $path => $files) {
697
			foreach ((array)$files as $file) {
698
				$extension = file_extension($file);
699
				if (in_array($extension, ['css', 'js', 'html'])) {
700
					$file                              = "$includes_dir/$extension/$file";
701
					$includes_map[$path][$extension][] = $file;
702
					$all_includes[$extension]          = array_diff($all_includes[$extension], [$file]);
703
				} else {
704
					$file = rtrim($file, '*');
705
					/**
706
					 * Wildcard support, it is possible to specify just path prefix and all files with this prefix will be included
707
					 */
708
					$found_files = array_filter(
709
						get_files_list($includes_dir, '/.*\.(css|js|html)$/i', 'f', '', true, 'name', '!include') ?: [],
710
						function ($f) use ($file) {
711
							// We need only files with specified mask and only those located in directory that corresponds to file's extension
712
							return preg_match("#^(css|js|html)/$file.*\\1$#i", $f);
713
						}
714
					);
715
					// Drop first level directory
716
					$found_files = _preg_replace('#^[^/]+/(.*)#', '$1', $found_files);
717
					$this->process_map_internal([$path => $found_files], $includes_dir, $includes_map, $all_includes);
718
				}
719
			}
720
		}
721
	}
722
	/**
723
	 * Replace functionalities by real packages names, take into account recursive dependencies
724
	 *
725
	 * @param array $dependencies
726
	 * @param array $functionalities
727
	 *
728
	 * @return array
729
	 */
730
	protected function normalize_dependencies ($dependencies, $functionalities) {
731
		/**
732
		 * First of all remove packages without any dependencies
733
		 */
734
		$dependencies = array_filter($dependencies);
735
		/**
736
		 * First round, process aliases among keys
737
		 */
738
		foreach (array_keys($dependencies) as $d) {
739
			if (isset($functionalities[$d])) {
740
				$package = $functionalities[$d];
741
				/**
742
				 * Add dependencies to existing package dependencies
743
				 */
744
				foreach ($dependencies[$d] as $dependency) {
745
					$dependencies[$package][] = $dependency;
746
				}
747
				/**
748
				 * Drop alias
749
				 */
750
				unset($dependencies[$d]);
751
			}
752
		}
753
		unset($d, $dependency);
754
		/**
755
		 * Second round, process aliases among dependencies
756
		 */
757
		foreach ($dependencies as &$depends_on) {
758
			foreach ($depends_on as &$dependency) {
759
				if (isset($functionalities[$dependency])) {
760
					$dependency = $functionalities[$dependency];
761
				}
762
			}
763
		}
764
		unset($depends_on, $dependency);
765
		/**
766
		 * Third round, process recursive dependencies
767
		 */
768
		foreach ($dependencies as &$depends_on) {
769
			foreach ($depends_on as &$dependency) {
770
				if ($dependency != 'System' && isset($dependencies[$dependency])) {
771
					foreach (array_diff($dependencies[$dependency], $depends_on) as $new_dependency) {
772
						$depends_on[] = $new_dependency;
773
					}
774
				}
775
			}
776
		}
777
		return array_map('array_unique', $dependencies);
778
	}
779
	/**
780
	 * Includes array is composed from dependencies and sometimes dependencies doesn't have any files, so we'll clean that
781
	 *
782
	 * @param array $dependencies
783
	 * @param array $includes_map
784
	 *
785
	 * @return array
786
	 */
787
	protected function clean_includes_arrays_without_files ($dependencies, $includes_map) {
788
		foreach ($dependencies as &$depends_on) {
789
			foreach ($depends_on as $index => &$dependency) {
790
				if (!isset($includes_map[$dependency])) {
791
					unset($depends_on[$index]);
792
				}
793
			}
794
			unset($dependency);
795
		}
796
		return $includes_map;
797
	}
798
}
799