Completed
Push — master ( 43053a...930904 )
by Vasily
02:43
created

Pool   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 330
Duplicated Lines 5.76 %

Coupling/Cohesion

Components 2
Dependencies 5

Importance

Changes 0
Metric Value
dl 19
loc 330
rs 6.96
c 0
b 0
f 0
wmc 53
lcom 2
cbo 5

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 5
A init() 0 3 1
A onReady() 0 4 1
A onConfigUpdated() 0 14 4
B applyConfig() 0 18 8
A getConfigDefaults() 0 4 1
B getInstance() 0 25 9
A setConnectionClass() 0 4 1
A enable() 0 8 2
A disable() 0 8 2
A onEnable() 0 3 1
A onDisable() 0 3 1
A onShutdown() 0 4 1
A onFinish() 0 3 1
A finish() 0 23 5
A attach() 10 11 4
A detach() 9 10 4
A connect() 0 9 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Pool often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Pool, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace PHPDaemon\Network;
3
4
use PHPDaemon\BoundSocket;
5
use PHPDaemon\Config;
6
use PHPDaemon\Core\Daemon;
7
use PHPDaemon\Core\EventLoop;
8
use PHPDaemon\Structures\ObjectStorage;
9
use PHPDaemon\Thread;
10
use PHPDaemon\Traits\EventLoopContainer;
11
12
/**
13
 * Pool of connections
14
 * @package PHPDaemon\Network
15
 * @author  Vasily Zorin <[email protected]>
16
 */
17
abstract class Pool extends ObjectStorage
18
{
19
20
    use EventLoopContainer;
21
22
    /**
23
     * @var string Default connection class
24
     */
25
    public $connectionClass;
26
27
    /**
28
     * @var string Name
29
     */
30
    public $name;
31
32
    /**
33
     * @var \PHPDaemon\Config\Section Configuration
34
     */
35
    public $config;
36
37
    /**
38
     * @var ConnectionPool[] Instances storage
39
     */
40
    protected static $instances = [];
41
42
    /**
43
     * @var integer Max concurrency
44
     */
45
    public $maxConcurrency = 0;
46
47
    /**
48
     * @var integer Max allowed packet
49
     */
50
    public $maxAllowedPacket = 0;
51
52
    /**
53
     * @var boolean Is finished?
54
     */
55
    protected $finished = false;
56
57
    /**
58
     * @var boolean Is enabled?
59
     */
60
    protected $enabled = false;
61
62
    /**
63
     * @var boolean Is overloaded?
64
     */
65
    protected $overload = false;
66
67
    /**
68
     * @var object|null Application instance object
69
     */
70
    public $appInstance;
71
72
    /**
73
     * Constructor
74
     * @param $config Config variables
75
     * @param boolean $init
76
     */
77
    public function __construct($config = [], $init = true)
78
    {
79
        if (is_array($config)) {
80
            $config = new Config\Section($config);
81
        }
82
        $this->config = $config;
83
        if ($this->connectionClass === null) {
84
            $e = explode('\\', get_class($this));
85
            $e[sizeof($e) - 1] = 'Connection';
86
            $this->connectionClass = '\\' . implode('\\', $e);
87
        }
88
        if ($this->eventLoop === null) {
89
            $this->eventLoop = EventLoop::$instance;
90
        }
91
        $this->onConfigUpdated();
92
        if ($init) {
93
            $this->init();
94
        }
95
    }
96
97
98
    /**
99
     * Init
100
     * @return void
101
     */
102
    protected function init()
103
    {
104
    }
105
106
    /**
107
     * Called when the worker is ready to go
108
     * @return void
109
     */
110
    public function onReady()
111
    {
112
        $this->enable();
113
    }
114
115
    /**
116
     * Called when worker is going to update configuration
117
     * @return void
118
     */
119
    public function onConfigUpdated()
120
    {
121
        if (Daemon::$process instanceof Thread\Worker) {
122
            if ($this->config === null) {
123
                $this->disable();
124
            } else {
125
                $this->enable();
126
            }
127
        }
128
        if ($defaults = $this->getConfigDefaults()) {
129
            $this->config->imposeDefault($defaults);
0 ignored issues
show
Documentation introduced by
$defaults is of type boolean, but the function expects a array.

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...
130
        }
131
        $this->applyConfig();
132
    }
133
134
    /**
135
     * Applies config
136
     * @return void
137
     */
138
    protected function applyConfig()
139
    {
140
        foreach ($this->config as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $this->config of type object<PHPDaemon\Config\Section> is not traversable.
Loading history...
141
            if (is_object($v) && $v instanceof Config\Entry\Generic) {
142
                $v = $v->getValue();
143
            }
144
            $k = strtolower($k);
145
            if ($k === 'connectionclass') {
146
                $this->connectionClass = $v;
147
            } elseif ($k === 'name') {
148
                $this->name = $v;
149
            } elseif ($k === 'maxallowedpacket') {
150
                $this->maxAllowedPacket = (int)$v;
151
            } elseif ($k === 'maxconcurrency') {
152
                $this->maxConcurrency = (int)$v;
153
            }
154
        }
155
    }
156
157
    /**
158
     * Setting default config options
159
     * @return boolean
160
     */
161
    protected function getConfigDefaults()
162
    {
163
        return false;
164
    }
165
166
    /**
167
     * Returns instance object
168
     * @param  string $arg name / array config / ConfigSection
169
     * @param  boolean $spawn Spawn? Default is true
170
     * @return this
171
     */
172
    public static function getInstance($arg = '', $spawn = true)
173
    {
174
        if ($arg === 'default') {
175
            $arg = '';
176
        }
177
        $class = static::class;
178
        if (is_string($arg)) {
179
            $key = $class . ':' . $arg;
180
            if (isset(self::$instances[$key])) {
181
                return self::$instances[$key];
182
            } elseif (!$spawn) {
183
                return false;
184
            }
185
            $k = '\PHPDaemon\Core\Pool:\\' . $class . ($arg !== '' ? ':' . $arg : '');
186
            $config = (isset(Daemon::$config->{$k}) && Daemon::$config->{$k} instanceof Config\Section) ? Daemon::$config->{$k} : new Config\Section;
187
            $obj = self::$instances[$key] = new $class($config);
188
            $obj->name = $arg;
189
        } elseif ($arg instanceof Config\Section) {
190
            $obj = new static($arg);
191
        } else {
192
            $obj = new static(new Config\Section($arg));
0 ignored issues
show
Documentation introduced by
new \PHPDaemon\Config\Section($arg) is of type object<PHPDaemon\Config\Section>, but the function expects a array.

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...
193
        }
194
        $obj->eventLoop = EventLoop::$instance;
195
        return $obj;
196
    }
197
198
    /**
199
     * Sets default connection class
200
     * @param  string $class Connection class name
201
     * @return void
202
     */
203
    public function setConnectionClass($class)
204
    {
205
        $this->connectionClass = $class;
206
    }
207
208
    /**
209
     * Enable socket events
210
     * @return void
211
     */
212
    public function enable()
213
    {
214
        if ($this->enabled) {
215
            return;
216
        }
217
        $this->enabled = true;
218
        $this->onEnable();
219
    }
220
221
    /**
222
     * Disable all events of sockets
223
     * @return void
224
     */
225
    public function disable()
226
    {
227
        if (!$this->enabled) {
228
            return;
229
        }
230
        $this->enabled = false;
231
        $this->onDisable();
232
    }
233
234
    /**
235
     * Called when ConnectionPool is now enabled
236
     * @return void
237
     */
238
    protected function onEnable()
239
    {
240
    }
241
242
    /**
243
     * Called when ConnectionPool is now disabled
244
     * @return void
245
     */
246
    protected function onDisable()
247
    {
248
    }
249
250
    /**
251
     * Called when application instance is going to shutdown
252
     * @param  boolean $graceful
253
     * @return boolean Ready to shutdown?
254
     */
255
    public function onShutdown($graceful = false)
256
    {
257
        return $this->finish($graceful);
258
    }
259
260
    /**
261
     * Called when ConnectionPool is finished
262
     * @return void
263
     */
264
    protected function onFinish()
265
    {
266
    }
267
268
    /**
269
     * Finishes ConnectionPool
270
     * @return boolean Success
271
     */
272
    public function finish($graceful = false)
273
    {
274
        $this->disable();
275
276
        if (!$this->finished) {
277
            $this->finished = true;
278
            $this->onFinish();
279
        }
280
281
        $result = true;
282
283
        foreach ($this as $conn) {
284
            if ($graceful) {
285
                if (!$conn->gracefulShutdown()) {
286
                    $result = false;
287
                }
288
            } else {
289
                $conn->finish();
290
            }
291
        }
292
293
        return $result;
294
    }
295
296
    /**
297
     * Attach Connection
298
     * @param  object $conn Connection
299
     * @param  mixed $inf Info
300
     * @return void
301
     */
302 View Code Duplication
    public function attach($conn, $inf = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
303
    {
304
        parent::attach($conn, $inf);
305
        if ($this->maxConcurrency && !$this->overload) {
306
            if ($this->count() >= $this->maxConcurrency) {
307
                $this->overload = true;
308
                $this->disable();
309
                return;
310
            }
311
        }
312
    }
313
314
    /**
315
     * Detach Connection
316
     * @param  object $conn Connection
317
     * @return void
318
     */
319 View Code Duplication
    public function detach($conn)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
320
    {
321
        parent::detach($conn);
322
        if ($this->overload) {
323
            if (!$this->maxConcurrency || ($this->count() < $this->maxConcurrency)) {
324
                $this->overload = false;
325
                $this->enable();
326
            }
327
        }
328
    }
329
330
    /**
331
     * Establish a connection with remote peer
332
     * @param  string $url URL
333
     * @param  callback $cb Callback
334
     * @param  string $class Optional. Connection class name
0 ignored issues
show
Documentation introduced by
Should the type for parameter $class not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
335
     * @return integer         Connection's ID. Boolean false when failed
0 ignored issues
show
Documentation introduced by
Should the return type not be object?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
336
     */
337
    public function connect($url, $cb, $class = null)
338
    {
339
        if ($class === null) {
340
            $class = $this->connectionClass;
341
        }
342
        $conn = new $class(null, $this);
343
        $conn->connect($url, $cb);
344
        return $conn;
345
    }
346
}
347