From 86873515aed6d0535975dc39bd55e6e501d36fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0tancl?= Date: Thu, 12 Nov 2020 19:33:31 +0100 Subject: [PATCH] Allow canceling pipelines by returning false from handle() --- docker-compose.yml | 0 src/JobPipeline.php | 6 ++++- tests/JobPipelineTest.php | 40 ++++++++++++++++++++++++++++++++++ tests/tmp/jobpipelinetest.json | 1 + 4 files changed, 46 insertions(+), 1 deletion(-) delete mode 100644 docker-compose.yml diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index e69de29..0000000 diff --git a/src/JobPipeline.php b/src/JobPipeline.php index 087f849..5559b89 100644 --- a/src/JobPipeline.php +++ b/src/JobPipeline.php @@ -57,7 +57,11 @@ class JobPipeline implements ShouldQueue public function handle(): void { foreach ($this->jobs as $job) { - app()->call([new $job(...$this->passable), 'handle']); + $result = app()->call([new $job(...$this->passable), 'handle']); + + if ($result === false) { + break; + } } } diff --git a/tests/JobPipelineTest.php b/tests/JobPipelineTest.php index 91626ba..abbbee6 100644 --- a/tests/JobPipelineTest.php +++ b/tests/JobPipelineTest.php @@ -75,6 +75,8 @@ class JobPipelineTest extends TestCase event(new TestEvent(new TestModel())); $this->artisan('queue:work --once'); + sleep(1); + $this->assertSame('bar', $this->valuestore->get('foo')); } @@ -110,6 +112,27 @@ class JobPipelineTest extends TestCase $this->assertSame(['a', 'b'], app('test_args')); } + + /** @test */ + public function the_pipeline_can_be_canceled_by_returning_false_from_any_job() + { + Event::listen(TestEvent::class, JobPipeline::make([ + FalseJob::class, + FooJob::class, + ])->send(function () { + return $this->valuestore; + })->shouldBeQueued(true)->toListener()); + + event(new TestEvent(new TestModel())); + $this->artisan('queue:work --once'); + + sleep(1); + + $this->assertTrue($this->valuestore->get('false_job_executed')); + + // Foo job is not excuted + $this->assertFalse($this->valuestore->has('foo')); + } } class FooJob @@ -193,3 +216,20 @@ class JobWithMultipleArguments app()->instance('test_args', [$this->first, $this->second]); } } + +class FalseJob +{ + protected $valuestore; + + public function __construct(Valuestore $valuestore) + { + $this->valuestore = $valuestore; + } + + public function handle() + { + $this->valuestore->put('false_job_executed', true); + + return false; + } +} diff --git a/tests/tmp/jobpipelinetest.json b/tests/tmp/jobpipelinetest.json index e69de29..9ae3f94 100644 --- a/tests/tmp/jobpipelinetest.json +++ b/tests/tmp/jobpipelinetest.json @@ -0,0 +1 @@ +{"false_job_executed":true} \ No newline at end of file