Skip to content

Commit

Permalink
Add ability to ensure inflection only happens once per object if defined
Browse files Browse the repository at this point in the history
  • Loading branch information
philipobenito committed Mar 14, 2024
1 parent 96de03d commit d486376
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/Inflector/Inflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,24 @@ class Inflector implements ArgumentResolverInterface, InflectorInterface
*/
protected $callback;

protected array $inflected = [];

public function __construct(
protected string $type,
protected $methods = [],
protected $properties = [],
?callable $callback = null
?callable $callback = null,
protected bool $oncePerMatch = false,
protected array $methods = [],
protected array $properties = [],
) {
$this->callback = $callback;
}

public function oncePerMatch(): InflectorInterface
{
$this->oncePerMatch = true;
return $this;
}

public function getType(): string
{
return $this->type;
Expand Down Expand Up @@ -64,6 +73,10 @@ public function setProperties(array $properties): InflectorInterface

public function inflect(object $object): void
{
if (true === $this->oncePerMatch && in_array($object, $this->inflected, true)) {
return;
}

$properties = $this->resolveArguments(array_values($this->properties));
$properties = array_combine(array_keys($this->properties), $properties);

Expand All @@ -81,5 +94,9 @@ public function inflect(object $object): void
if ($this->callback !== null) {
call_user_func($this->callback, $object);
}

if (true === $this->oncePerMatch) {
$this->inflected[] = $object;
}
}
}
22 changes: 22 additions & 0 deletions tests/Inflector/InflectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,26 @@ public function setBar($bar): void
$inflector->inflect($foo);
$this->assertSame($bar, $foo->bar);
}

public function testInflectorOnlyInflectsOncePerMatch(): void
{
$foo = new class {
public int $count = 0;
public function tick(): void
{
$this->count++;
}
};

$bar = new class {
};

$inflector = new Inflector('Type');
$inflector->oncePerMatch();
$inflector->invokeMethod('tick', []);

$inflector->inflect($foo);
$inflector->inflect($foo);
$this->assertSame(1, $foo->count);
}
}

0 comments on commit d486376

Please sign in to comment.