WRestController.php
2.56 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* @author Weavora Team <hello@weavora.com>
* @link http://weavora.com
* @copyright Copyright (c) 2011 Weavora LLC
*/
Yii::import("ext." . basename(__DIR__) . '.actions.*');
Yii::import("ext." . basename(__DIR__) . '.behaviors.*');
abstract class WRestController extends Controller
{
/**
* @var WRestResponse
*/
public $response = null;
protected $_modelName = "";
protected $_responseFormat = null;
public function init(){
$this->_modelName = ucfirst($this->_modelName);
Yii::app()->setComponent('request', Yii::createComponent(array(
'class' => 'ext.wrest.WHttpRequest',
)));
$this->request->parseJsonParams();
$this->request->getAllRestParams();
$this->request->setFormat($this->_responseFormat);
$this->response = WRestResponse::factory($this->request->getFormat());
return parent::init();
}
/**
* @desc
* @param type $status
* @param string $body
* @param type $content_type
*/
public function sendResponse($status = 200, $bodyParams = array())
{
if ($status != 200) {
$bodyParams = CMap::mergeArray($this->response->getErrorMessage($status), $bodyParams);
}
else {
if(!isset($bodyParams['success'])) {
if(isset($bodyParams['total'])) {
$total = (int)$bodyParams['total'];
unset($bodyParams['total']);
}
$bodyParams = array(
"success" => true,
"results" => $bodyParams
);
if(isset($total)) {
$bodyParams['total'] = (int)$total;
}
}
}
$this->response->setStatus($status);
$this->sendHeaders();
echo $this->response->setParams($bodyParams)->getBody();
Yii::app()->end();
}
public function sendHeaders()
{
$headers = $this->response->getHeaders();
foreach ($headers as $header){
header($header);
}
}
/**
* @return CActiveRecord
*/
public function getModel($scenario = '')
{
$id = $this->request->getParam('id');
$modelName = ucfirst($this->_modelName);
if (empty($this->_modelName) && class_exists($modelName)) {
$this->sendResponse(400);
}
if ($id) {
$model = call_user_func(array($modelName, 'model'));
$model = $model->findByPk($id);
if (is_null($model)) {
$this->sendResponse(400);
}
} else {
$model = new $modelName();
}
if ($scenario && $model)
$model->setScenario($scenario);
return $model;
}
/**
* @return WHttpRequest
*/
public function getRequest()
{
return Yii::app()->request;
}
}