Skip to content

Commit

Permalink
Resolve Faker formatter earlier
Browse files Browse the repository at this point in the history
  • Loading branch information
clxmstaab authored and guvra committed Feb 20, 2024
1 parent 3870dd4 commit e14618b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/Converter/Proxy/Faker.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
class Faker implements ConverterInterface
{
private Generator $faker;
private string $formatter;
private object $provider;
private string $method;
private array $arguments;

/**
Expand All @@ -36,33 +37,33 @@ public function setParameters(array $parameters): void
->addParameter('arguments', Parameter::TYPE_ARRAY, false, [])
->process($parameters);

$this->formatter = $input->get('formatter');
$formatter = $input->get('formatter');
$this->arguments = $input->get('arguments') ?? [];

foreach ($this->arguments as $name => $value) {
if ($value === '{{value}}') {
$this->placeholders[] = $name;
}
}

// Faster than calling the "format" method of the Faker generator
// (the "format" method uses call_user_func_array, which is very slow)
// @phpstan-ignore-next-line getFormatter function always returns an array with 2 items
[$this->provider, $this->method] = $this->faker->getFormatter($formatter);
}

/**
* @inheritdoc
*/
public function convert(mixed $value, array $context = []): mixed
{
// Faster than calling the "format" method of the Faker generator
// (the "format" method uses call_user_func_array, which is very slow)
// @phpstan-ignore-next-line getFormatter function always returns an array with 2 items
[$provider, $method] = $this->faker->getFormatter($this->formatter);

$arguments = $this->arguments;

// Replace all occurrences of "{{value}}" by $value
foreach ($this->placeholders as $name) {
$arguments[$name] = $value;
}

return $provider->$method(...$arguments);
return $this->provider->{$this->method}(...$arguments);
}
}
12 changes: 12 additions & 0 deletions tests/unit/Converter/Proxy/FakerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,16 @@ public function testFormatterNotSet(): void
$this->expectException(ValidationException::class);
$this->createFakerConverter();
}

/**
* Test creation of a converter with invalid formatter throws
*/
public function testInvalidFormatter(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->createFakerConverter([
'formatter' => 'doesNotExist',
'arguments' => [1, 1],
]);
}
}

0 comments on commit e14618b

Please sign in to comment.