|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace WonderNetwork\SlimKernel\Http; |
| 5 | + |
| 6 | +use Psr\Http\Message\ServerRequestInterface; |
| 7 | +use RuntimeException; |
| 8 | +use Slim\Exception\HttpBadRequestException; |
| 9 | +use Slim\Exception\HttpNotFoundException; |
| 10 | +use WonderNetwork\SlimKernel\Accessor\ArrayAccessor; |
| 11 | + |
| 12 | +/** |
| 13 | + * @property ArrayAccessor $params |
| 14 | + * @property ArrayAccessor $query |
| 15 | + * @property ArrayAccessor $server |
| 16 | + */ |
| 17 | +final class RequestParams { |
| 18 | + private ArrayAccessor $params; |
| 19 | + private ArrayAccessor $query; |
| 20 | + private ArrayAccessor $server; |
| 21 | + private ServerRequestInterface $request; |
| 22 | + |
| 23 | + public static function of(ServerRequestInterface $request): self { |
| 24 | + return new self($request); |
| 25 | + } |
| 26 | + |
| 27 | + public function __construct(ServerRequestInterface $request) { |
| 28 | + $this->params = ArrayAccessor::of($request->getParsedBody(), [$this, 'exceptionFactory']); |
| 29 | + $this->query = ArrayAccessor::of($request->getQueryParams(), [$this, 'exceptionFactory']); |
| 30 | + $this->server = ArrayAccessor::of($request->getServerParams(), [$this, 'exceptionFactory']); |
| 31 | + $this->request = $request; |
| 32 | + } |
| 33 | + |
| 34 | + public function exceptionFactory(string $message): HttpBadRequestException { |
| 35 | + return new HttpBadRequestException($this->request, $message); |
| 36 | + } |
| 37 | + |
| 38 | + public function __get(string $name): ArrayAccessor { |
| 39 | + switch ($name) { |
| 40 | + case 'params': |
| 41 | + return $this->params; |
| 42 | + case 'query': |
| 43 | + return $this->query; |
| 44 | + case 'server': |
| 45 | + return $this->server; |
| 46 | + } |
| 47 | + |
| 48 | + throw new RuntimeException("Unknown collection: $name"); |
| 49 | + } |
| 50 | + |
| 51 | + /** @return never */ |
| 52 | + public function notFound(string $message = null): void { |
| 53 | + throw new HttpNotFoundException($this->request, $message); |
| 54 | + } |
| 55 | + |
| 56 | + /** @return never */ |
| 57 | + public function badRequest(string $message = null): void { |
| 58 | + throw new HttpBadRequestException($this->request, $message); |
| 59 | + } |
| 60 | + |
| 61 | + public function request(): ServerRequestInterface { |
| 62 | + return $this->request; |
| 63 | + } |
| 64 | +} |
0 commit comments