Completed
Push — master ( 4de43c...7a7d43 )
by Paul
06:26
created

VictoireContext::iShouldSeeXQuantum()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 17
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 11
nc 2
nop 1
1
<?php
2
3
namespace Victoire\Tests\Features\Context;
4
5
use Behat\Behat\Hook\Scope\AfterStepScope;
6
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
7
use Behat\Behat\Hook\Scope\BeforeStepScope;
8
use Behat\Mink\Driver\Selenium2Driver;
9
use Behat\Mink\Element\DocumentElement;
10
use Behat\Mink\Element\Element;
11
use Behat\Mink\Session;
12
use Behat\Symfony2Extension\Context\KernelDictionary;
13
use Behat\Testwork\Hook\Scope\BeforeSuiteScope;
14
use Knp\FriendlyContexts\Context\RawMinkContext;
15
use Symfony\Component\Finder\Finder;
16
17
/**
18
 * This class gives some usefull methods for Victoire navigation.
19
 *
20
 * @property MinkContext minkContext
21
 */
22
class VictoireContext extends RawMinkContext
23
{
24
    use KernelDictionary;
25
    protected $minkContext;
26
27
    /**
28
     * @BeforeSuite
29
     *
30
     * @param BeforeSuiteScope $scope
31
     */
32
    public static function additionalContexts(BeforeSuiteScope $scope)
33
    {
34
        $environment = $scope->getEnvironment();
35
        $contextDir = __DIR__.'/../../../../../../Tests/Context/';
36
37
        if (!is_dir($contextDir)) {
38
            return;
39
        }
40
41
        $finder = new Finder();
42
        $finder->files()->in($contextDir)->name('*Context.php');
43
44
        foreach ($finder as $file) {
45
            $path = $file->getRealPath();
46
            include $path;
47
            $declaredClases = get_declared_classes();
48
            $newContext = end($declaredClases);
49
            $environment->registerContextClass($newContext);
50
        }
51
    }
52
53
    /**
54
     * @BeforeScenario
55
     *
56
     * @param BeforeScenarioScope $scope
57
     */
58
    public function gatherContexts(BeforeScenarioScope $scope)
59
    {
60
        $environment = $scope->getEnvironment();
61
        $this->minkContext = $environment->getContext('Victoire\Tests\Features\Context\MinkContext');
62
    }
63
64
    /**
65
     * @AfterBackground
66
     *
67
     * @param BeforeStepScope $scope
68
     */
69
    public function resetViewsReference(BeforeStepScope $scope)
0 ignored issues
show
Unused Code introduced by
The parameter $scope is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
70
    {
71
        $viewsReferences = $this->getContainer()->get('victoire_core.view_helper')->buildViewsReferences();
72
        $this->getContainer()->get('victoire_view_reference.manager')->saveReferences($viewsReferences);
73
    }
74
75
    /**
76
     * @AfterStep
77
     *
78
     * @param AfterStepScope $scope
79
     *
80
     * @throws \Exception
81
     */
82
    public function lookForJSErrors(AfterStepScope $scope)
83
    {
84
        /* @var Session $session */
85
        $session = $this->getSession();
86
87
        if (!($session->getDriver() instanceof Selenium2Driver)) {
88
            return;
89
        }
90
91
        try {
92
            $errors = $session->evaluateScript('window.jsErrors');
93
            $session->evaluateScript('window.jsErrors = []');
94
        } catch (\Exception $e) {
95
            throw $e;
96
        }
97
        if (!$errors || empty($errors)) {
98
            return;
99
        }
100
        $file = sprintf('%s:%d', $scope->getFeature()->getFile(), $scope->getStep()->getLine());
101
        $message = sprintf('Found %d javascript error%s', count($errors), count($errors) > 0 ? 's' : '');
102
        echo '-------------------------------------------------------------'.PHP_EOL;
103
        echo $file.PHP_EOL;
104
        echo $message.PHP_EOL;
105
        echo '-------------------------------------------------------------'.PHP_EOL;
106
        foreach ($errors as $index => $error) {
0 ignored issues
show
Bug introduced by
The expression $errors of type string is not traversable.
Loading history...
107
            echo sprintf('   #%d: %s', $index, $error).PHP_EOL;
108
        }
109
    }
110
111
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$email" missing
Loading history...
112
     * @Given I am logged in as :email
113
     */
114
    public function iAmLoggedInAsUser($email)
115
    {
116
        $this->minkContext->visit('/login');
117
        $this->minkContext->fillField('username', $email);
118
        $this->minkContext->fillField('password', 'test');
119
        $this->minkContext->pressButton('_submit');
120
    }
121
122
    /**
123
     * @Given I login as visitor
124
     */
125
    public function iLoginAsVisitor()
126
    {
127
        $this->getSession()->getDriver()->stop();
128
        $baseUrl = $this->minkContext->getMinkParameter('base_url');
129
        $url = str_replace('[email protected]:test', '[email protected]:test', $baseUrl);
130
        $this->minkContext->setMinkParameter('base_url', $url);
131
    }
132
133
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$domain" missing
Loading history...
134
     * @Given /^I visit homepage through domain "([^"]*)"$/
135
     */
136
    public function ivisitHomepageThroughDomain($domain)
137
    {
138
        $this->getSession()->getDriver()->stop();
139
        $url = sprintf('http://[email protected]:test@%s:8000/app_domain.php', $domain);
140
        $this->minkContext->setMinkParameter('base_url', $url);
141
        $this->minkContext->visitPath('/');
142
    }
143
144
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$arg" missing
Loading history...
145
     * @Then /^I fill in wysiwyg with "([^"]*)"$/
146
     */
147
    public function iFillInWysiwygOnFieldWith($arg)
148
    {
149
        $js = 'CKEDITOR.instances.victoire_widget_form_ckeditor_content.setData("'.$arg.'");';
150
        $this->getSession()->executeScript($js);
151
    }
152
153
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$widget" missing
Loading history...
introduced by
Doc comment for parameter "$nth" missing
Loading history...
introduced by
Doc comment for parameter "$slot" missing
Loading history...
154
     * @Then /^I select "([^"]*)" from the "([^"]*)" select of "([^"]*)" slot$/
155
     */
156
    public function iSelectFromTheSelectOfSlot($widget, $nth, $slot)
157
    {
158
        $slot = $this->getSession()->getPage()->find('xpath', 'descendant-or-self::*[contains(@id, "vic-slot-'.$slot.'")]');
159
        $selects = $slot->findAll('css', 'select[role="menu"]');
160
        $selects[$nth - 1]->selectOption(str_replace('\\"', '"', $widget));
161
    }
162
163
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$mode" missing
Loading history...
164
     * @Then /^I switch to "([^"]*)" mode$/
165
     */
166 View Code Duplication
    public function iSwitchToMode($mode)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
167
    {
168
        $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', 'descendant-or-self::*[@for="mode-switcher--'.$mode.'"]');
169
170
        if (null === $element) {
171
            $message = sprintf('Element not found in the page after 10 seconds"');
172
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
173
        }
174
        $element->click();
175
    }
176
177
    /**
178
     * @Then /^I (open|close|toggle) the hamburger menu$/
179
     */
180 View Code Duplication
    public function iOpenTheHamburgerMenu()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
181
    {
182
        $element = $this->findOrRetry(
183
            $this->getSession()->getPage(),
184
            'xpath',
185
            'descendant-or-self::*[@id="vic-menu-leftnavbar-trigger"]'
186
        );
187
188
        if (null === $element) {
189
            $message = sprintf('Element not found in the page after 10 seconds"');
190
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
191
        }
192
        $element->click();
193
    }
194
195
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$entity" missing
Loading history...
196
     * @When I open the widget mode drop for entity :entity
197
     */
198 View Code Duplication
    public function iOpenTheWidgetModeDrop($entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
199
    {
200
        $element = $this->findOrRetry(
201
            $this->getSession()->getPage(),
202
            'css',
203
            '[id^="picker-'.strtolower($entity).'"] .v-mode-trigger'
204
        );
205
        if (null === $element) {
206
            $message = sprintf('Element not found in the page after 10 seconds"');
207
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
208
        }
209
        $element->click();
210
    }
211
212
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$key" missing
Loading history...
213
     * @When I open the widget style tab :key
214
     */
215
    public function iOpenTheWidgetStyleTab($key)
216
    {
217
        $element = $this->findOrRetry(
218
            $this->getSession()->getPage(),
219
            'css',
220
            '[title="style-'.$key.'"]'
221
        );
222
        if (null === $element) {
223
            $message = sprintf('Element not found in the page after 10 seconds"');
224
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
225
        }
226
        $element->click();
227
    }
228
229
    /**
230
     * @When I follow the float action button
231
     */
232 View Code Duplication
    public function iFollowTheFloatAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
233
    {
234
        $element = $this->findOrRetry(
235
            $this->getSession()->getPage(),
236
            'css',
237
            '#v-float-container [data-flag="v-drop v-drop-fab"]'
238
        );
239
        if (null === $element) {
240
            $message = sprintf('Element not found in the page after 10 seconds"');
241
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
242
        }
243
        $element->click();
244
    }
245
246
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$entity" missing
Loading history...
247
     * @When I open the widget quantum collapse for entity :entity
248
     */
249 View Code Duplication
    public function iOpenTheWidgetQuantumCollapse($entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
250
    {
251
        $element = $this->findOrRetry(
252
            $this->getSession()->getPage(),
253
            'css',
254
            '[id^="picker-'.strtolower($entity).'"][data-state="visible"] [id^="picker-'.strtolower($entity).'"][data-state="visible"] .v-widget-form__quantum-btn'
255
        );
256
257
        if (null === $element) {
258
            $message = sprintf('Element not found in the page after 10 seconds"');
259
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
260
        }
261
        $element->click();
262
    }
263
264
    /**
265
     * @When I open the widget quantum collapse when static
266
     */
267 View Code Duplication
    public function iOpenTheWidgetQuantumCollapseWhenStatic()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
268
    {
269
        $element = $this->findOrRetry(
270
            $this->getSession()->getPage(),
271
            'css',
272
            '[data-state="visible"] [id^="picker-static"] .v-widget-form__quantum-btn'
273
        );
274
275
        if (null === $element) {
276
            $message = sprintf('Element not found in the page after 10 seconds"');
277
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
278
        }
279
        $element->click();
280
    }
281
282
    /**
283
     * @Then /^I open the settings menu$/
284
     */
285 View Code Duplication
    public function iOpenTheSettingsMenu()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
286
    {
287
        $element = $this->findOrRetry(
288
            $this->getSession()->getPage(),
289
            'xpath',
290
            'descendant-or-self::*[@id="v-settings-link"]'
291
        );
292
293
        if (null === $element) {
294
            $message = sprintf('Element not found in the page after 10 seconds"');
295
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
296
        }
297
        $element->click();
298
    }
299
300
    /**
301
     * @Then /^I open the additional menu drop$/
302
     */
303 View Code Duplication
    public function iOpenTheAdditionalsMenuDrop()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
304
    {
305
        $element = $this->findOrRetry(
306
            $this->getSession()->getPage(),
307
            'xpath',
308
            'descendant-or-self::*[@id="v-additionals-drop"]'
309
        );
310
311
        if (null === $element) {
312
            $message = sprintf('Element not found in the page after 10 seconds"');
313
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
314
        }
315
        $element->click();
316
    }
317
318
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
319
     * @When I follow the tab :name
320
     */
321
    public function iFollowTheTab($name)
322
    {
323
        $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', sprintf('descendant-or-self::a[contains(@class, "v-tabs-nav__anchor") and contains(normalize-space(text()), "%s")]', $name));
324
325
        // @TODO When the new styleguide is completly integrated, remove.
326
        if (null === $element) {
327
            $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', sprintf('descendant-or-self::a[@data-toggle="vic-tab" and normalize-space(text()) = "%s"]', $name));
328
        }
329
330
        if (null === $element) {
331
            $message = sprintf('Element not found in the page after 10 seconds"');
332
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
333
        }
334
        $element->click();
335
    }
336
337
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
338
     * @When I follow the drop trigger :name
339
     */
340 View Code Duplication
    public function iFollowTheDropTrigger($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
341
    {
342
        $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', sprintf('descendant-or-self::a[@data-flag*="v-drop" and normalize-space(text()) = "%s"]', $name));
343
344
        if (null === $element) {
345
            $message = sprintf('Element not found in the page after 10 seconds"');
346
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
347
        }
348
        $element->click();
349
    }
350
351
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
352
     * @When I follow the drop anchor :name
353
     */
354
    public function iFollowTheDropAnchor($name)
355
    {
356
        $page = $this->getSession()->getPage();
357
        $elements = $page->findAll('xpath', sprintf('descendant-or-self::a[contains(@class, "v-drop__anchor") and normalize-space(text()) = "%s"]', $name));
358
359
        if (count($elements) < 1) {
360
            $message = sprintf('Element not found in the page after 10 seconds"');
361
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
362
        }
363
364
        foreach ($elements as $element) {
365
            if ($element->getText() === $name) {
366
                $element->click();
367
            }
368
        }
369
    }
370
371
    /**
372
     * @Then /^I submit the widget$/
373
     * @Then /^I submit the modal$/
374
     */
375
    public function iSubmitTheWidget()
376
    {
377
        $element = $this->getSession()->getPage()->find('xpath', 'descendant-or-self::a[@data-modal="create"]');
378
379
        if (!$element) {
380
            $element = $this->getSession()->getPage()->find('xpath', 'descendant-or-self::a[@data-modal="update"]');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $element is correct as $this->getSession()->get...@data-modal="update"]') (which targets Behat\Mink\Element\Element::find()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
381
        }
382
        $element->click();
383
        $this->getSession()->wait(2000);
384
    }
385
386
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$widgetType" missing
Loading history...
387
     * @Given /^I edit an "([^"]*)" widget$/
388
     * @Given /^I edit the "([^"]*)" widget$/
389
     */
390
    public function iEditTheWidget($widgetType)
391
    {
392
        $selector = sprintf('.v-widget--%s > a.v-widget__overlay', strtolower($widgetType));
393
        $session = $this->getSession(); // get the mink session
394
        $element = $this->findOrRetry($session->getPage(), 'css', $selector);
395
396
        // errors must not pass silently
397
        if (null === $element) {
398
            throw new \InvalidArgumentException(sprintf('Could not evaluate CSS selector: "%s"', $selector));
399
        }
400
401
        // ok, let's hover it
402
        $element->mouseOver();
403
        $element->click();
404
    }
405
406
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$textBefore" missing
Loading history...
introduced by
Doc comment for parameter "$textAfter" missing
Loading history...
407
     * @Then /^"([^"]*)" should precede "([^"]*)"$/
408
     */
409
    public function shouldPrecedeForTheQuery($textBefore, $textAfter)
410
    {
411
        $element = $this->getSession()->getPage()->find(
412
            'xpath',
413
            sprintf('//*[normalize-space(text()) = "%s"][preceding::*[normalize-space(text()) = "%s"]]',
414
                $textAfter,
415
                $textBefore
416
            )
417
        );
418
        if (null === $element) {
419
            $message = sprintf('"%s" does not preceed "%s"', $textBefore, $textAfter);
420
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
421
        }
422
    }
423
424
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$option" missing
Loading history...
introduced by
Doc comment for parameter "$dropdown" missing
Loading history...
425
     * @When /^I select the option "(?P<option>[^"]*)" in the dropdown "(?P<dropdown>[^"]*)"$/
426
     */
427
    public function iSelectTheOptionInTheDropdown($option, $dropdown)
428
    {
429
        $link = $this->getSession()->getPage()->find('css', sprintf('a.vic-dropdown-toggle[title="%s"]', $dropdown));
430
        $link->click();
431
        $optionButton = $this->getSession()->getPage()->find('css', sprintf('ul[aria-labelledby="%sDropdownMenu"] > li > a[title="%s"]', $dropdown, $option));
432
        $optionButton->click();
433
    }
434
435
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$imageId" missing
Loading history...
introduced by
Doc comment for parameter "$fieldId" missing
Loading history...
436
     * @Then /^I attach image with id "(\d+)" to victoire field "(.+)"$/
437
     */
438
    public function attachImageToVictoireScript($imageId, $fieldId)
439
    {
440
        $script = sprintf('$("#%s input").val(%d)', $fieldId, $imageId);
441
        $this->getSession()->executeScript($script);
442
    }
443
444
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$element" missing
Loading history...
introduced by
Doc comment for parameter "$selector" missing
Loading history...
introduced by
Doc comment for parameter "$value" missing
Loading history...
445
     * @Then I should find css element :element with selector :selector and value :value
446
     */
447
    public function iShouldFindCssWithSelectorAndValue($element, $selector, $value)
448
    {
449
        $css = sprintf('%s[%s="%s"]', $element, $selector, $value);
450
        $session = $this->getSession();
451
        $element = $this->findOrRetry($session->getPage(), 'css', $css);
452
453
        if (null === $element) {
454
            $message = sprintf('Element not found. String generate: %s[%s="%s"]', $element, $selector, $value);
455
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
456
        }
457
    }
458
459
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
460
     * @Then I should see disable drop anchor :name
461
     */
462 View Code Duplication
    public function iShouldSeeDisableDropAnchor($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
463
    {
464
        $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', sprintf('descendant-or-self::*[contains(@class, \'v-drop__anchor--disabled\') and normalize-space(.) = "%s"]', $name));
465
466
        if (null === $element) {
467
            $message = sprintf('Element not found in the page after 10 seconds"');
468
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
469
        }
470
    }
471
472
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
473
     * @Then I should see disable tab :name
474
     */
475 View Code Duplication
    public function iShouldSeeDisableTab($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
476
    {
477
        $element = $this->findOrRetry($this->getSession()->getPage(), 'xpath', sprintf('descendant-or-self::li[@class="vic-disable" and normalize-space(.) = "%s"]', $name));
478
479
        if (null === $element) {
480
            $message = sprintf('Element not found in the page after 10 seconds"');
481
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
482
        }
483
    }
484
485
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$widgetMapMoved" missing
Loading history...
introduced by
Doc comment for parameter "$position" missing
Loading history...
introduced by
Doc comment for parameter "$widgetMapMovedTo" missing
Loading history...
486
     * @Then /^I move the widgetMap "(.+)" "(.+)" the widgetMap "(.*)"$/
487
     */
488
    public function iMoveWidgetUnder($widgetMapMoved, $position, $widgetMapMovedTo)
489
    {
490
        if (!$widgetMapMovedTo) {
491
            $widgetMapMovedTo = 'null';
492
        }
493
        $js = 'updateWidgetPosition({"parentWidgetMap": '.$widgetMapMovedTo.', "slot": "main_content", "position": "'.$position.'", "widgetMap": '.$widgetMapMoved.'})';
494
495
        $this->getSession()->executeScript($js);
496
    }
497
498
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$quantumPosition" missing
Loading history...
introduced by
Doc comment for parameter "$name" missing
Loading history...
499
     * @When /^I rename quantum "(.+)" with "(.+)"$/
500
     */
501
    public function iRenameQuantumWith($quantumPosition, $name)
502
    {
503
        $session = $this->getSession();
504
505
        $pencilSelector = sprintf('descendant-or-self::ul[contains(@class, \'vic-quantum-nav\')]/li[%s]/a/i[contains(@class, \'fa-pencil\')]', $quantumPosition);
506
        $pencil = $this->findOrRetry($session->getPage(), 'xpath', $pencilSelector);
507
        $pencil->click();
508
509
        $input = $this->findOrRetry($session->getPage(), 'css', '.quantum-edit-field');
510
        $input->setValue($name);
511
512
        //Click outside
513
        $list = $this->findOrRetry($session->getPage(), 'css', '.vic-quantum-nav');
514
        $list->click();
515
    }
516
517
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$quantumName" missing
Loading history...
518
     * @When /^I select quantum "(.+)"$/
519
     */
520
    public function iSelectQuantum($quantumName)
521
    {
522
        $session = $this->getSession();
523
524
        $quantumSelector = sprintf('descendant-or-self::a[contains(@class, \'v-btn--quantum\') and normalize-space(.) = "%s"]', $quantumName);
525
        $quantum = $this->findOrRetry($session->getPage(), 'xpath', $quantumSelector);
526
        $quantum->click();
527
    }
528
529
    /**
530
     * @When /^I create a new quantum$/
531
     */
532
    public function iCreateANewQuantum()
533
    {
534
        $session = $this->getSession();
535
536
        $element = $this->findOrRetry($session->getPage(), 'css', '#widget-new-tab');
537
        $element->click();
538
    }
539
540
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$nb" missing
Loading history...
541
     * @When /^I should see "(.+)" quantum$/
542
     * @When /^I should see "(.+)" quantum creation button$/
543
     */
544
    public function iShouldSeeXQuantum($nb)
545
    {
546
        $session = $this->getSession();
547
548
        $quantums = $this->findOrRetry(
549
            $session->getPage(),
550
            'xpath',
551
            'descendant-or-self::div[contains(@id, "v-quantum-tab")]/descendant-or-self::a[contains(@class, "v-btn--quantum")]',
552
            10000,
553
            'findAll'
554
        );
555
556
        if (count($quantums) != $nb) {
557
            $message = sprintf('%s quantum(s) found', count($quantums));
558
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
559
        }
560
    }
561
562
    /**
563
     * @When /^I should see the success message for Widget edit$/
564
     */
565
    public function iShouldSeeTheSuccessMessageForWidgetEdit()
566
    {
567
        $this->minkContext->assertPageContainsText('Victoire!');
568
    }
569
570
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$name" missing
Loading history...
571
     * @When I select :arg1 from the collapse menu
572
     */
573
    public function iSelectFromTheCollapseMenu($name)
574
    {
575
        $page = $this->getSession()->getPage();
576
577
        $menus = $page->findAll('xpath', sprintf('descendant-or-self::a[contains(@class, "v-mode-trigger")]'));
578
        if (count($menus) < 1) {
579
            $message = sprintf('Collapse menu not found in the page after 10 seconds"');
580
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
581
        }
582
583
        foreach ($menus as $menu) {
584
            if ($menu->isVisible()) {
585
                $menu->click();
586
            }
587
        }
588
589
        $links = $menu = $page->findAll('xpath', sprintf('descendant-or-self::div[contains(@class, "v-drop__menu")]//a[contains(@class, "v-drop__anchor") and normalize-space(text()) = "%s"]', $name));
0 ignored issues
show
Unused Code introduced by
$menu 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...
590
591
        if (count($links) < 1) {
592
            $message = sprintf('Menu link not found in the page after 10 seconds"');
593
            throw new \Behat\Mink\Exception\ResponseTextException($message, $this->getSession());
594
        }
595
596
        foreach ($links as $link) {
597
            if ($link->getText() === $name) {
598
                $link->click();
599
            }
600
        }
601
    }
602
603
    /**
604
     * Try to find value in element and retry for a given time.
605
     *
606
     * @param Element $element
607
     * @param string  $selectorType xpath|css
608
     * @param string  $value
609
     * @param int     $timeout
610
     * @param string  $method
611
     *
612
     * @return \Behat\Mink\Element\NodeElement|mixed|null|void
613
     */
614
    protected function findOrRetry(Element $element, $selectorType, $value, $timeout = 10000, $method = 'find')
615
    {
616
        if ($timeout <= 0) {
617
            return;
618
        }
619
620
        $item = $element->$method($selectorType, $value);
621
622 View Code Duplication
        if ($item) {
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...
623
            return $item;
624
        } else {
625
            $this->getSession()->wait(100);
626
627
            return $this->findOrRetry($element, $selectorType, $value, $timeout - 100);
628
        }
629
    }
630
631
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$field" missing
Loading history...
introduced by
Doc comment for parameter "$value" missing
Loading history...
introduced by
Doc comment for parameter "$entry" missing
Loading history...
632
     * Fill Select2 input field and select a value.
633
     *
634
     * @When /^(?:|I )fill in select2 input "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)" and select "(?P<entry>(?:[^"]|\\")*)"$/
635
     */
636
    public function iFillInSelect2InputWithAndSelect($field, $value, $entry)
0 ignored issues
show
introduced by
Declare public methods first,then protected ones and finally private ones
Loading history...
637
    {
638
        $page = $this->getSession()->getPage();
639
        $this->openField($page, $field);
640
        $this->fillSearchField($page, $field, $value);
641
        $this->selectValue($page, $field, $entry);
642
    }
643
644
    /**
645
     * Open Select2 choice list.
646
     *
647
     * @param DocumentElement $page
648
     * @param string          $field
649
     *
650
     * @throws \Exception
651
     */
652
    private function openField(DocumentElement $page, $field)
653
    {
654
        $fieldName = sprintf('select[name="%s"] + .select2-container', $field);
655
        $inputField = $page->find('css', $fieldName);
656
        if (!$inputField) {
657
            throw new \Exception(sprintf('No field "%s" found', $field));
658
        }
659
        $choice = $inputField->find('css', '.select2-selection');
660
        if (!$choice) {
661
            throw new \Exception(sprintf('No select2 choice found for "%s"', $field));
662
        }
663
        $choice->press();
664
    }
665
666
    /**
667
     * Fill Select2 search field.
668
     *
669
     * @param DocumentElement $page
670
     * @param string          $field
671
     * @param string          $value
672
     *
673
     * @throws \Exception
674
     */
675
    private function fillSearchField(DocumentElement $page, $field, $value)
676
    {
677
        $driver = $this->getSession()->getDriver();
678
        if ('Behat\Mink\Driver\Selenium2Driver' === get_class($driver)) {
679
            // Can't use `$this->getSession()->getPage()->find()` because of https://github.com/minkphp/MinkSelenium2Driver/issues/188
680
            $select2Input = $this->getSession()->getDriver()->getWebDriverSession()->element('xpath', "//html/descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), ' select2-search__field ')]");
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Mink\Driver\DriverInterface as the method getWebDriverSession() does only exist in the following implementations of said interface: Behat\Mink\Driver\Selenium2Driver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
681
            if (!$select2Input) {
682
                throw new \Exception(sprintf('No field "%s" found', $field));
683
            }
684
            $select2Input->postValue(['value' => [$value]]);
685
        } else {
686
            $select2Input = $page->find('css', '.select2-search__field');
687
            if (!$select2Input) {
688
                throw new \Exception(sprintf('No input found for "%s"', $field));
689
            }
690
            $select2Input->setValue($value);
691
        }
692
        $this->waitForLoadingResults();
693
    }
694
695
    /**
696
     * Select value in choice list.
697
     *
698
     * @param DocumentElement $page
699
     * @param string          $field
700
     * @param string          $value
701
     *
702
     * @throws \Exception
703
     */
704
    private function selectValue(DocumentElement $page, $field, $value)
705
    {
706
        $this->waitForLoadingResults();
707
        $chosenResults = $page->findAll('css', '.select2-results li');
708
        foreach ($chosenResults as $result) {
709
            if ($result->getText() == $value) {
710
                $result->click();
711
712
                return;
713
            }
714
        }
715
        throw new \Exception(sprintf('Value "%s" not found for "%s"', $value, $field));
716
    }
717
718
    /**
719
     * Wait the end of fetching Select2 results.
720
     *
721
     * @param int $time Time to wait in seconds
722
     */
723
    private function waitForLoadingResults($time = 60)
724
    {
725
        for ($i = 0; $i < $time; $i++) {
726
            if (!$this->getSession()->getPage()->find('css', '.select2-results__option.loading-results')) {
727
                return true;
728
            }
729
            sleep(1);
730
        }
731
        throw new \Exception(sprintf('Results are not load after "%d" seconds.', $time));
732
    }
733
}
734