Skip to content

Commit

Permalink
[!!!][TASK] Streamline root context with TYPO3 default naming
Browse files Browse the repository at this point in the history
  • Loading branch information
eliashaeussler committed Jan 7, 2025
1 parent e25b6fd commit 7d3c204
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 55 deletions.
12 changes: 6 additions & 6 deletions Classes/DependencyInjection/Extension/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
*
* Defines the following configuration structure for the {@see HandlebarsExtension}:
*
* - defaultData:
* - [data]: any default data passed to the renderer
* - variables:
* - [data]: any default variable passed to the renderer
*
* - view:
* - [templateRootPaths]: numeric array of template root paths
Expand All @@ -48,12 +48,12 @@ final class Configuration implements ConfigurationInterface
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('handlebars');
$rootNode = $treeBuilder->getRootNode();

/** @phpstan-ignore-next-line */
$rootNode
/* @phpstan-ignore method.notFound */
$treeBuilder
->getRootNode()
->children()
->arrayNode('default_data')
->arrayNode('variables')
->performNoDeepMerging()
->variablePrototype()->end()
->end()
Expand Down
13 changes: 8 additions & 5 deletions Classes/DependencyInjection/Extension/HandlebarsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
*/
final class HandlebarsExtension extends Extension
{
public const PARAMETER_DEFAULT_DATA = 'handlebars.default_data';
public const PARAMETER_TEMPLATE_ROOT_PATHS = 'handlebars.templateRootPaths';
public const PARAMETER_PARTIAL_ROOT_PATHS = 'handlebars.partialRootPaths';
public const PARAMETER_ROOT_CONTEXT = 'handlebars.rootContext';

/**
* @var string[]
Expand All @@ -53,7 +53,7 @@ final class HandlebarsExtension extends Extension
/**
* @var array<string|int, mixed>
*/
private array $defaultData = [];
private array $rootContext = [];

/**
* @param array<string|int, mixed>[] $configs
Expand All @@ -64,9 +64,9 @@ public function load(array $configs, ContainerBuilder $container): void
$this->parseConfiguration($configs);

$container->getParameterBag()->add([
self::PARAMETER_DEFAULT_DATA => $this->defaultData,
self::PARAMETER_TEMPLATE_ROOT_PATHS => $this->templateRootPaths,
self::PARAMETER_PARTIAL_ROOT_PATHS => $this->partialRootPaths,
self::PARAMETER_ROOT_CONTEXT => $this->rootContext,
]);
}

Expand All @@ -75,10 +75,11 @@ public function load(array $configs, ContainerBuilder $container): void
*/
private function parseConfiguration(array $configs): void
{
$this->defaultData = $this->mergeConfigs($configs, 'default_data');
$templateConfig = $this->mergeConfigs($configs, 'view');

$this->templateRootPaths = $templateConfig['templateRootPaths'] ?? [];
$this->partialRootPaths = $templateConfig['partialRootPaths'] ?? [];
$this->rootContext = $this->mergeConfigs($configs, 'variables');
}

/**
Expand All @@ -88,16 +89,18 @@ private function parseConfiguration(array $configs): void
private function mergeConfigs(array $configs, string $configKey): array
{
$mergedConfig = [];

foreach (array_column($configs, $configKey) as $concreteConfig) {
ArrayUtility::mergeRecursiveWithOverrule($mergedConfig, $concreteConfig);
}

return $mergedConfig;
}

private function reset(): void
{
$this->defaultData = [];
$this->templateRootPaths = [];
$this->partialRootPaths = [];
$this->rootContext = [];
}
}
14 changes: 7 additions & 7 deletions Classes/Event/BeforeRenderingEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@
class BeforeRenderingEvent
{
/**
* @param array<string|int, mixed> $data
* @param array<string|int, mixed> $variables
*/
public function __construct(
private readonly string $templatePath,
private array $data,
private array $variables,
private readonly HandlebarsRenderer $renderer,
) {}

Expand All @@ -50,17 +50,17 @@ public function getTemplatePath(): string
/**
* @return array<string|int, mixed>
*/
public function getData(): array
public function getVariables(): array
{
return $this->data;
return $this->variables;
}

/**
* @param array<string|int, mixed> $data
* @param array<string|int, mixed> $variables
*/
public function setData(array $data): self
public function setVariables(array $variables): self
{
$this->data = $data;
$this->variables = $variables;
return $this;
}

Expand Down
28 changes: 14 additions & 14 deletions Classes/Renderer/HandlebarsRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class HandlebarsRenderer implements RendererInterface
protected readonly bool $debugMode;

/**
* @param array<string|int, mixed> $defaultData
* @param array<string|int, mixed> $rootContext
*/
public function __construct(
#[Autowire('@handlebars.cache')]
Expand All @@ -68,8 +68,8 @@ public function __construct(
protected readonly LoggerInterface $logger,
#[Autowire('@handlebars.template_resolver')]
protected readonly TemplateResolverInterface $templateResolver,
#[Autowire('%handlebars.default_data%')]
protected array $defaultData = [],
#[Autowire('%handlebars.variables%')]
protected array $rootContext = [],
) {
$this->debugMode = $this->isDebugModeEnabled();
}
Expand All @@ -86,12 +86,12 @@ public function render(string $templatePath, array $data = []): string
}

/**
* @param array<string|int, mixed> $data
* @param array<string|int, mixed> $variables
* @throws InvalidTemplateFileException
* @throws TemplateCompilationException
* @throws TemplatePathIsNotResolvable
*/
protected function processRendering(string $templatePath, array $data): string
protected function processRendering(string $templatePath, array $variables): string
{
$fullTemplatePath = $this->templateResolver->resolveTemplatePath($templatePath);
$template = file_get_contents($fullTemplatePath);
Expand All @@ -106,19 +106,19 @@ protected function processRendering(string $templatePath, array $data): string
return '';
}

// Merge render data with default data
$mergedData = array_merge($this->defaultData, $data);
// Merge render data with root context
$mergedVariables = array_merge($this->rootContext, $variables);

// Compile template
$compileResult = $this->compile($template);
$renderer = $this->prepareCompileResult($compileResult);

// Dispatch before rendering event
$beforeRenderingEvent = new BeforeRenderingEvent($fullTemplatePath, $mergedData, $this);
$beforeRenderingEvent = new BeforeRenderingEvent($fullTemplatePath, $mergedVariables, $this);
$this->eventDispatcher->dispatch($beforeRenderingEvent);

// Render content
$content = $renderer($beforeRenderingEvent->getData(), [
$content = $renderer($beforeRenderingEvent->getVariables(), [
'debug' => Runtime::DEBUG_TAGS_HTML,
'helpers' => $this->helperRegistry->getAll(),
]);
Expand Down Expand Up @@ -259,17 +259,17 @@ public function resolvePartial(array $context, string $name): ?string
/**
* @return array<string|int, mixed>
*/
public function getDefaultData(): array
public function getRootContext(): array
{
return $this->defaultData;
return $this->rootContext;
}

/**
* @param array<string|int, mixed> $defaultData
* @param array<string|int, mixed> $rootContext
*/
public function setDefaultData(array $defaultData): self
public function setRootContext(array $rootContext): self
{
$this->defaultData = $defaultData;
$this->rootContext = $rootContext;
return $this;
}

Expand Down
2 changes: 1 addition & 1 deletion Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ services:
arguments: ['handlebars']

handlebars:
default_data: []
variables: []
view:
templateRootPaths: []
partialRootPaths: []
2 changes: 1 addition & 1 deletion Documentation/Configuration/Index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ how to use the extension:

Cache/Index
TemplatePaths/Index
DefaultData/Index
Variables/Index
Debugging/Index
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ data. This can be, for example, paths to assets or other firmly defined
content such as e-mail addresses or names/labels/etc.

The standard `HandlebarsRenderer` provides the possibility to specify an
array :php:`$defaultData` for this purpose. This data is merged with the
array :php:`$rootContext` for this purpose. This data is merged with the
concrete render data during each rendering and passed on to the `Renderer`.

.. _configure-default-data:
Expand All @@ -26,11 +26,11 @@ In your :file:`Services.yaml` file, add the following lines:
# Configuration/Services.yaml
handlebars:
default_data:
variables:
publicPath: /assets
# ...
All data will then be available as service parameter `%handlebars.default_data%`
All data will then be available as service parameter `%handlebars.variables%`
within the service container. So you can use it everywhere you need it in
your :file:`Services.yaml` file.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,32 +86,32 @@ public static function loadAddsResolvedParametersToContainerDataProvider(): \Gen
yield 'no configs' => [
[],
[
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_DEFAULT_DATA => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_TEMPLATE_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_PARTIAL_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_ROOT_CONTEXT => [],
],
];
yield 'default data' => [
[
[
'default_data' => [
'variables' => [
'foo' => 'baz',
],
],
[
'default_data' => [
'variables' => [
'foo' => 'yay',
'baz' => 'foo',
],
],
],
[
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_DEFAULT_DATA => [
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_TEMPLATE_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_PARTIAL_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_ROOT_CONTEXT => [
'foo' => 'yay',
'baz' => 'foo',
],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_TEMPLATE_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_PARTIAL_ROOT_PATHS => [],
],
];
yield 'template root paths' => [
Expand All @@ -128,9 +128,9 @@ public static function loadAddsResolvedParametersToContainerDataProvider(): \Gen
],
],
[
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_DEFAULT_DATA => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_TEMPLATE_ROOT_PATHS => $expectedRootPaths,
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_PARTIAL_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_ROOT_CONTEXT => [],
],
];
yield 'partial root paths' => [
Expand All @@ -147,9 +147,9 @@ public static function loadAddsResolvedParametersToContainerDataProvider(): \Gen
],
],
[
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_DEFAULT_DATA => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_TEMPLATE_ROOT_PATHS => [],
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_PARTIAL_ROOT_PATHS => $expectedRootPaths,
Src\DependencyInjection\Extension\HandlebarsExtension::PARAMETER_ROOT_CONTEXT => [],
],
];
}
Expand Down
10 changes: 5 additions & 5 deletions Tests/Unit/Event/BeforeRenderingEventTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,17 @@ public function getTemplatePathReturnsTemplatePath(): void
}

#[Framework\Attributes\Test]
public function getDataReturnsData(): void
public function getVariablesReturnsVariables(): void
{
self::assertSame(['foo' => 'baz'], $this->subject->getData());
self::assertSame(['foo' => 'baz'], $this->subject->getVariables());
}

#[Framework\Attributes\Test]
public function setDataModifiesData(): void
public function setVariablesModifiesVariables(): void
{
$this->subject->setData(['modified' => 'data']);
$this->subject->setVariables(['modified' => 'variables']);

self::assertSame(['modified' => 'data'], $this->subject->getData());
self::assertSame(['modified' => 'variables'], $this->subject->getVariables());
}

#[Framework\Attributes\Test]
Expand Down
12 changes: 7 additions & 5 deletions Tests/Unit/Renderer/HandlebarsRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ public function renderReturnsEmptyStringIfGivenTemplateIsEmpty(): void
}

#[Framework\Attributes\Test]
public function renderMergesDefaultDataWithGivenData(): void
public function renderMergesVariablesWithGivenVariables(): void
{
$this->helperRegistry->add('varDump', Src\Renderer\Helper\VarDumpHelper::class);
$this->subject->setDefaultData([
$this->subject->setRootContext([
'foo' => 'baz',
]);

Expand Down Expand Up @@ -241,10 +241,11 @@ public function resolvePartialResolvesGivenPartialUsingPartialResolver(): void
}

#[Framework\Attributes\Test]
public function getDefaultDataReturnsDefaultRenderData(): void
public function getRootContextReturnsDefaultVariables(): void
{
$this->subject->setDefaultData(['foo' => 'baz']);
self::assertSame(['foo' => 'baz'], $this->subject->getDefaultData());
$this->subject->setRootContext(['foo' => 'baz']);

self::assertSame(['foo' => 'baz'], $this->subject->getRootContext());
}

private function assertCacheIsEmptyForTemplate(string $template): void
Expand All @@ -264,6 +265,7 @@ private function assertCacheIsNotEmptyForTemplate(string $template): void
protected function tearDown(): void
{
self::assertTrue($this->clearCache(), 'Unable to clear Handlebars cache.');

parent::tearDown();
}

Expand Down

0 comments on commit 7d3c204

Please sign in to comment.