-
-
Notifications
You must be signed in to change notification settings - Fork 168
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1844 from bolt/check-for-extensions-in-twig
Make possible to check if an extension is present, directly in Twig
- Loading branch information
Showing
2 changed files
with
63 additions
and
2 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Bolt\Twig; | ||
|
||
use Bolt\Extension\ExtensionRegistry; | ||
use Tightenco\Collect\Support\Collection; | ||
use Twig\Extension\AbstractExtension; | ||
use Twig\TwigFunction; | ||
|
||
/** | ||
* Widget functionality Twig extension. | ||
*/ | ||
class ExtensionExtension extends AbstractExtension | ||
{ | ||
/** @var ExtensionRegistry */ | ||
private $registry; | ||
|
||
public function __construct(ExtensionRegistry $registry) | ||
{ | ||
$this->registry = $registry; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function getFunctions(): array | ||
{ | ||
return [ | ||
new TwigFunction('extension_exists', [$this, 'extensionExists']), | ||
new TwigFunction('extensions', [$this, 'getExtensions']), | ||
]; | ||
} | ||
|
||
public function getExtensions(): Collection | ||
{ | ||
$extensions = $this->registry->getExtensions(); | ||
|
||
$rows = []; | ||
|
||
foreach ($extensions as $extension) { | ||
$rows[] = [ | ||
'package' => $extension->getComposerPackage()->getName(), | ||
'class' => $extension->getClass(), | ||
'name' => $extension->getName(), | ||
]; | ||
} | ||
|
||
return new Collection($rows); | ||
} | ||
|
||
public function extensionExists(string $name): bool | ||
{ | ||
$extensions = $this->getExtensions(); | ||
|
||
return $extensions->where('package', $name)->isNotEmpty() || | ||
$extensions->where('class', $name)->isNotEmpty() || | ||
$extensions->where('name', $name)->isNotEmpty(); | ||
} | ||
} |