bestit / flagception-bundle

Feature flags on steroids!
MIT License
210 stars 42 forks source link

[Add] Support roles #30

Open migo315 opened 6 years ago

migo315 commented 6 years ago

Add one standard role provider for active features.

Example:

# For one role
constraint: has_role('ROLE_ADMIN')

# For multiple roles
constraint: "has_role('ROLE_ADMIN') or has_role('ROLE_MOD')"
migo315 commented 6 years ago

Will be implemented in the next version. However, not with the expression language but as a separate field, as in the symfony security component.

flagception:
    features:      
        # Only one role
        feature_123:
            roles: ROLE_ADMIN

        # Multiple roles
        feature_456:
            roles: ROLE_ADMIN,ROLE_MOD

        # Multiple roles (alternative formatting)
        feature_789:
            roles:
                - ROLE_ADMIN
                - ROLE_MOD
dsentker commented 4 years ago

Perhaps this will help others who are looking for a solution. I am using this implementation to get a user context:


namespace App\Utils\FeatureToggle;

use App\Entity\User;
use Flagception\Model\Context;
use Flagception\Decorator\ContextDecoratorInterface;
use Symfony\Component\Security\Core\Security;

class UserContextDecorator implements ContextDecoratorInterface
{

    /** @var Security */
    private $security;

    public function __construct(Security $security)
    {

        $this->security = $security;
    }

    public function getName(): string
    {
        return 'user_context_decorator';
    }

    public function decorate(Context $context): Context
    {
        $vars = $this->security->getUser() instanceof User
            ? [
                'user_id'    => $this->security->getUser()->getId(),
                'user_roles' => $this->security->getUser()->getRoles(),
            ]
            : [
                'user_id'    => null,
                'user_roles' => [],
            ];

        foreach ($vars as $key => $var) {
            $context->add($key, $var);
        }

        return $context;
    }
}

It is important that the getUser() method is only called in the decorate() method. Security::getUser() is always null when called too early.