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

Commit bf39471

Browse files
committed
configurable response factory
1 parent 2257aac commit bf39471

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/JwtAuthentication.php

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
use Psr\Log\LoggerInterface;
4747
use Psr\Log\LogLevel;
4848
use RuntimeException;
49-
use Tuupola\Middleware\DoublePassTrait;
5049
use Tuupola\Http\Factory\ResponseFactory;
5150
use Tuupola\Middleware\JwtAuthentication\RequestMethodRule;
5251
use Tuupola\Middleware\JwtAuthentication\RequestPathRule;
@@ -85,14 +84,20 @@ final class JwtAuthentication implements MiddlewareInterface
8584
"ignore" => null,
8685
"before" => null,
8786
"after" => null,
88-
"error" => null
87+
"error" => null,
88+
"responseFactory" => null,
8989
];
9090

9191
public function __construct(array $options = [])
9292
{
9393
/* Setup stack for rules */
9494
$this->rules = new \SplStack;
9595

96+
/* Make sure the response factory option is provided a default */
97+
if (!isset($options['responseFactory'])) {
98+
$options['responseFactory'] = null;
99+
}
100+
96101
/* Store passed in options overwriting any defaults. */
97102
$this->hydrate($options);
98103

@@ -139,7 +144,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
139144
$token = $this->fetchToken($request);
140145
$decoded = $this->decodeToken($token);
141146
} catch (RuntimeException | DomainException $exception) {
142-
$response = (new ResponseFactory)->createResponse(401);
147+
$response = call_user_func($this->options['responseFactory'], 401);
143148
return $this->processError($response, [
144149
"message" => $exception->getMessage(),
145150
"uri" => (string)$request->getUri()
@@ -158,7 +163,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
158163

159164
/* Modify $request before calling next middleware. */
160165
if (is_callable($this->options["before"])) {
161-
$response = (new ResponseFactory)->createResponse(200);
162166
$beforeRequest = $this->options["before"]($request, $params);
163167
if ($beforeRequest instanceof ServerRequestInterface) {
164168
$request = $beforeRequest;
@@ -452,4 +456,21 @@ private function rules(array $rules): void
452456
$this->rules->push($callable);
453457
}
454458
}
459+
460+
/**
461+
* Set the response factory.
462+
*/
463+
private function responseFactory(callable $factory = null): void
464+
{
465+
if ($factory === null) {
466+
$factory = function ($code, ...$args) {
467+
return (new ResponseFactory)->createResponse($code, ...$args);
468+
};
469+
}
470+
if ($factory instanceof Closure) {
471+
$this->options["responseFactory"] = $factory->bindTo($this);
472+
} else {
473+
$this->options["responseFactory"] = $factory;
474+
}
475+
}
455476
}

0 commit comments

Comments
 (0)