Skip to content

Commit 8297d19

Browse files
committed
multi domains feature added to group method.
1 parent 7d31425 commit 8297d19

File tree

6 files changed

+95
-37
lines changed

6 files changed

+95
-37
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
/vendor
22
/composer.lock
33
/.idea
4+
/.env

README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,13 @@ Create a class for example AuthMiddleware that implements IMiddleware contract
125125

126126
class AuthMiddleware implements IMiddleware
127127
{
128-
public function handle(IRequest $request)
128+
public function handle(IRequest $request,Callable $next)
129129
{
130130
if(!isset($_SESSION['admin']) && $_SESSION['admin'] !== 'zanko'){
131131
header("Location:/");
132132
exit();
133133
}
134+
$next($request);
134135
}
135136
}
136137
```
@@ -200,6 +201,34 @@ Also you would be able to bind middlewares to group method
200201
Router::executeRoutes();
201202
```
202203

204+
You can also use subdomains in <code>group</code> method like block code below
205+
```php
206+
use ZankoKhaledi\PhpSimpleRouter\Request;
207+
use ZankoKhaledi\PhpSimpleRouter\Router;
208+
use ZankoKhaledi\PhpSimpleRouter\Interfaces\IRoute;
209+
use App\Middelwares\AuthMiddleware;
210+
211+
require __DIR__ . "/vendor/autoload.php";
212+
213+
214+
Router::group([
215+
'domain' => 'example.local'
216+
,'prefix' => '/bar'
217+
,'middleware' => [AuthMiddleware::class]]
218+
,function (IRoute $router){
219+
// code
220+
});
221+
222+
Router::executeRoutes();
223+
224+
```
225+
By default you're host name is localhost you would be able to change it in <code>.env</code>
226+
file on root of you're project for example
227+
```.dotenv
228+
229+
HOSTNAME = mysite.local
230+
231+
```
203232
## Testing
204233

205234
```php

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
"require": {
55
"php": ">= 8.1",
66
"guzzlehttp/guzzle": "^7.0",
7-
"phpunit/phpunit" : "9.*"
7+
"phpunit/phpunit" : "9.*",
8+
"vlucas/phpdotenv": "^5.5"
89
},
910
"keywords": [
1011
"php",

src/Interfaces/IMiddleware.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@
44

55
interface IMiddleware
66
{
7-
public function handle(IRequest $request);
7+
public function handle(IRequest $request,callable $next);
88
}

src/Router.php

Lines changed: 61 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
namespace ZankoKhaledi\PhpSimpleRouter;
55

6+
7+
use Dotenv\Dotenv;
68
use Exception as ExceptionAlias;
79
use ZankoKhaledi\PhpSimpleRouter\Interfaces\IMiddleware;
810
use ZankoKhaledi\PhpSimpleRouter\Interfaces\IRoute;
@@ -29,6 +31,7 @@ final class Router implements IRoute
2931
private ?string $prefix = null;
3032
private ?array $routes = [];
3133
private array $middlewares = [];
34+
private ?string $host = null;
3235

3336

3437
const GET = 'GET';
@@ -37,15 +40,20 @@ final class Router implements IRoute
3740
const PATCH = 'PATCH';
3841
const DELETE = 'DELETE';
3942

43+
const HOSTNAME = 'localhost';
4044

4145
/**
4246
*
4347
* @throws ExceptionAlias
4448
*/
4549
private function __construct()
4650
{
51+
$env = Dotenv::createImmutable(dirname(__DIR__));
52+
$env->load();
53+
4754
$this->serverMode = php_sapi_name();
4855
$this->uri = $this->serverMode === 'cli-server' ? parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) : null;
56+
$this->host = $_ENV['HOSTNAME'] ?? static::HOSTNAME;
4957
}
5058

5159
/**
@@ -68,26 +76,6 @@ private static function getInstance(): ?static
6876
return static::$instance;
6977
}
7078

71-
/**
72-
* @param array $attributes
73-
* @param callable $callback
74-
* @return void
75-
*/
76-
public static function group(array $attributes, callable $callback): void
77-
{
78-
if (array_key_exists('prefix', $attributes)) {
79-
static::getInstance()->prefix = $attributes['prefix'];
80-
}
81-
if (array_key_exists('middleware', $attributes)) {
82-
static::getInstance()->middlewares = is_array($attributes['middleware']) && count($attributes['middleware']) ? [...$attributes['middleware']] : $attributes['middleware'];
83-
}
84-
85-
call_user_func($callback);
86-
87-
static::getInstance()->prefix = null;
88-
static::getInstance()->middlewares = [];
89-
}
90-
9179

9280
/**
9381
* @param string $path
@@ -178,7 +166,7 @@ public static function executeRoutes(): void
178166
public function middleware(array $middlewares): IRoute
179167
{
180168
foreach ($this->routes as $index => $route) {
181-
if ($this->routes[$index]['path'] === $this->path) {
169+
if ($route['domain'] . $route['path'] === $this->host . $this->path) {
182170
$this->routes[$index]['middlewares'] = [...$middlewares, ...$this->middlewares];
183171
}
184172
}
@@ -195,7 +183,7 @@ public function where(string $pattern): IRoute
195183
preg_match($pattern, $this->uri, $matches);
196184

197185
foreach ($this->routes as $index => $route) {
198-
if ($route['path'] === $this->path) {
186+
if ($route['domain'] . $route['path'] === $this->host . $this->path) {
199187
$this->routes[$index]['valid'] = count($matches) > 0;
200188
}
201189
}
@@ -204,6 +192,31 @@ public function where(string $pattern): IRoute
204192
}
205193

206194

195+
/**
196+
* @param array $attributes
197+
* @param callable $callback
198+
* @return void
199+
*/
200+
public static function group(array $attributes, callable $callback): void
201+
{
202+
if (array_key_exists('prefix', $attributes)) {
203+
static::getInstance()->prefix = $attributes['prefix'];
204+
}
205+
if (array_key_exists('middleware', $attributes)) {
206+
static::getInstance()->middlewares = is_array($attributes['middleware']) && count($attributes['middleware']) ? [...$attributes['middleware']] : $attributes['middleware'];
207+
}
208+
if (array_key_exists('domain', $attributes)) {
209+
static::getInstance()->host = $attributes['domain'];
210+
}
211+
212+
call_user_func($callback);
213+
214+
static::getInstance()->prefix = null;
215+
static::getInstance()->middlewares = [];
216+
static::getInstance()->host = $_ENV['HOSTNAME'] ?? static::HOSTNAME;
217+
}
218+
219+
207220
/**
208221
* @param string $method
209222
* @param mixed $path
@@ -221,7 +234,7 @@ private function addRoute(string $method, mixed $path, callable|array $callback)
221234
$this->path = $this->prefix !== null ? $this->prefix . $path : $path;
222235

223236
foreach ($this->routes as $index => $route) {
224-
if ($this->routes[$index]['path'] === $this->path && $this->routes[$index]['method'] === $method) {
237+
if ($route['domain'] . $route['path'] === $this->host . $this->path && $route['method'] === $method) {
225238
throw new ExceptionAlias("route $path added before.");
226239
}
227240
}
@@ -231,7 +244,8 @@ private function addRoute(string $method, mixed $path, callable|array $callback)
231244
'path' => $this->path,
232245
'callback' => $callback,
233246
'middlewares' => [...$this->middlewares],
234-
'valid' => true
247+
'valid' => true,
248+
'domain' => $this->host
235249
];
236250

237251
return $this;
@@ -244,13 +258,17 @@ private function addRoute(string $method, mixed $path, callable|array $callback)
244258
private function serve(): void
245259
{
246260
foreach ($this->routes as $index => $route) {
247-
if ($this->handleDynamicRouteParamsAndPath($route['path'], $this->uri) && $route['method'] === $_SERVER['REQUEST_METHOD'] && $route['valid']) {
248-
$this->handleRoute($route['callback'], $route['middlewares']);
249-
return;
261+
if ($this->handleDynamicRouteParamsAndPath($route['path'], $this->uri) &&
262+
$route['method'] === $_SERVER['REQUEST_METHOD'] &&
263+
$route['valid']
264+
) {
265+
if ($this->checkDomain($route['domain'])) {
266+
$this->handleRoute($route['callback'], $route['middlewares']);
267+
return;
268+
}
250269
}
251270
}
252271

253-
254272
header('Location:/route-not-found');
255273
exit();
256274
}
@@ -269,30 +287,40 @@ private function handleRoute(array|callable $callback, array $middlewares): void
269287
foreach ($middlewares as $middleware) {
270288
$instance = (new $middleware);
271289
if ($instance instanceof IMiddleware) {
272-
$instance->handle($this->request);
290+
$instance->handle($this->request, fn(Request $request) => $this->handleCallback($callback, $request));
291+
return;
273292
} else {
274293
throw new ExceptionAlias("$middleware must be type of IMiddleware interface.");
275294
}
276295
}
277296

278-
$this->handleCallback($callback);
297+
$this->handleCallback($callback, $this->request);
279298
}
280299

281300

282301
/**
283302
* @param callable|array $callback
284303
* @return void
285304
*/
286-
private function handleCallback(callable|array $callback): void
305+
private function handleCallback(callable|array $callback, Request $request): void
287306
{
288307
is_array($callback) ?
289-
call_user_func_array([new $callback[0], $callback[1]], [$this->request]) :
290-
call_user_func($callback, $this->request);
308+
call_user_func_array([new $callback[0], $callback[1]], [$request]) :
309+
call_user_func($callback, $request);
291310
}
292311

312+
/**
313+
* @param string $domain
314+
* @return bool
315+
*/
316+
private function checkDomain(string $domain): bool
317+
{
318+
return $domain === parse_url($_SERVER['HTTP_HOST'], PHP_URL_HOST);
319+
}
293320

294321
/**
295322
* @param string $route
323+
* @param string $uri
296324
* @return bool
297325
*/
298326
private function handleDynamicRouteParamsAndPath(string $route, string $uri): bool

src/RouterCollection.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ public static function executeRoutesFrom(string $path): void
2424
throw new \Exception("$route file doesn't exists.");
2525
}
2626
}
27-
2827
Router::executeRoutes();
2928
}
3029
}

0 commit comments

Comments
 (0)