Search code examples
phpsymfonysylius

Access currently logged in user in UserRepository in Sylius


I would like to do something like this.

sylius_backend_user_index:
    pattern: /
    methods: [GET]
    defaults:
        _controller: sylius.controller.user:indexAction
        _sylius:
            template: SyliusWebBundle:Backend/User:index.html.twig
            method: createFilterPaginator
            arguments: [$criteria, $sorting, $deleted, @service_container]

I would like to access service_container in createFilterPaginator method. Can any one help me to sort out this issue?


Solution

  • First of all, no need for the whole service container, you need only security.context. I assume you have already extended the UserRepository so you can overwrite the createFilterPaginator() method and it is correctly configured as the sylius.repository.user service.

    You have to add a simple setter to your respository:

    class UserRepository extends BaseUserRepository
    {
        protected $user;
    
        public setUserViaSecurityContext(SecurityContextInterface $securityContext)
        {
            $this->user = $securityContext->getToken()->getUser();
        }
    }
    

    Now you have to manipulate the service definition in a compiler pass

    namespace Acme\Bundle\YourBundle\DependencyInjection\Compiler;
    
    use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\Reference;
    
    class ModifyRepositoryPass implements CompilerPassInterface
    {
        public function process(ContainerBuilder $container)
        {
            $container
                ->findDefinition('sylius.repository.user')
                ->addMethodCall('setUserViaSecurityContext', array(
                    new Reference('security.context'),
                ))
            ;
        }
    }
    

    And call this Compiler pass in your bundles file:

    namespace Acme\Bundle\YourBundle;
    
    use Acme\Bundle\YourBundle\DependencyInjection\Compiler\ModifyRepositoryPass;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    
    class AcmeYourBundle extends Bundle
    {
        public function build(ContainerBuilder $container)
        {
            $container->addCompilerPass(new ModifyRepositoryPass());
        }
    }