Last active
October 7, 2021 21:16
-
-
Save Richard87/d3646e3932eed0330bbdc6fd32c1aa83 to your computer and use it in GitHub Desktop.
FeatureManager.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* License MIT | |
*/ | |
<?php | |
namespace App\Service; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Component\Security\Core\Security; | |
use Twig\Extension\AbstractExtension; | |
use Twig\TwigFunction; | |
class FeatureManager extends AbstractExtension | |
{ | |
private const FEATURES = [ | |
"super-admin-feature" => 'ROLE_SUPER_ADMIN', | |
"fancy-feature" => 'isTestUser', | |
"fancy-feature-2" => true, // or false | |
]; | |
public function __construct( | |
private Security $security, | |
private LoggerInterface $logger, | |
){} | |
public function getFunctions() | |
{ | |
return [new TwigFunction('haveFeature', [$this, 'have'])]; | |
} | |
public function have(string $feature, $yes = true, $no = false) | |
{ | |
$target = self::FEATURES[$feature] ?? false; | |
if (is_bool($target)) return $target ? $yes : $no; | |
if (is_string($target) && method_exists($this, $target)) return $this->$target() ? $yes : $no; | |
if (is_string($target)) return $this->security->isGranted($role) ? $yes : $no; | |
$this->logger->info("Feature $feature is DISABLED."); | |
return $no; | |
} | |
private function isTestUser() { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment