DefaultContext   B
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 407
Duplicated Lines 16.46 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 54
c 3
b 0
f 0
lcom 1
cbo 5
dl 67
loc 407
rs 7.0642

33 Methods

Rating   Name   Duplication   Size   Complexity  
A generatePageUrl() 0 18 3
A getRepository() 10 10 2
A findOneBy() 14 14 2
A iAmOnThePage() 0 4 1
A iShouldBeOnThePage() 0 5 1
A accessShouldBeForbidden() 0 6 1
A iShouldBeUnauthorizedOnThePage() 0 5 1
A iLeaveFieldEmpty() 0 4 1
A iShouldSeeFieldsOnError() 0 4 1
A iShouldSeeAlertMessage() 0 6 2
A iAmLoggedInWithAccount() 0 14 2
C whenIFillInFormWith() 0 29 8
A fillCheckbox() 0 14 3
A fillRadio() 0 11 3
A iShouldSeeResourceWithValueInThatList() 0 4 1
A iShouldNotSeeResourceWithValueInThatList() 0 4 1
A iShouldSeeThatMuchResourcesInTheList() 8 8 2
A iShouldBeOnTheResourcePage() 8 8 1
A iAmOnTheResourcePage() 0 8 1
A iAmOnTheResourcePageByName() 0 4 1
A iAmDoingSomethingWithResource() 9 9 1
A iAmDoingSomethingWithResourceByName() 0 4 1
A iShouldBeDoingSomethingWithResource() 10 10 1
A iShouldBeDoingSomethingWithResourceByName() 0 4 1
A assertStatusCodeEquals() 0 4 1
A iShouldSeeAssociatedGames() 0 4 1
A iShouldSeeButton() 0 6 1
A iShouldNotSeeButton() 0 6 1
A iShouldBeOn403() 0 7 1
A iShouldSeeCheckboxes() 0 6 1
A iShouldSeeOptionsInSelect() 0 7 1
A findField() 0 11 3
A iShouldSeeThatMuchServersInTheList() 8 8 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 DefaultContext 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 DefaultContext, 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 Sylius\Bundle\ResourceBundle\Behat\DefaultContext as SyliusDefaultContext;
15
use Behat\Gherkin\Node\TableNode;
16
17
class DefaultContext extends SyliusDefaultContext
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $actions = array(
23
        'viewing'  => 'show',
24
        'creation' => 'create',
25
        'editing'  => 'update',
26
        'building' => 'build',
27
        'testing'  => 'connection_test',
28
    );
29
30
    /** {@inheritdoc} */
31
    protected function generatePageUrl($page, array $parameters = array())
32
    {
33
        if (is_object($page)) {
34
            return $this->locatePath($this->generateUrl($page, $parameters));
0 ignored issues
show
Documentation introduced by
$page is of type object, but the function expects a string.

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...
35
        }
36
37
        $route  = str_replace(' ', '_', trim($page));
38
        $routes = $this->getContainer()->get('router')->getRouteCollection();
39
40
        if (null === $routes->get($route)) {
41
            $route = 'dedipanel_'.$route;
42
        }
43
44
        $route = str_replace(array_keys($this->actions), array_values($this->actions), $route);
45
        $route = str_replace(' ', '_', $route);
46
47
        return $this->locatePath($this->generateUrl($route, $parameters));
48
    }
49
50
    /**
51
     * @param string $baseName
52
     */
53 View Code Duplication
    protected function getRepository($resource, $baseName = null)
54
    {
55
        $service = 'dedipanel.';
56
57
        if (!empty($baseName)) {
58
            $service .= $baseName . '.';
59
        }
60
61
        return $this->getService($service . 'repository.'.$resource);
62
    }
63
64 View Code Duplication
    protected function findOneBy($type, array $criteria, $repoPrefix = '')
65
    {
66
        $resource = $this
67
            ->getRepository($type, $repoPrefix)
68
            ->findOneBy($criteria);
69
70
        if (null === $resource) {
71
            throw new \InvalidArgumentException(
72
                sprintf('%s for criteria "%s" was not found.', str_replace('_', ' ', ucfirst($type)), serialize($criteria))
73
            );
74
        }
75
76
        return $resource;
77
    }
78
79
    /**
80
     * @Given /^I am on the (.+) (page)?$/
81
     * @When /^I go to the (.+) (page)?$/
82
     */
83
    public function iAmOnThePage($page)
84
    {
85
        $this->getSession()->visit($this->generatePageUrl($page));
86
    }
87
88
    /**
89
     * @Then /^I should be on the (.+) (page)$/
90
     * @Then /^I should be redirected to the (.+) (page)$/
91
     * @Then /^I should still be on the (.+) (page)$/
92
     */
93
    public function iShouldBeOnThePage($page)
94
    {
95
        $this->assertSession()->addressEquals($this->generatePageUrl($page));
96
        $this->assertStatusCodeEquals(200);
97
    }
98
99
    /**
100
     * @Then /^access should be forbidden$/
101
     */
102
    public function accessShouldBeForbidden()
103
    {
104
        $this->assertStatusCodeEquals(403);
105
        $this->iShouldSeeAlertMessage(1, 'error');
106
        $this->assertSession()->pageTextContains("Vous n'avez pas accès à cette page.");
107
    }
108
109
    /**
110
     * @Then /^I should be unauthorized on the (.+) (page)$/
111
     */
112
    public function iShouldBeUnauthorizedOnThePage($page)
113
    {
114
        $this->assertSession()->addressEquals($this->generatePageUrl($page));
115
        $this->assertStatusCodeEquals(403);
116
    }
117
118
    /**
119
     * @Given /^I leave "([^"]*)" empty$/
120
     * @Given /^I leave "([^"]*)" field blank/
121
     */
122
    public function iLeaveFieldEmpty($field)
123
    {
124
        $this->fillField($field, '');
125
    }
126
127
    /**
128
     * @Then /^I should see (\d+) validation errors?$/
129
     */
130
    public function iShouldSeeFieldsOnError($amount)
131
    {
132
        $this->iShouldSeeAlertMessage($amount, 'error');
133
    }
134
135
    /**
136
     * @Then /^I should see (\d+) (?:alert )?((error|success) )?message$/
137
     */
138
    public function iShouldSeeAlertMessage($amount, $type = '')
139
    {
140
        $class = '.alert' . (!empty($type) ? '-' . $type : '');
141
142
        $this->assertSession()->elementsCount('css', $class . ' > ul > li', $amount);
143
    }
144
145
    /**
146
     * @Given /^I am logged in with (.*) account$/
147
     */
148
    public function iAmLoggedInWithAccount($username)
149
    {
150
        $password = 'test1234';
151
152
        if (isset($this->users[$username])) {
153
            $password = $this->users[$username];
0 ignored issues
show
Bug introduced by
The property users does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
154
        }
155
156
        $this->getSession()->visit($this->generatePageUrl('fos_user_security_login'));
157
158
        $this->fillField("Nom d'utilisateur", $username);
159
        $this->fillField('Mot de passe', $password);
160
        $this->pressButton('Connexion');
161
    }
162
163
    /**
164
     * @When /^I fill in (.+) form with:$/
165
     */
166
    public function whenIFillInFormWith($base, TableNode $table)
167
    {
168
        $page = $this->getSession()->getPage();
0 ignored issues
show
Unused Code introduced by
$page 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...
169
170
        foreach ($table->getTable() AS $item) {
171
            list($name,$value) = $item;
172
            $field     = $this->findField($base, $name);
173
            $fieldName = $field->getAttribute('name');
174
175
            if ($name == 'machine' || $name == 'game') {
176
                $key = ($name == 'machine' ? 'username' : 'name');
177
                $entity = $this->findOneBy($name, array($key => $value));
178
                $value = $entity->getId();
179
            }
180
181
            if ($field->getTagName() == 'select') {
182
                $this->selectOption($fieldName, $value);
183
            }
184
            elseif ($field->getAttribute('type') == 'checkbox') {
185
                $this->fillCheckbox($fieldName, $value);
186
            }
187
            elseif ($field->getAttribute('type') == 'radio') {
188
                $this->fillRadio($fieldName, $value);
189
            }
190
            else {
191
                $this->fillField($fieldName, $value);
192
            }
193
        }
194
    }
195
196
    public function fillCheckbox($fieldName, $value)
197
    {
198
        $page = $this->getSession()->getPage();
199
200
        if ($value == 'yes') {
201
            $page->checkField($fieldName);
202
        }
203
        elseif ($value == 'no') {
204
            $page->uncheckField($fieldName);
205
        }
206
        else {
207
            throw new \RuntimeException(sprintf('Unsupported value "%s" for the checkbox field "%s"', $value, $fieldName));
208
        }
209
    }
210
211
    public function fillRadio($fieldName, $value)
212
    {
213
        if ($value == 'yes') {
214
            $value = 1;
215
        }
216
        elseif ($value == 'no') {
217
            $value = 0;
218
        }
219
220
        $this->fillField($fieldName, $value);
221
    }
222
223
    /**
224
     * @Then /^I should see [\w\s]+ with [\w\s]+ "([^""]*)" in (that|the) list$/
225
     */
226
    public function iShouldSeeResourceWithValueInThatList($value)
227
    {
228
        $this->assertSession()->elementTextContains('css', 'table', $value);
229
    }
230
231
    /**
232
     * @Then /^I should not see [\w\s]+ with [\w\s]+ "([^""]*)" in (that|the) list$/
233
     */
234
    public function iShouldNotSeeResourceWithValueInThatList($value)
235
    {
236
        $this->assertSession()->elementTextNotContains('css', 'table', $value);
237
    }
238
239
    /**
240
     * @Then /^I should see (\d+) ([^"" ]*) in (that|the) list$/
241
     */
242 View Code Duplication
    public function iShouldSeeThatMuchResourcesInTheList($amount, $type)
243
    {
244
        if (1 === count($this->getSession()->getPage()->findAll('css', 'table'))) {
245
            $this->assertSession()->elementsCount('css', 'table tbody > tr', $amount);
246
        } else {
247
            $this->assertSession()->elementsCount('css', sprintf('table#%s tbody > tr', str_replace(' ', '-', $type)), $amount);
248
        }
249
    }
250
251
    /**
252
     * @Then /^I should be on the page of ([^""]*) with ([^""]*) "([^""]*)"$/
253
     * @Then /^I should still be on the page of ([^""]*) with ([^""]*) "([^""]*)"$/
254
     */
255 View Code Duplication
    public function iShouldBeOnTheResourcePage($type, $property, $value)
256
    {
257
        $type = str_replace(' ', '_', $type);
258
        $resource = $this->findOneBy($type, array($property => $value));
259
260
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('%s_show', $type), array('id' => $resource->getId())));
261
        $this->assertStatusCodeEquals(200);
262
    }
263
264
    /**
265
     * @Given /^I am on the page of ([^""]*) with ([^""]*) "([^""]*)"$/
266
     * @Given /^I go to the page of ([^""]*) with ([^""]*) "([^""]*)"$/
267
     */
268
    public function iAmOnTheResourcePage($type, $property, $value)
269
    {
270
        $type = str_replace(' ', '_', $type);
271
272
        $resource = $this->findOneBy($type, array($property => $value));
273
274
        $this->getSession()->visit($this->generatePageUrl(sprintf('%s_show', $type), array('id' => $resource->getId())));
275
    }
276
277
    /**
278
     * @Given /^I am on the page of (?!teamspeak)([^""(w)]*) "([^""]*)"$/
279
     * @Given /^I go to the page of (?!teamspeak)([^""(w)]*) "([^""]*)"$/
280
     */
281
    public function iAmOnTheResourcePageByName($type, $name)
282
    {
283
        $this->iAmOnTheResourcePage($type, 'name', $name);
284
    }
285
286
    /**
287
     * @Given /^I am (building|viewing|editing) ([^""]*) with ([^""]*) "([^""]*)"$/
288
     */
289 View Code Duplication
    public function iAmDoingSomethingWithResource($action, $type, $property, $value)
290
    {
291
        $type = str_replace(' ', '_', $type);
292
293
        $action = str_replace(array_keys($this->actions), array_values($this->actions), $action);
294
        $resource = $this->findOneBy($type, array($property => $value));
295
296
        $this->getSession()->visit($this->generatePageUrl(sprintf('%s_%s', $type, $action), array('id' => $resource->getId())));
297
    }
298
299
    /**
300
     * @Given /^I am (building|viewing|editing) (?!teamspeak)([^""(w)]*) "([^""]*)"$/
301
     */
302
    public function iAmDoingSomethingWithResourceByName($action, $type, $name)
303
    {
304
        $this->iAmDoingSomethingWithResource($action, $type, 'name', $name);
305
    }
306
307
    /**
308
     * @Then /^I should be (building|viewing|editing|testing) ([^"]*) with ([^"]*) "([^""]*)"$/
309
     */
310 View Code Duplication
    public function iShouldBeDoingSomethingWithResource($action, $type, $property, $value)
311
    {
312
        $type = str_replace(' ', '_', $type);
313
314
        $action = str_replace(array_keys($this->actions), array_values($this->actions), $action);
315
        $resource = $this->findOneBy($type, array($property => $value));
316
317
        $this->assertSession()->addressEquals($this->generatePageUrl(sprintf('dedipanel_%s_%s', $type, $action), array('id' => $resource->getId())));
318
        $this->assertStatusCodeEquals(200);
319
    }
320
321
    /**
322
     * @Then /^I should be (building|viewing|editing) (?!teamspeak)([^""(w)]*) "([^""]*)"$/
323
     */
324
    public function iShouldBeDoingSomethingWithResourceByName($action, $type, $name)
325
    {
326
        $this->iShouldBeDoingSomethingWithResource($action, $type, 'name', $name);
327
    }
328
329
    /**
330
     * Assert that given code equals the current one.
331
     *
332
     * @param integer $code
333
     */
334
    protected function assertStatusCodeEquals($code)
335
    {
336
        $this->assertSession()->statusCodeEquals($code);
337
    }
338
339
    /**
340
     * @Then /^I should see (\d+) associated games?$/
341
     */
342
    public function iShouldSeeAssociatedGames($amount)
343
    {
344
        $this->assertSession()->elementsCount('css', 'ul.associated-games > li', $amount);
345
    }
346
347
    /**
348
     * @Then /^I should see (\d+) buttons? "([^"]+)"$/
349
     */
350
    public function iShouldSeeButton($count, $value)
351
    {
352
        $locator = sprintf('a:contains("%s"), button:contains("%s")', $value, $value);
353
354
        $this->assertSession()->elementsCount('css', $locator, $count);
355
    }
356
357
    /**
358
     * @Then /^I should not see button "([^"]+)"$/
359
     */
360
    public function iShouldNotSeeButton($value)
361
    {
362
        $locator = sprintf('a:contains("%s"), button:contains("%s")', $value, $value);
363
364
        $this->assertSession()->elementsCount('css', $locator, 0);
365
    }
366
367
    /**
368
     * @Then /^I should be on 403 page$/
369
     * @Then /^I should be on 403 page with "([^"]+)"$/
370
     */
371
    public function iShouldBeOn403($message = "Vous n'avez pas accès à cette page.")
372
    {
373
        $this->assertStatusCodeEquals(403);
374
375
        $this->iShouldSeeAlertMessage(1, 'error');
376
        $this->assertSession()->pageTextContains($message);
377
    }
378
379
    /**
380
     * @Then /^I should see (\d+) "([^"]+)" checkbox(?:es)? in "([^"]+)" form$/
381
     */
382
    public function iShouldSeeCheckboxes($count, $type, $form)
383
    {
384
        $locator = sprintf('//input[@type="checkbox"][@name="%s[%s][]"]', $form, $type);
385
386
        $this->assertSession()->elementscount('xpath', $locator, $count);
387
    }
388
389
    /**
390
     * @Then /^I should see (\d+) "([^"]+)" options in "([^"]+)" form$/
391
     */
392
    public function iShouldSeeOptionsInSelect($count, $type, $form)
393
    {
394
        $xpath   = sprintf('%s[%s]', $form, $type);
395
        $locator = sprintf('//select[@name="%s" or @name="%s[]"]/option', $xpath, $xpath);
396
397
        $this->assertSession()->elementsCount('xpath', $locator, $count);
398
    }
399
400
    public function findField($form, $fieldName)
401
    {
402
        $page = $this->getSession()->getPage();
403
        $fieldName = sprintf('%s[%s]', $form, $fieldName);
404
405
        if ((null === $field = $page->findField($fieldName)) && (null === $field = $page->findField($fieldName . '[]'))) {
406
            throw new \RuntimeException(sprintf('Form field with id|name|label|value "%s" or "%s[]" not found.', $fieldName, $fieldName));
407
        }
408
409
        return $field;
410
    }
411
412
    /**
413
     * @Then /^I should see (\d+) ([^" ]*) servers in (that|the) list$/
414
     */
415 View Code Duplication
    public function iShouldSeeThatMuchServersInTheList($amount, $type)
416
    {
417
        if (1 === count($this->getSession()->getPage()->findAll('css', '.server-list'))) {
418
            $this->assertSession()->elementsCount('css', '.server-list > .server-item', $amount);
419
        } else {
420
            $this->assertSession()->elementsCount('css', sprintf('#%s.server-list > .server-item', $type), $amount);
421
        }
422
    }
423
}