<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\RestErrorBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use LifeStyle\Tools\RestErrorBundle\Api;

/**
 * Class Exception
 * @package LifeStyle\Tools\RestErrorBundle\EventListener
 */
class Exception
{
    /**
     * @var Api\Manager
     */
    protected $errorApiM;

    /**
     * @param Api\Manager $errorApiM
     */
    public function __construct(Api\Manager $errorApiM)
    {
        $this->errorApiM = $errorApiM;
    }

    /**
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernalException(GetResponseForExceptionEvent $event)
    {
        // we only use this exception handler for routes with the prefix api_rest_
        if (strpos($event->getRequest()->get('_route'), 'api_rest_') === false) {
            return;
        }

        $exceptionName = $this->errorApiM->error()->helper()->getClassNameFromObject($event->getException());

        // set error
        $this->errorApiM->error()->errors()->addError($event->getException()->getCode(),
            $event->getException()->getMessage(), 'internal', $exceptionName);
        // set status
        if ($exceptionName == "AccessDeniedHttpException") {
            $this->errorApiM->error()->errors()->setCode(403);
        } else {
            $this->errorApiM->error()->errors()->setCode(500);
        }
        //now check which response format the user expects (json or xml)
        $xml = [];
        preg_match("/.xml/i", $event->getRequest()->getUri(), $xml);

        // build the exception response
        if (!empty($xml)) {
            // error response as xml
            $response = $this->errorApiM->error()->response()->response();
            $response->setStatusCode($this->errorApiM->error()->errors()->getCode());
            $response->headers->set('Content-type', 'text/xml');
            $response->setContent($this->errorApiM->serializer()->serialize($this->errorApiM->error()->errors()->getErrors(),
                'xml'));
        } else {
            // error response as json
            $response = $this->errorApiM->error()->response()->jsonResponse();
            $response->setStatusCode($this->errorApiM->error()->errors()->getCode());
            $response->setContent($this->errorApiM->serializer()->serialize($this->errorApiM->error()->errors()->getErrors(),
                'json'));
        }

        // Exit with new response set
        $event->setResponse($response);
    }
}
