Completed
Push — master ( fdbeef...265a2d )
by jerome
21:34
created

ServerContext   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 418
Duplicated Lines 22.25 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 46
c 5
b 1
f 0
lcom 1
cbo 11
dl 93
loc 418
rs 8.3999

24 Methods

Rating   Name   Duplication   Size   Complexity  
A iAmOnTheVoipPage() 0 8 1
A iShouldBeOnTheVoipPage() 9 9 1
A iAmOnTheInstancePageByName() 0 6 1
A iAmDoingSomethingWithVoipResourceByName() 7 7 1
A iShouldBeDoingSomethingWithVoipResourceByName() 8 8 1
A iShouldBeOnTheServerPageByName() 0 4 1
A iShouldBeOnTheInstancePageByName() 8 8 1
A iAmOnTheInstanceIndex() 0 8 1
A iShouldBeOnTheInstanceIndexPage() 9 9 1
A iAmDoingSomethingWithVoipServer() 11 11 1
A iShouldBeDoingSomethingWithVoipServer() 12 12 1
A iClickNear() 13 13 2
A iShouldBeOnTheFtpPage() 8 8 1
A iShouldSeeThatMuchInstancesInTheList() 8 8 2
A thereAreMinecraftServers() 0 22 3
B thereIsMinecraftServer() 0 34 4
A thereAreSteamServers() 0 18 3
B thereIsSteamServer() 0 30 4
A thereAreTeamspeakServers() 0 14 3
B thereIsTeamspeakServer() 0 25 4
A thereAreTeamspeakInstances() 0 15 2
B thereIsTeamspeakInstance() 0 26 3
A getRepository() 0 10 2
A findOneBy() 0 15 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 ServerContext 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 ServerContext, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * This file is part of Dedipanel project
5
 *
6
 * (c) 2010-2015 Dedipanel <http://www.dedicated-panel.net>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace DP\Core\CoreBundle\Behat;
13
14
use Behat\Behat\Hook\Scope\BeforeFeatureScope;
15
use Behat\Gherkin\Node\TableNode;
16
use DP\GameServer\MinecraftServerBundle\Entity\MinecraftServer;
17
use DP\GameServer\SteamServerBundle\Entity\SteamServer;
18
use DP\VoipServer\TeamspeakServerBundle\Entity\TeamspeakServer;
19
use DP\VoipServer\TeamspeakServerBundle\Entity\TeamspeakServerInstance;
20
21
class ServerContext extends DefaultContext
22
{
23
    /**
24
     * @Given /^I am on the (teamspeak) instance creation page for "([^""]*)"$/
25
     * @When /^I go to the (teamspeak) instance creation page for "([^""]*)"$/
26
     */
27
    public function iAmOnTheVoipPage($type, $value)
28
    {
29
        $parts   = explode('@', $value);
30
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
31
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
32
33
        $this->getSession()->visit($this->generatePageUrl($type . ' instance creation', array('serverId' => $server->getId())));
34
    }
35
36
    /**
37
     * @Given /^I should be on the (teamspeak) instance creation page for "([^""]*)"$/
38
     * @Given /^I should still be on the (teamspeak) instance creation page for "([^""]*)"$/
39
     */
40 View Code Duplication
    public function iShouldBeOnTheVoipPage($type, $value)
41
    {
42
        $parts   = explode('@', $value);
43
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
44
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
45
46
        $this->assertSession()->addressEquals($this->generatePageUrl($type . ' instance creation', array('serverId' => $server->getId())));
47
        $this->assertStatusCodeEquals(200);
48
    }
49
50
    /**
51
     * @Given /^I am on the page of (teamspeak) instance "([^""]*)"$/
52
     * @Given /^I go to the page of (teamspeak) instance "([^""]*)"$/
53
     */
54
    public function iAmOnTheInstancePageByName($type, $name)
55
    {
56
        $resource = $this->findOneBy('instance', array('name' => $name), $type);
57
58
        $this->getSession()->visit($this->generatePageUrl(sprintf('%s_instance_show', $type), array('id' => $resource->getId(), 'serverId' => $resource->getServer()->getId())));
59
    }
60
61
    /**
62
     * @Given /^I am (building|viewing|editing) (teamspeak) instance "([^""]*)"$/
63
     */
64 View Code Duplication
    public function iAmDoingSomethingWithVoipResourceByName($action, $type, $name)
65
    {
66
        $action = str_replace(array_keys($this->actions), array_values($this->actions), $action);
67
        $resource = $this->findOneBy('instance', array('name' => $name), $type);
68
69
        $this->getSession()->visit($this->generatePageUrl(sprintf('%s_instance_%s', $type, $action), array('id' => $resource->getId(), 'serverId' => $resource->getServer()->getId())));
70
    }
71
72
    /**
73
     * @Then /^I should be (building|viewing|editing) (teamspeak) instance "([^""]*)"$/
74
     * @Then /^I should still be (building|viewing|editing) (teamspeak) instance "([^""]*)"$/
75
     */
76 View Code Duplication
    public function iShouldBeDoingSomethingWithVoipResourceByName($action, $type, $name)
77
    {
78
        $action = str_replace(array_keys($this->actions), array_values($this->actions), $action);
79
        $resource = $this->findOneBy('instance', array('name' => $name), $type);
80
81
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('%s_instance_%s', $type, $action), array('id' => $resource->getId(), 'serverId' => $resource->getServer()->getId())));
82
        $this->assertStatusCodeEquals(200);
83
    }
84
85
    /**
86
     * @Then /^I should be on the page of ([^""(w)]*) server "([^""]*)"$/
87
     * @Then /^I should still be on the page of ([^""(w)]*) server "([^""]*)"$/
88
     */
89
    public function iShouldBeOnTheServerPageByName($type, $name)
90
    {
91
        $this->iShouldBeOnTheResourcePage($type, 'name', $name);
92
    }
93
94
    /**
95
     * @Then /^I should be on the page of (teamspeak) instance "([^""]*)"$/
96
     * @Then /^I should still be on the page of (teamspeak) instance "([^""]*)"$/
97
     */
98 View Code Duplication
    public function iShouldBeOnTheInstancePageByName($type, $name)
99
    {
100
        $type = str_replace(' ', '_', $type);
101
        $resource = $this->findOneBy('instance', array('name' => $name), $type);
102
103
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('%s_instance_show', $type), array('id' => $resource->getId(), 'serverId' => $resource->getServer()->getId())));
104
        $this->assertStatusCodeEquals(200);
105
    }
106
107
    /**
108
     * @Given /^I am on the (teamspeak) "([^""]*)" instance index$/
109
     * @TODO: Refactorer comme iAmOnTheVoipPage()
110
     */
111
    public function iAmOnTheInstanceIndex($type, $value)
112
    {
113
        $parts   = explode('@', $value);
114
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
115
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
116
117
        $this->getSession()->visit($this->generatePageUrl(sprintf('dedipanel_%s_instance_index', $type), array('serverId' => $server->getId())));
118
    }
119
120
    /**
121
     * @Then /^I should be on the (teamspeak) "([^"]*)" instance index$/
122
     */
123 View Code Duplication
    public function iShouldBeOnTheInstanceIndexPage($type, $value)
124
    {
125
        $parts   = explode('@', $value);
126
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
127
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
128
129
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('dedipanel_%s_instance_index', $type), array('serverId' => $server->getId())));
130
        $this->assertStatusCodeEquals(200);
131
    }
132
133
    /**
134
     * @Given /^I am (building|viewing|editing) (teamspeak) "([^""]*)"$/
135
     */
136 View Code Duplication
    public function iAmDoingSomethingWithVoipServer($action, $type, $value)
137
    {
138
        $type = str_replace(' ', '_', $type);
139
140
        $action = str_replace(array_keys($this->actions), array_values($this->actions), $action);
141
        $parts   = explode('@', $value);
142
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
143
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
144
145
        $this->getSession()->visit($this->generatePageUrl(sprintf('dedipanel_%s_%s', $type, $action), array('id' => $server->getId())));
146
    }
147
148
    /**
149
     * @Then /^I should be (building|viewing|editing|testing) (teamspeak) "([^""]*)"$/
150
     */
151 View Code Duplication
    public function iShouldBeDoingSomethingWithVoipServer($action, $type, $value)
152
    {
153
        $type = str_replace(' ', '_', $type);
154
155
        $action  = str_replace(array_keys($this->actions), array_values($this->actions), $action);
156
        $parts   = explode('@', $value);
157
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
158
        $server  = $this->findOneBy($type, array('machine' => $machine->getId()));
159
160
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('dedipanel_%s_%s', $type, $action), array('id' => $server->getId())));
161
        $this->assertStatusCodeEquals(200);
162
    }
163
164
    /**
165
     * @When /^I (?:click|press|follow) "([^"]*)" near "([^"]*)"$/
166
     */
167 View Code Duplication
    public function iClickNear($button, $value)
168
    {
169
        $selector = sprintf('.server-list .server-item:contains("%s")', $value);
170
        $item = $this->assertSession()->elementExists('css', $selector);
171
172
        $locator = sprintf('button:contains("%s")', $button);
173
174
        if ($item->has('css', $locator)) {
175
            $item->find('css', $locator)->press();
176
        } else {
177
            $item->clickLink($button);
178
        }
179
    }
180
181
    /**
182
     * @Then /^I should be on the ftp page of ([^""]*) "([^""]*)"$/
183
     */
184 View Code Duplication
    public function iShouldBeOnTheFtpPage($type, $name)
185
    {
186
        $type = str_replace(' ', '_', $type);
187
        $resource = $this->findOneBy($type, array('name' => $name));
188
189
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('%s_ftp_show', $type), array('id' => $resource->getId())));
190
        $this->assertStatusCodeEquals(200);
191
    }
192
193
    /**
194
     * @Then /^I should see (\d+) ([^" ]*) instances in (that|the) list$/
195
     */
196 View Code Duplication
    public function iShouldSeeThatMuchInstancesInTheList($amount, $type)
197
    {
198
        if (1 === count($this->getSession()->getPage()->findAll('css', '.instance-list'))) {
199
            $this->assertSession()->elementsCount('css', '.instance-list > .instance-item', $amount);
200
        } else {
201
            $this->assertSession()->elementsCount('css', sprintf('#%s.instance-list > .instance-item', $type), $amount);
202
        }
203
    }
204
205
    /**
206
     * @Given /^there are following minecraft servers:$/
207
     */
208
    public function thereAreMinecraftServers(TableNode $table)
209
    {
210
        foreach ($table->getHash() as $data) {
211
            $this->thereIsMinecraftServer(
212
                $data['name'],
213
                $data['machine'],
214
                $data['port'],
215
                $data['queryPort'],
216
                $data['rconPort'],
217
                $data['rconPassword'],
218
                $data['game'],
219
                $data['installDir'],
220
                $data['maxplayers'],
221
                $data['minHeap'],
222
                $data['maxHeap'],
223
                (isset($data['installed']) && $data['installed'] == 'yes'),
224
                false
225
            );
226
        }
227
228
        $this->getEntityManager()->flush();
229
    }
230
231
    public function thereIsMinecraftServer($name, $machine = null, $port = 25565, $queryPort = 25565, $rconPort = 25575, $rconPassword = 'test', $game = 'minecraft', $installDir = 'test', $maxplayers = 2, $minHeap = 128, $maxHeap = 256, $installed = true, $flush = true)
232
    {
233
        if (null === $server = $this->getRepository('minecraft')->findOneBy(array('name' => $name))) {
234
            $game    = $this->thereIsGame($game);
235
            $machine = $this->thereIsMachine($machine);
236
237
            $server = new MinecraftServer();
238
            $server->setName($name);
239
            $server->setMachine($machine);
240
            $server->setPort($port);
241
            $server->setQueryPort($queryPort);
242
            $server->setRconPort($rconPort);
243
            $server->setRconPassword($rconPassword);
244
            $server->setGame($game);
245
            $server->setDir($installDir);
246
            $server->setMaxplayers($maxplayers);
247
            $server->setMinHeap($minHeap);
248
            $server->setMaxHeap($maxHeap);
249
250
            if ($installed) {
251
                $server->setInstallationStatus(101);
252
            }
253
254
            $this->validate($server);
255
256
            $this->getEntityManager()->persist($server);
257
258
            if ($flush) {
259
                $this->getEntityManager()->flush();
260
            }
261
        }
262
263
        return $server;
264
    }
265
266
    /**
267
     * @Given /^there are following steam servers:$/
268
     */
269
    public function thereAreSteamServers(TableNode $table)
270
    {
271
        foreach ($table->getHash() as $data) {
272
            $this->thereIsSteamServer(
273
                $data['name'],
274
                $data['machine'],
275
                $data['port'],
276
                $data['rconPassword'],
277
                $data['game'],
278
                $data['installDir'],
279
                $data['maxplayers'],
280
                (isset($data['installed']) && $data['installed'] == 'yes'),
281
                false
282
            );
283
        }
284
285
        $this->getEntityManager()->flush();
286
    }
287
288
    public function thereIsSteamServer($name, $machine = null, $port = 27025, $rconPassword = 'test', $game = 'Counter-Strike', $installDir = 'test', $maxplayers = 2, $installed = true, $flush = true)
289
    {
290
        if (null === $server = $this->getRepository('steam')->findOneBy(array('name' => $name))) {
291
            $game    = $this->thereIsGame($game);
292
            $machine = $this->thereIsMachine($machine);
293
294
            $server = new SteamServer();
295
            $server->setName($name);
296
            $server->setMachine($machine);
297
            $server->setPort($port);
298
            $server->setRconPassword($rconPassword);
299
            $server->setGame($game);
300
            $server->setDir($installDir);
301
            $server->setMaxplayers($maxplayers);
302
303
            if ($installed) {
304
                $server->setInstallationStatus(101);
305
            }
306
307
            $this->validate($server);
308
309
            $this->getEntityManager()->persist($server);
310
311
            if ($flush) {
312
                $this->getEntityManager()->flush();
313
            }
314
        }
315
316
        return $server;
317
    }
318
319
    /**
320
     * @Given /^there are following teamspeak servers:$/
321
     */
322
    public function thereAreTeamspeakServers(TableNode $table)
323
    {
324
        foreach ($table->getHash() as $data) {
325
            $this->thereIsTeamspeakServer(
326
                $data['machine'],
327
                $data['queryPassword'],
328
                $data['installDir'],
329
                (isset($data['installed']) && $data['installed'] == 'yes'),
330
                false
331
            );
332
        }
333
334
        $this->getEntityManager()->flush();
335
    }
336
337
    public function thereIsTeamspeakServer($machine, $queryPassword = 'test', $installDir = 'test', $installed = true, $flush = true)
338
    {
339
        $machine = $this->thereIsMachine($machine);
340
341
        if (null === $server = $this->getRepository('teamspeak')->findOneBy(array('machine' => $machine))) {
342
            $server = new TeamspeakServer();
343
            $server->setMachine($machine);
344
            $server->setQueryPassword($queryPassword);
345
            $server->setDir($installDir);
346
347
            if ($installed) {
348
                $server->setInstallationStatus(101);
349
            }
350
351
            $this->validate($server);
352
353
            $this->getEntityManager()->persist($server);
354
355
            if ($flush) {
356
                $this->getEntityManager()->flush();
357
            }
358
        }
359
360
        return $server;
361
    }
362
363
    /**
364
     * @Given /^there are following teamspeak instances:$/
365
     */
366
    public function thereAreTeamspeakInstances(TableNode $table)
367
    {
368
        foreach ($table->getHash() as $data) {
369
            $this->thereIsTeamspeakInstance(
370
                $data['instanceId'],
371
                $data['name'],
372
                $data['server'],
373
                $data['port'],
374
                $data['slots'],
375
                false
376
            );
377
        }
378
379
        $this->getEntityManager()->flush();
380
    }
381
382
    public function thereIsTeamspeakInstance($instanceId, $name = 'Test', $server = '[email protected]', $port = 9887, $slots = 2, $flush = true)
383
    {
384
        $parts   = explode('@', $server);
385
        $machine = $this->findOneBy('machine', array('username' => $parts[0]));
386
        $server  = $this->findOneBy('teamspeak', array('machine' => $machine->getId()));
387
388
        if (null === $instance = $this->getRepository('instance', 'teamspeak')->findOneBy(array('server' => $server->getId()))) {
389
            $instance = new TeamspeakServerInstance($server);
390
            $instance->setInstanceId($instanceId);
391
            $instance->setName($name);
392
            $instance->setPort($port);
393
            $instance->setMaxClients($slots);
394
            $instance->setAdminToken('test');
395
            $instance->setAutostart(true);
396
397
            $this->validate($server);
398
399
            $this->getEntityManager()->persist($server);
400
401
            if ($flush) {
402
                $this->getEntityManager()->flush();
403
            }
404
        }
405
406
        return $instance;
407
    }
408
409
    /**
410
     * @param string $baseName
411
     */
412
    protected function getRepository($resource, $baseName = null)
413
    {
414
        $service = 'dedipanel.';
415
416
        if (!empty($baseName)) {
417
            $service .= $baseName . '.';
418
        }
419
420
        return $this->getService($service . 'repository.'.$resource);
421
    }
422
423
    protected function findOneBy($type, array $criteria, $repoPrefix = '')
424
    {
425
        $resource = $this
426
            ->getRepository($type, $repoPrefix)
427
            ->findOneBy($criteria)
428
        ;
429
430
        if (null === $resource) {
431
            throw new \InvalidArgumentException(
432
                sprintf('%s for criteria "%s" was not found.', str_replace('_', ' ', ucfirst($type)), serialize($criteria))
433
            );
434
        }
435
436
        return $resource;
437
    }
438
}
439