<?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\Components\ExceptionTranslation;

/**
 * Translates the error messages of translatable exceptions
 */
class ExceptionTranslator
{
    /**
     * @var \Enlight_Components_Snippet_Manager
     */
    private $snippetManager;

    /**
     * @param \Enlight_Components_Snippet_Manager $snippetManager
     */
    public function __construct(\Enlight_Components_Snippet_Manager $snippetManager)
    {
        $this->snippetManager = $snippetManager;
    }

    /**
     * Return the translated message of $throwable.
     *
     * To be translatable, $exception must implement the interface LocalizableThrowable. If it doesn't, the message
     * of the $exception is returned.
     *
     * @param \Exception $exception
     * @return string Translated error message
     */
    public function translate(\Exception $exception)
    {
        if ($exception instanceof LocalizableThrowable) {
            return $exception->getLocalizedMessage($this->snippetManager);
        }

        if (!($exception instanceof TranslatableThrowable)) {
            return $exception->getMessage();
        }

        $translatedMessage = $this->snippetManager->getNamespace(
            $exception->getSnippetNamespace()
        )->get(
            $exception->getSnippetName()
        );

        if ($translatedMessage === null) {
            return $exception->getMessage();
        }

        if ($exception instanceof FormattedTranslatableThrowable) {
            $translatedMessage = $exception->format($translatedMessage);
        }

        return $translatedMessage;
    }
}
