Added uuid/uuidBy twig functions

This commit is contained in:
Igor Scheller 2023-01-28 01:21:51 +01:00 committed by Michael Weimann
parent a9cd00c37a
commit 8223193330
3 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,31 @@
<?php
namespace Engelsystem\Renderer\Twig\Extensions;
use Engelsystem\Helpers\Uuid as UuidHelper;
use Twig\Extension\AbstractExtension as TwigExtension;
use Twig\TwigFunction;
class Uuid extends TwigExtension
{
/**
* @return TwigFunction[]
*/
public function getFunctions(): array
{
return [
new TwigFunction('uuid', [$this, 'getUuid']),
new TwigFunction('uuidBy', [$this, 'getUuidBy']),
];
}
public function getUuid(): string
{
return UuidHelper::uuid();
}
public function getUuidBy(mixed $value, ?string $name = null): string
{
return UuidHelper::uuidBy($value, $name);
}
}

View File

@ -15,6 +15,7 @@ use Engelsystem\Renderer\Twig\Extensions\Markdown;
use Engelsystem\Renderer\Twig\Extensions\Session; use Engelsystem\Renderer\Twig\Extensions\Session;
use Engelsystem\Renderer\Twig\Extensions\Translation; use Engelsystem\Renderer\Twig\Extensions\Translation;
use Engelsystem\Renderer\Twig\Extensions\Url; use Engelsystem\Renderer\Twig\Extensions\Url;
use Engelsystem\Renderer\Twig\Extensions\Uuid;
use Symfony\Component\VarDumper\VarDumper; use Symfony\Component\VarDumper\VarDumper;
use Twig\Environment as Twig; use Twig\Environment as Twig;
use Twig\Extension\CoreExtension as TwigCore; use Twig\Extension\CoreExtension as TwigCore;
@ -37,6 +38,7 @@ class TwigServiceProvider extends ServiceProvider
'markdown' => Markdown::class, 'markdown' => Markdown::class,
'translation' => Translation::class, 'translation' => Translation::class,
'url' => Url::class, 'url' => Url::class,
'uuid' => Uuid::class,
]; ];
public function register(): void public function register(): void

View File

@ -0,0 +1,49 @@
<?php
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
use Engelsystem\Renderer\Twig\Extensions\Uuid;
use Illuminate\Support\Str;
class UuidTest extends ExtensionTest
{
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Uuid::getFunctions
*/
public function testGetGlobals(): void
{
$extension = new Uuid();
$functions = $extension->getFunctions();
$this->assertExtensionExists('uuid', [$extension, 'getUuid'], $functions);
$this->assertExtensionExists('uuidBy', [$extension, 'getUuidBy'], $functions);
}
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Uuid::getUuid
*/
public function testGetUuid(): void
{
$extension = new Uuid();
$uuid = $extension->getUuid();
$this->assertTrue(Str::isUuid($uuid));
}
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Uuid::getUuidBy
*/
public function testGetUuidBy(): void
{
$extension = new Uuid();
$uuid = $extension->getUuidBy('test');
$this->assertTrue(Str::isUuid($uuid));
$this->assertEquals('098f6bcd-4621-4373-8ade-4e832627b4f6', $uuid);
$uuid = $extension->getUuidBy('test', '1337');
$this->assertTrue(Str::isUuid($uuid));
$this->assertStringStartsWith('1337', $uuid);
}
}