Skip to content

Commit

Permalink
fake parameters are only created when feature is enabled (#30)
Browse files Browse the repository at this point in the history
Parameters not provided in a variation will be provided as NULL
  • Loading branch information
davidhoelzel authored Apr 25, 2024
1 parent d27c9ff commit eccfd1c
Show file tree
Hide file tree
Showing 17 changed files with 188 additions and 54 deletions.
7 changes: 7 additions & 0 deletions docs/BundleConfiguration.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ The bundle provides following defaults:
```yaml
twig_doc:
doc_identifier: TWIG_DOC
use_fake_parameter: false
directories:
- '%twig.default_path%/components'
categories:
Expand Down Expand Up @@ -51,6 +52,12 @@ MY_DOC_IDENTIFIER#}
<div class="fancy-component"></div>
```

### Fake Parameters

By default, the creation of fake parameters is disabled!

When enabled, the bundle fakes parameters based on parameter-config of the component

### Categories

The bundle groups components into categories and optionally into sub-categories.
Expand Down
40 changes: 39 additions & 1 deletion docs/ComponentConfiguration.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,46 @@ components:
### Parameter Provision
You must provide the types of your template parameters in the configuration.
You must provide the types of your template parameters in the configuration.
As twig templates are not aware of types, there is no other possibility at the moment.
Unless you enable use_fake_parameter in the bundle configuration, parameter-values for the components
must be configured in each variation for this component!
`use_fake_parameter: false`

When a parameter is not provided in a variation, it will be set to NULL.

Objects will not be provided as objects, only as arrays based on the variation configuration.

e.g:
```yaml
...
parameters:
car: App\Entity\Car
owner: String
variation:
blue:
car:
color: blue
manufacturer:
name: Mitsubishi
```
will result that car is provided as an array when the component is rendered:
```php
[
'color' => 'blue',
'manufacturer' => [
'name' => 'Mitsubishi'
],
'owner' => null
]
```

When you do not call fancy object-methods in your component-templates, this should suffice for most cases.

`use_fake_paramter: true`

As this bundle makes use of [Nelmio/Alice](https://github.com/nelmio/alice) and [FakerPhp](https://fakerphp.github.io), all you need to do is
define the types of your parameters in the component configuration.
The bundle will take care of creating a set of parameters for every component.
Expand Down
2 changes: 0 additions & 2 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="tests/bootstrap.php"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="true"
beStrictAboutOutputDuringTests="true"
failOnRisky="true"
failOnWarning="true"
Expand Down
30 changes: 27 additions & 3 deletions src/Component/ComponentItemFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
public function __construct(
private ValidatorInterface $validator,
private CategoryService $categoryService,
private Faker $faker
private Faker $faker,
private bool $useFakeParams
) {
}

Expand Down Expand Up @@ -105,7 +106,7 @@ private function parseVariations(?array $variations, ?array $parameters): array

if (!$variations) {
return [
'default' => $this->faker->getFakeData($parameters),
'default' => $this->createVariationParameters($parameters, []),
];
}

Expand All @@ -125,11 +126,34 @@ private function createVariationParameters(array $parameters, array $variation):
{
$params = [];

if ($this->useFakeParams) {
return $this->createFakeParamValues($parameters, $variation);
}

foreach ($parameters as $name => $type) {
if (\is_array($type)) {
$params[$name] = $this->createVariationParameters($type, $variation[$name] ?? []);
} else {
$params[$name] = $variation[$name] ?? null;
}
}

return $params;
}

private function createFakeParamValues(array $parameters, array $variation): array
{
$params = [];

foreach ($parameters as $name => $type) {
if (\is_array($type)) {
$paramValue[$name] = $this->createVariationParameters($type, $variation[$name] ?? []);
} else {
$paramValue = $this->faker->getFakeData([$name => $type], $variation[$name] ?? null);
if (\array_key_exists($name, $variation) && null === $variation[$name]) {
$paramValue = [$name => null];
} else {
$paramValue = $this->faker->getFakeData([$name => $type], $variation[$name] ?? null);
}
}
$params += $paramValue;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Component/Data/Generator/NullGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class NullGenerator implements GeneratorInterface
{
public function supports(string $type, mixed $context = null): bool
{
return null === $context || '' === $context;
return true;
}

public function generate(string $type, mixed $context = null): null
Expand Down
1 change: 1 addition & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->thenInvalid('The twig_doc documentation identifier must match \w (regex)')
->end()
->end()
->booleanNode('use_fake_parameter')->defaultFalse()->end()
->arrayNode('breakpoints')
->defaultValue([
'small' => 240,
Expand Down
3 changes: 3 additions & 0 deletions src/DependencyInjection/TwigDocExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,8 @@ public function load(array $configs, ContainerBuilder $container): void

$definition = $container->getDefinition('twig_doc.service.faker');
$definition->setArgument('$generators', tagged_iterator('twig_doc.data_generator'));

$definition = $container->getDefinition('twig_doc.service.component_factory');
$definition->setArgument('$useFakeParams', $config['use_fake_parameter']);
}
}
2 changes: 1 addition & 1 deletion templates/component/_invalid_component.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
{% if loop.first %}
<ul>
{% endif %}
<li>{{ key }}: {{ value }}</li>
<li>{{ key }}</li>
{% if loop.last %}
</ul>
{% endif %}
Expand Down
56 changes: 49 additions & 7 deletions tests/Functional/Service/ComponentItemFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Qossmic\TwigDocBundle\Exception\InvalidComponentConfigurationException;
use Qossmic\TwigDocBundle\Service\CategoryService;
use Qossmic\TwigDocBundle\Tests\TestApp\Entity\Car;
use Qossmic\TwigDocBundle\Tests\TestApp\Test\ConfigurableContainerTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

#[CoversClass(ComponentItemFactory::class)]
Expand All @@ -29,6 +30,8 @@
#[UsesClass(NullGenerator::class)]
class ComponentItemFactoryTest extends KernelTestCase
{
use ConfigurableContainerTrait;

#[DataProvider('getValidComponents')]
public function testValidComponent(array $componentData): void
{
Expand Down Expand Up @@ -115,8 +118,10 @@ public function testFactoryCreatesDefaultVariationWithParameterTypes(): void
],
];

$container = $this->createContainer(['twig_doc' => ['use_fake_parameter' => true]]);

/** @var ComponentItemFactory $factory */
$factory = self::getContainer()->get('twig_doc.service.component_factory');
$factory = $container->get('twig_doc.service.component_factory');

$component = $factory->create($data);

Expand All @@ -135,6 +140,40 @@ public function testFactoryCreatesDefaultVariationWithParameterTypes(): void
self::assertIsFloat($component->getVariations()['default']['complex']['amount']);
}

public function testCreateObjectParameter(): void
{
$data = [
'name' => 'component',
'title' => 'title',
'description' => 'description',
'category' => 'MainCategory',
'path' => 'path',
'renderPath' => 'renderPath',
'parameters' => [
'car' => Car::class,
],
'variations' => [
'variation1' => [
'car' => [
'color' => 'blue',
],
],
'variation2' => [
'car' => null,
],
],
];

$container = $this->createContainer(['twig_doc' => ['use_fake_parameter' => true]]);

/** @var ComponentItemFactory $factory */
$factory = $container->get('twig_doc.service.component_factory');

$component = $factory->create($data);

self::assertInstanceOf(ComponentItem::class, $component);
}

public function testCreateKeepsParamValueFromVariation(): void
{
$data = [
Expand Down Expand Up @@ -200,11 +239,14 @@ public function testCreateForObjectParameter(): void
static::assertIsArray($variations['fuchsia']);
static::assertArrayHasKey('car', $variations['fuchsia']);

$car = $variations['fuchsia']['car'];
$carData = $variations['fuchsia']['car'];

static::assertInstanceOf(Car::class, $car);
static::assertEquals('fuchsia', $car->getColor());
static::assertEquals('Mitsubishi', $car->getManufacturer()->getName());
static::assertEquals([
'color' => 'fuchsia',
'manufacturer' => [
'name' => 'Mitsubishi',
],
], $carData);
}

public function testCreateForParamWithOptionalVariationValue(): void
Expand All @@ -224,7 +266,7 @@ public function testCreateForParamWithOptionalVariationValue(): void
'variations' => [
'variation1' => [
'stringParam' => 'Some cool hipster text',
'optionalEmpty' => '',
'optionalEmpty' => null,
],
],
];
Expand All @@ -238,7 +280,7 @@ public function testCreateForParamWithOptionalVariationValue(): void
self::assertIsArray($variations);
self::assertArrayHasKey('variation1', $variations);
self::assertArrayHasKey('secondParam', $variations['variation1']);
self::assertIsString($variations['variation1']['secondParam']);
self::assertNull($variations['variation1']['secondParam']);
self::assertNull($variations['variation1']['optionalEmpty']);
}

Expand Down
8 changes: 6 additions & 2 deletions tests/TestApp/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class Kernel extends SymfonyKernel
{
use MicroKernelTrait;

public function __construct()
public function __construct(string $environment = 'test', bool $debug = false, private readonly array $extraConfigs = [])
{
parent::__construct('test', false);
parent::__construct($environment, $debug);
}

public function registerBundles(): iterable
Expand All @@ -42,6 +42,10 @@ protected function configureContainer(ContainerBuilder $container, LoaderInterfa
$loader->load(__DIR__.'/config/services.php');
$loader->load(__DIR__.'/config/packages/*.php', 'glob');
$loader->load(__DIR__.'/config/packages/*.yaml', 'glob');

foreach ($this->extraConfigs as $name => $config) {
$container->prependExtensionConfig($name, $config);
}
}

public function getCacheDir(): string
Expand Down
22 changes: 22 additions & 0 deletions tests/TestApp/Test/ConfigurableContainerTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Qossmic\TwigDocBundle\Tests\TestApp\Test;

use Qossmic\TwigDocBundle\Tests\TestApp\Kernel;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;

trait ConfigurableContainerTrait
{
public function createContainer(array $configs): ContainerInterface
{
$kernel = new Kernel(extraConfigs: $configs);
$filesystem = new Filesystem();
$filesystem->remove($kernel->getCacheDir());
$kernel->boot();

return $kernel->getContainer();
}
}
13 changes: 10 additions & 3 deletions tests/Unit/Component/ComponentItemFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public function testValidComponent(array $componentData): void
$componentItemFactory = new ComponentItemFactory(
$validatorMock,
$categoryServiceMock,
$this->createMock(Faker::class)
$this->createMock(Faker::class),
false
);

$item = $componentItemFactory->create($componentData);
Expand All @@ -57,7 +58,12 @@ public function testInvalidCategory(): void
->willReturn(null);
$validatorMock = $this->createMock(ValidatorInterface::class);

$componentItemFactory = new ComponentItemFactory($validatorMock, $categoryServiceMock, $this->createMock(Faker::class));
$componentItemFactory = new ComponentItemFactory(
$validatorMock,
$categoryServiceMock,
$this->createMock(Faker::class),
false
);

$componentItemFactory->create(['category' => 'Category']);
}
Expand All @@ -73,7 +79,8 @@ public function testGetParamsFromVariables(): void
$componentItemFactory = new ComponentItemFactory(
$this->createMock(ValidatorInterface::class),
$this->createMock(CategoryService::class),
$this->createMock(Faker::class)
$this->createMock(Faker::class),
false
);

$result = $componentItemFactory->getParamsFromVariables($variables);
Expand Down
5 changes: 3 additions & 2 deletions tests/Unit/Component/Data/Generator/NullGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ public function testSupports(): void
{
$generator = new NullGenerator();

static::assertTrue($generator->supports('any', null));
static::assertFalse($generator->supports('any', 'notEmpty'));
static::assertTrue($generator->supports('any'));
static::assertTrue($generator->supports('any', 'notEmpty'));
}

public function testGenerate(): void
{
$generator = new NullGenerator();

static::assertNull($generator->generate('any'));
static::assertNull($generator->generate('any', 'anyContext'));
}
}
Loading

0 comments on commit eccfd1c

Please sign in to comment.