Skip to content

Commit

Permalink
Have flush_after() return the callback's return (#691)
Browse files Browse the repository at this point in the history
  • Loading branch information
HypeMC authored Aug 29, 2024
1 parent 33d5870 commit 3eebbf9
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 7 deletions.
10 changes: 10 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1003,6 +1003,16 @@ once. To do this, wrap the operations in a ``flush_after()`` callback:
TagFactory::createMany(200); // instantiated/persisted but not flushed
}); // single flush

The ``flush_after()`` function forwards the callback’s return, in case you need to use the objects in your tests:

::

use function Zenstruck\Foundry\Persistence\flush_after;

[$category, $tag] = flush_after(fn() => [
CategoryFactory::createOne(),
TagFactory::createOne(),
]);

Not-persisted objects factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
8 changes: 5 additions & 3 deletions src/Persistence/PersistenceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,13 @@ public function save(object $object): object
}

/**
* @param callable():void $callback
* @param callable():mixed $callback
*/
public function flushAfter(callable $callback): void
public function flushAfter(callable $callback): mixed
{
$this->flush = false;

$callback();
$result = $callback();

$this->flush = true;

Expand All @@ -189,6 +189,8 @@ public function flushAfter(callable $callback): void
$this->flush($om);
}
}

return $result;
}

public function flush(ObjectManager $om): void
Expand Down
6 changes: 3 additions & 3 deletions src/Persistence/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,11 @@ function delete(object $object): object
}

/**
* @param callable():void $callback
* @param callable():mixed $callback
*/
function flush_after(callable $callback): void
function flush_after(callable $callback): mixed
{
Configuration::instance()->persistence()->flushAfter($callback);
return Configuration::instance()->persistence()->flushAfter($callback);
}

/**
Expand Down
6 changes: 5 additions & 1 deletion tests/Integration/Persistence/GenericFactoryTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -435,16 +435,20 @@ public function flush_after(): void
{
$this->factory()::repository()->assert()->empty();

flush_after(function() {
$object = null;
$return = flush_after(function() use (&$object) {
$object = $this->factory()::createOne();

// ensure auto-refresh does not break when in flush_after
$object->getProp1();

$this->factory()::repository()->assert()->empty();

return $object;
});

$this->factory()::repository()->assert()->count(1);
self::assertSame($object, $return);
}

/**
Expand Down

0 comments on commit 3eebbf9

Please sign in to comment.