|
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
|
|
|
|