Last active
October 13, 2016 13:58
-
-
Save pedrokoblitz/9df696239a02165442a6612917550232 to your computer and use it in GitHub Desktop.
Rest
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 | |
namespace App\Services\Rest; | |
use Illuminate\Contracts\Support\Jsonable; | |
use Illuminate\Contracts\Support\Arrayable; | |
class Message implements Jsonable, Arrayable | |
{ | |
protected $status; | |
protected $data; | |
protected $message; | |
public function __construct($status = "success", $data = array(), $message = "") | |
{ | |
$this->status = $status; | |
$this->data = $data; | |
$this->message = $message; | |
} | |
public function toArray() | |
{ | |
$data = method_exists($this->data, 'toArray') ? $this->data->toArray() : $this->data; | |
return [ | |
'status' => $this->status, | |
'data' => $data, | |
'message' => $this->message | |
]; | |
} | |
public function toJson($options = 0) | |
{ | |
return json_encode($this->toArray(), $options); | |
} | |
public function __toString() | |
{ | |
return $this->toJson(); | |
} | |
} |
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 | |
namespace App\Services\Rest; | |
use Illuminate\Http\JsonResponse; | |
class Response extends JsonResponse | |
{ | |
const LINE_BREAK = "\n"; | |
public function __construct($data, $code, $messages = array()) | |
{ | |
$message = $this->processMapperMessages($messages); | |
$data = $this->getResponseMessage($data, $code, $message); | |
parent::__construct($data, $code); | |
} | |
protected function processMapperMessages($messages) | |
{ | |
$string = ""; | |
if (is_array($messages) && !empty($messages)) { | |
foreach ($messages as $name => $group) { | |
foreach ($group as $message) { | |
$string .= $name . ": " . $message . self::LINE_BREAK; | |
} | |
} | |
} | |
return $string; | |
} | |
protected function getResponseMessage($data = array(), $code = 200, $message = "") | |
{ | |
if ($code < 400) { | |
$status = "success"; | |
if ($message !== "") { | |
$message = "Sua requisição foi completada com sucesso."; | |
} | |
} else { | |
$status = "error"; | |
if ($message !== "") { | |
if ($code === 404) { | |
$message = "Não encontrado"; | |
} elseif ($code === 304) { | |
$message = "Não modificado"; | |
} else { | |
$message = "Algo deu errado, verifique seus dados."; | |
} | |
} | |
\Log::error($message . $code); | |
} | |
return new Message($status, $data, $message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment