Skip to content
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

feat: introduce "recycle()" method #804

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
service('.zenstruck_foundry.story_registry'),
service('.zenstruck_foundry.persistence_manager')->nullOnInvalid(),
service('event_dispatcher'),
service('property_info'),
])
->public()
;
Expand Down
22 changes: 22 additions & 0 deletions src/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@
namespace Zenstruck\Foundry;

use Faker;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\PropertyInfo\Extractor\PhpStanExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoCacheExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
use Zenstruck\Foundry\Exception\FactoriesTraitNotUsed;
use Zenstruck\Foundry\Exception\FoundryNotBooted;
use Zenstruck\Foundry\Exception\PersistenceDisabled;
Expand Down Expand Up @@ -43,6 +50,8 @@ final class Configuration
/** @var \Closure():self|self|null */
private static \Closure|self|null $instance = null;

public readonly PropertyInfoExtractorInterface&PropertyInitializableExtractorInterface $propertyInfo;

/**
* @phpstan-param InstantiatorCallable $instantiator
*/
Expand All @@ -53,8 +62,21 @@ public function __construct(
public readonly StoryRegistry $stories,
private readonly ?PersistenceManager $persistence = null,
private readonly ?EventDispatcherInterface $eventDispatcher = null,
PropertyInfoExtractorInterface|null $propertyInfoExtractor = null,
) {
$this->instantiator = $instantiator;

// @phpstan-ignore assign.propertyType (DNF wa shipped in PHP 8.2, so we cannot make the parameter nullable and intersection)
$this->propertyInfo = $propertyInfoExtractor ?? new PropertyInfoCacheExtractor(
new PropertyInfoExtractor(
[$reflectionExtractor = new ReflectionExtractor()],
[$reflectionExtractor],
[$reflectionExtractor],
[$reflectionExtractor],
[$reflectionExtractor],
),
new ArrayAdapter()
);
}

/**
Expand Down
17 changes: 13 additions & 4 deletions src/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,20 +174,29 @@ protected function initialize(): static
*/
final protected function normalizeAttributes(array|callable $attributes = []): array
{
$attributes = [$this->defaults(), ...$this->attributes, $attributes];
$mergedAttributes = [$this->defaults()];

// we need to pick "recycled" attributes just after "defaults()" ones
// in order to be able to override them
if ($this instanceof ObjectFactory) {
$mergedAttributes[] = $this->recycledAttributes();
}

$mergedAttributes = [...$mergedAttributes, ...$this->attributes, $attributes];

$index = 1;

// find if an index was set by factory collection
foreach ($attributes as $i => $attr) {
foreach ($mergedAttributes as $i => $attr) {
if (\is_array($attr) && isset($attr['__index'])) {
$index = $attr['__index'];
unset($attributes[$i]);
unset($mergedAttributes[$i]);
break;
}
}

return \array_merge(
...\array_map(static fn(array|callable $attr) => \is_callable($attr) ? $attr($index) : $attr, $attributes)
...\array_map(static fn(array|callable $attr) => \is_callable($attr) ? $attr($index) : $attr, $mergedAttributes)
);
}

Expand Down
55 changes: 55 additions & 0 deletions src/ObjectFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Zenstruck\Foundry;

use Symfony\Component\TypeInfo\Type;
use Zenstruck\Foundry\Object\Event\AfterInstantiate;
use Zenstruck\Foundry\Object\Event\BeforeInstantiate;
use Zenstruck\Foundry\Object\Instantiator;
Expand All @@ -35,6 +36,9 @@ abstract class ObjectFactory extends Factory
/** @phpstan-var InstantiatorCallable|null */
private $instantiator;

/** @phpstan-var array<class-string, list<object>> */
private array $recycled = [];

/**
* @return class-string<T>
*/
Expand Down Expand Up @@ -105,6 +109,57 @@ public function afterInstantiate(callable $callback): static
return $clone;
}

/**
* @psalm-return static<T>
* @phpstan-return static
*/
final public function recycle(object ...$objects): static
{
$clone = clone $this;
foreach ($objects as $object) {
$clone->recycled[$object::class] ??= [];
$clone->recycled[$object::class][] = $object;
}

return $clone;
}

protected function normalizeParameter(string $field, mixed $value): mixed
{
if ($value instanceof self) {
// propagate "recycled" objects
$value = $value->recycle(...array_merge(...array_values($this->recycled)));
}

return parent::normalizeParameter($field, $value);
}

/**
* @internal
* @phpstan-return Parameters
*/
final protected function recycledAttributes(): array
{
$attributes = [];

$propertyInfo = Configuration::instance()->propertyInfo;

$properties = $propertyInfo->getProperties(static::class());
foreach ($properties ?? [] as $property) {
$types = $propertyInfo->getTypes(static::class(), $property);

foreach ($types ?? [] as $type) {
if (isset($this->recycled[$type->getClassName()]) && count($this->recycled[$type->getClassName()])) {
$attributes[$property] = self::faker()->randomElement($this->recycled[$type->getClassName()]);

break;
}
}
}

return $attributes;
}

/**
* @internal
*/
Expand Down
90 changes: 90 additions & 0 deletions tests/Unit/RecycleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

namespace Zenstruck\Foundry\Tests\Unit;

use PHPUnit\Framework\TestCase;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Tests\Fixture\Factories\Entity\Address\AddressFactory;
use Zenstruck\Foundry\Tests\Fixture\Factories\Entity\Category\CategoryFactory;
use Zenstruck\Foundry\Tests\Fixture\Factories\Entity\Contact\ContactFactory;

final class RecycleTest extends TestCase
{
use Factories;

public function test_it_can_recycle_an_object(): void
{
$address = AddressFactory::createOne();

$contact = ContactFactory::new()
->recycle($address)
->create();

self::assertSame($address, $contact->getAddress());
}

public function test_it_can_recycle_several_objects(): void
{
$address = AddressFactory::createOne();
$category = CategoryFactory::createOne();

$contact = ContactFactory::new()
->recycle($address, $category)
->create();

self::assertSame($address, $contact->getAddress());
self::assertSame($category, $contact->getCategory());
}

public function test_it_can_call_recycle_multiple_times(): void
{
$address = AddressFactory::createOne();
$category = CategoryFactory::createOne();

$contact = ContactFactory::new()
->recycle($address)
->recycle($category)
->create();

self::assertSame($address, $contact->getAddress());
self::assertSame($category, $contact->getCategory());
}

public function test_it_recycle_the_same_object_multiple_times(): void
{
$category = CategoryFactory::createOne();

$contact = ContactFactory::new()
->recycle($category)
->create();

self::assertSame($category, $contact->getCategory());
self::assertSame($category, $contact->getSecondaryCategory());
}

public function test_it_propagate_recycled_objects(): void
{
$category = CategoryFactory::createOne();

$address = AddressFactory::new(['contact' => ContactFactory::new()])
->recycle($category)
->create();

self::assertSame($category, $address->getContact()?->getCategory());
self::assertSame($category, $address->getContact()->getSecondaryCategory());
}

public function test_it_takes_randomly_an_item_when_multiple_recycled_objects_with_same_class_exist(): void
{
$categories = CategoryFactory::createMany(2);

$address = AddressFactory::new(['contact' => ContactFactory::new()])
->recycle(...$categories)
->create();

self::assertContains($address->getContact()?->getCategory(), $categories);
self::assertContains($address->getContact()?->getSecondaryCategory(), $categories);
}
}