Completed
Push — 62-logout-performance ( 400382...858f9a )
by Jonathan
01:37
created

RawDrupalContext::getAuthenticationManager()   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 0
1
<?php
2
3
namespace Drupal\DrupalExtension\Context;
4
5
use Behat\MinkExtension\Context\RawMinkContext;
6
use Behat\Mink\Exception\DriverException;
7
use Behat\Testwork\Hook\HookDispatcher;
8
use Behat\Behat\Context\Environment\InitializedContextEnvironment;
9
10
use Drupal\DrupalDriverManager;
11
use Drupal\DrupalExtension\DrupalParametersTrait;
12
use Drupal\DrupalExtension\Manager\DrupalAuthenticationManagerInterface;
13
use Drupal\DrupalExtension\Manager\DrupalUserManagerInterface;
14
15
use Drupal\DrupalExtension\Hook\Scope\AfterLanguageEnableScope;
16
use Drupal\DrupalExtension\Hook\Scope\AfterNodeCreateScope;
17
use Drupal\DrupalExtension\Hook\Scope\AfterTermCreateScope;
18
use Drupal\DrupalExtension\Hook\Scope\AfterUserCreateScope;
19
use Drupal\DrupalExtension\Hook\Scope\BaseEntityScope;
20
use Drupal\DrupalExtension\Hook\Scope\BeforeLanguageEnableScope;
21
use Drupal\DrupalExtension\Hook\Scope\BeforeNodeCreateScope;
22
use Drupal\DrupalExtension\Hook\Scope\BeforeUserCreateScope;
23
use Drupal\DrupalExtension\Hook\Scope\BeforeTermCreateScope;
24
use Drupal\DrupalExtension\Manager\FastLogoutInterface;
25
26
/**
27
 * Provides the raw functionality for interacting with Drupal.
28
 */
29
class RawDrupalContext extends RawMinkContext implements DrupalAwareInterface
30
{
31
32
    use DrupalParametersTrait;
33
34
  /**
35
   * Drupal driver manager.
36
   *
37
   * @var \Drupal\DrupalDriverManager
38
   */
39
    private $drupal;
40
41
  /**
42
   * Event dispatcher object.
43
   *
44
   * @var \Behat\Testwork\Hook\HookDispatcher
45
   */
46
    protected $dispatcher;
47
48
  /**
49
   * Drupal authentication manager.
50
   *
51
   * @var \Drupal\DrupalExtension\Manager\DrupalAuthenticationManagerInterface
52
   */
53
    protected $authenticationManager;
54
55
  /**
56
   * Drupal user manager.
57
   *
58
   * @var \Drupal\DrupalExtension\Manager\DrupalUserManagerInterface
59
   */
60
    protected $userManager;
61
62
  /**
63
   * Keep track of nodes so they can be cleaned up.
64
   *
65
   * @var array
66
   */
67
    protected $nodes = array();
68
69
  /**
70
   * Keep track of all terms that are created so they can easily be removed.
71
   *
72
   * @var array
73
   */
74
    protected $terms = array();
75
76
  /**
77
   * Keep track of any roles that are created so they can easily be removed.
78
   *
79
   * @var array
80
   */
81
    protected $roles = array();
82
83
  /**
84
   * Keep track of any languages that are created so they can easily be removed.
85
   *
86
   * @var array
87
   */
88
    protected $languages = array();
89
90
  /**
91
   * {@inheritDoc}
92
   */
93
    public function setDrupal(DrupalDriverManager $drupal)
94
    {
95
        $this->drupal = $drupal;
96
    }
97
98
  /**
99
   * {@inheritDoc}
100
   */
101
    public function getDrupal()
102
    {
103
        return $this->drupal;
104
    }
105
106
  /**
107
   * {@inheritDoc}
108
   */
109
    public function setUserManager(DrupalUserManagerInterface $userManager)
110
    {
111
        $this->userManager = $userManager;
112
    }
113
114
  /**
115
   * {@inheritdoc}
116
   */
117
    public function getUserManager()
118
    {
119
        return $this->userManager;
120
    }
121
122
  /**
123
   * {@inheritdoc}
124
   */
125
    public function setAuthenticationManager(DrupalAuthenticationManagerInterface $authenticationManager)
126
    {
127
        $this->authenticationManager = $authenticationManager;
128
    }
129
130
  /**
131
   * {@inheritdoc}
132
   */
133
    public function getAuthenticationManager()
134
    {
135
        return $this->authenticationManager;
136
    }
137
138
  /**
139
   * Magic setter.
140
   */
141
    public function __set($name, $value)
142
    {
143
        switch ($name) {
144
            case 'user':
145
                trigger_error('Interacting directly with the RawDrupalContext::$user property has been deprecated. Use RawDrupalContext::getUserManager->setCurrentUser() instead.', E_USER_DEPRECATED);
146
                // Set the user on the user manager service, so it is shared between all
147
                // contexts.
148
                $this->getUserManager()->setCurrentUser($value);
149
                break;
150
151
            case 'users':
152
                trigger_error('Interacting directly with the RawDrupalContext::$users property has been deprecated. Use RawDrupalContext::getUserManager->addUser() instead.', E_USER_DEPRECATED);
153
                // Set the user on the user manager service, so it is shared between all
154
                // contexts.
155
                if (empty($value)) {
156
                    $this->getUserManager()->clearUsers();
157
                } else {
158
                    foreach ($value as $user) {
159
                        $this->getUserManager()->addUser($user);
160
                    }
161
                }
162
                break;
163
        }
164
    }
165
166
  /**
167
   * Magic getter.
168
   */
169
    public function __get($name)
170
    {
171
        switch ($name) {
172
            case 'user':
173
                trigger_error('Interacting directly with the RawDrupalContext::$user property has been deprecated. Use RawDrupalContext::getUserManager->getCurrentUser() instead.', E_USER_DEPRECATED);
174
                // Returns the current user from the user manager service. This is shared
175
                // between all contexts.
176
                return $this->getUserManager()->getCurrentUser();
177
178
            case 'users':
179
                trigger_error('Interacting directly with the RawDrupalContext::$users property has been deprecated. Use RawDrupalContext::getUserManager->getUsers() instead.', E_USER_DEPRECATED);
180
                // Returns the current user from the user manager service. This is shared
181
                // between all contexts.
182
                return $this->getUserManager()->getUsers();
183
        }
184
    }
185
186
  /**
187
   * {@inheritdoc}
188
   */
189
    public function setDispatcher(HookDispatcher $dispatcher)
190
    {
191
        $this->dispatcher = $dispatcher;
192
    }
193
194
  /**
195
   * Get active Drupal Driver.
196
   *
197
   * @return \Drupal\Driver\DrupalDriver
198
   */
199
    public function getDriver($name = null)
200
    {
201
        return $this->getDrupal()->getDriver($name);
202
    }
203
204
  /**
205
   * Get driver's random generator.
206
   */
207
    public function getRandom()
208
    {
209
        return $this->getDriver()->getRandom();
210
    }
211
212
  /**
213
   * Massage node values to match the expectations on different Drupal versions.
214
   *
215
   * @beforeNodeCreate
216
   */
217
    public static function alterNodeParameters(BeforeNodeCreateScope $scope)
218
    {
219
        $node = $scope->getEntity();
220
221
        // Get the Drupal API version if available. This is not available when
222
        // using e.g. the BlackBoxDriver or DrushDriver.
223
        $api_version = null;
224
        $driver = $scope->getContext()->getDrupal()->getDriver();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\Context as the method getDrupal() does only exist in the following implementations of said interface: Drupal\DrupalExtension\Context\ConfigContext, Drupal\DrupalExtension\Context\DrupalContext, Drupal\DrupalExtension\C...xt\DrupalSubContextBase, Drupal\DrupalExtension\Context\DrushContext, Drupal\DrupalExtension\Context\MessageContext, Drupal\DrupalExtension\Context\RawDrupalContext, FeatureContext, FooFoo.

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...
225
        if ($driver instanceof \Drupal\Driver\DrupalDriver) {
226
            $api_version = $scope->getContext()->getDrupal()->getDriver()->version;
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\Context as the method getDrupal() does only exist in the following implementations of said interface: Drupal\DrupalExtension\Context\ConfigContext, Drupal\DrupalExtension\Context\DrupalContext, Drupal\DrupalExtension\C...xt\DrupalSubContextBase, Drupal\DrupalExtension\Context\DrushContext, Drupal\DrupalExtension\Context\MessageContext, Drupal\DrupalExtension\Context\RawDrupalContext, FeatureContext, FooFoo.

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...
227
        }
228
229
        // On Drupal 8 the timestamps should be in UNIX time.
230
        switch ($api_version) {
231
            case 8:
232
                foreach (array('changed', 'created', 'revision_timestamp') as $field) {
233
                    if (!empty($node->$field) && !is_numeric($node->$field)) {
234
                        $node->$field = strtotime($node->$field);
235
                    }
236
                }
237
                break;
238
        }
239
    }
240
241
  /**
242
   * Remove any created nodes.
243
   *
244
   * @AfterScenario
245
   */
246
    public function cleanNodes()
247
    {
248
        // Remove any nodes that were created.
249
        foreach ($this->nodes as $node) {
250
            $this->getDriver()->nodeDelete($node);
251
        }
252
        $this->nodes = array();
253
    }
254
255
  /**
256
   * Remove any created users.
257
   *
258
   * @AfterScenario
259
   */
260
    public function cleanUsers()
261
    {
262
        // Remove any users that were created.
263
        if ($this->userManager->hasUsers()) {
264
            foreach ($this->userManager->getUsers() as $user) {
265
                $this->getDriver()->userDelete($user);
266
            }
267
            $this->getDriver()->processBatch();
268
            $this->userManager->clearUsers();
269
            if ($this->loggedIn()) {
270
                $this->logout(true);
271
            }
272
        }
273
    }
274
275
  /**
276
   * Remove any created terms.
277
   *
278
   * @AfterScenario
279
   */
280
    public function cleanTerms()
281
    {
282
        // Remove any terms that were created.
283
        foreach ($this->terms as $term) {
284
            $this->getDriver()->termDelete($term);
285
        }
286
        $this->terms = array();
287
    }
288
289
  /**
290
   * Remove any created roles.
291
   *
292
   * @AfterScenario
293
   */
294
    public function cleanRoles()
295
    {
296
        // Remove any roles that were created.
297
        foreach ($this->roles as $rid) {
298
            $this->getDriver()->roleDelete($rid);
299
        }
300
        $this->roles = array();
301
    }
302
303
  /**
304
   * Remove any created languages.
305
   *
306
   * @AfterScenario
307
   */
308
    public function cleanLanguages()
309
    {
310
        // Delete any languages that were created.
311
        foreach ($this->languages as $language) {
312
            $this->getDriver()->languageDelete($language);
313
            unset($this->languages[$language->langcode]);
314
        }
315
    }
316
317
  /**
318
   * Clear static caches.
319
   *
320
   * @AfterScenario @api
321
   */
322
    public function clearStaticCaches()
323
    {
324
        $this->getDriver()->clearStaticCaches();
325
    }
326
327
  /**
328
   * Dispatch scope hooks.
329
   *
330
   * @param string $scope
0 ignored issues
show
Bug introduced by
There is no parameter named $scope. 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...
331
   *   The entity scope to dispatch.
332
   * @param \stdClass $entity
333
   *   The entity.
334
   */
335
    protected function dispatchHooks($scopeType, \stdClass $entity)
336
    {
337
        $fullScopeClass = 'Drupal\\DrupalExtension\\Hook\\Scope\\' . $scopeType;
338
        $scope = new $fullScopeClass($this->getDrupal()->getEnvironment(), $this, $entity);
339
        $callResults = $this->dispatcher->dispatchScopeHooks($scope);
340
341
        // The dispatcher suppresses exceptions, throw them here if there are any.
342
        foreach ($callResults as $result) {
343
            if ($result->hasException()) {
344
                $exception = $result->getException();
345
                throw $exception;
346
            }
347
        }
348
    }
349
350
  /**
351
   * Create a node.
352
   *
353
   * @return object
354
   *   The created node.
355
   */
356 View Code Duplication
    public function nodeCreate($node)
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...
357
    {
358
        $this->dispatchHooks('BeforeNodeCreateScope', $node);
359
        $this->parseEntityFields('node', $node);
360
        $saved = $this->getDriver()->createNode($node);
361
        $this->dispatchHooks('AfterNodeCreateScope', $saved);
362
        $this->nodes[] = $saved;
363
        return $saved;
364
    }
365
366
  /**
367
   * Parses the field values and turns them into the format expected by Drupal.
368
   *
369
   * Multiple values in a single field must be separated by commas. Wrap the
370
   * field value in double quotes in case it should contain a comma.
371
   *
372
   * Compound field properties are identified using a ':' operator, either in
373
   * the column heading or in the cell. If multiple properties are present in a
374
   * single cell, they must be separated using ' - ', and values should not
375
   * contain ':' or ' - '.
376
   *
377
   * Possible formats for the values:
378
   *   A
379
   *   A, B, "a value, containing a comma"
380
   *   A - B
381
   *   x: A - y: B
382
   *   A - B, C - D, "E - F"
383
   *   x: A - y: B,  x: C - y: D,  "x: E - y: F"
384
   *
385
   * See field_handlers.feature for examples of usage.
386
   *
387
   * @param string $entity_type
388
   *   The entity type.
389
   * @param \stdClass $entity
390
   *   An object containing the entity properties and fields as properties.
391
   *
392
   * @throws \Exception
393
   *   Thrown when a field name is invalid.
394
   */
395
    public function parseEntityFields($entity_type, \stdClass $entity)
396
    {
397
        $multicolumn_field = '';
398
        $multicolumn_fields = array();
399
400
        foreach (clone $entity as $field => $field_value) {
0 ignored issues
show
Bug introduced by
The expression clone $entity of type object<stdClass> is not traversable.
Loading history...
401
            // Reset the multicolumn field if the field name does not contain a column.
402
            if (strpos($field, ':') === false) {
403
                $multicolumn_field = '';
404
            } // Start tracking a new multicolumn field if the field name contains a ':'
405
            // which is preceded by at least 1 character.
406
            elseif (strpos($field, ':', 1) !== false) {
407
                list($multicolumn_field, $multicolumn_column) = explode(':', $field);
408
            } // If a field name starts with a ':' but we are not yet tracking a
409
            // multicolumn field we don't know to which field this belongs.
410
            elseif (empty($multicolumn_field)) {
411
                throw new \Exception('Field name missing for ' . $field);
412
            } // Update the column name if the field name starts with a ':' and we are
413
            // already tracking a multicolumn field.
414
            else {
415
                $multicolumn_column = substr($field, 1);
416
            }
417
418
            $is_multicolumn = $multicolumn_field && $multicolumn_column;
0 ignored issues
show
Bug introduced by
The variable $multicolumn_column does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
419
            $field_name = $multicolumn_field ?: $field;
420
            if ($this->getDriver()->isField($entity_type, $field_name)) {
421
                // Split up multiple values in multi-value fields.
422
                $values = array();
423
                foreach (str_getcsv($field_value) as $key => $value) {
424
                    $value = trim($value);
425
                    $columns = $value;
426
                    // Split up field columns if the ' - ' separator is present.
427
                    if (strstr($value, ' - ') !== false) {
428
                        $columns = array();
429
                        foreach (explode(' - ', $value) as $column) {
430
                            // Check if it is an inline named column.
431
                            if (!$is_multicolumn && strpos($column, ': ', 1) !== false) {
432
                                list ($key, $column) = explode(': ', $column);
433
                                $columns[$key] = $column;
434
                            } else {
435
                                $columns[] = $column;
436
                            }
437
                        }
438
                    }
439
                    // Use the column name if we are tracking a multicolumn field.
440
                    if ($is_multicolumn) {
441
                        $multicolumn_fields[$multicolumn_field][$key][$multicolumn_column] = $columns;
442
                        unset($entity->$field);
443
                    } else {
444
                        $values[] = $columns;
445
                    }
446
                }
447
                // Replace regular fields inline in the entity after parsing.
448
                if (!$is_multicolumn) {
449
                    $entity->$field_name = $values;
450
                    // Don't specify any value if the step author has left it blank.
451
                    if ($field_value === '') {
452
                        unset($entity->$field_name);
453
                    }
454
                }
455
            }
456
        }
457
458
        // Add the multicolumn fields to the entity.
459
        foreach ($multicolumn_fields as $field_name => $columns) {
460
            // Don't specify any value if the step author has left it blank.
461
            if (count(array_filter($columns, function ($var) {
462
                return ($var !== '');
463
            })) > 0) {
464
                $entity->$field_name = $columns;
465
            }
466
        }
467
    }
468
469
  /**
470
   * Create a user.
471
   *
472
   * @return object
473
   *   The created user.
474
   */
475
    public function userCreate($user)
476
    {
477
        $this->dispatchHooks('BeforeUserCreateScope', $user);
478
        $this->parseEntityFields('user', $user);
479
        $this->getDriver()->userCreate($user);
480
        $this->dispatchHooks('AfterUserCreateScope', $user);
481
        $this->userManager->addUser($user);
482
        return $user;
483
    }
484
485
  /**
486
   * Create a term.
487
   *
488
   * @return object
489
   *   The created term.
490
   */
491 View Code Duplication
    public function termCreate($term)
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...
492
    {
493
        $this->dispatchHooks('BeforeTermCreateScope', $term);
494
        $this->parseEntityFields('taxonomy_term', $term);
495
        $saved = $this->getDriver()->createTerm($term);
496
        $this->dispatchHooks('AfterTermCreateScope', $saved);
497
        $this->terms[] = $saved;
498
        return $saved;
499
    }
500
501
  /**
502
   * Creates a language.
503
   *
504
   * @param \stdClass $language
505
   *   An object with the following properties:
506
   *   - langcode: the langcode of the language to create.
507
   *
508
   * @return object|FALSE
509
   *   The created language, or FALSE if the language was already created.
510
   */
511
    public function languageCreate(\stdClass $language)
512
    {
513
        $this->dispatchHooks('BeforeLanguageCreateScope', $language);
514
        $language = $this->getDriver()->languageCreate($language);
515
        if ($language) {
516
            $this->dispatchHooks('AfterLanguageCreateScope', $language);
517
            $this->languages[$language->langcode] = $language;
518
        }
519
        return $language;
520
    }
521
522
  /**
523
   * Log-in the given user.
524
   *
525
   * @param \stdClass $user
526
   *   The user to log in.
527
   */
528
    public function login(\stdClass $user)
529
    {
530
        $this->getAuthenticationManager()->logIn($user);
531
    }
532
533
  /**
534
   * Logs the current user out.
535
   *
536
   * @param bool $fast
537
   *   Utilize direct logout by session if available.
538
   */
539
    public function logout($fast = false)
540
    {
541
        if ($fast && $this->getAuthenticationManager() instanceof FastLogoutInterface) {
542
            $this->getAuthenticationManager()->fastLogout();
543
        } else {
544
            $this->getAuthenticationManager()->logOut();
545
        }
546
    }
547
548
  /**
549
   * Determine if the a user is already logged in.
550
   *
551
   * @return boolean
552
   *   Returns TRUE if a user is logged in for this session.
553
   */
554
    public function loggedIn()
555
    {
556
        return $this->getAuthenticationManager()->loggedIn();
557
    }
558
559
  /**
560
   * User with a given role is already logged in.
561
   *
562
   * @param string $role
563
   *   A single role, or multiple comma-separated roles in a single string.
564
   *
565
   * @return boolean
566
   *   Returns TRUE if the current logged in user has this role (or roles).
567
   */
568
    public function loggedInWithRole($role)
569
    {
570
        return $this->loggedIn() && $this->getUserManager()->currentUserHasRole($role);
571
    }
572
573
  /**
574
   * Returns the Behat context that corresponds with the given class name.
575
   *
576
   * This is inspired by InitializedContextEnvironment::getContext() but also
577
   * returns subclasses of the given class name. This allows us to retrieve for
578
   * example DrupalContext even if it is overridden in a project.
579
   *
580
   * @param string $class
581
   *   A fully namespaced class name.
582
   *
583
   * @return \Behat\Behat\Context\Context|false
584
   *   The requested context, or FALSE if the context is not registered.
585
   *
586
   * @throws \Exception
587
   *   Thrown when the environment is not yet initialized, meaning that contexts
588
   *   cannot yet be retrieved.
589
   */
590
    protected function getContext($class)
591
    {
592
        /** @var InitializedContextEnvironment $environment */
593
        $environment = $this->drupal->getEnvironment();
594
        // Throw an exception if the environment is not yet initialized. To make
595
        // sure state doesn't leak between test scenarios, the environment is
596
        // reinitialized at the start of every scenario. If this code is executed
597
        // before a test scenario starts (e.g. in a `@BeforeScenario` hook) then the
598
        // contexts cannot yet be retrieved.
599
        if (!$environment instanceof InitializedContextEnvironment) {
600
            throw new \Exception('Cannot retrieve contexts when the environment is not yet initialized.');
601
        }
602
        foreach ($environment->getContexts() as $context) {
603
            if ($context instanceof $class) {
604
                return $context;
605
            }
606
        }
607
608
        return false;
609
    }
610
}
611