ayanozturk /
phprest
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Phprest\ErrorHandler\Formatter; |
||
| 4 | |||
| 5 | use Exception; |
||
| 6 | use League\BooBoo\Formatter\AbstractFormatter; |
||
| 7 | use League\Container\ContainerInterface; |
||
| 8 | use Phprest\Application; |
||
| 9 | use Phprest\Config; |
||
| 10 | use Phprest\Entity; |
||
| 11 | use Phprest\Service; |
||
| 12 | use Symfony\Component\HttpFoundation\Request; |
||
| 13 | use Symfony\Component\HttpFoundation\Response; |
||
| 14 | |||
| 15 | class JsonXml extends AbstractFormatter |
||
| 16 | { |
||
| 17 | use Service\Hateoas\Getter; |
||
| 18 | use Service\Hateoas\Util; |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 19 | |||
| 20 | protected Config $config; |
||
| 21 | protected ?Request $request; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param Config $config |
||
| 25 | * @param null|Request $request |
||
| 26 | */ |
||
| 27 | 73 | public function __construct(Config $config, Request $request = null) |
|
| 28 | { |
||
| 29 | 73 | $this->config = $config; |
|
| 30 | 73 | $this->request = $request; |
|
| 31 | 73 | } |
|
| 32 | |||
| 33 | /** |
||
| 34 | * @param Exception $exception |
||
| 35 | * |
||
| 36 | * @return string |
||
| 37 | */ |
||
| 38 | 3 | public function format($exception) |
|
| 39 | { |
||
| 40 | 3 | $response = new Response(); |
|
| 41 | |||
| 42 | try { |
||
| 43 | 3 | $response = $this->serialize( |
|
| 44 | 3 | $this->config->isDebug() ? new Entity\DebugError($exception) : new Entity\Error($exception), |
|
| 45 | 3 | is_null($this->request) ? Request::createFromGlobals() : $this->request, |
|
| 46 | $response |
||
| 47 | ); |
||
| 48 | 1 | } catch (Exception $e) { |
|
| 49 | 1 | $response->setContent( |
|
| 50 | 1 | $this->serviceHateoas()->getSerializer()->serialize( |
|
| 51 | 1 | $this->config->isDebug() ? new Entity\DebugError($e) : new Entity\Error($e), |
|
| 52 | 1 | 'json' |
|
| 53 | ) |
||
| 54 | ); |
||
| 55 | |||
| 56 | 1 | $vendor = $this->getContainer()->get(Application::CONTAINER_ID_VENDOR); |
|
| 57 | 1 | $apiVersion = $this->getContainer()->get(Application::CONTAINER_ID_API_VERSION); |
|
| 58 | |||
| 59 | 1 | $response->headers->set('Content-Type', 'application/vnd.' . $vendor . '-v' . $apiVersion . '+json'); |
|
| 60 | } |
||
| 61 | |||
| 62 | 3 | $response->setStatusCode(method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : 500); |
|
| 63 | |||
| 64 | 3 | $response->sendHeaders(); |
|
| 65 | |||
| 66 | 3 | return $response->getContent(); |
|
| 67 | } |
||
| 68 | |||
| 69 | /** |
||
| 70 | * @return ContainerInterface |
||
| 71 | */ |
||
| 72 | 3 | public function getContainer() |
|
| 73 | { |
||
| 74 | 3 | return $this->config->getContainer(); |
|
| 75 | } |
||
| 76 | } |
||
| 77 |