sfelix-martins /
json-exception-handler
| 1 | <?php |
||
| 2 | |||
| 3 | namespace SMartins\JsonHandler; |
||
| 4 | |||
| 5 | use Illuminate\Database\Eloquent\ModelNotFoundException; |
||
| 6 | |||
| 7 | trait ModelNotFoundHandler |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * Set the response if Exception is ModelNotFound. |
||
| 11 | * |
||
| 12 | * @param ModelNotFoundException $exception |
||
| 13 | */ |
||
| 14 | public function modelNotFoundException(ModelNotFoundException $exception) |
||
| 15 | { |
||
| 16 | $entity = $this->extractEntityName($exception->getModel()); |
||
| 17 | |||
| 18 | $ids = implode($exception->getIds(), ','); |
||
| 19 | |||
| 20 | $error = [[ |
||
| 21 | 'status' => 404, |
||
| 22 | 'code' => $this->getCode('model_not_found'), |
||
| 23 | 'source' => ['pointer' => 'data/id'], |
||
| 24 | 'title' => $exception->getMessage(), |
||
| 25 | 'detail' => __('exception::exceptions.model_not_found.title', ['model' => $entity]), |
||
| 26 | ]]; |
||
| 27 | |||
| 28 | $this->jsonApiResponse->setStatus(404); |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 29 | $this->jsonApiResponse->setErrors($error); |
||
| 30 | } |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Get entitie name based on model path to mount the message. |
||
| 34 | * |
||
| 35 | * @param string $model |
||
| 36 | * @return string |
||
| 37 | */ |
||
| 38 | public function extractEntityName($model) |
||
| 39 | { |
||
| 40 | $classNames = (array) explode('\\', $model); |
||
| 41 | |||
| 42 | $entityName = end($classNames); |
||
| 43 | |||
| 44 | if ($this->entityHasTranslation($entityName)) { |
||
| 45 | return __('exception::exceptions.models.'.$entityName); |
||
| 46 | } |
||
| 47 | |||
| 48 | return $entityName; |
||
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Check if entity returned on ModelNotFoundException has translation on |
||
| 53 | * exceptions file |
||
| 54 | * @param string $entityName The model name to check if has translation |
||
| 55 | * @return bool Has translation or not |
||
| 56 | */ |
||
| 57 | public function entityHasTranslation(string $entityName): bool |
||
| 58 | { |
||
| 59 | $hasKey = in_array($entityName, $this->translationModelKeys()); |
||
| 60 | |||
| 61 | if ($hasKey) { |
||
| 62 | return ! empty($hasKey); |
||
| 63 | } |
||
| 64 | |||
| 65 | return false; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Get the models keys on exceptions lang file |
||
| 70 | * @return array An array with keys to translate |
||
| 71 | */ |
||
| 72 | private function translationModelKeys(): array |
||
| 73 | { |
||
| 74 | return array_keys(__('exception::exceptions.models')); |
||
| 75 | } |
||
| 76 | } |
||
| 77 |