Race   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 18
c 1
b 0
f 1
dl 0
loc 56
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A race() 0 28 4
A rpInterrupt() 0 5 4
A rpException() 0 3 2
1
<?php
2
/**
3
 * Race
4
 * User: moyo
5
 * Date: 04/08/2017
6
 * Time: 12:26 AM
7
 */
8
9
namespace Carno\Promise\Features;
10
11
use Carno\Promise\Exception\RacingLoser;
12
use Carno\Promise\Promise;
13
use Carno\Promise\Promised;
14
use Carno\Promise\Stacked;
15
use Throwable;
16
17
trait Race
18
{
19
    /**
20
     * @param Promised ...$promises
21
     * @return Promised
22
     */
23
    public static function race(Promised ...$promises) : Promised
24
    {
25
        /**
26
         * @var Promise $race
27
         */
28
29
        $race = Promise::deferred();
30
31
        $sid = Stacked::in(...$promises);
32
33
        foreach ($promises as $promise) {
34
            $promise->then(static function (...$args) use ($race, $sid) {
35
                if ($race->pended()) {
36
                    $race->resolve(...$args);
37
                    $race->rpInterrupt($sid);
38
                }
39
            }, static function (...$args) use ($race) {
40
                if ($race->pended()) {
41
                    $race->reject(...$args);
42
                }
43
            });
44
        }
45
46
        $race->then(null, static function (...$args) use ($race, $sid) {
47
            $race->rpInterrupt($sid, $race->rpException(...$args));
0 ignored issues
show
Bug introduced by
$args is expanded, but the parameter $test of Carno\Promise\Promise::rpException() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

47
            $race->rpInterrupt($sid, $race->rpException(/** @scrutinizer ignore-type */ ...$args));
Loading history...
48
        });
49
50
        return $race;
51
    }
52
53
    /**
54
     * @param int $sid
55
     * @param Throwable $e
56
     */
57
    private function rpInterrupt(int $sid, Throwable $e = null) : void
58
    {
59
        foreach (Stacked::out($sid) as $promised) {
60
            if ($promised->pended()) {
61
                $e ? $promised->throw($e) : $promised->reject();
62
            }
63
        }
64
    }
65
66
    /**
67
     * @param mixed $test
68
     * @return Throwable
69
     */
70
    private function rpException($test = null) : Throwable
71
    {
72
        return $test instanceof Throwable ? $test : new RacingLoser();
73
    }
74
}
75