Skip to content

Instantly share code, notes, and snippets.

@asvae
Last active March 6, 2016 18:19
Show Gist options
  • Save asvae/8a5904c68206fd7b3e30 to your computer and use it in GitHub Desktop.
Save asvae/8a5904c68206fd7b3e30 to your computer and use it in GitHub Desktop.
Laravel: custom fluent json response
<?php
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ApiJsonResponse extends JsonResponse
{
protected $apiData;
protected $apiMessage;
protected $apiErrors;
protected $apiRedirect;
/**
* Constructor.
*
* @param array $data
*/
public function __construct($data = null)
{
$this->apiData = $data;
parent::__construct();
}
/**
* @param Request $request
*
* @return $this
* @throws \Exception
*/
public function prepare(Request $request)
{
$this->setData($this->compileData());
return parent::prepare($request);
}
/**
* @param array|string $error
*
* @return $this
*/
public function error($error)
{
if (is_string($error)){
$error = ['error' => $error];
}
$this->apiErrors = $error;
return $this;
}
/**
* @param array|string $message
*
* @return $this
*/
public function message($message)
{
$this->apiMessage = $message;
return $this;
}
/**
* Like message, but with translation.
*
* @param array|string $path
*
* @return $this
*/
public function trans($path)
{
$this->apiMessage = trans($path);
return $this;
}
public function redirect($path)
{
$this->apiRedirect = $path;
}
/**
* Alias for "setStatusCode" method.
*
* @param $code
* @param null $text
*
* @return $this
*/
public function withStatus($code, $text = null)
{
$this->setStatusCode($code, $text);
return $this;
}
/**
* @return array
* @throws \Exception
*/
protected function compileData()
{
if ($this->hasNotOnlyError()) {
throw new \Exception('You can\'t set both error and message in api response');
}
$data = [ ];
if ($this->hasData()) {
$data['data'] = $this->apiData;
}
if ($this->hasMessage()) {
$data['message'] = $this->apiMessage;
}
if ($this->hasError()) {
$data['errors'] = $this->apiErrors;
}
if ($this->hasRedirect()) {
$data['redirect'] = $this->apiErrors;
}
return $data;
}
/**
* @return bool
*/
protected function hasNotOnlyError()
{
if ( ! $this->hasError()) {
return false;
};
if ($this->hasMessage() || $this->hasData()) {
return true;
}
return false;
}
/**
* @return bool
*/
protected function hasData()
{
return isset( $this->apiData );
}
/**
* @return bool
*/
protected function hasMessage()
{
return isset( $this->apiMessage );
}
/**
* @return bool
*/
protected function hasError()
{
return isset( $this->apiErrors );
}
/**
* @return bool
*/
protected function hasRedirect()
{
return isset( $this->apiRedirect );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment