Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 4de29f2

Browse files
committed
configurable response factory
1 parent 2257aac commit 4de29f2

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/JwtAuthentication.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ final class JwtAuthentication implements MiddlewareInterface
8585
"ignore" => null,
8686
"before" => null,
8787
"after" => null,
88-
"error" => null
88+
"error" => null,
89+
"responseFactory" => null,
8990
];
9091

9192
public function __construct(array $options = [])
@@ -139,7 +140,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
139140
$token = $this->fetchToken($request);
140141
$decoded = $this->decodeToken($token);
141142
} catch (RuntimeException | DomainException $exception) {
142-
$response = (new ResponseFactory)->createResponse(401);
143+
$response = call_user_func($this->options['responseFactory'], 401);
143144
return $this->processError($response, [
144145
"message" => $exception->getMessage(),
145146
"uri" => (string)$request->getUri()
@@ -158,7 +159,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
158159

159160
/* Modify $request before calling next middleware. */
160161
if (is_callable($this->options["before"])) {
161-
$response = (new ResponseFactory)->createResponse(200);
162162
$beforeRequest = $this->options["before"]($request, $params);
163163
if ($beforeRequest instanceof ServerRequestInterface) {
164164
$request = $beforeRequest;
@@ -452,4 +452,21 @@ private function rules(array $rules): void
452452
$this->rules->push($callable);
453453
}
454454
}
455+
456+
/**
457+
* Set the response factory.
458+
*/
459+
private function responseFactory(callable $factory = null): void
460+
{
461+
if ($factory === null) {
462+
$factory = function ($code, ...$args) {
463+
return (new ResponseFactory)->createResponse($code, ...$args);
464+
};
465+
}
466+
if ($factory instanceof Closure) {
467+
$this->options["responseFactory"] = $factory->bindTo($this);
468+
} else {
469+
$this->options["responseFactory"] = $factory;
470+
}
471+
}
455472
}

0 commit comments

Comments
 (0)