Skip to content

Introduce stimulus_controller to ease Stimulus Values API usage #109

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
Feb 10, 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
4 changes: 4 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
</argument>
</service>

<service id="webpack_encore.twig_stimulus_extension" class="Symfony\WebpackEncoreBundle\Twig\StimulusTwigExtension">
<tag name="twig.extension" />
</service>

<service id="webpack_encore.entrypoint_lookup.cache_warmer" class="Symfony\WebpackEncoreBundle\CacheWarmer\EntrypointCacheWarmer">
<tag name="kernel.cache_warmer" />
<argument /> <!-- build list of entrypoint paths -->
Expand Down
77 changes: 77 additions & 0 deletions src/Twig/StimulusTwigExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of the Symfony WebpackEncoreBundle package.
* (c) Fabien Potencier <[email protected]>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\WebpackEncoreBundle\Twig;

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class StimulusTwigExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('stimulus_controller', [$this, 'renderStimulusController'], ['needs_environment' => true, 'is_safe' => ['all']]),
];
}

public function renderStimulusController(Environment $env, array $data): string
{
if (!$data) {
return '';
}

$controllers = [];
$values = [];

foreach ($data as $controllerName => $controllerValues) {
$controllerName = twig_escape_filter($env, $this->normalizeControllerName($controllerName), 'html_attr');
$controllers[] = $controllerName;

foreach ($controllerValues as $key => $value) {
if (!is_scalar($value)) {
$value = json_encode($value);
}

$key = twig_escape_filter($env, $this->normalizeKeyName($key), 'html_attr');
$value = twig_escape_filter($env, $value, 'html_attr');

$values[] = 'data-'.$controllerName.'-'.$key.'-value="'.$value.'"';
}
}

return rtrim('data-controller="'.implode(' ', $controllers).'" '.implode(' ', $values));
}

/**
* Normalize a Stimulus controller name into its HTML equivalent (no special character and / becomes --).
*
* @see https://stimulus.hotwire.dev/reference/controllers
*/
private function normalizeControllerName(string $str): string
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this belongs here. It seems to me that the UX packages should be responsible for calling this function with their already-normalized name. I'd almost rather throw an exception if something invalid is passed (but probably, just do nothing).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea was to allow users to pass the same value they have in their controller.json file: @symfony/ux-dropzone/dropzone, and this would be transformed to the proper HTML equivalent. But perhaps should we have an alternate way of doing this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, that's a really good point. I'd like to keep it then for DX.

{
return preg_replace('/^@/', '', str_replace('_', '-', str_replace('/', '--', $str)));
}

/**
* Normalize a Stimulus Value API key into its HTML equivalent ("kebab case").
* Backport features from symfony/string.
*
* @see https://stimulus.hotwire.dev/reference/values
*/
private function normalizeKeyName(string $str): string
{
// Adapted from ByteString::camel
$str = ucfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $str))));

// Adapted from ByteString::snake
return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1-\2', $str));
}
}
79 changes: 79 additions & 0 deletions tests/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupInterface;
use Symfony\WebpackEncoreBundle\Asset\TagRenderer;
use Symfony\WebpackEncoreBundle\CacheWarmer\EntrypointCacheWarmer;
use Symfony\WebpackEncoreBundle\Twig\StimulusTwigExtension;
use Symfony\WebpackEncoreBundle\WebpackEncoreBundle;

class IntegrationTest extends TestCase
Expand Down Expand Up @@ -178,6 +179,84 @@ public function testAutowireDefaultBuildArgument()
$this->assertTrue(true);
}

public function provideRenderStimulusController()
{
yield 'empty' => [
'data' => [],
'expected' => '',
];

yield 'single-controller-no-data' => [
'data' => [
'my-controller' => [],
],
'expected' => 'data-controller="my-controller"',
];

yield 'single-controller-scalar-data' => [
'data' => [
'my-controller' => [
'myValue' => 'scalar-value',
],
],
'expected' => 'data-controller="my-controller" data-my-controller-my-value-value="scalar-value"',
];

yield 'single-controller-typed-data' => [
'data' => [
'my-controller' => [
'boolean' => true,
'number' => 4,
'string' => 'str',
],
],
'expected' => 'data-controller="my-controller" data-my-controller-boolean-value="1" data-my-controller-number-value="4" data-my-controller-string-value="str"',
];

yield 'single-controller-nested-data' => [
'data' => [
'my-controller' => [
'myValue' => ['nested' => 'array'],
],
],
'expected' => 'data-controller="my-controller" data-my-controller-my-value-value="&#x7B;&quot;nested&quot;&#x3A;&quot;array&quot;&#x7D;"',
];

yield 'multiple-controllers-scalar-data' => [
'data' => [
'my-controller' => [
'myValue' => 'scalar-value',
],
'another-controller' => [
'anotherValue' => 'scalar-value 2',
],
],
'expected' => 'data-controller="my-controller another-controller" data-my-controller-my-value-value="scalar-value" data-another-controller-another-value-value="scalar-value&#x20;2"',
];

yield 'normalize-names' => [
'data' => [
'@symfony/ux-dropzone/dropzone' => [
'my"Key"' => true,
],
],
'expected' => 'data-controller="symfony--ux-dropzone--dropzone" data-symfony--ux-dropzone--dropzone-my-key-value="1"',
];
}

/**
* @dataProvider provideRenderStimulusController
*/
public function testRenderStimulusController(array $data, string $expected)
{
$kernel = new WebpackEncoreIntegrationTestKernel(true);
$kernel->boot();
$twig = $this->getTwigEnvironmentFromBootedKernel($kernel);

$extension = new StimulusTwigExtension();
$this->assertSame($expected, $extension->renderStimulusController($twig, $data));
}

private function getContainerFromBootedKernel(WebpackEncoreIntegrationTestKernel $kernel)
{
if ($kernel::VERSION_ID >= 40100) {
Expand Down