Skip to content

Instantly share code, notes, and snippets.

@Richard87
Last active October 7, 2021 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Richard87/d3646e3932eed0330bbdc6fd32c1aa83 to your computer and use it in GitHub Desktop.
Save Richard87/d3646e3932eed0330bbdc6fd32c1aa83 to your computer and use it in GitHub Desktop.
FeatureManager.php
/*
* 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