Skip to content

Commit

Permalink
Add serializer support
Browse files Browse the repository at this point in the history
  • Loading branch information
brendt committed Apr 27, 2021
1 parent 1399068 commit 634a4be
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions src/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

class Task
{
protected const SERIALIZATION_TOKEN = '[[serialized::';

protected string $name;

protected int $order;
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/ForkTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\Fork\Tests;

use DateTime;
use PHPUnit\Framework\TestCase;
use Spatie\Fork\Fork;

Expand Down Expand Up @@ -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()
{
Expand Down

0 comments on commit 634a4be

Please sign in to comment.