Skip to content

Instantly share code, notes, and snippets.

@nkt
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkt/a89affc3c2916a3d1f52 to your computer and use it in GitHub Desktop.
Save nkt/a89affc3c2916a3d1f52 to your computer and use it in GitHub Desktop.
<?php
namespace App\CoreBundle\HttpFoundation;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\ConstraintViolationListInterface;
/**
* @author Nikita Gusakov <dev@nkt.me>
*/
class ApiResponse extends Response
{
public function __construct($data = null, $status = Response::HTTP_OK, array $headers = [])
{
if ($data instanceof ConstraintViolationListInterface) {
$errors = [];
foreach ($data as $error) {
$errors[$error->getPropertyPath()] = $error->getMessage();
}
$data = $errors;
$status = Response::HTTP_BAD_REQUEST;
} elseif ($data instanceof Collection) {
$data = $data->toArray();
}
$content = json_encode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException(json_last_error_msg());
}
$headers = array_replace(['Content-Type' => 'application/json'], $headers);
parent::__construct($content, $status, $headers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment