-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
executable file
·281 lines (234 loc) · 9.22 KB
/
Router.php
File metadata and controls
executable file
·281 lines (234 loc) · 9.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php
// core/Router.php
namespace Core;
class Router
{
private static $instance = null;
private $routes = [];
private $apiRoutes = [];
private $auth;
private $basePath = '';
private function __construct()
{
$this->basePath = defined("BASE_PATH") ? BASE_PATH : "";
$this->auth = Auth::getInstance();
}
private function isAjaxRequest()
{
$requestedWith = strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '');
if ($requestedWith === 'xmlhttprequest') {
return true;
}
$accept = strtolower($_SERVER['HTTP_ACCEPT'] ?? '');
return strpos($accept, 'application/json') !== false;
}
private function sendNoCacheHeaders()
{
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
}
// シングルトンパターンでインスタンスを取得
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
// 通常のルートを登録(ページ用)
public function add($method, $path, $handler, $authRequired = false)
{
$this->routes[] = [
'method' => $method,
'path' => $path,
'handler' => $handler,
'authRequired' => $authRequired
];
return $this;
}
// GETルートを登録
public function get($path, $handler, $authRequired = false)
{
return $this->add('GET', $path, $handler, $authRequired);
}
// POSTルートを登録
public function post($path, $handler, $authRequired = false)
{
return $this->add('POST', $path, $handler, $authRequired);
}
// APIルートを登録(JSON応答用)
public function api($method, $path, $handler, $authRequired = false)
{
$this->apiRoutes[] = [
'method' => $method,
'path' => "/api" . $path,
'handler' => $handler,
'authRequired' => $authRequired
];
return $this;
}
// API GETルートを登録
public function apiGet($path, $handler, $authRequired = false)
{
return $this->api('GET', $path, $handler, $authRequired);
}
// API POSTルートを登録
public function apiPost($path, $handler, $authRequired = false)
{
return $this->api('POST', $path, $handler, $authRequired);
}
// API DELETEルートを登録
public function apiDelete($path, $handler, $authRequired = false)
{
return $this->api('DELETE', $path, $handler, $authRequired);
}
// パスパラメータを抽出
private function extractParams($route, $path)
{
$routeParts = explode('/', trim($route, '/'));
$pathParts = explode('/', trim($path, '/'));
if (count($routeParts) !== count($pathParts)) {
return null;
}
$params = [];
foreach ($routeParts as $index => $routePart) {
if (strpos($routePart, ':') === 0) {
$paramName = substr($routePart, 1);
$params[$paramName] = $pathParts[$index];
} elseif (preg_match('/^\{(.+)\}$/', $routePart, $m)) {
$params[$m[1]] = $pathParts[$index];
} elseif ($routePart !== $pathParts[$index]) {
return null;
}
}
return $params;
}
// ルートの一致をチェック
private function matchRoute($route, $method, $path)
{
if ($route['method'] !== $method) {
return [false, []];
}
// 完全一致の場合
if ($route['path'] === $path) {
return [true, []];
}
// パラメータ付きルートの場合
$params = $this->extractParams($route['path'], $path);
if ($params !== null) {
return [true, $params];
}
return [false, []];
}
// リクエストを処理
public function dispatch()
{
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$baseDir = dirname($_SERVER['SCRIPT_NAME']);
// /public を除去(ルートの.htaccessからリダイレクトされた場合)
$baseDir = preg_replace('#/public$#', '', $baseDir);
// ベースディレクトリの調整
if ($baseDir !== '/' && strpos($path, $baseDir) === 0) {
$path = substr($path, strlen($baseDir));
}
// /index.php 配下のURLでも通常ルートとして扱う
if (strpos($path, '/index.php') === 0) {
$path = substr($path, strlen('/index.php'));
if ($path === '') {
$path = '/';
}
}
// 特別なケース: 組織コードの重複チェックAPI
if (strpos($path, '/api/organizations/check-code') !== false && $method === 'GET') {
$controller = new \Controllers\OrganizationController();
// クエリパラメータをそのまま渡す
$params = $_GET;
$response = $controller->apiCheckCodeUnique($params);
$this->sendNoCacheHeaders();
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
// API用ルートを先にチェック
foreach ($this->apiRoutes as $route) {
list($matched, $params) = $this->matchRoute($route, $method, $path);
if ($matched) {
// 認証が必要なルートの場合
if ($route['authRequired'] && !$this->auth->check()) {
$this->sendNoCacheHeaders();
header('Content-Type: application/json');
http_response_code(401);
echo json_encode(['error' => '認証が必要です']);
exit;
}
// JSONリクエストの処理
$requestData = [];
if ($method === 'POST' || $method === 'PUT') {
// まず$_POSTを確認
if (!empty($_POST)) {
$requestData = $_POST;
} else {
// $_POSTが空の場合はphp://inputからデータを取得
$input = file_get_contents('php://input');
if (!empty($input)) {
$contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (strpos($contentType, 'application/json') !== false) {
$requestData = json_decode($input, true) ?? [];
} else {
// 他のフォーマット(例:x-www-form-urlencoded)
parse_str($input, $requestData);
}
}
}
} else if ($method === 'DELETE') {
$input = file_get_contents('php://input');
if (!empty($input)) {
$requestData = json_decode($input, true) ?? [];
}
}
// ハンドラを実行
$response = call_user_func($route['handler'], $params, $requestData);
// 通常フォームからAPIへ直接送られた場合は、成功時に画面遷移へフォールバックする
if (($method === 'POST' || $method === 'PUT') && !$this->isAjaxRequest()) {
if (!empty($response['success']) && !empty($response['redirect'])) {
header('Location: ' . $response['redirect']);
exit;
}
if (!empty($response['error'])) {
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION['error'] = $response['error'];
}
$fallbackUrl = $_SERVER['HTTP_REFERER'] ?? $this->basePath . '/';
header('Location: ' . $fallbackUrl);
exit;
}
}
// JSON応答を返す
$this->sendNoCacheHeaders();
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
}
// 通常ルートをチェック
foreach ($this->routes as $route) {
list($matched, $params) = $this->matchRoute($route, $method, $path);
if ($matched) {
// 認証が必要なルートの場合
if ($route['authRequired'] && !$this->auth->check()) {
header('Location: ' . $this->basePath . '/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
exit;
}
// ハンドラを実行
call_user_func($route['handler'], $params);
exit;
}
}
// 一致するルートがなかった場合
header("HTTP/1.0 404 Not Found");
$this->sendNoCacheHeaders();
echo "404 Not Found";
}
}