Completed
Pull Request — master (#4)
by Adam
02:24
created

MQTTClientExtension::beforeCompile()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 89

Duplication

Lines 5
Ratio 5.62 %

Code Coverage

Tests 62
CRAP Score 3

Importance

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

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
		'symfonyEvets' => 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 1
		if ($configuration['loop'] === NULL) {
96 1
			if ($builder->getByType(React\EventLoop\LoopInterface::class) === NULL) {
97 1
				$loop = $builder->addDefinition($this->prefix('client.loop'))
98 1
					->setType(React\EventLoop\LoopInterface::class)
99 1
					->setFactory('React\EventLoop\Factory::create');
100
101
			} else {
102 1
				$loop = $builder->getDefinitionByType(React\EventLoop\LoopInterface::class);
103
			}
104
105
		} else {
106
			$loop = $builder->getDefinition(ltrim($configuration['loop'], '@'));
107
		}
108
109 1
		$connection = new Mqtt\DefaultConnection(
110 1
			$configuration['connection']['username'],
111 1
			$configuration['connection']['password'],
112 1
			NULL,
113 1
			$configuration['connection']['clientID'],
114 1
			$configuration['connection']['keepAlive'],
115 1
			$configuration['connection']['protocol'],
116 1
			$configuration['connection']['clean']
117
		);
118
119 1
		$clientConfiguration = new Client\Configuration(
120 1
			$configuration['broker']['httpHost'],
121 1
			$configuration['broker']['port'],
122 1
			$configuration['broker']['address'],
123 1
			$configuration['broker']['dns']['enable'],
124 1
			$configuration['broker']['dns']['address'],
125 1
			$configuration['broker']['secured']['enable'],
126 1
			$configuration['broker']['secured']['sslSettings'],
127 1
			$connection
128
		);
129
130 1
		if ($builder->findByType(Log\LoggerInterface::class) === []) {
131 1
			$builder->addDefinition($this->prefix('server.logger'))
132 1
				->setType(Logger\Console::class);
133
		}
134
135 1
		$builder->addDefinition($this->prefix('client.client'))
136 1
			->setType(Client\Client::class)
137 1
			->setArguments([
138 1
				'eventLoop'     => $loop,
139 1
				'configuration' => $clientConfiguration,
140
			]);
141
142 1
		if ($configuration['console'] === TRUE) {
143
			// Define all console commands
144
			$commands = [
145 1
				'client' => Commands\ClientCommand::class,
146
			];
147
148 1
			foreach ($commands as $name => $cmd) {
149 1
				$builder->addDefinition($this->prefix('commands' . lcfirst($name)))
150 1
					->setType($cmd);
151
			}
152
		}
153 1
	}
154
155
	/**
156
	 * {@inheritdoc}
157
	 */
158
	public function beforeCompile()
159
	{
160 1
		parent::beforeCompile();
161
162
		// Get container builder
163 1
		$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 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...
166 1
			$configuration = $this->validateConfig($this->defaults);
167
		} else {
168
			$configuration = $this->getConfig($this->defaults);
169
		}
170
171
		// Get container builder
172 1
		$builder = $this->getContainerBuilder();
173
174 1
		if ($configuration['symfonyEvets'] === TRUE) {
175 1
			$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcher\EventDispatcherInterface::class));
176
177 1
			$client = $builder->getDefinition($builder->getByType(Client\Client::class));
178 1
			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 1
			$client->addSetup('?->onStart[] = function() {?->dispatch(new ?(...func_get_args()));}', [
181 1
				'@self',
182 1
				$dispatcher,
183 1
				new Nette\PhpGenerator\PhpLiteral(Events\StartEvent::class),
184
			]);
185 1
			$client->addSetup('?->onOpen[] = function() {?->dispatch(new ?(...func_get_args()));}', [
186 1
				'@self',
187 1
				$dispatcher,
188 1
				new Nette\PhpGenerator\PhpLiteral(Events\OpenEvent::class),
189
			]);
190 1
			$client->addSetup('?->onConnect[] = function() {?->dispatch(new ?(...func_get_args()));}', [
191 1
				'@self',
192 1
				$dispatcher,
193 1
				new Nette\PhpGenerator\PhpLiteral(Events\ConnectEvent::class),
194
			]);
195 1
			$client->addSetup('?->onDisconnect[] = function() {?->dispatch(new ?(...func_get_args()));}', [
196 1
				'@self',
197 1
				$dispatcher,
198 1
				new Nette\PhpGenerator\PhpLiteral(Events\DisconnectEvent::class),
199
			]);
200 1
			$client->addSetup('?->onClose[] = function() {?->dispatch(new ?(...func_get_args()));}', [
201 1
				'@self',
202 1
				$dispatcher,
203 1
				new Nette\PhpGenerator\PhpLiteral(Events\CloseEvent::class),
204
			]);
205 1
			$client->addSetup('?->onPing[] = function() {?->dispatch(new ?(...func_get_args()));}', [
206 1
				'@self',
207 1
				$dispatcher,
208 1
				new Nette\PhpGenerator\PhpLiteral(Events\PingEvent::class),
209
			]);
210 1
			$client->addSetup('?->onPong[] = function() {?->dispatch(new ?(...func_get_args()));}', [
211 1
				'@self',
212 1
				$dispatcher,
213 1
				new Nette\PhpGenerator\PhpLiteral(Events\PongEvent::class),
214
			]);
215 1
			$client->addSetup('?->onPublish[] = function() {?->dispatch(new ?(...func_get_args()));}', [
216 1
				'@self',
217 1
				$dispatcher,
218 1
				new Nette\PhpGenerator\PhpLiteral(Events\PublishEvent::class),
219
			]);
220 1
			$client->addSetup('?->onSubscribe[] = function() {?->dispatch(new ?(...func_get_args()));}', [
221 1
				'@self',
222 1
				$dispatcher,
223 1
				new Nette\PhpGenerator\PhpLiteral(Events\SubscribeEvent::class),
224
			]);
225 1
			$client->addSetup('?->onUnsubscribe[] = function() {?->dispatch(new ?(...func_get_args()));}', [
226 1
				'@self',
227 1
				$dispatcher,
228 1
				new Nette\PhpGenerator\PhpLiteral(Events\UnsubscribeEvent::class),
229
			]);
230 1
			$client->addSetup('?->onMessage[] = function() {?->dispatch(new ?(...func_get_args()));}', [
231 1
				'@self',
232 1
				$dispatcher,
233 1
				new Nette\PhpGenerator\PhpLiteral(Events\MessageEvent::class),
234
			]);
235 1
			$client->addSetup('?->onWarning[] = function() {?->dispatch(new ?(...func_get_args()));}', [
236 1
				'@self',
237 1
				$dispatcher,
238 1
				new Nette\PhpGenerator\PhpLiteral(Events\WarningEvent::class),
239
			]);
240 1
			$client->addSetup('?->onError[] = function() {?->dispatch(new ?(...func_get_args()));}', [
241 1
				'@self',
242 1
				$dispatcher,
243 1
				new Nette\PhpGenerator\PhpLiteral(Events\ErrorEvent::class),
244
			]);
245
		}
246 1
	}
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