Standardize response codes.

Lumen already has built in response codes, using them will make the code less error prone.
This commit is contained in:
AsafMah 2015-10-08 14:34:06 +03:00
parent 381c16c833
commit f954b5481e

View File

@ -1,24 +1,15 @@
<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
trait RESTActions {
protected $statusCodes = [
'done' => 200,
'created' => 201,
'removed' => 204,
'not_valid' => 400,
'not_found' => 404,
'conflict' => 409,
'permissions' => 401
];
public function all()
{
$m = self::MODEL;
return $this->respond('done', $m::all());
return $this->respond(Response::HTTP_OK, $m::all());
}
public function get($id)
@ -26,16 +17,16 @@ trait RESTActions {
$m = self::MODEL;
$model = $m::find($id);
if(is_null($model)){
return $this->respond('not_found');
return $this->respond(Response::HTTP_NOT_FOUND);
}
return $this->respond('done', $model);
return $this->respond(Response::HTTP_OK, $model);
}
public function add(Request $request)
{
$m = self::MODEL;
$this->validate($request, $m::$rules);
return $this->respond('created', $m::create($request->all()));
return $this->respond(Response::HTTP_CREATED, $m::create($request->all()));
}
public function put(Request $request, $id)
@ -44,25 +35,25 @@ trait RESTActions {
$this->validate($request, $m::$rules);
$model = $m::find($id);
if(is_null($model)){
return $this->respond('not_found');
return $this->respond(Response::HTTP_NOT_FOUND);
}
$model->update($request->all());
return $this->respond('done', $model);
return $this->respond(Response::HTTP_OK, $model);
}
public function remove($id)
{
$m = self::MODEL;
if(is_null($m::find($id))){
return $this->respond('not_found');
return $this->respond(Response::HTTP_NOT_FOUND);
}
$m::destroy($id);
return $this->respond('removed');
return $this->respond(Response::HTTP_NO_CONTENT);
}
protected function respond($status, $data = [])
{
return response()->json($data, $this->statusCodes[$status]);
return response()->json($data, $status);
}
}
}