Symfony:使用从角色继承的属性填充用户对象

I have following entities:

  • User - standard entity implementing AdvancedUserInterface, \Serializable
  • Role - standard entity implementing RoleInterface
  • View - 'custom' entity

Any user may have multiple roles (many-to-many relationship defined). Any role may have multiple view (many-to-many relationship defined).

As part of standard Symfony setup User method getRoles returns roles as an arrayCollection where role has format ROLE_1. This part works great and I have it populated from database and then can verify them with built-in RoleVoter using method is_granted('ROLE_1').

What I would like to achieve is to load on user login a list of views inherited by user from roles for them to be available the same way roles are (in format VIEW_1). This way I could write my own voter and verify these views with method is_granted('VIEW_1').

I know that it is possible to have it done as there are examples of custom voters verifying eg. SUBSCRIPTION_X attribute view custom voter and the voter part is quite clear. Unfortunatelly they ommit the part where actual custom attributes loading is done.

I assume that it is done via UserRepository (implementing UserProviderInterface) in method loadUserByUsername($login) but could not find any example which would be applicable to attributes inherited from roles like views I intend to use. I include current version of loadUserByUsername I use but without any success in getting views available for logged-in user:

public function loadUserByUsername($login)
{

    $user = $this->createQueryBuilder('u')
        ->where('u.login = :login')
        ->select('u, r, v')
        ->leftJoin('u.roles', 'r')
        ->leftJoin('r.views', 'v')
        ->setParameter('login', $login)
        ->getQuery()
        ->getOneOrNullResult();

    if ($user) {
        $message = sprintf(
            'Unable to find an active admin AppBundle:User object identified by "%s".',
            $login
        );
        throw new UsernameNotFoundException($message);
    }

    return $user;
}

I could of course easily put some custom method in UserRepository fetching views and put it in User entity method getRoles to populate views the way I populate roles but it would be just bad design polluting entity.

So the question is how to make views inherited by user from roles available in logged-in user object the same way roles are available?