FeatureManager.php
This file contains 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