Nano Hash - криптовалюты, майнинг, программирование

Twig GlobalsInterface ломает панель инструментов отладки Symfony

Симфони 4.3.1

У меня есть Twig-Extension, в котором я глобально добавляю переменные в Twig. Как только я реализую Twig\Extension\GlobalsInterface в своем классе, панель инструментов отладки Symfony просто отображает «Произошла ошибка при загрузке панели инструментов веб-отладки». Однако переменные прекрасно добавляются в глобальную область видимости.

Вот мое расширение:

<?php

namespace App\Twig;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;

class GlobalVarsExtension extends AbstractExtension implements GlobalsInterface
{
    protected $em;

    protected $tokenStorage;

    protected $authorizationChecker;

    public function __construct(EntityManagerInterface $em, AuthorizationCheckerInterface $authorizationChecker, TokenStorageInterface $tokenStorage)
    {
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->authorizationChecker = $authorizationChecker;
    }


    public function getGlobals()
    {
        $globalVars = [];

        if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
            if (null !== $token = $this->tokenStorage->getToken()) {
                $globalVars['user'] = $token->getUser();
            }
        }

        return $globalVars;
    }
}

Это интерфейс, который я реализую:

<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extension;

/**
 * Enables usage of the deprecated Twig\Extension\AbstractExtension::getGlobals() method.
 *
 * Explicitly implement this interface if you really need to implement the
 * deprecated getGlobals() method in your extensions.
 *
 * @author Fabien Potencier <[email protected]>
 */
interface GlobalsInterface
{
    /**
     * Returns a list of global variables to add to the existing list.
     *
     * @return array An array of global variables
     */
    public function getGlobals();
}

class_alias('Twig\Extension\GlobalsInterface', 'Twig_Extension_GlobalsInterface');

Я следовал их документации по добавлению глобальных переменных: https://twig.symfony.com/doc/2.x/advanced.html#id1

Вот журнал изменений от Twig, в котором указано, что метод устарел: https://twig.symfony.com/doc/1.x/deprecated.html#extensions

Что мне не хватает? Или есть другой подход, добавляющий глобальные переменные?

Изменить:

После осознания того, что я полностью пропустил журнал ошибок symfony, и ошибка возникает по совершенно другой причине...

Журнал ошибок:

[2019-06-13 15:49:18] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: "The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL." at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php line 49 {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49)"} []
[2019-06-13 15:49:18] request.CRITICAL: Exception thrown when handling an exception (Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php line 49) {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49)"} []
[2019-06-13 15:49:18] php.CRITICAL: Uncaught Exception: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49, Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49)"} []
[2019-06-13 15:49:18] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: "The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL." at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php line 49 {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49, Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49)"} []
[2019-06-13 15:49:18] request.CRITICAL: Exception thrown when handling an exception (Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php line 49) {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. at /var/www/rekkt.de/vendor/symfony/security-core/Authorization/AuthorizationChecker.php:49)"} []

Изменить2:

Итак, с данным журналом ошибок это то, что я изменил, и теперь он работает хорошо.

public function getGlobals()
    {
        $globalVars = [];

        if (null !== $token = $this->tokenStorage->getToken()) {
            $globalVars['user'] = $token->getUser();
        }

        return $globalVars;
    }
13.06.2019

Ответы:


1

Прежде всего, вы не должны внедрять весь контейнер в свое расширение.

Всегда старайтесь вводить только то, что вам нужно. В вашем примере вы можете напрямую ввести AuthorizationCheckerInterface вместо ContainerInterface.

Что касается вашей ошибки, без журналов немного сложно догадаться, но вы должны попытаться проверить, не возвращает ли метод getToken() null, прежде чем вызывать для него getUser().

<?php

namespace App\Twig;

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;


class GlobalVarsExtension extends AbstractExtension implements GlobalsInterface
{
    protected $em;

    protected $tokenStorage;

    protected $authorizationChecker;

    public function __construct(EntityManagerInterface $em, AuthorizationCheckerInterface $authorizationChecker, TokenStorageInterface $tokenStorage)
    {
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->authorizationChecker = $authorizationChecker;
    }


   public function getGlobals()
   {
    $globalVars = [];

    if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
        if (null !== $token = $this->tokenStorage->getToken()) {
            $globalVars['user'] = $token->getUser();
        }
    }

    return $globalVars;
   }
}
13.06.2019
  • Только начал с symfony два дня назад и совершенно забыл об отдельном файле журнала symfony, только что проверил apache-erroglog и удивился, почему там нет ничего важного. Я обновляю свой вопрос вашим улучшенным кодом и соответствующим журналом ошибок. 13.06.2019
  • Новые материалы

    Кластеризация: более глубокий взгляд
    Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

    Как написать эффективное резюме
    Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

    Частный метод Python: улучшение инкапсуляции и безопасности
    Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

    Как я автоматизирую тестирование с помощью Jest
    Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

    Понимание расстояния Вассерштейна: мощная метрика в машинном обучении
    В обширной области машинного обучения часто возникает необходимость сравнивать и измерять различия между распределениями вероятностей. Традиционные метрики расстояния, такие как евклидово..

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..