Completed
Push — master ( 60d32e...f4448b )
by Vuong
06:35
created

Async::setSleepTimeWait()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @link https://github.com/vuongxuongminh/yii2-async
4
 * @copyright Copyright (c) 2019 Vuong Xuong Minh
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace vxm\async;
9
10
use Yii;
11
use Closure;
12
use Throwable;
13
14
use yii\base\Component;
15
16
use Spatie\Async\Pool;
17
use Spatie\Async\Runtime\ParentRuntime;
18
19
/**
20
 * Support run code async. To use it, you just config it to your application components in configure file:
21
 *
22
 * ```php
23
 * 'components' => [
24
 *      'async' => 'vxm\async\Async'
25
 * ]
26
 *
27
 * ```
28
 *
29
 * And after that you can run an async code:
30
 *
31
 * ```php
32
 *
33
 * Yii::$app->async->run(function () {
34
 *
35
 *      sleep(15);
36
 * });
37
 *
38
 * ```
39
 *
40
 * If you want to wait until task done, you just to call [[wait]].
41
 *
42
 * ```php
43
 *
44
 * Yii::$app->async->run(function () {
45
 *
46
 *      sleep(15);
47
 * })->wait();
48
 *
49
 * ```
50
 *
51
 * Run multi tasks:
52
 *
53
 * ```php
54
 *
55
 * Yii::$app->async->run(function () {
56
 *
57
 *      sleep(15);
58
 * });
59
 *
60
 * Yii::$app->async->run(function () {
61
 *
62
 *      sleep(15);
63
 * });
64
 *
65
 * Yii::$app->async->wait(); // sleep 30s
66
 * ```
67
 *
68
 * @property string $autoload path of autoload file for runtime task execute environment.
69
 * @property int $sleepTimeWait time to sleep on wait tasks execute.
70
 * @property int $concurrency tasks executable.
71
 * @property int $timeout of task executable.
72
 *
73
 * @author Vuong Minh <[email protected]>
74
 * @since 1.0.0
75
 */
76
class Async extends Component
77
{
78
79
    /**
80
     * @event SuccessEvent an event that is triggered when task done.
81
     */
82
    const EVENT_SUCCESS = 'success';
83
84
    /**
85
     * @event ErrorEvent an event that is triggered when task error.
86
     */
87
    const EVENT_ERROR = 'error';
88
89
    /**
90
     * @event \yii\base\Event an event that is triggered when task timeout.
91
     */
92
    const EVENT_TIMEOUT = 'timeout';
93
94
    /**
95
     * @var Pool handling tasks.
96
     */
97
    protected $pool;
98
99
    /**
100
     * Async constructor.
101
     *
102
     * @param array $config
103
     * @throws \yii\base\InvalidConfigException
104
     */
105 4
    public function __construct($config = [])
106
    {
107 4
        $pool = $this->pool = Yii::createObject(Pool::class);
108 4
        $pool->autoload(__DIR__ . '/RuntimeAutoload.php');
109
110 4
        parent::__construct($config);
111 4
    }
112
113
    /**
114
     * Execute async task.
115
     *
116
     * @param callable|\Spatie\Async\Task|Task $callable need to execute.
117
     * @param array $callbacks event. Have key is an event name, value is a callable triggered when event happen,
118
     * have three events `error`, `success`, `timeout`.
119
     * @return static
120
     * @throws \yii\base\InvalidConfigException
121
     */
122 4
    public function run($callable, array $callbacks = []): self
123
    {
124 4
        $task = Yii::createObject([
125 4
            'class' => ChildRuntimeTask::class,
126 4
            'app' => Yii::$app,
127 4
            'callable' => $callable
128
        ]);
129 4
        $process = ParentRuntime::createProcess($task)
130 4
            ->then(Closure::fromCallable([$this, 'success']))
131 4
            ->catch(Closure::fromCallable([$this, 'error']))
132 4
            ->timeout(Closure::fromCallable([$this, 'timeout']));
133
134 4
        foreach ($callbacks as $name => $callback) {
135
136 2
            switch (strtolower($name)) {
137 2
                case 'success':
138 1
                    $process->then($callback);
139 1
                    break;
140 1
                case 'error':
141 1
                case 'catch':
142
                    $process->catch($callback);
143
                    break;
144 1
                case 'timeout':
145 1
                    $process->timeout($callback);
146 1
                    break;
147
                default:
148 2
                    break;
149
            }
150
151
        }
152
153 4
        $this->pool->add($process);
154
155 4
        return $this;
156
    }
157
158
    /**
159
     * This method is called when task executed success.
160
     * When overriding this method, make sure you call the parent implementation to ensure the
161
     * event is triggered.
162
     *
163
     * @param mixed $output of task executed.
164
     * @throws \yii\base\InvalidConfigException
165
     */
166
    public function success($output): void
167
    {
168
        $event = Yii::createObject([
169
            'class' => SuccessEvent::class,
170
            'output' => $output
171
        ]);
172
173
        $this->trigger(self::EVENT_SUCCESS, $event);
174
    }
175
176
    /**
177
     * This method is called when task executed error.
178
     * When overriding this method, make sure you call the parent implementation to ensure the
179
     * event is triggered.
180
     *
181
     * @param Throwable $throwable when executing task.
182
     * @throws \yii\base\InvalidConfigException
183
     */
184 3
    public function error(Throwable $throwable): void
185
    {
186 3
        $event = Yii::createObject([
187 3
            'class' => ErrorEvent::class,
188 3
            'throwable' => $throwable
189
        ]);
190
191 3
        $this->trigger(self::EVENT_ERROR, $event);
192 3
    }
193
194
    /**
195
     * This method is called when task executed timeout.
196
     * When overriding this method, make sure you call the parent implementation to ensure the
197
     * event is triggered.
198
     *
199
     * @throws \yii\base\InvalidConfigException
200
     */
201
    public function timeout(): void
202
    {
203
        $event = Yii::createObject(Event::class);
204
205
        $this->trigger(self::EVENT_TIMEOUT, $event);
206
    }
207
208
    /**
209
     * Wait until all tasks done.
210
     */
211 3
    public function wait(): void
212
    {
213 3
        $this->pool->wait();
214 3
    }
215
216
    /**
217
     * Set concurrency process do tasks.
218
     *
219
     * @param int $concurrency
220
     */
221
    public function setConcurrency(int $concurrency): void
222
    {
223
        $this->pool->concurrency($concurrency);
224
    }
225
226
    /**
227
     * Set timeout of task when execute.
228
     *
229
     * @param int $timeout
230
     */
231 4
    public function setTimeout(int $timeout): void
232
    {
233 4
        $this->pool->timeout($timeout);
234 4
    }
235
236
    /**
237
     * Set sleep time when wait tasks execute.
238
     *
239
     * @param int $sleepTimeWait
240
     */
241
    public function setSleepTimeWait(int $sleepTimeWait): void
242
    {
243
        $this->pool->sleepTime($sleepTimeWait);
244
    }
245
246
    /**
247
     * Set autoload for environment tasks execute.
248
     * @param string $autoload
249
     */
250
    public function setAutoload(string $autoload): void
251
    {
252
        $this->pool->autoload(Yii::getAlias($autoload));
0 ignored issues
show
Bug introduced by
It seems like \Yii::getAlias($autoload) targeting yii\BaseYii::getAlias() can also be of type boolean; however, Spatie\Async\Pool::autoload() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
253
    }
254
255
}
256