diff --git a/CHANGELOG.md b/CHANGELOG.md index da3f9fdc4..a3e0433d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ - [#1303](https://github.com/hyperf/hyperf/pull/1303) Deleted useless `$httpMethod` for `Hyperf\RpcServer\Router\Router`. +## Fixed + +- [#1330](https://github.com/hyperf/hyperf/pull/1330) Fixed bug when using `(new Parallel())->add($callback, $key)` and the parameter `$key` is a not string index, the returned result will sort `$key` from 0. + # v1.1.17 - 2020-01-24 ## Added diff --git a/src/utils/src/Parallel.php b/src/utils/src/Parallel.php index 3f7193c61..589e28557 100644 --- a/src/utils/src/Parallel.php +++ b/src/utils/src/Parallel.php @@ -39,10 +39,10 @@ class Parallel public function add(callable $callable, $key = null) { - if (is_string($key)) { - $this->callbacks[$key] = $callable; - } else { + if (is_null($key)) { $this->callbacks[] = $callable; + } else { + $this->callbacks[$key] = $callable; } } diff --git a/src/utils/tests/ParallelTest.php b/src/utils/tests/ParallelTest.php index 06632c9dc..a1e1b66fc 100644 --- a/src/utils/tests/ParallelTest.php +++ b/src/utils/tests/ParallelTest.php @@ -117,6 +117,39 @@ class ParallelTest extends TestCase $this->assertEquals(count($res), 4); } + public function testParallelKeys() + { + $parallel = new Parallel(); + $callback = function () { + return 1; + }; + for ($i = 0; $i < 4; ++$i) { + $parallel->add($callback); + } + $res = $parallel->wait(); + $parallel->clear(); + $this->assertSame([1, 1, 1, 1], $res); + + for ($i = 0; $i < 4; ++$i) { + $parallel->add($callback, 'id_' . $i); + } + $res = $parallel->wait(); + $parallel->clear(); + $this->assertSame(['id_0' => 1, 'id_1' => 1, 'id_2' => 1, 'id_3' => 1], $res); + + for ($i = 0; $i < 4; ++$i) { + $parallel->add($callback, $i - 1); + } + $res = $parallel->wait(); + $parallel->clear(); + $this->assertSame([-1 => 1, 0 => 1, 1 => 1, 2 => 1], $res); + + $parallel->add($callback, 1.0); + $res = $parallel->wait(); + $parallel->clear(); + $this->assertSame([1.0 => 1], $res); + } + public function testParallelThrows() { $parallel = new Parallel();