Completed
Push — master ( 3830bc...2c9d17 )
by Samuel
02:31
created

ApiPresenter::actionDefault()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.005

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 20
ccs 16
cts 17
cp 0.9412
rs 8.8571
cc 5
eloc 16
nc 5
nop 1
crap 5.005
1
<?php
2
3
namespace Kelemen\ApiNette\Presenter;
4
5
use Kelemen\ApiNette\Api;
6
use Kelemen\ApiNette\Exception\ApiNetteException;
7
use Kelemen\ApiNette\Exception\UnresolvedRouteException;
8
use Kelemen\ApiNette\Exception\ValidationFailedException;
9
use Nette\Application\UI\Presenter;
10
use Nette\Http\IResponse;
11
use Kelemen\ApiNette\Response\JsonApiResponse;
12
use Tracy\Debugger;
13
use Exception;
14
15
class ApiPresenter extends Presenter
16
{
17
    /** @var Api */
18
    private $api;
19
20
    /**
21
     * @param Api $api
22
     */
23 10
    public function __construct(Api $api)
24
    {
25 10
        parent::__construct();
26 10
        $this->api = $api;
27 10
    }
28
29
    /**
30
     * Run api handling
31
     * @param $params
32
     */
33 10
    public function actionDefault($params)
34
    {
35
        try {
36 10
            $response = $this->api->run($params);
37 10
        } catch (UnresolvedRouteException $e) {
38 2
            $response = new JsonApiResponse(IResponse::S400_BAD_REQUEST, ['error' => 'Unresolved api route']);
39 9
        } catch (ValidationFailedException $e) {
40 2
            $response = new JsonApiResponse(IResponse::S400_BAD_REQUEST, [
41 2
                'error' => 'Bad input parameter',
42 2
                'errors' => $e->getValidator()->getErrors()
43 1
            ]);
44 7
        } catch (ApiNetteException $e) { // UnresolvedHandlerException, UnresolvedMiddlewareException
45 4
            Debugger::log($e, 'apiError');
46 4
            $response = new JsonApiResponse(IResponse::S500_INTERNAL_SERVER_ERROR, ['error' => 'Internal server error']);
47 4
        } catch (Exception $e) {
48 2
            Debugger::log($e, 'error');
49 2
            $response = new JsonApiResponse(IResponse::S500_INTERNAL_SERVER_ERROR, ['error' => 'Internal server error']);
50
        }
51 10
        $this->sendResponse($response);
52
    }
53
}
54