Skip to content

Instantly share code, notes, and snippets.

@nkt
Last active Aug 29, 2015
Embed
What would you like to do?
<?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