Completed
Push — mater ( 02259a )
by Vasily
05:33
created

Pool::autoscan()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 4
1
<?php
2
namespace PHPDaemon\Clients\Redis;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Core\CallbackWrapper;
6
use PHPDaemon\Network\ClientConnection;
7
8
/**
9
 * @package    NetworkClients
10
 * @subpackage RedisClient
11
 * @author     Vasily Zorin <[email protected]>
12
 */
13
class Pool extends \PHPDaemon\Network\Client {
14
	public $servConnSub = [];
15
16
	protected $currentMasterAddr;
17
18
	/**
19
	 * @TODO
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
20
	 * @param  string  $key
21
	 * @param  integer $timeout
22
	 * @return Lock
23
	 */
24
	public function lock($key, $timeout) {
25
		return new Lock($key, $timeout, $this);
26
	}
27
28
	/**
29
	 * Easy wrapper for queue of eval's
30
	 * @param  callable  $cb
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cb not be callable|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...
31
	 * @return MultiEval
32
	 */
33
	public function meval($cb = null) {
34
		return new MultiEval($cb, $this);
0 ignored issues
show
Bug introduced by
It seems like $cb defined by parameter $cb on line 33 can also be of type null; however, PHPDaemon\Clients\Redis\MultiEval::__construct() does only seem to accept callable, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
35
	}
36
37
	/**
38
	 * Wrapper for scans commands
39
	 * @param  string  $cmd    Command
40
	 * @param  array   $args   Arguments
41
	 * @param  cllable $cbEnd  Callback
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cbEnd not be cllable|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...
42
	 * @param  integer $limit  Limit
0 ignored issues
show
Documentation introduced by
Should the type for parameter $limit not be integer|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...
43
	 * @return AutoScan
44
	 */
45
	public function autoscan($cmd, $args = [], $cbEnd = null, $limit = null) {
46
		return new AutoScan($this, $cmd, $args, $cbEnd, $limit);
47
	}
48
49
	/**
50
	 * Setting default config options
51
	 * Overriden from NetworkClient::getConfigDefaults
52
	 * @return array|bool
53
	 */
54
	protected function getConfigDefaults() {
55
		return [
56
			/* [string|array] Default servers */
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
57
			'servers'        => 'tcp://127.0.0.1',
58
59
			/* [integer] Default port */
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
60
			'port'           => 6379,
61
62
			/* [integer] Maximum connections per server */
63
			'maxconnperserv' => 32,
64
65
			/* [integer] Maximum allowed size of packet */
66
			'max-allowed-packet' => new \PHPDaemon\Config\Entry\Size('1M'),
67
68
			/* [boolean] If true, race condition between UNSUBSCRIBE and PUBLISH will be journaled */
69
			'log-pub-sub-race-condition' => true,
70
71
			/* [integer] Select storage number */
72
			'select' => null,
73
74
			/* [integer] <master name> for Sentinel */
75
			'sentinel-master' => null,
76
		];
77
	}
78
79
	/**
80
	 * @TODO
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
81
	 * @param  string $chan
82
	 * @return integer
83
	 */
84
	public function getLocalSubscribersCount($chan) {
85
		foreach ($this->servConnSub as $conn)  {
86
			return $conn->getLocalSubscribersCount($chan);
87
		}
88
		return 0;
89
	}
90
91
	/**
92
	 * Magic __call
93
	 * Example:
94
	 * $redis->lpush('mylist', microtime(true));
95
	 * @param  string $name Command name
0 ignored issues
show
Bug introduced by
There is no parameter named $name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
96
	 * @param  array  $args Arguments
97
	 * @return void
98
	 */
99
	public function __call($cmd, $args) {
100
		$cb = null;
101 View Code Duplication
		for ($i = sizeof($args) - 1; $i >= 0; --$i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
102
			$a = $args[$i];
103
			if ((is_array($a) || is_object($a)) && is_callable($a)) {
104
				$cb = CallbackWrapper::wrap($a);
105
				$args = array_slice($args, 0, $i);
106
				break;
107
			}
108
			elseif ($a !== null) {
109
				break;
110
			}
111
		}
112
		reset($args);
113
		$cmd = strtoupper($cmd);
114
115
		if ($this->sendSubCommand($cmd, $args, $cb)) {
0 ignored issues
show
Bug introduced by
It seems like $cb can also be of type null; however, PHPDaemon\Clients\Redis\Pool::sendSubCommand() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
116
			return;
117
		}
118
119
		if ($cmd === 'SENTINEL' || !isset($this->config->sentinelmaster->value)) {
0 ignored issues
show
Bug introduced by
The property sentinelmaster does not seem to exist in PHPDaemon\Config\Section.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
120
			$this->sendCommand(null, $cmd, $args, $cb);
0 ignored issues
show
Bug introduced by
It seems like $cb can also be of type null; however, PHPDaemon\Clients\Redis\Pool::sendCommand() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
121
			return;
122
		}
123
		if ($this->currentMasterAddr !== null) {
124
			$this->sendCommand($this->currentMasterAddr, $cmd, $args, $cb);
0 ignored issues
show
Bug introduced by
It seems like $cb can also be of type null; however, PHPDaemon\Clients\Redis\Pool::sendCommand() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
125
			return;
126
		}
127
		$this->sentinel('get-master-addr-by-name', $this->config->sentinelmaster->value, function($redis) use ($cmd, $args, $cb) {
0 ignored issues
show
Documentation Bug introduced by
The method sentinel does not exist on object<PHPDaemon\Clients\Redis\Pool>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 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...
128
			$this->currentMasterAddr = 'tcp://' . $redis->result[0] .':' . $redis->result[1];
129
			$this->sendCommand($this->currentMasterAddr, $cmd, $args, $cb);
130
		});
131
	}
132
133
	/**
134
	 * @TODO
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
135
	 * @param  string   $addr
136
	 * @param  string   $cmd
137
	 * @param  array    $args
138
	 * @param  callable $cb
139
	 * @callback $cb ( )
140
	 * @return void
141
	 */
142
	protected function sendCommand($addr, $cmd, $args, $cb) {
143
		$this->getConnection($addr, function ($conn) use ($cmd, $args, $cb) {
144
			if (!$conn->isConnected()) {
145
				call_user_func($cb, false);
146
				return;
147
			}
148
149
			if ($this->sendSubCommand($cmd, $args, $cb)) {
150
				return;
151
			}
152
153
			$conn->command($cmd, $args, $cb);
154
		});
155
	}
156
157
	/**
158
	 * @TODO
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
159
	 * @param  string   $cmd
160
	 * @param  array    $args
161
	 * @param  callable $cb
162
	 * @callback $cb ( )
163
	 * @return boolean
164
	 */
165
	protected function sendSubCommand($cmd, $args, $cb) {
166
		if (in_array($cmd, ['SUBSCRIBE', 'PSUBSCRIBE', 'UNSUBSCRIBE', 'PUNSUBSCRIBE', 'UNSUBSCRIBEREAL'])) {
167
			foreach ($this->servConnSub as $conn)  {
168
				$conn->command($cmd, $args, $cb);
169
				return true;
170
			}
171
172
		}
173
		return false;
174
	}
175
}
176