Completed
Push — develop ( 3062c0...09456b )
by Mathias
07:45
created

CoreContext::generateUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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\MinkContext;
14
use Behat\MinkExtension\Context\RawMinkContext;
15
use Core\Repository\RepositoryService;
16
use Jobs\Repository\Categories;
17
use Zend\Mvc\Application;
18
19
20
/**
21
 * Class FeatureContext
22
 * @package Yawik\Behat
23
 */
24
class CoreContext extends RawMinkContext
25
{
26
    use CommonContextTrait;
27
28
	static protected $application;
29
	
30
	static private $jobCategoryChecked = false;
31
	
32
	/**
33
	 * @BeforeScenario
34
	 * @param BeforeScenarioScope $scope
35
	 */
36
	public function setupContexts(BeforeScenarioScope $scope)
37
	{
38
		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...
39
			/* @var Categories $catRepo */
40
			$catRepo = $this->getRepositories()->get('Jobs/Category');
41
			$all = $catRepo->findAll();
42
			if(count($all) <= 1){
43
				$catRepo->createDefaultCategory('professions');
44
				$catRepo->createDefaultCategory('industries');
45
				$catRepo->createDefaultCategory('employmentTypes');
46
			}
47
			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...
48
		}
49
	}
50
	
51
	/**
52
	 * @return Application
53
	 */
54
	public function getApplication()
55
	{
56
		if(!is_object(static::$application)){
57
			$configFile = realpath(__DIR__.'/../../../config/config.php');
58
			$config = include($configFile);
59
			static::$application = Application::init($config);
60
		}
61
		return static::$application;
62
	}
63
	
64
	/**
65
	 * @return \Zend\ServiceManager\ServiceManager
66
	 */
67
	public function getServiceManager()
68
	{
69
		return $this->getApplication()->getServiceManager();
70
	}
71
	
72
	/**
73
	 * @return \Zend\EventManager\EventManagerInterface
74
	 */
75
	public function getEventManager()
76
	{
77
		return $this->getApplication()->getEventManager();
78
	}
79
	
80
	/**
81
	 * @return RepositoryService
82
	 */
83
	public function getRepositories()
84
	{
85
		return $this->getServiceManager()->get('repositories');
86
	}
87
	
88
	/**
89
	 * @param $name
90
	 * @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...
91
	 *
92
	 * @return string
93
	 */
94
	public function generateUrl($name)
95
	{
96
		return $this->minkContext->locatePath($name);
97
	}
98
99
	/**
100
	 * @When /^I hover over the element "([^"]*)"$/
101
	 */
102
	public function iHoverOverTheElement($locator)
103
	{
104
		$session = $this->minkContext->getSession(); // get the mink session
105
		$element = $session->getPage()->find('css', $locator); // runs the actual query and returns the element
106
		
107
		// errors must not pass silently
108
		if (null === $element) {
109
			throw new \InvalidArgumentException(sprintf('Could not evaluate CSS selector: "%s"', $locator));
110
		}
111
		
112
		// ok, let's hover it
113
		$element->mouseOver();
114
	}
115
	
116
	/**
117
	 * @Given /^I wait for (\d+) seconds$/
118
	 */
119
	public function iWaitForSecond($second)
120
	{
121
		sleep($second);
122
	}
123
	
124
	/**
125
	 * @Then /^I wait for the ajax response$/
126
	 */
127
	public function iWaitForTheAjaxResponse()
128
	{
129
		$this->getSession()->wait(5000, '(0 === jQuery.active)');
130
	}
131
	
132
	/**
133
	 * Some forms do not have a Submit button just pass the ID
134
	 *
135
	 * @Given /^I submit the form with id "([^"]*)"$/
136
	 */
137
	public function iSubmitTheFormWithId($arg)
138
	{
139
		$node = $this->minkContext->getSession()->getPage()->find('css', $arg);
140
		if($node) {
141
			$this->minkContext->getSession()->executeScript("jQuery('$arg').submit();");
142
		} else {
143
			throw new \Exception('Element not found');
144
		}
145
	}
146
	
147
	/**
148
	 * @Then I switch to popup :name
149
	 *
150
	 * @param $name
151
	 */
152
	public function iSwitchToPopup($name)
153
	{
154
		$this->iSetMainWindowName();
155
		$this->getSession()->switchToWindow($name);
156
	}
157
	
158
	/**
159
	 * @Then I set main window name
160
	 */
161
	public function iSetMainWindowName()
162
	{
163
		$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...
164
		$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...
165
		$this->getSession()->executeScript($script);
166
	}
167
	
168
	/**
169
	 * @Then I switch back to main window
170
	 */
171
	public function iSwitchBackToMainWindow()
172
	{
173
		$this->getSession()->switchToWindow('main_window');
174
	}
175
	
176
	public function iVisit($url)
177
	{
178
		$this->minkContext->getSession()->visit($url);
179
	}
180
	
181
	/**
182
	 * @When I scroll :selector into view
183
	 *
184
	 * @param string $selector Allowed selectors: #id, .className, //xpath
185
	 *
186
	 * @throws \Exception
187
	 */
188
	public function scrollIntoView($selector)
189
	{
190
		$locator = substr($selector, 0, 1);
191
		
192
		switch ($locator) {
193
			case '/' : // XPath selector
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
194
				$function = <<<JS
195
(function(){
196
  var elem = document.evaluate($selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
197
  elem.scrollIntoView(false);
198
})()
199
JS;
200
				break;
201
			
202
			case '#' : // ID selector
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
203
				$selector = substr($selector, 1);
204
				$function = <<<JS
205
(function(){
206
  var elem = document.getElementById("$selector");
207
  elem.scrollIntoView(false);
208
})()
209
JS;
210
				break;
211
			
212
			case '.' : // Class selector
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

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