Last active
June 23, 2016 02:26
-
-
Save jjsquady/bd888ca5a24fbcc4b1c9cc55c5496704 to your computer and use it in GitHub Desktop.
RestController Abstract Class for Laravel Eloquent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: squad | |
* Date: 22/06/16 | |
* Time: 14:33 | |
*/ | |
namespace App\Http\Api; | |
use App; | |
use App\Http\Controllers\Controller; | |
use Exception; | |
use Illuminate\Http\Request; | |
abstract Class RestController extends Controller | |
{ | |
/** | |
* Obtem a view a ser exibida | |
* @var | |
*/ | |
protected $defaultView; | |
/** | |
* Mensagem de retorno ao tentar encontrar um model com ID inválido | |
* @var string | |
*/ | |
protected $invalidIdMessage = 'ID inválido'; | |
/** | |
* Mensagem de retorno ao ocorrer um erro ao excluir um model | |
* @var string | |
*/ | |
protected $deleteErrorMessage = 'Erro ao excluir registro.'; | |
/** | |
* Mensagem de retorno ao remover um model | |
* @var string | |
*/ | |
protected $deleteSuccessMessage = 'Registro removido com sucesso.'; | |
/** | |
* Mensagem de retorno ao não encontrar um model | |
* @var string | |
*/ | |
protected $notFoundMessage = 'Registro não encontrado.'; | |
/** | |
* Array contendo os relacionamentos encadeados do model | |
* implementa: ->with(...) | |
* @array | |
*/ | |
protected $withRelations; | |
/** | |
* Lista com os campos a serem retornados, se vazia/nula | |
* retorna todos os campos/propriedades do model | |
* @array | |
*/ | |
protected $fields; | |
/** | |
* Número de itens por página | |
* implementa: paginate(perPage) | |
* @var int | |
*/ | |
protected $perPage = 10; | |
/** | |
* Instância do model passado pelo controller | |
* @object | |
*/ | |
protected $model; | |
/** | |
* Guarda o resultado das queries | |
* @var | |
*/ | |
private $data; | |
/** | |
* Guarda a requisição atual | |
* @var | |
*/ | |
private $request; | |
/** | |
* Obtém os models relaciondos nos relacionamentos passados | |
* por withRelations | |
* @param $data | |
*/ | |
private function getRelations() | |
{ | |
foreach($this->withRelations as $relation => $fields) { | |
$this->data = $this->data->with([$relation => function($query) use ($fields) { | |
return $query->get($fields); | |
}]); | |
} | |
} | |
/** | |
* Ordena os dados, caso haja um parametro 'sort' na request | |
*/ | |
private function orderBy() | |
{ | |
if(!$this->request->has('sort')) { | |
return; | |
} | |
$sort = $this->request->get('sort'); | |
$direction = $this->request->has('order') ? $this->request->get('order') : 'asc'; | |
$this->data = $this->data->orderBy($sort, $direction); | |
} | |
/** | |
* Realiza a paginação dos dados, listando a quantidade de items | |
* pelo número contido em $this->perPage, e retornando os campos contidos em $fields | |
*/ | |
private function paginate() | |
{ | |
$this->data = $this->data->paginate($this->perPage, $this->fields); | |
} | |
/** | |
* Realiza a busca dos dados (Sofa\Eloquece) | |
*/ | |
private function search() | |
{ | |
$this->data = $this->model->search($this->request->get('search')); | |
} | |
/** | |
* Extrai o número de itens por página padrão | |
*/ | |
private function perPage() | |
{ | |
$this->perPage = $this->request->has('per_page') ? | |
(int)$this->request->get('per_page') : | |
$this->perPage; | |
} | |
/** | |
* Carrega a view padrão | |
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View | |
* @throws Exception | |
*/ | |
public function view() | |
{ | |
if(empty($this->defaultView)) { | |
throw (new Exception('$defaultView property not found')); | |
} | |
return view($this->defaultView); | |
} | |
/** | |
* Realiza a consulta e retorna uma coleção de models | |
* @param Request $request | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function index(Request $request) | |
{ | |
$this->request = $request; | |
$this->perPage(); | |
$this->search(); | |
$this->getRelations(); | |
$this->orderBy(); | |
$this->paginate(); | |
return response()->json([ | |
'pagination' => [ | |
'total' => $this->data->total(), | |
'per_page' => $this->data->perPage(), | |
'current_page' => $this->data->currentPage(), | |
'last_page' => $this->data->lastPage(), | |
'from' => (($this->data->currentPage() - 1) * $this->data->perPage()) + 1, | |
'to' => (($this->data->currentPage() - 1) * $this->data->perPage()) + $this->data->count() | |
], | |
'data' => $this->data->items() | |
]); | |
} | |
/** | |
* Retorna um model | |
* @param $id | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function show($id) | |
{ | |
$model = $this->model->find($id); | |
if(empty($model)) { | |
return response()->json([ | |
'erro' => true, | |
'message' => $this->notFoundMessage | |
], 422); | |
} | |
return response()->json($model); | |
} | |
/** | |
* Armazena um novo model | |
* @param Request $request | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function storeModel(Request $request) | |
{ | |
if(!$request instanceof \Illuminate\Http\Request) { | |
$request->validate(); | |
} | |
return response()->json($this->model->create($request->all())); | |
} | |
/** | |
* Atualiza um model | |
* @param Request $request | |
* @param $id | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function updateModel(Request $request, $id) | |
{ | |
if(!$request instanceof \Illuminate\Http\Request) { | |
$request->validate(); | |
} | |
$model = $this->model->find($id); | |
if (empty($model)) { | |
return response()->json([ | |
'erro' => true, | |
'message' => $this->invalidIdMessage | |
], 422); | |
} | |
$model->fill($request->all()); | |
$model->save(); | |
return response()->json($model); | |
} | |
/** | |
* Exclui um model | |
* @param $id | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function destroy($id) | |
{ | |
if ($this->model->destroy($id)) { | |
return response()->json([ | |
'message' => $this->deleteSuccessMessage | |
]); | |
} | |
return response()->json([ | |
'erro' => true, | |
'message' => $this->deleteErrorMessage | |
], 422); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment