| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib; |
| 39 | |
| 40 | class Route { |
| 41 | protected static array $routes = []; |
| 42 | protected static array $fallback = []; |
| 43 | |
| 44 | /** |
| 45 | * ルート設定を言語固有のハンドラで初期化する |
| 46 | * |
| 47 | * @param array $routes ルート設定の配列 |
| 48 | * @return void |
| 49 | */ |
| 50 | public static function init(array $routes): void { |
| 51 | self::$routes = $routes; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * ルートを追加する |
| 56 | * |
| 57 | * @param string $method HTTPメソッド |
| 58 | * @param string $path URLパス |
| 59 | * @param string|callable $class ハンドラクラスとメソッド、またはコールバック |
| 60 | * @param array $params オプションのパラメータ |
| 61 | * @return array ルート設定 |
| 62 | */ |
| 63 | public static function add(string $method, string $path, string|callable $class, |
| 64 | array $params = []): array { |
| 65 | $route = [ |
| 66 | 'method' => $method, |
| 67 | 'path' => $path, |
| 68 | 'class' => $class, |
| 69 | 'params' => $params, |
| 70 | ]; |
| 71 | |
| 72 | self::$routes[] = $route; |
| 73 | return $route; |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * 404処理用のフォールバックルートを設定する |
| 78 | * |
| 79 | * @param array|string|callable $class |
| 80 | * @return void |
| 81 | */ |
| 82 | public static function setFallback(array|string|callable $class): void { |
| 83 | self::$fallback = [ |
| 84 | 'class' => $class, |
| 85 | 'params' => [], |
| 86 | ]; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * 適切なルートをマッチさせて実行する |
| 91 | * |
| 92 | * @param string $uri リクエストURI |
| 93 | * @return void |
| 94 | */ |
| 95 | public static function dispatch(string $uri): void { |
| 96 | // URIをパスとクエリ文字列に分割 |
| 97 | $uriParts = explode('?', $uri, 2); |
| 98 | $path = trim($uriParts[0], " \t\n\r\0\x0B/"); |
| 99 | |
| 100 | // ルートパスの処理(/?page=2のようなクエリパラメータを含む場合も処理) |
| 101 | if ($path === '') { |
| 102 | self::executeClass([ |
| 103 | 'class' => [new \Site\Controller\Home(), 'show'], |
| 104 | 'params' => ['lang' => 'ja'], |
| 105 | ]); |
| 106 | return; |
| 107 | } |
| 108 | |
| 109 | if ($path === 'en') { |
| 110 | self::executeClass([ |
| 111 | 'class' => [new \Site\Controller\Home(), 'show'], |
| 112 | 'params' => ['lang' => 'en'], |
| 113 | ]); |
| 114 | return; |
| 115 | } |
| 116 | |
| 117 | // パスに対してルートをマッチングする |
| 118 | foreach (self::$routes as $route) { |
| 119 | $matches = []; |
| 120 | |
| 121 | if (self::matchRoute($route['path'], $path, $matches)) { |
| 122 | $params = self::extractParams($route['path'], $path); |
| 123 | $params = array_merge($route['params'], $params); |
| 124 | |
| 125 | if (is_string($route['class'])) { |
| 126 | [ $class, $method ] = explode('@', $route['class']); |
| 127 | $controller = new $class(); |
| 128 | self::executeClass([ |
| 129 | 'class' => [ $controller, $method ], |
| 130 | 'params' => $params, |
| 131 | ]); |
| 132 | |
| 133 | return; |
| 134 | } elseif (is_callable($route['class'])) { |
| 135 | self::executeClass([ |
| 136 | 'class' => $route['class'], |
| 137 | 'params' => $params, |
| 138 | ]); |
| 139 | |
| 140 | return; |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // マッチするルートがない場合、フォールバックを実行 |
| 146 | self::executeClass(self::$fallback); |
| 147 | } |
| 148 | |
| 149 | /** |
| 150 | * ルートパターンとパスをマッチングする |
| 151 | * |
| 152 | * @param string $pattern ルートパターン |
| 153 | * @param string $path 現在のパス |
| 154 | * @param array $matches マッチを格納する参照 |
| 155 | * @return bool |
| 156 | */ |
| 157 | protected static function matchRoute(string $pattern, string $path, |
| 158 | array &$matches = []): bool { |
| 159 | // ルートパターンを正規表現パターンに変換 |
| 160 | $pattern = preg_replace('/\{([^:}]+)(?::([^}]+))?\}/', '(?P<$1>[^/]+)', $pattern); |
| 161 | $pattern = str_replace('/', '\/', $pattern); |
| 162 | return (bool)preg_match('/^'.$pattern.'$/', $path, $matches); |
| 163 | } |
| 164 | |
| 165 | /** |
| 166 | * パターンに基づいてパスから名前付きパラメータを抽出する |
| 167 | * |
| 168 | * @param string $pattern ルートパターン |
| 169 | * @param string $path 現在のパス |
| 170 | * @return array |
| 171 | */ |
| 172 | protected static function extractParams(string $pattern, string $path): array { |
| 173 | $params = []; |
| 174 | $patternParts = explode('/', $pattern); |
| 175 | $pathParts = explode('/', $path); |
| 176 | |
| 177 | foreach ($patternParts as $k => $v) { |
| 178 | if (preg_match('/\{([^:}]+)(?::([^}]+))?\}/', $v, $matches)) { |
| 179 | if (isset($pathParts[$k])) { |
| 180 | $params[$matches[1]] = $pathParts[$k]; |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | return $params; |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * ルートクラスを実行する |
| 190 | * |
| 191 | * @param array $route ルート設定 |
| 192 | * @return void |
| 193 | */ |
| 194 | protected static function executeClass(array $route): void { |
| 195 | if (is_callable($route['class'])) { |
| 196 | call_user_func($route['class'], $route['params'] ?? []); |
| 197 | } |
| 198 | } |
| 199 | } |