Ubiquity  2.0.0
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  parent::__construct();
44  }
45 
46  public function isValid(){
47  if(isset($this->restCache["authorizations"])){
48  if(\array_search(Startup::getAction(), $this->restCache["authorizations"])!==false){
49  return $this->server->isValid();
50  }
51  }
52  return true;
53  }
54 
55  public function onInvalidControl(){
56  throw new \Exception('HTTP/1.1 401 Unauthorized, you need an access token for this request',401);
57  }
58 
63  public function connect(){
64  $this->server->connect($this);
65  }
66 
67  public function initialize(){
68  $thisClass=\get_class($this);
69  if(!isset($this->model))
70  $this->model=CacheManager::getRestResource($thisClass);
71  if(!isset($this->model)){
72  $modelsNS=$this->config["mvcNS"]["models"];
73  $this->model=$modelsNS."\\".$this->responseFormatter->getModel($thisClass);
74  }
75  $this->connectDb($this->config);
76  }
77 
78  public function finalize(){
79  parent::finalize();
80  $this->server->finalizeTokens();
81  }
82 
83 
84 
85  public function _errorHandler($e){
86  $code=500;
87  if($e->getCode()!==0)
88  $code=$e->getCode();
89  $this->_setResponseCode($code);
90  echo $this->responseFormatter->formatException($e);
91  }
92 
93  public function _setResponseCode($value){
94  \http_response_code($value);
95  }
96 
97  protected function connectDb($config){
98  $db=$config["database"];
99  if($db["dbName"]!==""){
100  DAO::connect($db["type"],$db["dbName"],@$db["serverName"],@$db["port"],@$db["user"],@$db["password"],@$db["options"],@$db["cache"]);
101  }
102  }
103 
110  protected function _setValuesToObject($instance,$values=null){
111  if(URequest::isJSON()){
112  $values=\json_decode($values,true);
113  }
114  URequest::setValuesToObject($instance,$values);
115  }
116 
121  public function index() {
122  $datas=DAO::getAll($this->model);
123  echo $this->responseFormatter->get($datas);
124  }
125 
130  public function getById($id){
131  return $this->getOne($id,true,true);
132  }
133 
141  public function get($condition="1=1",$loadManyToOne=false,$loadOneToMany=false,$useCache=false){
142  try{
143  $condition=\urldecode($condition);
144  $loadManyToOne=UString::isBooleanTrue($loadManyToOne);
145  $loadOneToMany=UString::isBooleanTrue($loadOneToMany);
146  $useCache=UString::isBooleanTrue($useCache);
147  $datas=DAO::getAll($this->model,$condition,$loadManyToOne,$loadOneToMany,$useCache);
148  echo $this->responseFormatter->get($datas);
149  }catch (\Exception $e){
150  $this->_setResponseCode(500);
151  echo $this->responseFormatter->formatException($e);
152  }
153  }
154 
162  public function getOne($keyValues,$loadManyToOne=false,$loadOneToMany=false,$useCache=false){
163  $keyValues=\urldecode($keyValues);
164  $loadManyToOne=UString::isBooleanTrue($loadManyToOne);
165  $loadOneToMany=UString::isBooleanTrue($loadOneToMany);
166  $useCache=UString::isBooleanTrue($useCache);
167  $data=DAO::getOne($this->model, $keyValues,$loadManyToOne,$loadOneToMany,$useCache);
168  if(isset($data)){
169  $_SESSION["_restInstance"]=$data;
170  echo $this->responseFormatter->getOne($data);
171  }
172  else{
173  $this->_setResponseCode(404);
174  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
175  }
176  }
177 
178  public function _format($arrayMessage){
179  return $this->responseFormatter->format($arrayMessage);
180  }
181 
187  public function getOneToMany($member,$useCache=false){
188  if(isset($_SESSION["_restInstance"])){
189  $useCache=UString::isBooleanTrue($useCache);
190  $datas=DAO::getOneToMany($_SESSION["_restInstance"], $member,$useCache);
191  echo $this->responseFormatter->get($datas);
192  }else{
193  throw new \Exception("You have to call getOne before calling getOneToMany.");
194  }
195  }
196 
202  public function getManyToMany($member,$useCache=false){
203  if(isset($_SESSION["_restInstance"])){
204  $useCache=UString::isBooleanTrue($useCache);
205  $datas=DAO::getManyToMany($_SESSION["_restInstance"], $member,null,$useCache);
206  echo $this->responseFormatter->get($datas);
207  }else{
208  throw new \Exception("You have to call getOne before calling getManyToMany.");
209  }
210  }
211 
218  public function update(...$keyValues){
219  $instance=DAO::getOne($this->model, $keyValues);
220  if(isset($instance)){
221  $this->_setValuesToObject($instance,URequest::getInput());
222  $result=DAO::update($instance);
223  if($result){
224  echo $this->responseFormatter->format(["status"=>"updated","data"=>$this->responseFormatter->cleanRestObject($instance)]);
225  }else{
226  throw new \Exception("Unable to update the instance");
227  }
228  }else{
229  $this->_setResponseCode(404);
230  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
231  }
232  }
233 
239  public function add(){
241  $instance=new $model();
242  if(isset($instance)){
243  $this->_setValuesToObject($instance,URequest::getInput());
244  $result=DAO::insert($instance);
245  if($result){
246  echo $this->responseFormatter->format(["status"=>"inserted","data"=>$this->responseFormatter->cleanRestObject($instance)]);
247  }else{
248  throw new \Exception("Unable to insert the instance");
249  }
250  }else{
251  $this->_setResponseCode(500);
252  echo $this->responseFormatter->format(["message"=>"Unable to create ".$model." instance"]);
253  }
254  }
255 
263  public function delete(...$keyValues){
264  $instance=DAO::getOne($this->model, $keyValues);
265  if(isset($instance)){
266  $result=DAO::remove($instance);
267  if($result){
268  echo $this->responseFormatter->format(["status"=>"deleted","data"=>$this->responseFormatter->cleanRestObject($instance)]);
269  }else{
270  throw new \Exception("Unable to delete the instance");
271  }
272  }else{
273  $this->_setResponseCode(404);
274  echo $this->responseFormatter->format(["message"=>"No result found","keyValues"=>$keyValues]);
275  }
276  }
277 }
_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:348
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:376
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:107
static getRestCacheController($controllerClass)
static getInput()
Returns the query data, for PUT, DELETE PATCH methods.
Definition: URequest.php:45
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.