Skip to content

Commit

Permalink
feat: better handling of class string as middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ipranjal committed Oct 3, 2024
1 parent 8a9e173 commit 21fc246
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/Pipeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ public function __construct(array $middlewares = [])

/**
* Add middleware(s) or Pipeline
* @param array<callable|\Closure|string> $middlewares
* @template T of MiddlewareInterface
* @param array<callable|\Closure|class-string<T>> $middlewares
* @return array<\Closure>
*/
public function validateMiddleware(array $middlewares): array
Expand All @@ -39,11 +40,19 @@ public function validateMiddleware(array $middlewares): array
if(is_array($middlewares) ) {
foreach ($middlewares as $middleware) {
if(is_string($middleware)) {
$middleware = new $middleware();
}
if ($middleware instanceof MiddlewareInterface) {
$middleware = $middleware->run(...);
}
if(class_exists($middleware)) {
$middlewareObj = new $middleware;
if($middlewareObj instanceof MiddlewareInterface) {
$callable = [$middlewareObj, 'run'];
$middleware = \Closure::fromCallable(callback: $callable);
} else {
throw new \Scrawler\Exception\InvalidMiddlewareException('Middleware class does not implement MiddlewareInterface');
}
} else {
throw new \Scrawler\Exception\InvalidMiddlewareException('Middleware class does not exist');
}

}
if(is_callable($middleware)) {
$middleware = \Closure::fromCallable(callback: $middleware);
}
Expand Down

0 comments on commit 21fc246

Please sign in to comment.