Test Failed
Pull Request — master (#5)
by Adam
01:44
created

MQTTClientExtension::beforeCompile()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 89

Duplication

Lines 5
Ratio 5.62 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 5
loc 89
rs 8.24
c 0
b 0
f 0
ccs 0
cts 63
cp 0
cc 3
nc 4
nop 0
crap 12

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
 * MQTTClientExtension.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec http://www.ipublikuj.eu
8
 * @package        iPublikuj:MQTTClient!
9
 * @subpackage     DI
10
 * @since          1.0.0
11
 *
12
 * @date           12.03.17
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\MQTTClient\DI;
18
19
use Nette;
20
use Nette\DI;
21
use Nette\PhpGenerator as Code;
22
23
use BinSoul\Net\Mqtt;
24
25
use Symfony\Component\EventDispatcher;
26
27
use React;
28
29
use Psr\Log;
30
31
use IPub\MQTTClient;
32
use IPub\MQTTClient\Client;
33
use IPub\MQTTClient\Commands;
34
use IPub\MQTTClient\Events;
35
use IPub\MQTTClient\Logger;
36
37
/**
38
 * MQTT client extension container
39
 *
40
 * @package        iPublikuj:MQTTClient!
41
 * @subpackage     DI
42
 *
43
 * @author         Adam Kadlec <[email protected]>
44
 *
45
 * @method DI\ContainerBuilder getContainerBuilder()
46
 * @method array getConfig(array $default)
47
 * @method string prefix($id)
48
 */
49 1
final class MQTTClientExtension extends DI\CompilerExtension
50
{
51
	/**
52
	 * @var array
53
	 */
54
	private $defaults = [
55
		'broker'        => [
56
			'httpHost' => NULL,
57
			'port'     => 1883,
58
			'address'  => NULL,
59
			'dns'      => [
60
				'enable'  => TRUE,
61
				'address' => '8.8.8.8',
62
			],
63
			'secured'  => [
64
				'enable'      => FALSE,
65
				'sslSettings' => [],
66
			],
67
		],
68
		'connection'    => [
69
			'username'  => '',
70
			'password'  => '',
71
			'clientID'  => '',
72
			'keepAlive' => 60,
73
			'protocol'  => 4,
74
			'clean'     => TRUE,
75
		],
76
		'loop'          => NULL,
77
		'console'       => FALSE,
78
		'symfonyEvents' => FALSE,
79
	];
80
81
	/**
82
	 * {@inheritdoc}
83
	 */
84
	public function loadConfiguration()
85
	{
86
		// Get container builder
87 1
		$builder = $this->getContainerBuilder();
88
		/** @var array $configuration */
89 1 View Code Duplication
		if (method_exists($this, 'validateConfig')) {
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...
90 1
			$configuration = $this->validateConfig($this->defaults);
91
		} else {
92
			$configuration = $this->getConfig($this->defaults);
93
		}
94
95
		if ($configuration['loop'] === NULL) {
96
			if ($builder->getByType(React\EventLoop\LoopInterface::class) === NULL) {
97
				$loop = $builder->addDefinition($this->prefix('client.loop'))
98
					->setType(React\EventLoop\LoopInterface::class)
99
					->setFactory('React\EventLoop\Factory::create');
100
101
			} else {
102
				$loop = $builder->getDefinitionByType(React\EventLoop\LoopInterface::class);
103
			}
104
105
		} else {
106
			$loop = $builder->getDefinition(ltrim($configuration['loop'], '@'));
107
		}
108
109
		$connection = new Mqtt\DefaultConnection(
110
			$configuration['connection']['username'],
111
			$configuration['connection']['password'],
112
			NULL,
113
			$configuration['connection']['clientID'],
114
			$configuration['connection']['keepAlive'],
115
			$configuration['connection']['protocol'],
116
			$configuration['connection']['clean']
117
		);
118
119
		$clientConfiguration = new Client\Configuration(
120
			$configuration['broker']['httpHost'],
121
			$configuration['broker']['port'],
122
			$configuration['broker']['address'],
123
			$configuration['broker']['dns']['enable'],
124
			$configuration['broker']['dns']['address'],
125
			$configuration['broker']['secured']['enable'],
126
			$configuration['broker']['secured']['sslSettings'],
127
			$connection
128
		);
129
130
		if ($builder->findByType(Log\LoggerInterface::class) === []) {
131
			$builder->addDefinition($this->prefix('server.logger'))
132
				->setType(Logger\Console::class);
133
		}
134
135
		$builder->addDefinition($this->prefix('client.client'))
136
			->setType(Client\Client::class)
137
			->setArguments([
138
				'eventLoop'     => $loop,
139
				'configuration' => $clientConfiguration,
140
			]);
141
142
		if ($configuration['console'] === TRUE) {
143
			// Define all console commands
144
			$commands = [
145
				'client' => Commands\ClientCommand::class,
146
			];
147
148
			foreach ($commands as $name => $cmd) {
149
				$builder->addDefinition($this->prefix('commands' . lcfirst($name)))
150
					->setType($cmd);
151
			}
152
		}
153
	}
154
155
	/**
156
	 * {@inheritdoc}
157
	 */
158
	public function beforeCompile()
159
	{
160
		parent::beforeCompile();
161
162
		// Get container builder
163
		$builder = $this->getContainerBuilder();
0 ignored issues
show
Unused Code introduced by
$builder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
164
		/** @var array $configuration */
165 View Code Duplication
		if (method_exists($this, 'validateConfig')) {
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...
166
			$configuration = $this->validateConfig($this->defaults);
167
		} else {
168
			$configuration = $this->getConfig($this->defaults);
169
		}
170
171
		// Get container builder
172
		$builder = $this->getContainerBuilder();
173
174
		if ($configuration['symfonyEvents'] === TRUE) {
175
			$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcher\EventDispatcherInterface::class));
176
177
			$client = $builder->getDefinition($builder->getByType(Client\Client::class));
178
			assert($client instanceof DI\ServiceDefinition);
0 ignored issues
show
Bug introduced by
The class Nette\DI\ServiceDefinition does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
179
180
			$client->addSetup('?->onStart[] = function() {?->dispatch(new ?(...func_get_args()));}', [
181
				'@self',
182
				$dispatcher,
183
				new Nette\PhpGenerator\PhpLiteral(Events\StartEvent::class),
184
			]);
185
			$client->addSetup('?->onOpen[] = function() {?->dispatch(new ?(...func_get_args()));}', [
186
				'@self',
187
				$dispatcher,
188
				new Nette\PhpGenerator\PhpLiteral(Events\OpenEvent::class),
189
			]);
190
			$client->addSetup('?->onConnect[] = function() {?->dispatch(new ?(...func_get_args()));}', [
191
				'@self',
192
				$dispatcher,
193
				new Nette\PhpGenerator\PhpLiteral(Events\ConnectEvent::class),
194
			]);
195
			$client->addSetup('?->onDisconnect[] = function() {?->dispatch(new ?(...func_get_args()));}', [
196
				'@self',
197
				$dispatcher,
198
				new Nette\PhpGenerator\PhpLiteral(Events\DisconnectEvent::class),
199
			]);
200
			$client->addSetup('?->onClose[] = function() {?->dispatch(new ?(...func_get_args()));}', [
201
				'@self',
202
				$dispatcher,
203
				new Nette\PhpGenerator\PhpLiteral(Events\CloseEvent::class),
204
			]);
205
			$client->addSetup('?->onPing[] = function() {?->dispatch(new ?(...func_get_args()));}', [
206
				'@self',
207
				$dispatcher,
208
				new Nette\PhpGenerator\PhpLiteral(Events\PingEvent::class),
209
			]);
210
			$client->addSetup('?->onPong[] = function() {?->dispatch(new ?(...func_get_args()));}', [
211
				'@self',
212
				$dispatcher,
213
				new Nette\PhpGenerator\PhpLiteral(Events\PongEvent::class),
214
			]);
215
			$client->addSetup('?->onPublish[] = function() {?->dispatch(new ?(...func_get_args()));}', [
216
				'@self',
217
				$dispatcher,
218
				new Nette\PhpGenerator\PhpLiteral(Events\PublishEvent::class),
219
			]);
220
			$client->addSetup('?->onSubscribe[] = function() {?->dispatch(new ?(...func_get_args()));}', [
221
				'@self',
222
				$dispatcher,
223
				new Nette\PhpGenerator\PhpLiteral(Events\SubscribeEvent::class),
224
			]);
225
			$client->addSetup('?->onUnsubscribe[] = function() {?->dispatch(new ?(...func_get_args()));}', [
226
				'@self',
227
				$dispatcher,
228
				new Nette\PhpGenerator\PhpLiteral(Events\UnsubscribeEvent::class),
229
			]);
230
			$client->addSetup('?->onMessage[] = function() {?->dispatch(new ?(...func_get_args()));}', [
231
				'@self',
232
				$dispatcher,
233
				new Nette\PhpGenerator\PhpLiteral(Events\MessageEvent::class),
234
			]);
235
			$client->addSetup('?->onWarning[] = function() {?->dispatch(new ?(...func_get_args()));}', [
236
				'@self',
237
				$dispatcher,
238
				new Nette\PhpGenerator\PhpLiteral(Events\WarningEvent::class),
239
			]);
240
			$client->addSetup('?->onError[] = function() {?->dispatch(new ?(...func_get_args()));}', [
241
				'@self',
242
				$dispatcher,
243
				new Nette\PhpGenerator\PhpLiteral(Events\ErrorEvent::class),
244
			]);
245
		}
246
	}
247
248
	/**
249
	 * @param Nette\Configurator $config
250
	 * @param string $extensionName
251
	 *
252
	 * @return void
253
	 */
254
	public static function register(Nette\Configurator $config, string $extensionName = 'mqttClient')
255
	{
256
		$config->onCompile[] = function (Nette\Configurator $config, DI\Compiler $compiler) use ($extensionName) {
257
			$compiler->addExtension($extensionName, new MQTTClientExtension);
258
		};
259
	}
260
}
261