forked from jamesmoey/yii-restapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestapiModule.php
80 lines (70 loc) · 2.57 KB
/
RestapiModule.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
<?php
class RestApiModule extends CWebModule {
/**
* Configuration Map to setup REST model.
*
* <code>
* array(
* 'ModelRestName' => array(
* 'class' => 'application.path.alias.ModelRestName',
* 'excludeAll' => true,
* 'exclude' => array( 'field_to_exclude', 'field_to_exclude', ),
* 'include' => array( 'addition_field_to_include', ),
* 'attributeAccessControl' => true,
* 'defaultCriteria' => array for CDbCriteria,
* ),
* );
* </code>
*/
public $modelMap;
public $accessControl = false;
public $validOrigin = array();
public function checkModel($model) {
if (!isset($this->modelMap[$model])) return false;
return true;
}
public function includeModel($model) {
$classname = Yii::import($this->modelMap[$model]['class']);
$this->modelMap[$classname] = $this->modelMap[$model];
return $classname;
}
public function getDefaultCriteria($model) {
if (isset($this->modelMap[$model]['defaultCriteria'])) {
return $this->modelMap[$model]['defaultCriteria'];
} else return array();
}
public function getExcludedAttribute($model) {
if (isset($this->modelMap[$model]['excludeAll']) && $this->modelMap[$model]['excludeAll'] === true) {
$instance = new $model();
$attributes = array_keys($instance->getAttributes());
if (isset($this->modelMap[$model]['include'])) {
return array_intersect($attributes, array_diff($attributes, $this->modelMap[$model]['include']));
} else {
return $attributes;
}
} else return isset($this->modelMap[$model]['exclude'])?$this->modelMap[$model]['exclude']:array();
}
public function getIncludedAttribute($model) {
return isset($this->modelMap[$model]['include'])?$this->modelMap[$model]['include']:array();
}
public function getCheckAttributeAccessControl($model) {
return (isset($this->modelMap[$model]) && isset($this->modelMap[$model]['attributeAccessControl']) && $this->modelMap[$model]['attributeAccessControl']);
}
protected function init() {
Yii::import($this->getId().".components.*");
Yii::import($this->getId().".models.*");
if (empty($this->modelMap)) {
Yii::log("Model Map is not set. No Model will rest.", CLogger::LEVEL_ERROR, "restapi");
}
if (is_string($this->modelMap)) {
$this->modelMap = require(Yii::getPathOfAlias($this->modelMap).".php");
}
parent::init();
}
public function validOrigin($origin) {
foreach ($this->validOrigin as $valid) {
if (preg_match($valid, $origin) > 0) return true;
}
return false;
}
}