<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\ExceptionHandling;

use Exception;
use Psr\Log\LoggerInterface;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;

trait SubscriberExceptionHandling
{
    /**
     * Takes every exception and logs it together with the event/hook name and the subscriber function.
     *
     * @param Exception $e
     * @param \Enlight_Event_EventArgs $args
     * @throws Exception
     */
    private function handleException(Exception $e, \Enlight_Event_EventArgs $args)
    {
        /** @var LoggerInterface $logger */
        $logger = $this->get('viison_common.logger');

        $message = sprintf(
            'Error during execution of event/hook "%s": %s',
            $args->getName(),
            $e->getMessage()
        );

        $stackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

        $logger->error(
            $message,
            [
                'user' => ViisonCommonUtil::getCurrentUser() ? ViisonCommonUtil::getCurrentUser()->getName() : null,
                'subscriberClass' => $stackTrace[1]['class'],
                'subscriberMethod' => $stackTrace[1]['function'],
                'subscriberFile' => $stackTrace[0]['file'],
                'exception' => ViisonCommonUtil::exceptionToArray($e),
            ]
        );

        if ($e instanceof \RuntimeException || $e instanceof \LogicException) {
            throw $e;
        }
    }
}
