forked from nizsheanez/yii2-json-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Action.php
84 lines (74 loc) · 2.11 KB
/
Action.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace nizsheanez\jsonRpc;
use yii;
use ReflectionClass;
use ReflectionMethod;
use yii\web\HttpException;
/**
* @author alex.sharov, Konstantin Shuplenkov
*/
class Action extends \yii\base\Action
{
use traits\Serializable;
use traits\Request;
public function run()
{
$this->failIfNotAJsonRpcRequest();
Yii::beginProfile('service.request');
$output = null;
try {
$this->setRequestMessage(file_get_contents('php://input'));
$this->result = $this->tryToRunMethod();
} catch (Exception $e) {
Yii::error($e, 'service.error');
$this->exception = new Exception($e->getMessage(), Exception::INTERNAL_ERROR);
}
Yii::endProfile('service.request');
return $this->toJson();
}
/**
* @return string|callable|ReflectionMethod
*/
protected function getHandler()
{
$class = new ReflectionClass($this->controller);
if (!$class->hasMethod($this->getMethod())) {
throw new Exception("Method not found", Exception::METHOD_NOT_FOUND);
}
$method = $class->getMethod($this->getMethod());
return $method;
}
/**
* @param string|callable|\ReflectionMethod $method
* @param array $params
*
* @return mixed
*/
protected function runMethod($method, $params)
{
return $method->invokeArgs($this->controller, $params);
}
/**
* @return mixed
* @throws Exception
*/
protected function tryToRunMethod()
{
$method = $this->getHandler();
Yii::beginProfile('service.request.action');
$output = $this->runMethod($method, $this->getParams($method));
Yii::endProfile('service.request.action');
Yii::info($method, 'service.output');
Yii::info($output, 'service.output');
return $output;
}
/**
* @throws HttpException
*/
protected function failIfNotAJsonRpcRequest()
{
if (!Yii::$app->request->isPost || !$this->checkContentType()) {
throw new HttpException(404, "Page not found");
}
}
}