Completed
Push — master ( e85667...590689 )
by Alexey
37:35
created

CommandTrait::predis()   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 72
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 72
rs 6.3883
c 0
b 0
f 0
cc 8
eloc 31
nc 2
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace yiicod\socketio\commands;
4
5
use Symfony\Component\Process\Process;
6
use Yii;
7
use yii\helpers\ArrayHelper;
8
use yii\helpers\Console;
9
use yii\helpers\Json;
10
use yiicod\socketio\Broadcast;
11
12
trait CommandTrait
13
{
14
    /**
15
     * @var string
16
     */
17
    public $server = 'locahost:1212';
18
19
    /**
20
     * [
21
     *     key => 'path to key',
22
     *     cert => 'path to cert',
23
     * ]
24
     *
25
     * @var array
26
     */
27
    public $ssl = [];
28
29
    /**
30
     * Process job by id and connection
31
     */
32
    public function actionProcess($handler, $data)
33
    {
34
        Broadcast::process($handler, @unserialize($data) ?? []);
35
    }
36
37
    public function nodejs()
38
    {
39
        // Automatically send every new message to available log routes
40
        Yii::getLogger()->flushInterval = 1;
41
42
        $cmd = sprintf('node %s/%s', realpath(dirname(__FILE__) . '/../server'), 'index.js');
43
        $args = array_filter([
44
            'server' => $this->server,
45
            'pub' => json_encode(array_filter([
46
                'host' => Broadcast::getDriver()->hostname,
47
                'port' => Broadcast::getDriver()->port,
48
                'password' => Broadcast::getDriver()->password,
49
            ])),
50
            'sub' => json_encode(array_filter([
51
                'host' => Broadcast::getDriver()->hostname,
52
                'port' => Broadcast::getDriver()->port,
53
                'password' => Broadcast::getDriver()->password,
54
            ])),
55
            'channels' => implode(',', Broadcast::channels()),
56
            'nsp' => Broadcast::getManager()->nsp,
57
            'ssl' => empty($this->ssl) ? null : json_encode($this->ssl),
58
            'runtime' => Yii::getAlias('@runtime/logs'),
59
        ], 'strlen');
60
        foreach ($args as $key => $value) {
61
            $cmd .= ' -' . $key . '=\'' . $value . '\'';
62
        }
63
64
        $process = new Process($cmd);
65
66
        return $process;
67
    }
68
69
    /**
70
     * Predis proccess
71
     */
72
    public function predis()
73
    {
74
        $pubSubLoop = function () {
75
            $client = Broadcast::getDriver()->getConnection(true);
76
77
            // Initialize a new pubsub consumer.
78
            $pubsub = $client->pubSubLoop();
79
80
            $channels = [];
81
            foreach (Broadcast::channels() as $key => $channel) {
82
                $channels[$key] = $channel . '.io';
83
            }
84
85
            // Subscribe to your channels
86
            $pubsub->subscribe(ArrayHelper::merge(['control_channel'], $channels));
87
88
            // Start processing the pubsup messages. Open a terminal and use redis-cli
89
            // to push messages to the channels. Examples:
90
            //   ./redis-cli PUBLISH notifications "this is a test"
91
            //   ./redis-cli PUBLISH control_channel quit_loop
92
            foreach ($pubsub as $message) {
0 ignored issues
show
Bug introduced by
The expression $pubsub of type object<Predis\PubSub\Consumer>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
93
                switch ($message->kind) {
94
                    case 'subscribe':
95
                        $this->output("Subscribed to {$message->channel}\n");
0 ignored issues
show
Bug introduced by
It seems like output() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
96
                        break;
97
                    case 'message':
98
                        if ('control_channel' == $message->channel) {
99
                            if ('quit_loop' == $message->payload) {
100
                                $this->output("Aborting pubsub loop...\n", Console::FG_RED);
0 ignored issues
show
Bug introduced by
It seems like output() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
101
                                $pubsub->unsubscribe();
102
                            } else {
103
                                $this->output("Received an unrecognized command: {$message->payload}\n", Console::FG_RED);
0 ignored issues
show
Bug introduced by
It seems like output() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
104
                            }
105
                        } else {
106
                            $payload = Json::decode($message->payload);
107
                            $data = $payload['data'] ?? [];
108
109
//                            $pid = pcntl_fork();
110
//                            if ($pid == -1) {
111
//                                exit('Error while forking process.');
112
//                            } elseif ($pid) {
113
//                                //parent. Wait for the child and continues
114
//                                pcntl_wait($status);
115
//                                $exitStatus = pcntl_wexitstatus($status);
116
//                                if ($exitStatus !== 0) {
117
//                                    //put job back to queue or other stuff
118
//                                }
119
//                            }else {
120
                            Broadcast::on($payload['name'], $data);
121
//                                Yii::$app->end();
122
//                            }
123
                            // Received the following message from {$message->channel}:") {$message->payload}";
124
                        }
125
                        break;
126
                }
127
            }
128
129
            // Always unset the pubsub consumer instance when you are done! The
130
            // class destructor will take care of cleanups and prevent protocol
131
            // desynchronizations between the client and the server.
132
            unset($pubsub);
133
        };
134
135
        // Auto recconnect on redis timeout
136
        try {
137
            $pubSubLoop();
138
        } catch (\Predis\Connection\ConnectionException $e) {
139
            $pubSubLoop();
140
        }
141
142
        return true;
143
    }
144
}
145