Completed
Push — master ( 1092e2...11ab51 )
by Alexander
06:55
created

HandlesApiErrors::renderApiError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 9.4285
1
<?php
2
3
namespace Flugg\Responder\Traits;
4
5
use Exception;
6
use Flugg\Responder\Exceptions\Http\ApiException;
7
use Flugg\Responder\Exceptions\Http\ResourceNotFoundException;
8
use Flugg\Responder\Exceptions\Http\UnauthenticatedException;
9
use Flugg\Responder\Exceptions\Http\UnauthorizedException;
10
use Flugg\Responder\Exceptions\Http\ValidationFailedException;
11
use Illuminate\Auth\Access\AuthorizationException;
12
use Illuminate\Auth\AuthenticationException;
13
use Illuminate\Database\Eloquent\ModelNotFoundException;
14
use Illuminate\Database\Eloquent\RelationNotFoundException;
15
use Illuminate\Http\JsonResponse;
16
use Illuminate\Validation\ValidationException;
17
18
/**
19
 * Use this trait in your exceptions handler to give you access to methods you may
20
 * use to let the package catch and handle any API exceptions.
21
 *
22
 * @package flugger/laravel-responder
23
 * @author  Alexander Tømmerås <[email protected]>
24
 * @license The MIT License
25
 */
26
trait HandlesApiErrors
27
{
28
    /**
29
     * Transform Laravel exceptions into API exceptions.
30
     *
31
     * @param  Exception $exception
32
     * @return void
33
     * @throws UnauthenticatedException
34
     * @throws UnauthorizedException
35
     * @throws ResourceNotFoundException
36
     * @throws RelationNotFoundException
37
     * @throws ValidationFailedException
38
     */
39
    protected function transformException(Exception $exception)
40
    {
41
        if ($exception instanceof AuthenticationException) {
42
            throw new UnauthenticatedException();
43
        }
44
45
        if ($exception instanceof AuthorizationException) {
46
            throw new UnauthorizedException();
47
        }
48
49
        if ($exception instanceof ModelNotFoundException) {
50
            throw new ResourceNotFoundException();
51
        }
52
53
        if ($exception instanceof RelationNotFoundException) {
54
            throw new RelationNotFoundException();
55
        }
56
57
        if ($exception instanceof ValidationException) {
58
            throw new ValidationFailedException($exception->validator);
59
        }
60
    }
61
62
    /**
63
     * Renders any API exception into a JSON error response.
64
     *
65
     * @param  ApiException $exception
66
     * @return JsonResponse
67
     */
68
    protected function renderApiError(ApiException $exception):JsonResponse
69
    {
70
        return app('responder.error')
71
            ->setError($exception->getErrorCode(), $exception->getMessage())
72
            ->addData($exception->getData())
73
            ->respond($exception->getStatusCode());
74
    }
75
}