Completed
Push — master ( c1aac3...a8898a )
by Nazar
04:03
created

Static_files   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 64
ccs 28
cts 28
cp 1
rs 10
wmc 12
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
C serve_static_files() 0 48 11
A serve_static_file() 0 5 1
1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Request\Route;
9
use
10
	cs\ExitException,
11
	cs\Response;
12
13
trait Static_files {
14
	/**
15
	 * @throws ExitException
16
	 */
17 28
	protected function serve_static_files () {
18 28
		$path = $this->path;
19
		if (
20 28
			$this->method != 'GET' ||
21 24
			!in_array(php_sapi_name(), ['cli', 'cli-server']) ||
22 28
			strlen($path) < 2
23
		) {
24 26
			return;
25
		}
26 6
		$path = realpath(DIR.$path);
27
		if (
28 6
			strpos($path, DIR) !== 0 ||
29 6
			strpos(basename($path), '.') === 0
30
		) {
31 6
			return;
32
		}
33 2
		$path      = substr($path, strlen(DIR));
34 2
		$extension = file_extension($path);
35
		/**
36
		 * Public cache
37
		 */
38 2
		if (strpos($path, '/storage/pcache') === 0) {
39 2
			if (!in_array($extension, ['css', 'js', 'html'])) {
40 2
				throw new ExitException(403);
41
			}
42 2
			$this->serve_static_file($path);
43
		}
44
		/**
45
		 * Uploaded files
46
		 */
47 2
		if (strpos($path, '/storage/public') === 0) {
48
			$headers = [
49 2
				'x-frame-options' => 'DENY',
50
				'content-type'    => 'application/octet-stream'
51
			];
52 2
			$this->serve_static_file($path, $headers);
53
		}
54 2
		if ($extension == 'php') {
55 2
			throw new ExitException(404);
56
		}
57
		/**
58
		 * System, modules and themes includes
59
		 */
60 2
		if (preg_match('#^/((modules/\w+/)?includes|themes/\w+)/.+#', $path)) {
61 2
			$this->serve_static_file($path);
62
		}
63 2
		throw new ExitException(404);
64
	}
65
	/**
66
	 * @param string   $path
67
	 * @param string[] $headers
68
	 *
69
	 * @throws ExitException
70
	 */
71 2
	protected function serve_static_file ($path, $headers = []) {
72 2
		$headers += ['cache-control' => 'max-age=2592000, public'];
73 2
		Response::instance()->init('', fopen(DIR.$path, 'rb'), $headers);
74 2
		throw new ExitException;
75
	}
76
}
77