| Total Complexity | 11 |
| Total Lines | 55 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 9 | class ModelResponse extends Response |
||
| 10 | { |
||
| 11 | /** @var \Illuminate\Database\Eloquent\Model */ |
||
| 12 | protected $model; |
||
| 13 | |||
| 14 | /** @var string */ |
||
| 15 | protected $resourceClass; |
||
| 16 | |||
| 17 | /** @var int */ |
||
| 18 | protected $statusCode; |
||
| 19 | |||
| 20 | public function __construct(Model $model, ?string $resourceClass = null) |
||
| 21 | { |
||
| 22 | $this->model = $model; |
||
| 23 | $this->resourceClass = $resourceClass; |
||
| 24 | } |
||
| 25 | |||
| 26 | public function toResponse($request) |
||
| 27 | { |
||
| 28 | // Respond appropriately to a deleted model |
||
| 29 | if ($this->deleted()) { |
||
| 30 | return new JsonResponse(null, $this->statusCode ?? 204); |
||
| 31 | } |
||
| 32 | |||
| 33 | // Return the model directly if no resource is provided |
||
| 34 | if (empty($this->resourceClass)) { |
||
| 35 | return $this->model; |
||
| 36 | } |
||
| 37 | |||
| 38 | return (new $this->resourceClass($this->model)) |
||
| 39 | ->toResponse($request) |
||
| 40 | ->setStatusCode($this->calculateStatus()); |
||
| 41 | } |
||
| 42 | |||
| 43 | protected function calculateStatus(): int |
||
| 50 | } |
||
| 51 | |||
| 52 | protected function deleted(): bool |
||
| 66 |