Completed
Push — master ( bc20b9...9515fd )
by Dmitry
02:03
created

QueueController::actionTestErrorHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace hiqdev\assetpackagist\console;
4
5
use hiqdev\assetpackagist\commands\AbstractPackageCommand;
6
use hiqdev\assetpackagist\repositories\PackageRepository;
7
use Yii;
8
use yii\base\Event;
9
use yii\console\Controller;
10
use yii\helpers\Console;
11
use zhuravljov\yii\queue\ErrorEvent;
12
use zhuravljov\yii\queue\JobEvent;
13
use zhuravljov\yii\queue\Queue;
14
15
/**
16
 * Manages service Queue
17
 * @package hiqdev\assetpackagist\console
18
 */
19
class QueueController extends Controller
20
{
21
    public function init()
22
    {
23
        $this->attachEventHandlers();
24
    }
25
26
    /**
27
     * Runs the queue in $channel
28
     * @param string $channel Channel name
29
     */
30
    public function actionRun($channel)
31
    {
32
        Yii::$app->queue->run($channel);
33
    }
34
35
    /**
36
     * Test action to ensure that ErrorHandler flushes stack immediately
37
     */
38
    public function actionTestErrorHandler()
39
    {
40
        Yii::info(Console::renderColoredString('Lorem ipsum for time %y' . time() . '%n ' . "\n"), \hiqdev\assetpackagist\commands\CollectDependenciesCommand::class);
41
        sleep(1);
42
    }
43
44
    /**
45
     * Attaches handlers on Queue events
46
     */
47
    private function attachEventHandlers()
48
    {
49
        $out = function ($string) {
50
            $this->stdout(Console::renderColoredString($string));
51
        };
52
53
        Event::on(Queue::class, Queue::EVENT_BEFORE_WORK, function ($event) use ($out) {
54
            /** @var JobEvent $event */
55
            $out("%Y[{$event->channel}]%n %GNew job%n '" . get_class($event->job) . "'\n");
56
        });
57
58
        Event::on(Queue::class, Queue::EVENT_AFTER_WORK, function ($event) use ($out) {
59
            /** @var JobEvent $event */
60
            $out("%Y[{$event->channel}]%n %GJob%n '" . get_class($event->job) . "' %Gis completed%n\n");
61
        });
62
63
        Event::on(Queue::class, Queue::EVENT_AFTER_ERROR, function ($event) use ($out) {
64
            /** @var ErrorEvent $event */
65
            $out("%Y[{$event->channel}]%n %RJob '" . get_class($event->job) . "' finished with error:%n '" . $event->error . "'\n");
66
        });
67
68
        Event::on(AbstractPackageCommand::class, AbstractPackageCommand::EVENT_BEFORE_RUN, function ($event) use ($out) {
69
            /** @var AbstractPackageCommand $command */
70
            $command = $event->sender;
71
            $out("%g[" . get_class($command) . "]%n Working on package %N" . $command->getPackage()->getFullName() . "%n\n");
72
        });
73
    }
74
}
75
76