GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

FeatureContext::isSubstringInArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4285
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the CCDNForum ForumBundle
5
 *
6
 * (c) CCDN (c) CodeConsortium <http://www.codeconsortium.com/>
7
 *
8
 * Available on github <http://www.github.com/codeconsortium/>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace CCDNForum\ForumBundle\features\bootstrap;
15
16
use Behat\MinkExtension\Context\RawMinkContext;
17
use Behat\Mink\Element\NodeElement;
18
19
use Behat\Symfony2Extension\Context\KernelAwareInterface;
20
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
21
use Symfony\Component\HttpKernel\KernelInterface;
22
23
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
24
use CCDNForum\ForumBundle\features\bootstrap\WebUser;
25
26
/**
27
 *
28
 * Features context.
29
 *
30
 * @category CCDNForum
31
 * @package  ForumBundle
32
 *
33
 * @author   Reece Fowell <[email protected]>
34
 * @license  http://opensource.org/licenses/MIT MIT
35
 * @version  Release: 2.0
36
 * @link     https://github.com/codeconsortium/CCDNForumForumBundle
37
 *
38
 */
39
class FeatureContext extends RawMinkContext implements KernelAwareInterface
40
{
41
    /**
42
     *
43
     * Kernel.
44
     *
45
     * @var KernelInterface
46
     */
47
    private $kernel;
48
49
    /**
50
     *
51
     * Parameters.
52
     *
53
     * @var array
54
     */
55
    private $parameters;
56
57
    /**
58
     *
59
     * Initializes context.
60
     * Every scenario gets it's own context object.
61
     *
62
     * @param array $parameters context parameters (set them up through behat.yml)
63
     */
64
    public function __construct(array $parameters)
65
    {
66
        // Initialize your context here
67
        $this->parameters = $parameters;
68
69
        // Web user context.
70
        $this->useContext('web-user', new WebUser());
71
    }
72
73
    /**
74
     *
75
     * {@inheritdoc}
76
     */
77
    public function setKernel(KernelInterface $kernel)
78
    {
79
        $this->kernel = $kernel;
80
    }
81
82
    /**
83
     *
84
     * @BeforeScenario
85
     */
86
    public function purgeDatabase()
87
    {
88
        $entityManager = $this->kernel->getContainer()->get('doctrine.orm.entity_manager');
89
90
        $purger = new ORMPurger($entityManager);
91
        $purger->purge();
92
    }
93
94
    private function getPage()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
95
    {
96
        return $this->getMainContext()->getSession()->getPage();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method getSession() does only exist in the following implementations of said interface: Behat\MinkExtension\Context\MinkContext, Behat\MinkExtension\Context\RawMinkContext, CCDNForum\ForumBundle\fe...ootstrap\FeatureContext, CCDNForum\ForumBundle\features\bootstrap\WebUser.

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...
97
    }
98
99
    /**
100
     *
101
     * @Given /^I am logged in as "([^"]*)"$/
102
     */
103
    public function iAmLoggedInAs($user)
104
    {
105
        $session = $this->getMainContext()->getSession();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method getSession() does only exist in the following implementations of said interface: Behat\MinkExtension\Context\MinkContext, Behat\MinkExtension\Context\RawMinkContext, CCDNForum\ForumBundle\fe...ootstrap\FeatureContext, CCDNForum\ForumBundle\features\bootstrap\WebUser.

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...
106
        $session->setBasicAuth($user . '@foo.com', 'root');
107
    }
108
109
    private function getAttributesFromElement(NodeElement $element)
110
    {
111
        $attr = array();
112
        $attr['id']    = strtolower($element->getAttribute('id'));
113
        $attr['name']  = strtolower($element->getAttribute('name'));
114
        $attr['label'] = strtolower($element->getAttribute('label'));
115
        $attr['value'] = strtolower($element->getAttribute('value'));
116
        $attr['text']  = strtolower($element->getText());
117
        $attr['title'] = strtolower($element->getAttribute('title'));
118
119
        return $attr;
120
    }
121
122
    private function isSubstringInArray($attributes, $searchStr)
123
    {
124
        foreach ($attributes as $attribute) {
125
            if ($attribute == $searchStr) {
126
                return true;
127
            }
128
        }
129
130
        return false;
131
    }
132
133
    /**
134
     *
135
     * @Given /^I should see category named "([^"]*)" on category list$/
136
     */
137
    public function iShouldSeeCategoryNamedOnCategoryList($categoryId)
138
    {
139
        $this->iShouldSeeForTheQuery($categoryId, 'span.lead');
140
    }
141
142
    /**
143
     *
144
     * @Given /^I should not see category named "([^"]*)" on category list$/
145
     */
146
    public function iShouldNotSeeCategoryNamedOnCategoryList($categoryId)
147
    {
148
        $this->iShouldNotSeeForTheQuery($categoryId, 'span.lead');
149
    }
150
151
    /**
152
     *
153
     * @Given /^I should see board named "([^"]*)" on category list$/
154
     */
155
    public function iShouldSeeBoardNamedOnCategoryList($boardId)
156
    {
157
        $this->iShouldSeeForTheQuery($boardId, 'table > tbody > tr > td');
158
    }
159
160
    /**
161
     *
162
     * @Given /^I should not see board named "([^"]*)" on category list$/
163
     */
164
    public function iShouldNotSeeBoardNamedOnCategoryList($boardId)
165
    {
166
        $this->iShouldNotSeeForTheQuery($boardId, 'table > tbody > tr > td');
167
    }
168
169
170
    /**
171
     *
172
     * @Given /^I should see board named "([^"]*)" on topic list$/
173
     */
174
    public function iShouldSeeBoardNamedOnTopicList($topicId)
175
    {
176
        $this->iShouldSeeForTheQuery($topicId, 'span.lead');
177
    }
178
179
    /**
180
     *
181
     * @Given /^I should not see board named "([^"]*)" on topic list$/
182
     */
183
    public function iShouldNotSeeBoardNamedOnTopicList($topicId)
184
    {
185
        $this->iShouldNotSeeForTheQuery($topicId, 'span.lead');
186
    }
187
188
    /**
189
     *
190
     * @Given /^I should see topic named "([^"]*)" on topic list$/
191
     */
192
    public function iShouldSeeTopicNamedOnTopicList($topicId)
193
    {
194
        $this->iShouldSeeForTheQuery($topicId, 'table > tbody > tr > td');
195
    }
196
197
    /**
198
     *
199
     * @Given /^I should not see topic named "([^"]*)" on topic list$/
200
     */
201
    public function iShouldNotSeeTopicNamedOnTopicList($topicId)
202
    {
203
        $this->iShouldNotSeeForTheQuery($topicId, 'table > tbody > tr > td');
204
    }
205
206
    /**
207
     * @Given /^I follow "([^"]*)" from the links on post "([^"]*)"$/
208
     */
209
    public function iFollowFromTheLinksOnPost($linkText, $postId)
210
    {
211
        $link = null;
212
        $items = $this->getPage()->findAll('css', '[id^=' . $postId . '] > header a');
213
214
        $didFindIt = false;
215
        $linkTextLower = strtolower($linkText);
216
        $whatWeFound = array();
217
        foreach ($items as $item) {
218
            $attr = $this->getAttributesFromElement($item);
219
            $whatWeFound[] = $attr;
220
            if ($this->isSubstringInArray($attr, $linkTextLower)) {
221
                $didFindIt = true;
222
                $link = $item;
223
                break;
224
            }
225
        }
226
227
        WebTestCase::assertTrue($didFindIt, 'Could not find the link');
228
        WebTestCase::assertNotNull($link, 'Could not find the link');
229
230
        $link->click();
231
    }
232
233
    /**
234
     *
235
     * @Given /^I should see "([^"]*)" from the links on post "([^"]*)"$/
236
     */
237
    public function shouldSeeFromTheLinksOnPost($text, $postId)
238
    {
239
        // http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
240
        $items = array_map(
241
            function ($element) { return strtolower($element->getText()); },
242
            $this->getPage()->findAll('css', '[id^=' . $postId . '] > header ul li a')
243
        );
244
245
        $didFindIt = false;
246
        $textLower = strtolower($text);
247
        foreach ($items as $item) {
248
            if (strpos($item, $textLower) !== false) {
249
                $didFindIt = true;
250
                break;
251
            }
252
        }
253
254
        WebTestCase::assertTrue($didFindIt, "$text was not found.");
255
    }
256
257
    /**
258
     *
259
     * @Given /^I should not see "([^"]*)" from the links on post "([^"]*)"$/
260
     */
261
    public function shouldNotSeeFromTheLinksOnPost($text, $postId)
262
    {
263
        // http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
264
        $items = array_map(
265
            function ($element) { return strtolower($element->getText()); },
266
            $this->getPage()->findAll('css', '[id^=' . $postId . '] > header ul li a')
267
        );
268
269
        $didFindIt = false;
270
        $textLower = strtolower($text);
271
        foreach ($items as $item) {
272
            if (strpos($item, $textLower) !== false) {
273
                $didFindIt = true;
274
                break;
275
            }
276
        }
277
278
        WebTestCase::assertFalse($didFindIt, "$text was found but should not.");
279
    }
280
281
    /**
282
     * @Given /^I follow "([^"]*)" for the query "([^"]*)"$/
283
     */
284
    public function iFollowForTheQuery($linkText, $cssQuery)
285
    {
286
        $items = $this->getPage()->findAll('css', $cssQuery);
287
288
        $didFindIt = false;
289
        $link = null;
290
        $linkTextLower = strtolower($linkText);
291
        $whatWeFound = array();
292
        foreach ($items as $item) {
293
            $attr = $this->getAttributesFromElement($item);
294
            $whatWeFound[] = $attr;
295
            if ($this->isSubstringInArray($attr, $linkTextLower)) {
296
                $didFindIt = true;
297
                $link = $item;
298
                break;
299
            }
300
        }
301
302
        WebTestCase::assertTrue($didFindIt, 'Could not find the link');
303
        WebTestCase::assertNotNull($link, 'Could not find the link');
304
305
        $link->click();
306
    }
307
308
    /**
309
     *
310
     * @Then /^"([^"]*)" should precede "([^"]*)" for the query "([^"]*)"$/
311
     */
312
    public function shouldPrecedeForTheQuery($textBefore, $textAfter, $cssQuery)
313
    {
314
        // http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
315
        $items = array_map(
316
            function ($element) { return $element->getText(); },
317
            $this->getPage()->findAll('css', $cssQuery)
318
        );
319
320
        WebTestCase::assertTrue(in_array($textBefore, $items), 'The before text was not found!');
321
        WebTestCase::assertTrue(in_array($textAfter,  $items), 'The after text was not found!');
322
        WebTestCase::assertGreaterThan(array_search($textBefore, $items), array_search($textAfter, $items), "$textBefore does not proceed $textAfter");
323
    }
324
325
    /**
326
     *
327
     * @Given /^I should see "([^"]*)" for the query "([^"]*)"$/
328
     */
329
    public function iShouldSeeForTheQuery($text, $cssQuery)
330
    {
331
        // http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
332
        $items = array_map(
333
            function ($element) { return strtolower($element->getText()); },
334
            $this->getPage()->findAll('css', $cssQuery)
335
        );
336
337
        $didFindIt = false;
338
        $textLower = strtolower($text);
339
        foreach ($items as $item) {
340
            if (strpos($item, $textLower) !== false) {
341
                $didFindIt = true;
342
                break;
343
            }
344
        }
345
346
        WebTestCase::assertTrue($didFindIt, "$text was not found.");
347
    }
348
349
    /**
350
     *
351
     * @Given /^I should not see "([^"]*)" for the query "([^"]*)"$/
352
     */
353
    public function iShouldNotSeeForTheQuery($text, $cssQuery)
354
    {
355
        // http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
356
        $items = array_map(
357
            function ($element) { return strtolower($element->getText()); },
358
            $this->getPage()->findAll('css', $cssQuery)
359
        );
360
361
        $didFindIt = false;
362
        $textLower = strtolower($text);
363
        foreach ($items as $item) {
364
            if (strpos($item, $textLower) !== false) {
365
                $didFindIt = true;
366
                break;
367
            }
368
        }
369
370
        WebTestCase::assertFalse($didFindIt, "$text was found but should not.");
371
    }
372
373
    /**
374
     *
375
     * @Given /^I select from "([^"]*)" a date "([^"]*)"$/
376
     */
377
    public function iSelectFromADateDaysFromNow($cssQuery, $diff)
378
    {
379
        $items = $this->getPage()->findAll('css', $cssQuery);
380
381
        $fields = array();
382
        foreach ($items as $item) {
383
            $id = $item->getAttribute('id');
384
385
            if (substr($id, strlen($id) - strlen('year'), strlen($id)) == 'year') {
386
                $fields['year'] = $item;
387
                continue;
388
            }
389
390
            if (substr($id, strlen($id) - strlen('month'), strlen($id)) == 'month') {
391
                $fields['month'] = $item;
392
                continue;
393
            }
394
395
            if (substr($id, strlen($id) - strlen('day'), strlen($id)) == 'day') {
396
                $fields['day'] = $item;
397
                continue;
398
            }
399
        }
400
401
        WebTestCase::assertCount(3, $fields, 'Date fields could not be found!');
402
        WebTestCase::assertArrayHasKey('year', $fields, 'The year field could not be found!');
403
        WebTestCase::assertArrayHasKey('month', $fields, 'The month field could not be found!');
404
        WebTestCase::assertArrayHasKey('day', $fields, 'The day field could not be found!');
405
406
        $date = new \Datetime($diff);
407
408
        $filterFunc = function ($options, $has) {
409
            foreach ($options as $option) {
410
                if ($option->getText() == $has) {
411
                    return true;
412
                }
413
            }
414
415
            return false;
416
        };
417
418
        WebTestCase::assertTrue(call_user_func_array($filterFunc, array($fields['year']->findAll('css', 'option'), $date->format('Y'))));
419
        WebTestCase::assertTrue(call_user_func_array($filterFunc, array($fields['month']->findAll('css', 'option'), $date->format('M'))));
420
        WebTestCase::assertTrue(call_user_func_array($filterFunc, array($fields['day']->findAll('css', 'option'), $date->format('j'))));
421
422
        $fields['year']->selectOption($date->format('Y'));
423
        $fields['month']->selectOption($date->format('M'));
424
        $fields['day']->selectOption($date->format('j'));
425
    }
426
427
    /**
428
     *
429
     * @Given /^I dump$/
430
     */
431
    public function iDump()
432
    {
433
        ldd(substr($this->getPage()->getHtml(), 0, 9000));
434
    }
435
}
436