Completed
Pull Request — master (#234)
by Дмитрий
07:51
created

Pool::getInstance()   C

Complexity

Conditions 9
Paths 24

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 9
dl 0
loc 24
rs 5.3563
eloc 19
c 1
b 1
f 0
nc 24
nop 2
1
<?php
2
namespace PHPDaemon\Network;
3
4
use PHPDaemon\BoundSocket;
5
use PHPDaemon\Config;
6
use PHPDaemon\Core\Daemon;
7
use PHPDaemon\Core\Debug;
8
use PHPDaemon\Structures\ObjectStorage;
9
use PHPDaemon\Thread;
10
11
/**
12
 * Pool of connections
13
 * @package PHPDaemon\Network
14
 * @author  Vasily Zorin <[email protected]>
15
 */
16
abstract class Pool extends ObjectStorage
17
{
18
19
    /**
20
     * @var string Default connection class
21
     */
22
    public $connectionClass;
23
24
    /**
25
     * @var string Name
26
     */
27
    public $name;
28
29
    /**
30
     * @var \PHPDaemon\Config\Section Configuration
31
     */
32
    public $config;
33
34
    /**
35
     * @var ConnectionPool[] Instances storage
36
     */
37
    protected static $instances = [];
38
39
    /**
40
     * @var integer Max concurrency
41
     */
42
    public $maxConcurrency = 0;
43
44
    /**
45
     * @var integer Max allowed packet
46
     */
47
    public $maxAllowedPacket = 0;
48
49
    /**
50
     * @var boolean Is finished?
51
     */
52
    protected $finished = false;
53
54
    /**
55
     * @var boolean Is enabled?
56
     */
57
    protected $enabled = false;
58
59
    /**
60
     * @var boolean Is overloaded?
61
     */
62
    protected $overload = false;
63
64
    /**
65
     * @var object|null Application instance object
66
     */
67
    public $appInstance;
68
69
    /**
70
     * Constructor
71
     * @param array   $config Config variables
72
     * @param boolean $init
73
     */
74
    public function __construct($config = [], $init = true)
75
    {
76
        $this->config = $config;
0 ignored issues
show
Documentation Bug introduced by
It seems like $config of type array is incompatible with the declared type object<PHPDaemon\Config\Section> of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
77
        $this->onConfigUpdated();
78
        if ($this->connectionClass === null) {
79
            $e                     = explode('\\', get_class($this));
80
            $e[sizeof($e) - 1]     = 'Connection';
81
            $this->connectionClass = '\\' . implode('\\', $e);
82
        }
83
        if ($init) {
84
            $this->init();
85
        }
86
    }
87
88
    /**
89
     * Init
90
     * @return void
91
     */
92
    protected function init()
93
    {
94
    }
95
96
    /**
97
     * Called when the worker is ready to go
98
     * @return void
99
     */
100
    public function onReady()
101
    {
102
        $this->enable();
103
    }
104
105
    /**
106
     * Called when worker is going to update configuration
107
     * @return void
108
     */
109
    public function onConfigUpdated()
110
    {
111
        if (Daemon::$process instanceof Thread\Worker) {
112
            if ($this->config === null) {
113
                $this->disable();
114
            } else {
115
                $this->enable();
116
            }
117
        }
118
        if ($defaults = $this->getConfigDefaults()) {
119
            $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...
120
        }
121
        $this->applyConfig();
122
    }
123
124
    /**
125
     * Applies config
126
     * @return void
127
     */
128
    protected function applyConfig()
129
    {
130
        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...
131
            if (is_object($v) && $v instanceof Config\Entry\Generic) {
132
                $v = $v->getValue();
133
            }
134
            $k = strtolower($k);
135
            if ($k === 'connectionclass') {
136
                $this->connectionClass = $v;
137
            } elseif ($k === 'name') {
138
                $this->name = $v;
139
            } elseif ($k === 'maxallowedpacket') {
140
                $this->maxAllowedPacket = (int)$v;
141
            } elseif ($k === 'maxconcurrency') {
142
                $this->maxConcurrency = (int)$v;
143
            }
144
        }
145
    }
146
147
    /**
148
     * Setting default config options
149
     * @return boolean
150
     */
151
    protected function getConfigDefaults()
152
    {
153
        return false;
154
    }
155
156
    /**
157
     * Returns instance object
158
     * @param  string  $arg   name / array config / ConfigSection
159
     * @param  boolean $spawn Spawn? Default is true
160
     * @return this
161
     */
162
    public static function getInstance($arg = '', $spawn = true)
163
    {
164
        if ($arg === 'default') {
165
            $arg = '';
166
        }
167
        $class = get_called_class();
168
        if (is_string($arg)) {
169
            $key = $class . ':' . $arg;
170
            if (isset(self::$instances[$key])) {
171
                return self::$instances[$key];
172
            } elseif (!$spawn) {
173
                return false;
174
            }
175
            $k         = '\PHPDaemon\Core\Pool:\\' . $class . ($arg !== '' ? ':' . $arg : '');
176
            $config    = (isset(Daemon::$config->{$k}) && Daemon::$config->{$k} instanceof Config\Section) ? Daemon::$config->{$k} : new Config\Section;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 152 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
177
            $obj       = self::$instances[$key] = new $class($config);
178
            $obj->name = $arg;
179
            return $obj;
180
        } elseif ($arg instanceof Config\Section) {
181
            return new static($arg);
182
        } else {
183
            return 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...
184
        }
185
    }
186
187
    /**
188
     * Sets default connection class
189
     * @param  string $class Connection class name
190
     * @return void
191
     */
192
    public function setConnectionClass($class)
193
    {
194
        $this->connectionClass = $class;
195
    }
196
197
    /**
198
     * Enable socket events
199
     * @return void
200
     */
201
    public function enable()
202
    {
203
        if ($this->enabled) {
204
            return;
205
        }
206
        $this->enabled = true;
207
        $this->onEnable();
208
    }
209
210
    /**
211
     * Disable all events of sockets
212
     * @return void
213
     */
214
    public function disable()
215
    {
216
        if (!$this->enabled) {
217
            return;
218
        }
219
        $this->enabled = false;
220
        $this->onDisable();
221
    }
222
223
    /**
224
     * Called when ConnectionPool is now enabled
225
     * @return void
226
     */
227
    protected function onEnable()
228
    {
229
    }
230
231
    /**
232
     * Called when ConnectionPool is now disabled
233
     * @return void
234
     */
235
    protected function onDisable()
236
    {
237
    }
238
239
    /**
240
     * Called when application instance is going to shutdown
241
     * @param  boolean $graceful
242
     * @return boolean Ready to shutdown?
243
     */
244
    public function onShutdown($graceful = false)
245
    {
246
        return $this->finish($graceful);
247
    }
248
249
    /**
250
     * Called when ConnectionPool is finished
251
     * @return void
252
     */
253
    protected function onFinish()
254
    {
255
    }
256
257
    /**
258
     * Finishes ConnectionPool
259
     * @return boolean Success
260
     */
261
    public function finish($graceful = false)
262
    {
263
        $this->disable();
264
        
265
        if (!$this->finished) {
266
            $this->finished = true;
267
            $this->onFinish();
268
        }
269
        
270
        $result = true;
271
272
        foreach ($this as $conn) {
273
            if ($graceful) {
274
                if (!$conn->gracefulShutdown()) {
275
                    $result = false;
276
                }
277
            } else {
278
                $conn->finish();
279
            }
280
        }
281
282
        return $result;
283
    }
284
285
    /**
286
     * Attach Connection
287
     * @param  object $conn Connection
288
     * @param  mixed  $inf  Info
289
     * @return void
290
     */
291 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...
292
    {
293
        parent::attach($conn, $inf);
294
        if ($this->maxConcurrency && !$this->overload) {
295
            if ($this->count() >= $this->maxConcurrency) {
296
                $this->overload = true;
297
                $this->disable();
298
                return;
299
            }
300
        }
301
    }
302
303
    /**
304
     * Detach Connection
305
     * @param  object $conn Connection
306
     * @return void
307
     */
308 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...
309
    {
310
        parent::detach($conn);
311
        if ($this->overload) {
312
            if (!$this->maxConcurrency || ($this->count() < $this->maxConcurrency)) {
313
                $this->overload = false;
314
                $this->enable();
315
            }
316
        }
317
    }
318
319
    /**
320
     * Establish a connection with remote peer
321
     * @param  string   $url   URL
322
     * @param  callback $cb    Callback
323
     * @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...
324
     * @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...
325
     */
326
    public function connect($url, $cb, $class = null)
327
    {
328
        if ($class === null) {
329
            $class = $this->connectionClass;
330
        }
331
        $conn = new $class(null, $this);
332
        $conn->connect($url, $cb);
333
        return $conn;
334
    }
335
}
336