Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
87.50% |
14 / 16 |
|
60.00% |
3 / 5 |
CRAP | |
0.00% |
0 / 1 |
| BaseController | |
87.50% |
14 / 16 |
|
60.00% |
3 / 5 |
6.07 | |
0.00% |
0 / 1 |
| sendResponse | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
1 | |||
| sendError | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| sendValidationError | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| sendNotFound | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| sendUnauthorized | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Controllers\Api\V1; |
| 4 | |
| 5 | use App\Http\Controllers\Controller; |
| 6 | use Illuminate\Http\JsonResponse; |
| 7 | |
| 8 | class BaseController extends Controller |
| 9 | { |
| 10 | /** |
| 11 | * Success response method |
| 12 | */ |
| 13 | public function sendResponse(mixed $result, string $message = 'Success', int $code = 200): JsonResponse |
| 14 | { |
| 15 | $response = [ |
| 16 | 'success' => true, |
| 17 | 'data' => $result, |
| 18 | 'message' => $message, |
| 19 | ]; |
| 20 | |
| 21 | return response()->json($response, $code); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Error response method |
| 26 | */ |
| 27 | public function sendError(string $error, array $errorMessages = [], int $code = 400): JsonResponse |
| 28 | { |
| 29 | $response = [ |
| 30 | 'success' => false, |
| 31 | 'message' => $error, |
| 32 | ]; |
| 33 | |
| 34 | if (!empty($errorMessages)) { |
| 35 | $response['errors'] = $errorMessages; |
| 36 | } |
| 37 | |
| 38 | return response()->json($response, $code); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Validation error response method |
| 43 | */ |
| 44 | public function sendValidationError(array $errors): JsonResponse |
| 45 | { |
| 46 | return $this->sendError('Validation failed', $errors, 422); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Not found response method |
| 51 | */ |
| 52 | public function sendNotFound(string $message = 'Resource not found'): JsonResponse |
| 53 | { |
| 54 | return $this->sendError($message, [], 404); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Unauthorized response method |
| 59 | */ |
| 60 | public function sendUnauthorized(string $message = 'Unauthorized'): JsonResponse |
| 61 | { |
| 62 | return $this->sendError($message, [], 401); |
| 63 | } |
| 64 | } |