<?php
/**
 * Webservice exception listener
 *
 * 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  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\EventListener;

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

/**
 * Catch exceptions
 */
class WsExceptionListener
{

    /**
     * The error storage
     * 
     * @var ErrorStorage
     */
    protected $errors;

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

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

    /**
     * Constructor
     * 
     * @param ErrorStorage $errorStorage
     * @param ResponseBuilder $responseBuilder
     * @param Kernel $kernel
     */
    public function __construct(ErrorStorage $errorStorage, ResponseBuilder $responseBuilder, Kernel $kernel)
    {
        $this->errors = $errorStorage;
        $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);
    }

}
