<?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 Sso\ApiBundle\Api\Exception;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Sso\ApiBundle\Api\Error\Type\Internal as InternalError;
use Sso\ApiBundle\Api\Exception\Type\Base as BaseException;
use Sso\ApiBundle\Api\Response\Builder as XmlResponse;

/**
 * Class Listener
 * @package Sso\ApiBundle\Api\Exception
 */
class Listener
{

    /**
     * Listen to kernel exceptions
     *
     * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
     */
    public function onKernalException(GetResponseForExceptionEvent $event)
    {
        // We don't do anything on other controllers than webservice-controller
        if ('_sso_webservice_service' !== $event->getRequest()->get('_route')) {
            return;
        }

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

        // Xml-builder
        $xmlResponse = new XmlResponse();
        $xmlResponse->exception($exception);

        // Create new response
        $response = new Response();
        $response->headers->set('Content-type', 'text/xml');
        $response->setContent($xmlResponse->output());

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

}
