|
1
|
|
|
<?php namespace Pz\Doctrine\Rest; |
|
2
|
|
|
|
|
3
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
|
4
|
|
|
use Pz\Doctrine\Rest\Exceptions\RestException; |
|
5
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
|
6
|
|
|
|
|
7
|
|
|
class RestResponse extends JsonResponse |
|
8
|
|
|
{ |
|
9
|
|
|
public static function create($data, $status, array $headers = []): static |
|
10
|
|
|
{ |
|
11
|
|
|
return new static($data, $status, $headers); |
|
12
|
5 |
|
} |
|
13
|
|
|
|
|
14
|
5 |
|
/** |
|
15
|
|
|
* @return static |
|
16
|
|
|
*/ |
|
17
|
|
|
public static function noContent() |
|
18
|
|
|
{ |
|
19
|
|
|
return static::create(null, static::HTTP_NO_CONTENT); |
|
20
|
1 |
|
} |
|
21
|
|
|
|
|
22
|
1 |
|
/** |
|
23
|
|
|
* @return static |
|
24
|
|
|
*/ |
|
25
|
|
|
public static function createForbidden() |
|
26
|
|
|
{ |
|
27
|
|
|
return static::create(null, static::HTTP_FORBIDDEN); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
11 |
|
* @param \Error|\Exception|RestException $exception |
|
32
|
|
|
* |
|
33
|
11 |
|
* @return RestResponse |
|
34
|
1 |
|
* @throws \Error|\Exception|RestException |
|
35
|
|
|
*/ |
|
36
|
|
|
public static function exception(\Exception $exception) |
|
37
|
11 |
|
{ |
|
38
|
|
|
if (!$exception instanceof RestException) { |
|
39
|
|
|
$exception = RestException::createFromException($exception); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return RestResponse::create(['errors' => $exception->errors()], $exception->getCode()); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* RestResponse constructor. |
|
47
|
30 |
|
* |
|
48
|
|
|
* @param mixed|null $data |
|
49
|
30 |
|
* @param int $status |
|
50
|
|
|
* @param array $headers |
|
51
|
30 |
|
*/ |
|
52
|
30 |
|
public function __construct($data, $status, array $headers = []) |
|
53
|
|
|
{ |
|
54
|
|
|
$headers['Content-Type'] = RestRequestContract::JSON_API_CONTENT_TYPE; |
|
55
|
|
|
|
|
56
|
|
|
parent::__construct($data, $status, $headers, false); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|