<?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 Sso\WebserviceBundle\EventListener;

use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;

/**
 * Listen to kernel events
 */
class ExceptionListener
{

    /**
     * @var ErrorHandlerInterface
     */
    private $errorHandler;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * ExceptionListener constructor.
     * @param ErrorHandlerInterface $errorHandler
     * @param LoggerInterface $logger
     */
    public function __construct(ErrorHandlerInterface $errorHandler, LoggerInterface $logger)
    {
        $this->errorHandler = $errorHandler;
        $this->logger = $logger;
    }

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

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

        //log the exception
        $message = [
            'Application Error',
            'Code: ' . $exception->getCode(),
            'File: ' . $exception->getFile(),
            'Line: ' . $exception->getLine(),
            'Message: ' . $exception->getMessage(),
            'Stacktrace: ' . $exception->getTraceAsString()
        ];
        $this->logger->error(get_class($exception));
        $this->logger->error(implode(PHP_EOL, $message));

        //build reponse
        $this->errorHandler->addError(500, 'code42', 'code42', 'CriticalError', 'Internal Unknown Error');

        $response = new Response();
        $response->setStatusCode(500);
        $response->headers->set('Content-type', 'text/xml');
        $response->setContent($this->errorHandler->buildResponse('xml'));

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