Test Failed
Push — master ( 3b9ce6...02c765 )
by Maximo
02:14
created

Api::handleException()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 21
nc 16
nop 1
dl 0
loc 31
ccs 0
cts 22
cp 0
crap 56
rs 8.6506
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style introduced by
End of line character is invalid; expected "\n" but found "\r\n"
Loading history...
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Bootstrap;
6
7
use function Gewaer\Core\appPath;
8
use Phalcon\Di\FactoryDefault;
9
use Phalcon\Mvc\Micro;
10
use Gewaer\Http\Response;
11
use Phalcon\Http\Request;
12
use Throwable;
13
use Dmkit\Phalcon\Auth\Middleware\Micro as AuthMicro;
14
use Gewaer\Exception\ServerErrorHttpException;
15
use Gewaer\Constants\Flags;
16
use Baka\Http\RouterCollection;
17
18
/**
19
 * Class Api
20
 *
21
 * @package Gewaer\Bootstrap
22
 *
23
 * @property Micro $application
24
 */
25
class Api extends AbstractBootstrap
26
{
27
    /**
28
     * Run the application
29
     *
30
     * @return mixed
31
     */
32 1
    public function run()
33
    {
34
        try {
35 1
            $config = $this->container->getConfig()->jwt->toArray();
36
37
            //if the router has jwt ignore url we always overwrite the app config
38 1
            $routerJwtIgnoreUrl = RouterCollection::getJwtIgnoreRoutes();
39 1
            if (!empty($routerJwtIgnoreUrl)) {
40 1
                $config['ignoreUri'] = $routerJwtIgnoreUrl;
41
            }
42
            elseif (!$this->container->getConfig()->application->jwtSecurity) {
43
                //ignore token validation if disable
44
                $config['ignoreUri'] = ['regex: *'];
45
            }
46
47
            //JWT Validation
48 1
            $auth = new AuthMicro($this->application, $config);
0 ignored issues
show
Unused Code introduced by
The assignment to $auth is dead and can be removed.
Loading history...
49
50 1
            return $this->application->handle();
51
        } catch (Throwable $e) {
52
            $this->handleException($e)->send();
53
        }
54
    }
55
56
    /**
57
     * Handle the exception we throw from our api
58
     *
59
     * @param Throwable $e
60
     * @return Response
61
     */
62
    public function handleException(Throwable $e): Response
63
    {
64
        $response = new Response();
65
        $request = new Request();
66
        $identifier = $request->getServerAddress();
67
        $config = $this->container->getConfig();
68
69
        $httpCode = (method_exists($e, 'getHttpCode')) ? $e->getHttpCode() : 400;
70
        $httpMessage = (method_exists($e, 'getHttpMessage')) ? $e->getHttpMessage() : 'Bad Request';
71
        $data = (method_exists($e, 'getData')) ? $e->getData() : [];
72
73
        $message = $e->getMessage();
0 ignored issues
show
Unused Code introduced by
The assignment to $message is dead and can be removed.
Loading history...
74
        $response->setHeader('Access-Control-Allow-Origin', '*'); //@todo check why this fales on nginx
75
        $response->setStatusCode($httpCode, $httpMessage);
76
        $response->setContentType('application/json');
77
        $response->setJsonContent([
78
            'errors' => [
79
                'type' => $httpMessage,
80
                'identifier' => $identifier,
81
                'message' => $e->getMessage(),
82
                'trace' => strtolower($config->app->env) != Flags::PRODUCTION ? $e->getTraceAsString() : null,
83
                'data' => $data,
84
            ],
85
        ]);
86
87
        //only log when server error production is seerver error or dev
88
        if ($e instanceof ServerErrorHttpException || strtolower($config->app->env) != Flags::PRODUCTION) {
89
            $this->container->getLog()->error($e);
90
        }
91
92
        return $response;
93
    }
94
95
    /**
96
     * @return mixed
97
     */
98 4
    public function setup()
99
    {
100
        //set the default DI
101 4
        $this->container = new FactoryDefault();
102
        //set all the services
103 4
        $this->providers = require appPath('api/config/providers.php');
104
105
        //run my parents setup
106 4
        parent::setup();
107 4
    }
108
}
109