Completed
Pull Request — develop (#509)
by ANTHONIUS
21:03
created

CoreContext   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 302
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 12
dl 0
loc 302
rs 9.68
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeSuite() 0 4 1
A setupContexts() 0 14 3
A getApplication() 0 7 2
A getServiceManager() 0 4 1
A getEventManager() 0 4 1
A getRepositories() 0 4 1
A generateUrl() 0 4 1
A iHoverOverTheElement() 0 13 2
A iWaitForSecond() 0 4 1
A iWaitForTheAjaxResponse() 0 4 1
A iSubmitTheFormWithId() 0 9 2
A iSwitchToPopup() 0 5 1
A iSetMainWindowName() 0 6 1
A iSwitchBackToMainWindow() 0 4 1
A iVisit() 0 4 1
B scrollIntoView() 0 45 5
A iClickLocationSelector() 0 6 1
A getElement() 0 6 1
A iFillInLocationSearch() 0 8 1
A iClickOn() 0 3 1
A iClickOnTheText() 0 19 3
A iShouldSeeText() 0 6 1
A iGoToDashboardPage() 0 5 1
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
10
namespace Yawik\Behat;
11
12
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
13
use Behat\MinkExtension\Context\RawMinkContext;
14
use Core\Repository\RepositoryService;
15
use Jobs\Repository\Categories;
16
use Core\Application;
17
18
/**
19
 * Class FeatureContext
20
 * @package Yawik\Behat
21
 */
22
class CoreContext extends RawMinkContext
23
{
24
    use CommonContextTrait;
25
26
    protected static $application;
27
    
28
    private static $jobCategoryChecked = false;
29
30
    private $config;
31
32
    /**
33
     * @BeforeSuite
34
     */
35
    public static function beforeSuite()
36
    {
37
        putenv('APPLICATION_ENV=test');
38
    }
39
40
    /**
41
     * @BeforeScenario
42
     * @param BeforeScenarioScope $scope
43
     */
44
    public function setupContexts(BeforeScenarioScope $scope)
45
    {
46
        if (false === static::$jobCategoryChecked) {
0 ignored issues
show
Bug introduced by
Since $jobCategoryChecked is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $jobCategoryChecked to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
47
            /* @var Categories $catRepo */
48
            $catRepo = $this->getRepositories()->get('Jobs/Category');
49
            $all = $catRepo->findAll();
50
            if (count($all) <= 1) {
51
                $catRepo->createDefaultCategory('professions');
52
                $catRepo->createDefaultCategory('industries');
53
                $catRepo->createDefaultCategory('employmentTypes');
54
            }
55
            static::$jobCategoryChecked = true;
0 ignored issues
show
Bug introduced by
Since $jobCategoryChecked is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $jobCategoryChecked to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
56
        }
57
    }
58
59
    /**
60
     * @return Application
0 ignored issues
show
Documentation introduced by
Should the return type not be Application|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
61
     */
62
    public function getApplication()
63
    {
64
        if (!is_object(static::$application)) {
65
            static::$application = Application::init();
66
        }
67
        return static::$application;
68
    }
69
    
70
    /**
71
     * @return \Zend\ServiceManager\ServiceManager
72
     */
73
    public function getServiceManager()
74
    {
75
        return $this->getApplication()->getServiceManager();
76
    }
77
    
78
    /**
79
     * @return \Zend\EventManager\EventManagerInterface
80
     */
81
    public function getEventManager()
82
    {
83
        return $this->getApplication()->getEventManager();
84
    }
85
    
86
    /**
87
     * @return RepositoryService
88
     */
89
    public function getRepositories()
90
    {
91
        return $this->getServiceManager()->get('repositories');
92
    }
93
    
94
    /**
95
     * @param $name
96
     * @param array $params
0 ignored issues
show
Bug introduced by
There is no parameter named $params. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
97
     *
98
     * @return string
99
     */
100
    public function generateUrl($name)
101
    {
102
        return $this->minkContext->locatePath($name);
103
    }
104
105
    /**
106
     * @When /^I hover over the element "([^"]*)"$/
107
     */
108
    public function iHoverOverTheElement($locator)
109
    {
110
        $session = $this->minkContext->getSession(); // get the mink session
111
        $element = $session->getPage()->find('css', $locator); // runs the actual query and returns the element
112
        
113
        // errors must not pass silently
114
        if (null === $element) {
115
            throw new \InvalidArgumentException(sprintf('Could not evaluate CSS selector: "%s"', $locator));
116
        }
117
        
118
        // ok, let's hover it
119
        $element->mouseOver();
120
    }
121
    
122
    /**
123
     * @Given /^I wait for (\d+) seconds$/
124
     */
125
    public function iWaitForSecond($second)
126
    {
127
        sleep($second);
128
    }
129
    
130
    /**
131
     * @Then /^I wait for the ajax response$/
132
     */
133
    public function iWaitForTheAjaxResponse()
134
    {
135
        $this->getSession()->wait(5000, '(0 === jQuery.active)');
136
    }
137
    
138
    /**
139
     * Some forms do not have a Submit button just pass the ID
140
     *
141
     * @Given /^I submit the form with id "([^"]*)"$/
142
     */
143
    public function iSubmitTheFormWithId($arg)
144
    {
145
        $node = $this->minkContext->getSession()->getPage()->find('css', $arg);
146
        if ($node) {
147
            $this->minkContext->getSession()->executeScript("jQuery('$arg').submit();");
148
        } else {
149
            throw new \Exception('Element not found');
150
        }
151
    }
152
    
153
    /**
154
     * @Then I switch to popup :name
155
     *
156
     * @param $name
157
     */
158
    public function iSwitchToPopup($name)
159
    {
160
        $this->iSetMainWindowName();
161
        $this->getSession()->switchToWindow($name);
162
    }
163
    
164
    /**
165
     * @Then I set main window name
166
     */
167
    public function iSetMainWindowName()
168
    {
169
        $window_name = 'main_window';
0 ignored issues
show
Coding Style introduced by
$window_name does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
170
        $script = 'window.name = "' . $window_name . '"';
0 ignored issues
show
Coding Style introduced by
$window_name does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
171
        $this->getSession()->executeScript($script);
172
    }
173
    
174
    /**
175
     * @Then I switch back to main window
176
     */
177
    public function iSwitchBackToMainWindow()
178
    {
179
        $this->getSession()->switchToWindow('main_window');
180
    }
181
    
182
    public function iVisit($url)
183
    {
184
        $this->minkContext->getSession()->visit($url);
185
    }
186
    
187
    /**
188
     * @When I scroll :selector into view
189
     *
190
     * @param string $selector Allowed selectors: #id, .className, //xpath
191
     *
192
     * @throws \Exception
193
     */
194
    public function scrollIntoView($selector)
195
    {
196
        $locator = substr($selector, 0, 1);
197
        
198
        switch ($locator) {
199
            case '/': // XPath selector
200
                $function = <<<JS
201
(function(){
202
  var elem = document.evaluate($selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
203
  elem.scrollIntoView(false);
204
})(jQuery)
205
JS;
206
                break;
207
            
208
            case '#': // ID selector
209
                $selector = substr($selector, 1);
210
                $function = <<<JS
211
(function(){
212
  var elem = document.getElementById("$selector");
213
  elem.scrollIntoView(false);
214
})(jQuery)
215
JS;
216
                break;
217
            
218
            case '.': // Class selector
219
                $selector = substr($selector, 1);
220
                $function = <<<JS
221
(function(){
222
  var elem = document.getElementsByClassName("$selector");
223
  elem[0].scrollIntoView(false);
224
})(jQuery)
225
JS;
226
                break;
227
            
228
            default:
229
                throw new \Exception(__METHOD__ . ' Couldn\'t find selector: ' . $selector . ' - Allowed selectors: #id, .className, //xpath');
230
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
231
        }
232
        
233
        try {
234
            $this->getSession()->executeScript($function);
235
        } catch (\Exception $e) {
236
            throw new \Exception(__METHOD__ . ' failed'. ' Message: for this locator:"'.$selector.'"');
237
        }
238
    }
239
    
240
    /**
241
     * @When I click location selector
242
     */
243
    public function iClickLocationSelector()
244
    {
245
        $locator = '#jobBase-geoLocation-span .select2';
246
        $element = $this->getElement($locator);
247
        $element->click();
248
    }
249
    
250
    /**
251
     * @param $locator
252
     * @param string $selector
253
     *
254
     * @return \Behat\Mink\Element\NodeElement|mixed|null
255
     */
256
    public function getElement($locator, $selector='css')
257
    {
258
        $page = $this->minkContext->getSession()->getPage();
259
        $element = $page->find('css', $locator);
260
        return $element;
261
    }
262
    
263
    /**
264
     * @When I fill in location search with :term
265
     * @param $term
266
     */
267
    public function iFillInLocationSearch($term)
268
    {
269
        $locator = '.select2-container--open .select2-search__field';
270
        $element = $this->getElement($locator);
271
        $element->focus();
272
        $element->setValue($term);
273
        $this->iWaitForTheAjaxResponse();
274
    }
275
    
276
    public function iClickOn()
277
    {
278
    }
279
    
280
    /**
281
     * Click some text
282
     *
283
     * @When /^I click on the text "([^"]*)"$/
284
     */
285
    public function iClickOnTheText($text)
286
    {
287
        $session = $this->getSession();
288
        $element = $session->getPage()->find(
289
            'xpath',
290
            $session->getSelectorsHandler()->selectorToXpath('xpath', '*//*[text()="'. $text .'"]')
291
        );
292
        if (null === $element) {
293
            $element = $session->getPage()->find(
294
                'named',
295
                array('id',$text)
296
            );
297
        }
298
        if (null === $element) {
299
            throw new \InvalidArgumentException(sprintf('Cannot find text: "%s"', $text));
300
        }
301
        
302
        $element->click();
303
    }
304
305
    /**
306
     * @Then /^(?:|I )should see translated text "(?P<text>(?:[^"]|\\")*)"$/
307
     */
308
    public function iShouldSeeText($text)
309
    {
310
        $translator = $this->getServiceManager()->get('translator');
311
        $translated = $translator->translate($text);
312
        $this->minkContext->assertSession()->pageTextContains($translated);
313
    }
314
315
    /**
316
     * @When I go to dashboard page
317
     */
318
    public function iGoToDashboardPage()
319
    {
320
        $url = $this->buildUrl('lang/dashboard');
321
        $this->iVisit($url);
322
    }
323
}
324