<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\WebserviceBundle\EventListener;

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use LifeStyle\Tools\WebserviceBundle\Error\Storage as ErrorStorage;
use LifeStyle\Tools\WebserviceBundle\Response\Builder as ResponseBuilder;
use LifeStyle\Tools\WebserviceBundle\Exception\HiddenException;

/**
 * Class WsExceptionListener
 * @package LifeStyle\Tools\WebserviceBundle\EventListener
 */
class WsExceptionListener
{

    /**
     * Response builder
     *
     * @var ResponseBuilder
     */
    protected $responseBuilder;

    /**
     * Kernel
     *
     * @var Kernel
     */
    protected $kernel;

    /**
     * Constructor
     *
     * @param ErrorStorage $errorStorage
     * @param ResponseBuilder $responseBuilder
     * @param Kernel $kernel
     */
    public function __construct(ResponseBuilder $responseBuilder, Kernel $kernel)
    {
        $this->responseBuilder = $responseBuilder;
        $this->kernel = $kernel;
    }

    /**
     * Received kernal exception
     *
     * Create xml-response and set new response
     *
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernalException(GetResponseForExceptionEvent $event)
    {
        // Do not catch exceptions outside webservice
        $request = $event->getRequest();
        if (!$request->attributes->get('_wsRoute')) {
            return;
        }

        // Receive exception
        $exception = $event->getException();

        // Xml-builder
        $this->responseBuilder->setDebug($this->kernel->isDebug());
        if (!($exception instanceof HiddenException)) {
            $this->responseBuilder->exception($exception);
        }

        // Create new response
        $statusCode = $exception->getCode() ? $exception->getCode() : 500;
        $response = new Response($this->responseBuilder->output(), $statusCode, array('Content-type', 'text/xml'));

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

}
