Completed
Push — master ( 3e86c6...4cb4e0 )
by Alexander
03:57
created

HandlesApiErrors::transformExceptions()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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