From 634a4be38de72f3ba340c3242ad79fd937503375 Mon Sep 17 00:00:00 2001 From: Brent Roose Date: Tue, 27 Apr 2021 15:27:31 +0200 Subject: [PATCH] Add serializer support --- README.md | 10 ++++++++++ src/Task.php | 20 +++++++++++++++++--- tests/ForkTest.php | 14 ++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8ce0fd3..4670a9b 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,16 @@ $results = Fork::new() ); ``` +Finally, return values from child tasks are serialized using PHP's built-in `serialize` method. This means that you can return anything you can normally serialize in PHP, including objects: + +```php +$result = Fork::new() + ->run( + fn () => new DateTime('2021-01-01'), + fn () => new DateTime('2021-01-02'), + ); +``` + ## Testing ```bash diff --git a/src/Task.php b/src/Task.php index c342f6f..6640757 100644 --- a/src/Task.php +++ b/src/Task.php @@ -7,6 +7,8 @@ class Task { + protected const SERIALIZATION_TOKEN = '[[serialized::'; + protected string $name; protected int $order; @@ -89,10 +91,14 @@ public function execute(): string | bool { $output = ($this->callable)(); - return json_encode($output); + if (is_string($output)) { + return $output; + } + + return self::SERIALIZATION_TOKEN . serialize($output); } - public function output(): ?string + public function output(): mixed { foreach ($this->connection->read() as $output) { $this->output .= $output; @@ -102,7 +108,15 @@ public function output(): ?string $this->triggerSuccessCallback(); - return $this->output; + $output = $this->output; + + if (str_starts_with($output, self::SERIALIZATION_TOKEN)) { + $output = unserialize( + substr($output, strlen(self::SERIALIZATION_TOKEN)) + ); + } + + return $output; } public function onSuccess(callable $callback): self diff --git a/tests/ForkTest.php b/tests/ForkTest.php index cbf2f6c..653b5c3 100644 --- a/tests/ForkTest.php +++ b/tests/ForkTest.php @@ -2,6 +2,7 @@ namespace Spatie\Fork\Tests; +use DateTime; use PHPUnit\Framework\TestCase; use Spatie\Fork\Fork; @@ -141,6 +142,19 @@ public function it_will_not_hang_by_truncating_the_result_when_large_output_is_r $this->assertCount(3, $result); } + /** @test */ + public function it_can_return_objects() + { + $result = Fork::new() + ->run( + fn () => new DateTime('2021-01-01'), + fn () => new DateTime('2021-01-02'), + ); + + $this->assertEquals('2021-01-01', $result[0]->format('Y-m-d')); + $this->assertEquals('2021-01-02', $result[1]->format('Y-m-d')); + } + /** @test */ public function output_in_after() {