diff --git a/docs/index.rst b/docs/index.rst index 69724435..579078db 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -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 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/Persistence/PersistenceManager.php b/src/Persistence/PersistenceManager.php index 3c1b1acf..324089ff 100644 --- a/src/Persistence/PersistenceManager.php +++ b/src/Persistence/PersistenceManager.php @@ -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; @@ -189,6 +189,8 @@ public function flushAfter(callable $callback): void $this->flush($om); } } + + return $result; } public function flush(ObjectManager $om): void diff --git a/src/Persistence/functions.php b/src/Persistence/functions.php index 69afbbf8..364c8123 100644 --- a/src/Persistence/functions.php +++ b/src/Persistence/functions.php @@ -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); } /** diff --git a/tests/Integration/Persistence/GenericFactoryTestCase.php b/tests/Integration/Persistence/GenericFactoryTestCase.php index ec3071bc..af504f9c 100644 --- a/tests/Integration/Persistence/GenericFactoryTestCase.php +++ b/tests/Integration/Persistence/GenericFactoryTestCase.php @@ -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); } /**