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

Commit

Permalink
configurable response factory
Browse files Browse the repository at this point in the history
  • Loading branch information
dakujem committed Oct 13, 2019
1 parent 2257aac commit 4de29f2
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/JwtAuthentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ final class JwtAuthentication implements MiddlewareInterface
"ignore" => null,
"before" => null,
"after" => null,
"error" => null
"error" => null,
"responseFactory" => null,
];

public function __construct(array $options = [])
Expand Down Expand Up @@ -139,7 +140,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
$token = $this->fetchToken($request);
$decoded = $this->decodeToken($token);
} catch (RuntimeException | DomainException $exception) {
$response = (new ResponseFactory)->createResponse(401);
$response = call_user_func($this->options['responseFactory'], 401);
return $this->processError($response, [
"message" => $exception->getMessage(),
"uri" => (string)$request->getUri()
Expand All @@ -158,7 +159,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

/* Modify $request before calling next middleware. */
if (is_callable($this->options["before"])) {
$response = (new ResponseFactory)->createResponse(200);
$beforeRequest = $this->options["before"]($request, $params);
if ($beforeRequest instanceof ServerRequestInterface) {
$request = $beforeRequest;
Expand Down Expand Up @@ -452,4 +452,21 @@ private function rules(array $rules): void
$this->rules->push($callable);
}
}

/**
* Set the response factory.
*/
private function responseFactory(callable $factory = null): void
{
if ($factory === null) {
$factory = function ($code, ...$args) {
return (new ResponseFactory)->createResponse($code, ...$args);
};
}
if ($factory instanceof Closure) {
$this->options["responseFactory"] = $factory->bindTo($this);
} else {
$this->options["responseFactory"] = $factory;
}
}
}

0 comments on commit 4de29f2

Please sign in to comment.