Completed
Push — master ( 8a9369...6732b2 )
by kacper
04:04
created

AsyncCall::run()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 4
nop 5
1
<?php
2
3
4
namespace Async;
5
6
use SuperClosure\Serializer;
7
use Symfony\Component\Console\Exception\InvalidArgumentException;
8
9
/**
10
 * Class AsyncCall
11
 * @package Async
12
 */
13
class AsyncCall
14
{
15
    const CONSOLE_EXECUTE = 'php ' . __DIR__ . '/../../bin/console app:run-child-process ';
16
17
    /**
18
     * @var bool
19
     */
20
    private static $shutdownFunctionRegistered = false;
21
    /**
22
     * @var AsyncProcess[]
23
     */
24
    private static $processList = [];
25
    /**
26
     * @var Serializer
27
     */
28
    private static $serializer;
29
    /**
30
     * @var int
31
     */
32
    private static $processesLimit = 0;
33
34
    /**
35
     * @param $processesLimit
36
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
37
     */
38
    public static function setProcessLimit($processesLimit)
39
    {
40
        if ($processesLimit < 0) {
41
            throw new InvalidArgumentException('Processes limit Must be possitive itiger');
42
        }
43
        self::$processesLimit = (int)$processesLimit;
44
    }
45
46
    /**
47
     * @param callable $job
48
     * @param callable $callback
49
     * @param callable $onError
50
     * @param float $timeout
51
     * @param float $idleTimeout
52
     * @throws \Symfony\Component\Process\Exception\InvalidArgumentException
53
     * @throws \Symfony\Component\Process\Exception\RuntimeException
54
     * @throws \Symfony\Component\Process\Exception\LogicException
55
     * @throws \RuntimeException
56
     */
57
    public static function run(
58
        callable $job,
59
        callable $callback = null,
60
        callable $onError = null,
61
        $timeout = null,
62
        $idleTimeout = null
63
    ) {
64
        self::registerShutdownFunction();
65
66
        if (!self::$serializer) {
67
            self::$serializer = new Serializer();
68
        }
69
70
        // we got process limit so wait for them to finish
71
        if (0 !== self::$processesLimit && self::$processesLimit >= count(self::$processList)) {
72
            self::waitForProcessesToFinish(self::$processesLimit);
73
        }
74
75
        $process = new AsyncProcess(self::CONSOLE_EXECUTE . base64_encode(self::$serializer->serialize($job)));
0 ignored issues
show
Documentation introduced by
$job is of type callable, but the function expects a object<Closure>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
        $process->setTimeout($timeout);
77
        $process->setIdleTimeout($idleTimeout);
78
        $process->startJob($callback, $onError);
79
80
        //echo $process->getCommandLine() . PHP_EOL;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
        self::$processList[] = $process;
82
    }
83
84
    private static function registerShutdownFunction()
85
    {
86
        if (!self::$shutdownFunctionRegistered) {
87
            register_shutdown_function(
88
                function () {
89
                    self::waitForProcessesToFinish();
90
                }
91
            );
92
            self::$shutdownFunctionRegistered = true;
93
        }
94
    }
95
96
    /**
97
     * @param int $maxProcessToWait
98
     */
99
    private static function waitForProcessesToFinish($maxProcessToWait = 0)
100
    {
101
        while (true) {
102
            $processAmount = count(self::$processList);
103
104
            if (0 === $processAmount) {
105
                break;
106
            }
107
            if ($maxProcessToWait > $processAmount) {
108
                break;
109
            }
110
111
            foreach (self::$processList as $i => $process) {
112
                if ($process->getStatus() === AsyncProcess::STATUS_TERMINATED || (!$process->hasCallbackSet() && !$process->hasOnErrorSet())) {
113
                    unset(self::$processList[$i]);
114
                    continue;
115
                }
116
            }
117
        }
118
    }
119
}