Skip to content

[TwigBridge][TwigBundle] Twig serialize filter #40323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.3.0
-----

* Added a new `serialize` filter to serialize objects using the Serializer component

5.2.0
-----

Expand Down
28 changes: 28 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/SerializerExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*/
final class SerializerExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('serialize', [SerializerRuntime::class, 'serialize']),
];
}
}
33 changes: 33 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/SerializerRuntime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\Serializer\SerializerInterface;
use Twig\Extension\RuntimeExtensionInterface;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*/
final class SerializerRuntime implements RuntimeExtensionInterface
{
private $serializer;

public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}

public function serialize($data, string $format = 'json', array $context = []): string
{
return $this->serializer->serialize($data, $format, $context);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Symfony\Bridge\Twig\Tests\Extension\Fixtures;

use Symfony\Component\Serializer\Annotation\Groups;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*/
class SerializerModelFixture
{
/**
* @Groups({"read"})
*/
public $name = 'howdy';

public $title = 'fixture';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Tests\Extension;

use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Extension\SerializerExtension;
use Symfony\Bridge\Twig\Extension\SerializerRuntime;
use Symfony\Bridge\Twig\Tests\Extension\Fixtures\SerializerModelFixture;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

/**
* @author Jesse Rushlow <jr@rushlow.dev>
*/
class SerializerExtensionTest extends TestCase
{
/**
* @dataProvider serializerDataProvider
*/
public function testSerializeFilter(string $template, string $expectedResult)
{
$twig = $this->getTwig($template);

self::assertSame($expectedResult, $twig->render('template', ['object' => new SerializerModelFixture()]));
}

public function serializerDataProvider(): \Generator
{
yield ['{{ object|serialize }}', '{&quot;name&quot;:&quot;howdy&quot;,&quot;title&quot;:&quot;fixture&quot;}'];
yield ['{{ object|serialize(\'yaml\') }}', '{ name: howdy, title: fixture }'];
yield ['{{ object|serialize(\'yaml\', {groups: \'read\'}) }}', '{ name: howdy }'];
}

private function getTwig(string $template): Environment
{
$meta = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$runtime = new SerializerRuntime(new Serializer([new ObjectNormalizer($meta)], [new JsonEncoder(), new YamlEncoder()]));

$mockRuntimeLoader = $this->createMock(RuntimeLoaderInterface::class);
$mockRuntimeLoader
->method('load')
->willReturnMap([
['Symfony\Bridge\Twig\Extension\SerializerRuntime', $runtime],
])
;

$twig = new Environment(new ArrayLoader(['template' => $template]));
$twig->addExtension(new SerializerExtension());
$twig->addRuntimeLoader($mockRuntimeLoader);

return $twig;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"twig/twig": "^2.13|^3.0.4"
},
"require-dev": {
"doctrine/annotations": "^1.12",
"egulias/email-validator": "^2.1.10",
"phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0",
"symfony/asset": "^4.4|^5.0",
Expand Down
7 changes: 6 additions & 1 deletion src/Symfony/Bundle/TwigBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.3.0
-----

* Added support for the new `serialize` filter (from Twig Bridge)

5.2.0
-----

Expand Down Expand Up @@ -33,7 +38,7 @@ CHANGELOG
4.1.0
-----

* added priority to Twig extensions
* added priority to Twig extensions
* deprecated relying on the default value (`false`) of the `twig.strict_variables` configuration option. The `%kernel.debug%` parameter will be the new default in 5.0

4.0.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,5 +120,10 @@ public function process(ContainerBuilder $container)
} else {
$container->getDefinition('workflow.twig_extension')->addTag('twig.extension');
}

if ($container->has('serializer')) {
$container->getDefinition('twig.runtime.serializer')->addTag('twig.runtime');
$container->getDefinition('twig.extension.serializer')->addTag('twig.extension');
}
}
}
7 changes: 7 additions & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use Symfony\Bridge\Twig\Extension\HttpKernelRuntime;
use Symfony\Bridge\Twig\Extension\ProfilerExtension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Bridge\Twig\Extension\SerializerExtension;
use Symfony\Bridge\Twig\Extension\SerializerRuntime;
use Symfony\Bridge\Twig\Extension\StopwatchExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Extension\WebLinkExtension;
Expand Down Expand Up @@ -160,5 +162,10 @@
->factory([TwigErrorRenderer::class, 'isDebug'])
->args([service('request_stack'), param('kernel.debug')]),
])

->set('twig.runtime.serializer', SerializerRuntime::class)
->args([service('serializer')])

->set('twig.extension.serializer', SerializerExtension::class)
;
};