Completed
Push — master ( ae87f2...118397 )
by Nazar
04:02
created

Static_files::serve_static_files()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 48
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 35.0138

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 28
c 1
b 0
f 0
nc 12
nop 0
dl 0
loc 48
ccs 10
cts 24
cp 0.4167
crap 35.0138
rs 5.2653

How to fix   Complexity   

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) 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 26
	protected function serve_static_files () {
18 26
		$path = explode('?', $this->path)[0];
19
		if (
20 26
			$this->method != 'GET' ||
21 22
			!in_array(PHP_SAPI, ['cli', 'cli-server']) ||
22 26
			strlen($path) < 2
23
		) {
24 24
			return;
25
		}
26 4
		$path = realpath(DIR.$path);
27
		if (
28 4
			strpos($path, DIR) !== 0 ||
29 4
			strpos(basename($path), '.') === 0
30
		) {
31 4
			return;
32
		}
33
		$path      = substr($path, strlen(DIR));
34
		$extension = file_extension($path);
35
		if ($extension == 'php') {
36
			throw new ExitException(404);
37
		}
38
		/**
39
		 * Public cache
40
		 */
41
		if (strpos($path, '/storage/pcache') === 0) {
42
			if (!in_array($extension, ['css', 'js', 'html'])) {
43
				throw new ExitException(403);
44
			}
45
			$this->serve_static_file($path);
46
		}
47
		/**
48
		 * Uploaded files
49
		 */
50
		if (strpos($path, '/storage/public') === 0) {
51
			$headers = [
52
				'x-frame-options' => 'DENY',
53
				'content-type'    => 'application/octet-stream'
54
			];
55
			$this->serve_static_file($path, $headers);
56
		}
57
		/**
58
		 * System, modules and themes includes
59
		 */
60
		if (preg_match('#^/((modules/\w+/)?includes|themes/\w+)/.+#', $path)) {
61
			$this->serve_static_file($path);
62
		}
63
		throw new ExitException(404);
64
	}
65
	/**
66
	 * @param string   $path
67
	 * @param string[] $headers
68
	 *
69
	 * @throws ExitException
70
	 */
71
	protected function serve_static_file ($path, $headers = []) {
72
		$headers += ['cache-control' => 'max-age=2592000, public'];
73
		Response::instance()->init('', fopen(DIR.$path, 'rb'), $headers);
74
		throw new ExitException;
75
	}
76
}
77