Last active
August 29, 2015 14:05
-
-
Save nkt/a89affc3c2916a3d1f52 to your computer and use it in GitHub Desktop.
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\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