From cb717952f1fe85d0e02ca318c60048e86d8f1de9 Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Mon, 27 Mar 2017 11:42:11 -0500 Subject: [PATCH] Validate number of required promises --- lib/functions.php | 12 ++++++++++-- test/SomeTest.php | 18 +++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/functions.php b/lib/functions.php index 1c0a24e..14ed607 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -445,12 +445,20 @@ namespace Amp\Promise { * @throws \Error If a non-Promise is in the array. */ function some(array $promises, int $required = 1): Promise { - if (empty($promises)) { - return new Success([[], []]); + if ($required < 0) { + throw new \Error("Number of promises required must be non-negative"); } $pending = \count($promises); + if ($required > $pending) { + throw new \Error("Too few promises provided"); + } + + if (empty($promises)) { + return new Success([[], []]); + } + $deferred = new Deferred; $values = []; $exceptions = []; diff --git a/test/SomeTest.php b/test/SomeTest.php index 8271a9d..e822bac 100644 --- a/test/SomeTest.php +++ b/test/SomeTest.php @@ -11,7 +11,23 @@ use Amp\Loop; class SomeTest extends \PHPUnit\Framework\TestCase { public function testEmptyArray() { - $this->assertSame([[], []], Promise\wait(Promise\some([]))); + $this->assertSame([[], []], Promise\wait(Promise\some([], 0))); + } + + /** + * @expectedException \Error + * @expectedExceptionMessage Too few promises provided + */ + public function testEmptyArrayWithNonZeroRequired() { + Promise\some([], 1); + } + + /** + * @expectedException \Error + * @expectedExceptionMessage non-negative + */ + public function testInvalidRequiredNumberOfPromises() { + Promise\some([], -1); } public function testSuccessfulPromisesArray() {