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

Static_files::serve_static_files()   C

Complexity

Conditions 11
Paths 15

Size

Total Lines 48
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 11
eloc 28
c 2
b 1
f 1
nc 15
nop 0
dl 0
loc 48
ccs 24
cts 24
cp 1
crap 11
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 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