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 Kelemen\ApiNette\Logger\Logger; |
10
|
|
|
use Nette\Application\UI\Presenter; |
11
|
|
|
use Nette\Http\IResponse; |
12
|
|
|
use Kelemen\ApiNette\Response\JsonApiResponse; |
13
|
|
|
use Tracy\Debugger; |
14
|
|
|
use Exception; |
15
|
|
|
|
16
|
|
|
class ApiPresenter extends Presenter |
17
|
|
|
{ |
18
|
|
|
/** @var Api */ |
19
|
|
|
private $api; |
20
|
|
|
|
21
|
|
|
/** @var Logger */ |
22
|
|
|
private $logger; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param Api $api |
26
|
|
|
* @param Logger $logger |
27
|
|
|
*/ |
28
|
12 |
|
public function __construct(Api $api, Logger $logger) |
29
|
|
|
{ |
30
|
12 |
|
parent::__construct(); |
31
|
12 |
|
$this->api = $api; |
32
|
12 |
|
$this->logger = $logger; |
33
|
12 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Run api handling |
37
|
|
|
* @param $params |
38
|
|
|
*/ |
39
|
12 |
|
public function actionDefault($params) |
40
|
|
|
{ |
41
|
12 |
|
$this->logger->start(); |
42
|
|
|
|
43
|
|
|
try { |
44
|
12 |
|
$response = $this->api->run($params, $this->logger); |
45
|
11 |
|
} catch (UnresolvedRouteException $e) { |
46
|
2 |
|
$response = new JsonApiResponse(IResponse::S400_BAD_REQUEST, ['error' => 'Unresolved api route']); |
47
|
9 |
|
} catch (ValidationFailedException $e) { |
48
|
2 |
|
$response = new JsonApiResponse(IResponse::S400_BAD_REQUEST, [ |
49
|
2 |
|
'error' => 'Bad input parameter', |
50
|
2 |
|
'errors' => $e->getValidator()->getErrors() |
51
|
1 |
|
]); |
52
|
7 |
|
} catch (ApiNetteException $e) { // UnresolvedHandlerException, UnresolvedMiddlewareException, ValidatorException |
53
|
4 |
|
Debugger::log($e, 'apiError'); |
54
|
4 |
|
$response = new JsonApiResponse(IResponse::S500_INTERNAL_SERVER_ERROR, ['error' => 'Internal server error']); |
55
|
4 |
|
} catch (Exception $e) { |
56
|
2 |
|
Debugger::log($e, 'error'); |
57
|
2 |
|
$response = new JsonApiResponse(IResponse::S500_INTERNAL_SERVER_ERROR, ['error' => 'Internal server error']); |
58
|
|
|
} |
59
|
12 |
|
$this->logger->finish($response); |
60
|
12 |
|
$this->sendResponse($response); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|