Completed
Push — master ( 2f0acd...8465e8 )
by Nazar
08:23
created

Controller::controller_router()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 16
c 0
b 0
f 0
nc 24
nop 1
dl 0
loc 23
ccs 17
cts 17
cp 1
crap 7
rs 6.7272
1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2015-2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\App\Router;
9
use
10
	cs\Page,
11
	cs\Response;
12
13
/**
14
 * @property string[] $controller_path Path that will be used by controller to render page
15
 */
16
trait Controller {
17
	/**
18
	 * Call methods necessary for module page rendering
19
	 *
20
	 * @param \cs\Request $Request
21
	 *
22
	 * @throws \cs\ExitException
23
	 */
24 8
	protected function controller_router ($Request) {
25 8
		$suffix = '';
26 8
		if ($Request->cli_path) {
27 2
			$suffix = '\\cli';
28 8
		} elseif ($Request->admin_path) {
29 2
			$suffix = '\\admin';
30 8
		} elseif ($Request->api_path) {
31 6
			$suffix = '\\api';
32
		}
33 8
		$controller_class = class_exists("cs\\custom\\modules\\$Request->current_module$suffix\\Controller")
34 2
			? "cs\\custom\\modules\\$Request->current_module$suffix\\Controller"
35 8
			: "cs\\modules\\$Request->current_module$suffix\\Controller";
36 8
		foreach ($this->controller_path as $index => $path) {
37
			/**
38
			 * Starting from index 2 we need to maintain underscore-separated string that includes all paths from index 1 and till current
39
			 */
40 8
			if ($index > 1) {
41 2
				$path = implode('_', array_slice($this->controller_path, 1, $index));
42
			}
43 8
			$next_exists = isset($this->controller_path[$index + 1]);
44 8
			$this->controller_router_handler($Request, $controller_class, $path, !$next_exists);
45
		}
46 8
	}
47
	/**
48
	 * Call methods that corresponds for specific paths in URL
49
	 *
50
	 * @param \cs\Request $Request
51
	 * @param string      $controller_class
52
	 * @param string      $method_name
53
	 * @param bool        $required
54
	 *
55
	 * @throws \cs\ExitException
56
	 */
57 8
	protected function controller_router_handler ($Request, $controller_class, $method_name, $required = true) {
58 8
		$method_name = str_replace('.', '_', $method_name);
59 8
		$this->controller_router_handler_internal($Request, $controller_class, $method_name, $required);
60 8
	}
61
	/**
62
	 * @param \cs\Request $Request
63
	 * @param string      $controller_class
64
	 * @param string      $method_name
65
	 * @param bool        $required
66
	 *
67
	 * @throws \cs\ExitException
68
	 */
69 8
	protected function controller_router_handler_internal ($Request, $controller_class, $method_name, $required) {
70 8
		$Response = Response::instance();
71 8
		$found    = $this->controller_router_handler_internal_execute($controller_class, $method_name, $Request, $Response);
72 8
		if (!$Request->cli_path && !$Request->api_path) {
73 4
			return;
74
		}
75 6
		$request_method = strtolower($Request->method);
76 6
		$found          = $this->controller_router_handler_internal_execute($controller_class, $method_name.'_'.$request_method, $Request, $Response) || $found;
77 6
		if ($found || !$required) {
78 6
			return;
79
		}
80 2
		$this->handler_not_found(
81 2
			$this->controller_router_available_methods($this->working_directory, $controller_class, $method_name),
82
			$request_method,
83
			$Request
84
		);
85 2
	}
86
	/**
87
	 * @param string $working_directory
88
	 * @param string $controller_class
89
	 * @param string $method_name
90
	 *
91
	 * @return string[]
92
	 */
93 2
	protected function controller_router_available_methods ($working_directory, $controller_class, $method_name) {
94 2
		$structure = file_exists("$working_directory/index.json") ? file_get_json("$working_directory/index.json") : ['index'];
95 2
		$structure = $this->controller_router_available_methods_to_flat_structure($structure);
96 2
		$methods   = array_filter(
97 2
			get_class_methods($controller_class) ?: [],
98 2
			function ($found_method) use ($method_name, $structure) {
99 2
				if (!preg_match("/^{$method_name}_[a-z_]+$/", $found_method)) {
100 2
					return false;
101
				}
102 2
				foreach ($structure as $structure_method) {
103 2
					if (strpos($found_method, $structure_method) === 0 && strpos($method_name, $structure_method) !== 0) {
104 2
						return false;
105
					}
106
				}
107 2
				return true;
108 2
			}
109
		);
110 2
		if (method_exists($controller_class, $method_name)) {
111
			$methods[] = $method_name;
112
		}
113 2
		$methods = _strtoupper(_substr($methods, strlen($method_name) + 1));
114 2
		natcasesort($methods);
115 2
		return array_values($methods);
116
	}
117
	/**
118
	 * @param array  $structure
119
	 * @param string $prefix
120
	 *
121
	 * @return string[]
122
	 */
123 2
	protected function controller_router_available_methods_to_flat_structure ($structure, $prefix = '') {
124
		// First key in order to avoid warning when `$flat_structure` is empty at `return`
125 2
		$flat_structure = [[]];
126 2
		foreach ($structure as $path => $nested_structure) {
127 2
			if (!is_array($nested_structure)) {
128 2
				$path             = $nested_structure;
129 2
				$nested_structure = [];
130
			}
131 2
			$flat_structure[] = [$prefix.$path];
132 2
			$flat_structure[] = $this->controller_router_available_methods_to_flat_structure($nested_structure, $prefix.$path.'_');
133
		}
134 2
		return array_merge(...$flat_structure);
135
	}
136
	/**
137
	 * @param string      $controller_class
138
	 * @param string      $method_name
139
	 * @param \cs\Request $Request
140
	 * @param Response    $Response
141
	 *
142
	 * @return bool
143
	 */
144 8
	protected function controller_router_handler_internal_execute ($controller_class, $method_name, $Request, $Response) {
145 8
		if (!method_exists($controller_class, $method_name)) {
146 8
			return false;
147
		}
148 6
		$result = $controller_class::$method_name($Request, $Response);
149 6
		if ($result !== null) {
150 2
			Page::instance()->{$Request->api_path ? 'json' : 'content'}($result);
151
		}
152 6
		return true;
153
	}
154
}
155