Skip to content

Commit 3e782b8

Browse files
committed
WIP add collection action endpoint
1 parent bad98dc commit 3e782b8

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

src/Endpoint/CollectionAction.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
namespace Tobyz\JsonApiServer\Endpoint;
4+
5+
use Closure;
6+
use Nyholm\Psr7\Response;
7+
use Psr\Http\Message\ResponseInterface;
8+
use Tobyz\JsonApiServer\Context;
9+
use Tobyz\JsonApiServer\Exception\ForbiddenException;
10+
use Tobyz\JsonApiServer\Exception\MethodNotAllowedException;
11+
use Tobyz\JsonApiServer\OpenApi\OpenApiPathsProvider;
12+
use Tobyz\JsonApiServer\Resource\Collection;
13+
use Tobyz\JsonApiServer\Schema\Concerns\HasDescription;
14+
use Tobyz\JsonApiServer\Schema\Concerns\HasVisibility;
15+
16+
class CollectionAction implements Endpoint, OpenApiPathsProvider
17+
{
18+
use HasVisibility;
19+
use HasDescription;
20+
21+
public string $method = 'POST';
22+
23+
public function __construct(public string $name, public Closure $handler)
24+
{
25+
}
26+
27+
public static function make(string $name, Closure $handler): static
28+
{
29+
return new static($name, $handler);
30+
}
31+
32+
public function method(string $method): static
33+
{
34+
$this->method = strtoupper($method);
35+
36+
return $this;
37+
}
38+
39+
public function handle(Context $context): ?ResponseInterface
40+
{
41+
$segments = explode('/', $context->path());
42+
43+
if (count($segments) !== 2 || $segments[1] !== $this->name) {
44+
return null;
45+
}
46+
47+
if ($context->request->getMethod() !== $this->method) {
48+
throw new MethodNotAllowedException();
49+
}
50+
51+
if (!$this->isVisible($context)) {
52+
throw new ForbiddenException();
53+
}
54+
55+
($this->handler)($context);
56+
57+
return new Response(204);
58+
}
59+
60+
public function getOpenApiPaths(Collection $collection): array
61+
{
62+
return [
63+
"/{$collection->name()}/$this->name" => [
64+
'post' => [
65+
'description' => $this->getDescription(),
66+
'tags' => [$collection->name()],
67+
'responses' => [
68+
'204' => [],
69+
],
70+
],
71+
],
72+
];
73+
}
74+
}

0 commit comments

Comments
 (0)