Completed
Push — master ( 59df22...469807 )
by Nazar
04:12
created

Controller::controller_router()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 1
b 0
f 0
nc 24
nop 1
dl 0
loc 23
rs 6.7272
1
<?php
2
/**
3
 * @package   CleverStyle CMS
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
	protected function controller_router ($Request) {
25
		$suffix = '';
26
		if ($Request->cli_path) {
27
			$suffix = '\\cli';
28
		} elseif ($Request->admin_path) {
29
			$suffix = '\\admin';
30
		} elseif ($Request->api_path) {
31
			$suffix = '\\api';
32
		}
33
		$controller_class = class_exists("cs\\custom\\modules\\$Request->current_module$suffix\\Controller")
34
			? "cs\\custom\\modules\\$Request->current_module$suffix\\Controller"
35
			: "cs\\modules\\$Request->current_module$suffix\\Controller";
36
		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
			if ($index > 1) {
41
				$path = implode('_', array_slice($this->controller_path, 1, $index));
42
			}
43
			$next_exists = isset($this->controller_path[$index + 1]);
44
			$this->controller_router_handler($Request, $controller_class, $path, !$next_exists);
45
		}
46
	}
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
	protected function controller_router_handler ($Request, $controller_class, $method_name, $required = true) {
58
		$method_name = str_replace('.', '_', $method_name);
59
		$this->controller_router_handler_internal($Request, $controller_class, $method_name, $required);
60
	}
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
	protected function controller_router_handler_internal ($Request, $controller_class, $method_name, $required) {
70
		$Response = Response::instance();
71
		$found    = $this->controller_router_handler_internal_execute($controller_class, $method_name, $Request, $Response);
72
		if (!$Request->cli_path && !$Request->api_path) {
73
			return;
74
		}
75
		$request_method = strtolower($Request->method);
76
		$found          = $this->controller_router_handler_internal_execute($controller_class, $method_name.'_'.$request_method, $Request, $Response) || $found;
77
		if ($found || !$required) {
78
			return;
79
		}
80
		$this->handler_not_found(
81
			$this->controller_router_available_methods($this->working_directory, $controller_class, $method_name),
82
			$request_method,
83
			$Request
84
		);
85
	}
86
	/**
87
	 * @param string $working_directory
88
	 * @param string $controller_class
89
	 * @param string $method_name
90
	 *
91
	 * @return string[]
92
	 */
93
	protected function controller_router_available_methods ($working_directory, $controller_class, $method_name) {
94
		$structure = file_exists("$working_directory/index.json") ? file_get_json("$working_directory/index.json") : ['index'];
95
		$structure = $this->controller_router_available_methods_to_flat_structure($structure);
96
		$methods   = array_filter(
97
			get_class_methods($controller_class),
98
			function ($found_method) use ($method_name, $structure) {
99
				if (!preg_match("/^{$method_name}_[a-z_]+$/", $found_method)) {
100
					return false;
101
				}
102
				foreach ($structure as $structure_method) {
103
					if (strpos($found_method, $structure_method) === 0 && strpos($method_name, $structure_method) !== 0) {
104
						return false;
105
					}
106
				}
107
				return true;
108
			}
109
		);
110
		if (method_exists($controller_class, $method_name)) {
111
			$methods[] = $method_name;
112
		}
113
		$methods = _strtoupper(_substr($methods, strlen($method_name) + 1));
114
		natcasesort($methods);
115
		return array_values($methods);
116
	}
117
	/**
118
	 * @param array  $structure
119
	 * @param string $prefix
120
	 *
121
	 * @return string[]
122
	 */
123
	protected function controller_router_available_methods_to_flat_structure ($structure, $prefix = '') {
124
		/**
125
		 * Hack: first key in order to avoid warning when `$flat_structure` is empty at `return`
126
		 */
127
		$flat_structure = [[]];
128
		foreach ($structure as $path => $nested_structure) {
129
			if (!is_array($nested_structure)) {
130
				$path             = $nested_structure;
131
				$nested_structure = [];
132
			}
133
			$flat_structure[] = [$prefix.$path];
134
			$flat_structure[] = $this->controller_router_available_methods_to_flat_structure($nested_structure, $prefix.$path.'_');
135
		}
136
		return array_merge(...$flat_structure);
137
	}
138
	/**
139
	 * @param string      $controller_class
140
	 * @param string      $method_name
141
	 * @param \cs\Request $Request
142
	 * @param Response    $Response
143
	 *
144
	 * @return bool
145
	 */
146
	protected function controller_router_handler_internal_execute ($controller_class, $method_name, $Request, $Response) {
147
		if (!method_exists($controller_class, $method_name)) {
148
			return false;
149
		}
150
		$result = $controller_class::$method_name($Request, $Response);
151
		if ($result !== null) {
152
			Page::instance()->{$Request->api_path ? 'json' : 'content'}($result);
153
		}
154
		return true;
155
	}
156
}
157