I am working on Symfony 2.7 WebApp. One of the packages I created includes a service that offers some user-related stuff, for example. userHasPurchases() .
The problem is that turning on Twig Extesion interrupts another service:
AppShopService
namespace AppShopBundle\Service; use AppBundle\Entity\User; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; ... class AppShopService { protected $user; public function __construct(TokenStorageInterface $tokenStorage, ...) { $this->user = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null; ... } public function userHasPurchases(User $user) { $user = $user ? $user : $this->user; $result = $user... return result; } }
AppShopBundle \ Resources \ Config \ services.yml
services: app_shop.service: class: AppShopBundle\Service\AppShopService arguments: - "@security.token_storage" - ...
So far, everything is working fine: AppShopServices is created with the current user and userHasPurchases() works as expected.
Now I am adding Twig Extension to be able to use userHasPurchases() in my templates:
Extension twig
namespace AppShopBundle\Twig; use AppShopBundle\Service\AppShopService; class AppShopExtension extends \Twig_Extension { private $shopService; public function __construct(AppShopService $shopService) { $this->shopService = $shopService; } public function getName() { return 'app_shop_bundle_extension'; } public function getFunctions() { $functions = array(); $functions[] = new \Twig_SimpleFunction('userHasPurchases', array( $this, 'userHasPurchases' )); return $functions; } public function userHasPurchases($user) { return $this->shopService->userHasPurchases($user); } }
Enabling an extension in AppShopBundle \ Resources \ config \ services.yml
services: app_shop.service: class: AppShopBundle\Service\AppShopService arguments: - "@security.token_storage" - ... app_shop.twig_extension: class: AppShopBundle\Twig\AppShopExtension arguments: - "@app_shop.service" tags: - { name: twig.extension }
After entering Twig Extension , AppShopService and its userHasPurchases method no longer works. The problem is that the AppShopService constructor no longer sets user , since $tokenStorage->getToken() now returns null .
How is this possible? I have not changed anything except Twig Extension . As soon as I remove Twig Extension from services.yml everything works correctly again.
My only assumption is that the fo Twig Extension is created before any security. But why?
Any idea what might be wrong here?