Ubiquity  2.0.3
php rapid development framework
RestController.php
Go to the documentation of this file.
1 <?php
2 
4 
11 
17 abstract class RestController extends Controller {
18  protected $config;
19  protected $model;
20  protected $contentType;
21  protected $restCache;
25  protected $responseFormatter;
26 
30  protected $server;
31 
32  public function __construct(){
33  if(!\headers_sent()){
34  @\set_exception_handler(array ($this,'_errorHandler' ));
35  $this->config=Startup::getConfig();
36  $this->server=new RestServer($this->config);
37  $this->server->cors();
38  $this->responseFormatter=new ResponseFormatter();
39  $this->contentType="application/json";
40  $this->server->_setContentType($this->contentType);
41  $this->restCache=CacheManager::getRestCacheController(\get_class($this));
42  }
43  if (! $this->isValid (Startup::getAction()))
44  $this->onInvalidControl ();
45  }
46 
47  public function isValid($action){
48  if(isset($this->restCache["authorizations"])){
49  if(\array_search($action, $this->restCache["authorizations"])!==false){
50  return $this->server->isValid();
51  }
52  }
53  return true;
54  }
55 
56  public function onInvalidControl(){
57  throw new \Exception('HTTP/1.1 401 Unauthorized, you need an access token for this request',401);
58  }
59 
64  public function connect(){
65  $this->server->connect($this);
66  }
67 
68  public function initialize(){
69  $thisClass=\get_class($this);
70  if(!isset($this->model))
71  $this->model=CacheManager::getRestResource($thisClass);
72  if(!isset($this->model)){
73  $modelsNS=$this->config["mvcNS"]["models"];
74  $this->model=$modelsNS."\\".$this->responseFormatter->getModel($thisClass);
75  }
76  $this->connectDb($this->config);
77  }
78 
79  public function finalize(){
80  parent::finalize();
81  $this->server->finalizeTokens();
82  }
83 
84 
85 
86  public function _errorHandler($e){
87  $code=500;
88  if($e->getCode()!==0)
89  $code=$e->getCode();
90  $this->_setResponseCode($code);
91  echo $this->responseFormatter->formatException($e);
92  }
93 
94  public function _setResponseCode($value){
95  \http_response_code($value);
96  }
97 
98  protected function connectDb($config){
99  $db=$config["database"];
100  if($db["dbName"]!==""){
101  DAO::connect($db["type"],$db["dbName"],@$db["serverName"],@$db["port"],@$db["user"],@$db["password"],@$db["options"],@$db["cache"]);
102  }
103  }
104 
111  protected function _setValuesToObject($instance,$values=null){
112  if(URequest::isJSON()){
113  $values=\json_decode($values,true);
114  }
115  URequest::setValuesToObject($instance,$values);
116  }
117 
122  public function index() {
123  $datas=DAO::getAll($this->model);
124  echo $this->responseFormatter->get($datas);
125  }
126 
131  public function getById($id){
132  return $this->getOne($id,true,true);
133  }
134 
142  public function get($condition="1=1",$loadManyToOne=false,$loadOneToMany=false,$useCache=false){
143  try{
144  $condition=\urldecode($condition);
145  $loadManyToOne=UString::isBooleanTrue($loadManyToOne);
146  $loadOneToMany=UString::isBooleanTrue($loadOneToMany);
147  $useCache=UString::isBooleanTrue($useCache);
148  $datas=DAO::getAll($this->model,$condition,$loadManyToOne,$loadOneToMany,$useCache);
149  echo $this->responseFormatter->get($datas);
150  }catch (\Exception $e){
151  $this->_setResponseCode(500);
152  echo $this->responseFormatter->formatException($e);
153  }
154  }
155 
163  public function getOne($keyValues,$loadManyToOne=false,$loadOneToMany=false,$useCache=false){
164  $keyValues=\urldecode($keyValues);
165  $loadManyToOne=UString::isBooleanTrue($loadManyToOne);
166  $loadOneToMany=UString::isBooleanTrue($loadOneToMany);
167  $useCache=UString::isBooleanTrue($useCache);
168  $data=DAO::getOne($this->model, $keyValues,$loadManyToOne,$loadOneToMany,$useCache);
169  if(isset($data)){
170  $_SESSION["_restInstance"]=$data;
171  echo $this->responseFormatter->getOne($data);
172  }
173  else{
174  $this->_setResponseCode(404);
175  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
176  }
177  }
178 
179  public function _format($arrayMessage){
180  return $this->responseFormatter->format($arrayMessage);
181  }
182 
188  public function getOneToMany($member,$useCache=false){
189  if(isset($_SESSION["_restInstance"])){
190  $useCache=UString::isBooleanTrue($useCache);
191  $datas=DAO::getOneToMany($_SESSION["_restInstance"], $member,$useCache);
192  echo $this->responseFormatter->get($datas);
193  }else{
194  throw new \Exception("You have to call getOne before calling getOneToMany.");
195  }
196  }
197 
203  public function getManyToMany($member,$useCache=false){
204  if(isset($_SESSION["_restInstance"])){
205  $useCache=UString::isBooleanTrue($useCache);
206  $datas=DAO::getManyToMany($_SESSION["_restInstance"], $member,null,$useCache);
207  echo $this->responseFormatter->get($datas);
208  }else{
209  throw new \Exception("You have to call getOne before calling getManyToMany.");
210  }
211  }
212 
219  public function update(...$keyValues){
220  $instance=DAO::getOne($this->model, $keyValues);
221  if(isset($instance)){
222  $this->_setValuesToObject($instance,URequest::getInput());
223  $result=DAO::update($instance);
224  if($result){
225  echo $this->responseFormatter->format(["status"=>"updated","data"=>$this->responseFormatter->cleanRestObject($instance)]);
226  }else{
227  throw new \Exception("Unable to update the instance");
228  }
229  }else{
230  $this->_setResponseCode(404);
231  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
232  }
233  }
234 
240  public function add(){
242  $instance=new $model();
243  if(isset($instance)){
244  $this->_setValuesToObject($instance,URequest::getInput());
245  $result=DAO::insert($instance);
246  if($result){
247  echo $this->responseFormatter->format(["status"=>"inserted","data"=>$this->responseFormatter->cleanRestObject($instance)]);
248  }else{
249  throw new \Exception("Unable to insert the instance");
250  }
251  }else{
252  $this->_setResponseCode(500);
253  echo $this->responseFormatter->format(["message"=>"Unable to create ".$model." instance"]);
254  }
255  }
256 
264  public function delete(...$keyValues){
265  $instance=DAO::getOne($this->model, $keyValues);
266  if(isset($instance)){
267  $result=DAO::remove($instance);
268  if($result){
269  echo $this->responseFormatter->format(["status"=>"deleted","data"=>$this->responseFormatter->cleanRestObject($instance)]);
270  }else{
271  throw new \Exception("Unable to delete the instance");
272  }
273  }else{
274  $this->_setResponseCode(404);
275  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
276  }
277  }
278 }
_setValuesToObject($instance, $values=null)
Updates $instance with $values To eventually be redefined in derived classes.
static getRestResource($controllerClass)
static getOne($className, $keyValues, $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an instance of $className from the database, from $keyvalues values of the primary key...
Definition: DAO.php:363
static setValuesToObject($object, $values=null)
Affects member to member the values of the associative array $values to the members of the object $ob...
Definition: URequest.php:21
update(... $keyValues)
Update an instance of $model selected by the primary key $keyValues Require members values in $_POST ...
static connect($dbType, $dbName, $serverName="127.0.0.1", $port="3306", $user="root", $password="", $options=[], $cache=false)
Establishes the connection to the database using the past parameters.
Definition: DAO.php:395
getById($id)
Default route for requiring a single object ("{id}","methods"=>["get","options"]) ...
Base class for controllers.
Definition: Controller.php:18
static getManyToMany($instance, $member, $array=null, $useCache=NULL)
Assigns / loads the child records in the $member member of $instance.
Definition: DAO.php:127
add()
Insert a new instance of $model Require members values in $_POST array .
static getAll($className, $condition='', $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an array of $className objects from the database.
Definition: DAO.php:193
static isJSON()
Returns true if request contentType is set to json.
Definition: URequest.php:125
static getRestCacheController($controllerClass)
static getInput()
Returns the query data, for PUT, DELETE PATCH methods.
Definition: URequest.php:63
static getOneToMany($instance, $member, $useCache=NULL, $annot=null)
Assign / load the child records in the $member member of $instance.
Definition: DAO.php:71
connect()
Realise the connection to the server To override in derived classes to define your own authentication...
getOne($keyValues, $loadManyToOne=false, $loadOneToMany=false, $useCache=false)
Get the first object corresponding to the $keyValues.
getOneToMany($member, $useCache=false)
static remove($instance)
Deletes the object $instance from the database.
getManyToMany($member, $useCache=false)
static update($instance, $updateMany=false)
Updates an existing $instance in the database.
index()
Returns all objects for the resource $model ("cache"=>false)
static insert($instance, $insertMany=false)
Inserts a new instance $ instance into the database.