1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* HiAPI Yii2 base project for building API |
4
|
|
|
* |
5
|
|
|
* @link https://github.com/hiqdev/hiapi |
6
|
|
|
* @package hiapi |
7
|
|
|
* @license BSD-3-Clause |
8
|
|
|
* @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/) |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace hiapi\controllers; |
12
|
|
|
|
13
|
|
|
use hiapi\bus\ApiCommandsBusInterface; |
14
|
|
|
use hiapi\components\QueryParamAuth; |
15
|
|
|
use hiqdev\yii\compat\yii; |
16
|
|
|
use hiqdev\yii2\autobus\components\AutoBusInterface; |
17
|
|
|
use hiqdev\yii2\autobus\components\BranchedAutoBus; |
18
|
|
|
use yii\base\Module; |
19
|
|
|
use yii\filters\auth\CompositeAuth; |
20
|
|
|
use yii\filters\auth\HttpBearerAuth; |
21
|
|
|
use yii\filters\ContentNegotiator; |
22
|
|
|
use yii\web\Controller; |
23
|
|
|
use yii\web\Response; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Class ApiController |
27
|
|
|
* |
28
|
|
|
* @author Dmytro Naumenko <[email protected]> |
29
|
|
|
*/ |
30
|
|
|
class ApiController extends Controller |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* @var AutoBusInterface|BranchedAutoBus |
34
|
|
|
*/ |
35
|
|
|
private $autoBus; |
36
|
|
|
|
37
|
|
|
public function __construct( |
38
|
|
|
string $id, |
39
|
|
|
Module $module, |
40
|
|
|
ApiCommandsBusInterface $autoBus, |
41
|
|
|
array $config = [] |
42
|
|
|
) { |
43
|
|
|
$this->autoBus = $autoBus; |
44
|
|
|
|
45
|
|
|
parent::__construct($id, $module, $config); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function behaviors() |
49
|
|
|
{ |
50
|
|
|
return array_merge(parent::behaviors(), [ |
51
|
|
|
'contentNegotiator' => [ |
52
|
|
|
'class' => ContentNegotiator::class, |
53
|
|
|
'formats' => [ |
54
|
|
|
'application/json' => Response::FORMAT_JSON, |
55
|
|
|
'application/vnd.api+json' => Response::FORMAT_JSON, |
56
|
|
|
], |
57
|
|
|
], |
58
|
|
|
'auth' => [ |
59
|
|
|
'class' => CompositeAuth::class, |
60
|
|
|
'optional' => ['command'], |
61
|
|
|
'authMethods' => [ |
62
|
|
|
HttpBearerAuth::class, |
63
|
|
|
[ |
64
|
|
|
'class' => QueryParamAuth::class, |
65
|
|
|
'tokenParam' => 'access_token', |
66
|
|
|
], |
67
|
|
|
], |
68
|
|
|
], |
69
|
|
|
]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function actionCommand($version, $resource, $action, $bulk = false) // todo: use $version, $bulk |
73
|
|
|
{ |
74
|
|
|
$handledCommand = $this->autoBus->runCommand($this->buildCommandName($resource, $action, $bulk), []); |
75
|
|
|
|
76
|
|
|
$this->response->getHeaders()->fromArray($handledCommand->getHeaders()); |
77
|
|
|
$this->response->setStatusCode($handledCommand->getStatusCode()); |
78
|
|
|
$this->response->content = $handledCommand->getBody(); |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
return $this->response->send(); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
private function buildCommandName($resource, $action, $bulk = false) // todo use $bulk |
85
|
|
|
{ |
86
|
|
|
return $resource . ucfirst($action); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|