Completed
Push — master ( e47027...b0b769 )
by Biao
03:37
created

BaseTask::task()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 23
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 31
rs 8.6186
1
<?php
2
3
namespace Hhxsv5\LaravelS\Swoole\Task;
4
5
use Swoole\Timer;
6
7
abstract class BaseTask
8
{
9
    /**
10
     * The number of seconds before the task should be delayed.
11
     *
12
     * @var int|null
13
     */
14
    protected $delay;
15
16
    public function delay($delay)
17
    {
18
        if ($delay !== null && $delay <= 0) {
19
            throw new \InvalidArgumentException('The delay must be greater than 0');
20
        }
21
        $this->delay = $delay;
22
        return $this;
23
    }
24
25
    /**
26
     * Delay in seconds, null means no delay.
27
     * @return int|null
28
     */
29
    public function getDelay()
30
    {
31
        return $this->delay;
32
    }
33
34
    /**
35
     * Deliver a task
36
     * @param mixed $task The task object
37
     * @return bool|mixed
38
     */
39
    protected function task($task)
40
    {
41
        $deliver = function () use ($task) {
42
            /**@var \Swoole\Http\Server $swoole */
43
            $swoole = app('swoole');
44
            if ($swoole->taskworker) {
45
                $taskWorkerNum = isset($swoole->setting['task_worker_num']) ? (int)$swoole->setting['task_worker_num'] : 0;
46
                if ($taskWorkerNum < 2) {
47
                    throw new \InvalidArgumentException('LaravelS: async task needs to set task_worker_num >= 2');
48
                }
49
                $workerNum = isset($swoole->setting['worker_num']) ? $swoole->setting['worker_num'] : 0;
50
                $totalNum = $workerNum + $taskWorkerNum;
51
52
                $getAvailableId = function ($startId, $endId, $excludeId) {
53
                    $ids = range($startId, $endId);
54
                    $ids = array_flip($ids);
55
                    unset($ids[$excludeId]);
56
                    return array_rand($ids);
57
                };
58
                $availableId = $getAvailableId($workerNum, $totalNum - 1, $swoole->worker_id);
59
                return $swoole->sendMessage($task, $availableId);
60
            } else {
61
                $taskId = $swoole->task($task);
62
                return $taskId !== false;
63
            }
64
        };
65
        if ($this->delay !== null && $this->delay > 0) {
66
            Timer::after($this->delay * 1000, $deliver);
67
            return true;
68
        } else {
69
            return $deliver();
70
        }
71
    }
72
}