1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JDesrosiers\Resourceful\Controller; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Cache\Cache; |
6
|
|
|
use JDesrosiers\Resourceful\Resourceful; |
7
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
8
|
|
|
use Symfony\Component\HttpFoundation\Request; |
9
|
|
|
use Symfony\Component\HttpFoundation\Response; |
10
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
11
|
|
|
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException; |
12
|
|
|
|
13
|
|
|
class PutResourceController |
14
|
|
|
{ |
15
|
|
|
private $service; |
16
|
|
|
private $schema; |
17
|
|
|
|
18
|
11 |
|
public function __construct(Cache $service, $schema) |
19
|
|
|
{ |
20
|
11 |
|
$this->service = $service; |
21
|
11 |
|
$this->schema = $schema; |
22
|
11 |
|
} |
23
|
|
|
|
24
|
7 |
|
public function __invoke(Resourceful $app, Request $request, $id) |
25
|
|
|
{ |
26
|
7 |
|
$requestJson = $request->getContent() ?: "{}"; |
27
|
7 |
|
$data = json_decode($requestJson); |
28
|
7 |
|
if (json_last_error() !== JSON_ERROR_NONE) { |
29
|
1 |
|
throw new BadRequestHttpException("Invalid JSON: " . json_last_error_msg()); |
30
|
|
|
} |
31
|
|
|
|
32
|
6 |
|
$this->validate($app, $id, $data); |
33
|
|
|
|
34
|
4 |
|
$isCreated = !$this->service->contains($request->getRequestUri()); |
35
|
4 |
|
if ($this->service->save($request->getRequestUri(), $data) === false) { |
36
|
1 |
|
throw new ServiceUnavailableHttpException(null, "Failed to save resource"); |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
$response = JsonResponse::create($data, $isCreated ? Response::HTTP_CREATED : Response::HTTP_OK); |
40
|
3 |
|
return $app["allow"]($request, $response, $app); |
41
|
|
|
} |
42
|
|
|
|
43
|
6 |
|
private function validate(Resourceful $app, $id, $data) |
44
|
|
|
{ |
45
|
6 |
|
if (!property_exists($data, "id") || $id !== $data->id) { |
46
|
1 |
|
throw new BadRequestHttpException("The `id` in the body must match the `id` in the URI"); |
47
|
|
|
} |
48
|
5 |
|
$schema = $app["json-schema.schema-store"]->get($this->schema); |
49
|
5 |
|
$validation = $app["json-schema.validator"]->validate($data, $schema); |
50
|
5 |
|
if (!$validation->valid) { |
51
|
1 |
|
throw new BadRequestHttpException(json_encode($validation->errors)); |
52
|
|
|
} |
53
|
4 |
|
} |
54
|
|
|
} |
55
|
|
|
|