Completed
Pull Request — master (#236)
by Pieter
03:17
created

RawDrupalContext   C

Complexity

Total Complexity 63

Size/Duplication

Total Lines 473
Duplicated Lines 6.55 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 12
Bugs 0 Features 2
Metric Value
wmc 63
c 12
b 0
f 2
lcom 1
cbo 8
dl 31
loc 473
rs 5.8893

25 Methods

Rating   Name   Duplication   Size   Complexity  
A setDrupal() 0 3 1
A getDrupal() 0 3 1
A setDispatcher() 0 3 1
A setDrupalParameters() 0 3 1
A getDrupalParameter() 0 3 2
A getDrupalText() 7 7 2
A getDriver() 0 3 1
A getRandom() 0 3 1
B alterNodeParameters() 0 15 5
A cleanNodes() 0 7 2
A cleanUsers() 0 10 3
A cleanTerms() 0 7 2
A cleanRoles() 0 7 2
A cleanLanguages() 0 7 2
A clearStaticCaches() 0 3 1
A dispatchHooks() 0 13 3
A nodeCreate() 8 8 1
D parseEntityFields() 0 67 16
A userCreate() 8 8 1
A termCreate() 8 8 1
A languageCreate() 0 9 2
B login() 0 31 6
A logout() 0 3 1
A loggedIn() 0 9 1
A loggedInWithRole() 0 3 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RawDrupalContext often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RawDrupalContext, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Drupal\DrupalExtension\Context;
4
5
use Behat\MinkExtension\Context\RawMinkContext;
6
use Behat\Testwork\Hook\HookDispatcher;
7
8
use Drupal\DrupalDriverManager;
9
10
use Drupal\DrupalExtension\Hook\Scope\AfterLanguageEnableScope;
11
use Drupal\DrupalExtension\Hook\Scope\AfterNodeCreateScope;
12
use Drupal\DrupalExtension\Hook\Scope\AfterTermCreateScope;
13
use Drupal\DrupalExtension\Hook\Scope\AfterUserCreateScope;
14
use Drupal\DrupalExtension\Hook\Scope\BaseEntityScope;
15
use Drupal\DrupalExtension\Hook\Scope\BeforeLanguageEnableScope;
16
use Drupal\DrupalExtension\Hook\Scope\BeforeNodeCreateScope;
17
use Drupal\DrupalExtension\Hook\Scope\BeforeUserCreateScope;
18
use Drupal\DrupalExtension\Hook\Scope\BeforeTermCreateScope;
19
20
21
/**
22
 * Provides the raw functionality for interacting with Drupal.
23
 */
24
class RawDrupalContext extends RawMinkContext implements DrupalAwareInterface {
25
26
  /**
27
   * Drupal driver manager.
28
   *
29
   * @var \Drupal\DrupalDriverManager
30
   */
31
  private $drupal;
32
33
  /**
34
   * Test parameters.
35
   *
36
   * @var array
37
   */
38
  private $drupalParameters;
39
40
  /**
41
   * Event dispatcher object.
42
   *
43
   * @var \Behat\Testwork\Hook\HookDispatcher
44
   */
45
  protected $dispatcher;
46
47
  /**
48
   * Keep track of nodes so they can be cleaned up.
49
   *
50
   * @var array
51
   */
52
  protected $nodes = array();
53
54
  /**
55
   * Current authenticated user.
56
   *
57
   * A value of FALSE denotes an anonymous user.
58
   *
59
   * @var stdClass|bool
60
   */
61
  public $user = FALSE;
62
63
  /**
64
   * Keep track of all users that are created so they can easily be removed.
65
   *
66
   * @var array
67
   */
68
  protected $users = array();
69
70
  /**
71
   * Keep track of all terms that are created so they can easily be removed.
72
   *
73
   * @var array
74
   */
75
  protected $terms = array();
76
77
  /**
78
   * Keep track of any roles that are created so they can easily be removed.
79
   *
80
   * @var array
81
   */
82
  protected $roles = array();
83
84
  /**
85
   * Keep track of any languages that are created so they can easily be removed.
86
   *
87
   * @var array
88
   */
89
  protected $languages = array();
90
91
  /**
92
   * {@inheritDoc}
93
   */
94
  public function setDrupal(DrupalDriverManager $drupal) {
95
    $this->drupal = $drupal;
96
  }
97
98
  /**
99
   * {@inheritDoc}
100
   */
101
  public function getDrupal() {
102
    return $this->drupal;
103
  }
104
105
  /**
106
   * {@inheritDoc}
107
   */
108
  public function setDispatcher(HookDispatcher $dispatcher) {
109
    $this->dispatcher = $dispatcher;
110
  }
111
112
  /**
113
   * Set parameters provided for Drupal.
114
   */
115
  public function setDrupalParameters(array $parameters) {
116
    $this->drupalParameters = $parameters;
117
  }
118
119
  /**
120
   * Returns a specific Drupal parameter.
121
   *
122
   * @param string $name
123
   *   Parameter name.
124
   *
125
   * @return mixed
126
   */
127
  public function getDrupalParameter($name) {
128
    return isset($this->drupalParameters[$name]) ? $this->drupalParameters[$name] : NULL;
129
  }
130
131
  /**
132
   * Returns a specific Drupal text value.
133
   *
134
   * @param string $name
135
   *   Text value name, such as 'log_out', which corresponds to the default 'Log
136
   *   out' link text.
137
   * @throws \Exception
138
   * @return
139
   */
140 View Code Duplication
  public function getDrupalText($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...
141
    $text = $this->getDrupalParameter('text');
142
    if (!isset($text[$name])) {
143
      throw new \Exception(sprintf('No such Drupal string: %s', $name));
144
    }
145
    return $text[$name];
146
  }
147
148
  /**
149
   * Get active Drupal Driver.
150
   */
151
  public function getDriver($name = NULL) {
152
    return $this->getDrupal()->getDriver($name);
153
  }
154
155
  /**
156
   * Get driver's random generator.
157
   */
158
  public function getRandom() {
159
    return $this->getDriver()->getRandom();
160
  }
161
162
  /**
163
   * Massage node values to match the expectations on different Drupal versions.
164
   *
165
   * @beforeNodeCreate
166
   */
167
  public function alterNodeParameters(BeforeNodeCreateScope $scope) {
168
    $drupal_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\DrupalContext, Drupal\DrupalExtension\C...xt\DrupalSubContextBase, Drupal\DrupalExtension\Context\DrushContext, Drupal\DrupalExtension\Context\MessageContext, Drupal\DrupalExtension\Context\RawDrupalContext.

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...
169
    $node = $scope->getEntity();
170
171
    // On Drupal 8 the timestamps should be in UNIX time.
172
    switch ($drupal_version) {
173
      case 8:
174
        foreach (array('changed', 'created', 'revision_timestamp') as $field) {
175
          if (!empty($node->$field) && !is_numeric($node->$field)) {
176
            $node->$field = strtotime($node->$field);
177
          }
178
        }
179
      break;
180
    }
181
  }
182
183
  /**
184
   * Remove any created nodes.
185
   *
186
   * @AfterScenario
187
   */
188
  public function cleanNodes() {
189
    // Remove any nodes that were created.
190
    foreach ($this->nodes as $node) {
191
      $this->getDriver()->nodeDelete($node);
192
    }
193
    $this->nodes = array();
194
  }
195
196
  /**
197
   * Remove any created users.
198
   *
199
   * @AfterScenario
200
   */
201
  public function cleanUsers() {
202
    // Remove any users that were created.
203
    if (!empty($this->users)) {
204
      foreach ($this->users as $user) {
205
        $this->getDriver()->userDelete($user);
206
      }
207
      $this->getDriver()->processBatch();
208
      $this->users = array();
209
    }
210
  }
211
212
  /**
213
   * Remove any created terms.
214
   *
215
   * @AfterScenario
216
   */
217
  public function cleanTerms() {
218
    // Remove any terms that were created.
219
    foreach ($this->terms as $term) {
220
      $this->getDriver()->termDelete($term);
221
    }
222
    $this->terms = array();
223
  }
224
225
  /**
226
   * Remove any created roles.
227
   *
228
   * @AfterScenario
229
   */
230
  public function cleanRoles() {
231
    // Remove any roles that were created.
232
    foreach ($this->roles as $rid) {
233
      $this->getDriver()->roleDelete($rid);
234
    }
235
    $this->roles = array();
236
  }
237
238
  /**
239
   * Remove any created languages.
240
   *
241
   * @AfterScenario
242
   */
243
  public function cleanLanguages() {
244
    // Delete any languages that were created.
245
    foreach ($this->languages as $language) {
246
      $this->getDriver()->languageDelete($language);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Drupal\Driver\DriverInterface as the method languageDelete() does only exist in the following implementations of said interface: Drupal\Driver\DrupalDriver.

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...
247
      unset($this->languages[$language->langcode]);
248
    }
249
  }
250
251
  /**
252
   * Clear static caches.
253
   *
254
   * @AfterScenario @api
255
   */
256
  public function clearStaticCaches() {
257
    $this->getDriver()->clearStaticCaches();
258
  }
259
260
  /**
261
   * Dispatch scope hooks.
262
   *
263
   * @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...
264
   *   The entity scope to dispatch.
265
   * @param stdClass $entity
266
   *   The entity.
267
   */
268
  protected function dispatchHooks($scopeType, \stdClass $entity) {
269
    $fullScopeClass = 'Drupal\\DrupalExtension\\Hook\\Scope\\' . $scopeType;
270
    $scope = new $fullScopeClass($this->getDrupal()->getEnvironment(), $this, $entity);
271
    $callResults = $this->dispatcher->dispatchScopeHooks($scope);
272
273
    // The dispatcher suppresses exceptions, throw them here if there are any.
274
    foreach ($callResults as $result) {
275
      if ($result->hasException()) {
276
        $exception = $result->getException();
277
        throw $exception;
278
      }
279
    }
280
  }
281
282
  /**
283
   * Create a node.
284
   *
285
   * @return object
286
   *   The created node.
287
   */
288 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...
289
    $this->dispatchHooks('BeforeNodeCreateScope', $node);
290
    $this->parseEntityFields('node', $node);
291
    $saved = $this->getDriver()->createNode($node);
292
    $this->dispatchHooks('AfterNodeCreateScope', $saved);
293
    $this->nodes[] = $saved;
294
    return $saved;
295
  }
296
297
  /**
298
   * Parse multi-value fields. Possible formats:
299
   *    A, B, C
300
   *    A - B, C - D, E - F
301
   *
302
   * @param string $entity_type
303
   *   The entity type.
304
   * @param \stdClass $entity
305
   *   An object containing the entity properties and fields as properties.
306
   */
307
  public function parseEntityFields($entity_type, \stdClass $entity) {
308
    $multicolumn_field = '';
309
    $multicolumn_fields = array();
310
311
    foreach ($entity as $field => $field_value) {
0 ignored issues
show
Bug introduced by
The expression $entity of type object<stdClass> is not traversable.
Loading history...
312
      // Reset the multicolumn field if the field name does not contain a column.
313
      if (strpos($field, ':') === FALSE) {
314
        $multicolumn_field = '';
315
      }
316
      // Start tracking a new multicolumn field if the field name contains a ':'
317
      // which is preceded by at least 1 character.
318
      elseif (strpos($field, ':', 1) !== FALSE) {
319
        list($multicolumn_field, $multicolumn_column) = explode(':', $field);
320
      }
321
      // If a field name starts with a ':' but we are not yet tracking a
322
      // multicolumn field we don't know to which field this belongs.
323
      elseif (empty($multicolumn_field)) {
324
        throw new \Exception('Field name missing for ' . $field);
325
      }
326
      // Update the column name if the field name starts with a ':' and we are
327
      // already tracking a multicolumn field.
328
      else {
329
        $multicolumn_column = substr($field, 1);
330
      }
331
332
      $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...
333
      $field_name = $multicolumn_field ?: $field;
334
      if ($this->getDriver()->isField($entity_type, $field_name)) {
335
        // Split up multiple values in multi-value fields.
336
        $values = array();
337
        foreach (explode(', ', $field_value) as $key => $value) {
338
          $columns = $value;
339
          // Split up field columns if the ' - ' separator is present.
340
          if (strstr($value, ' - ') !== FALSE) {
341
            $columns = array();
342
            foreach (explode(' - ', $value) as $column) {
343
              // Check if it is an inline named column.
344
              if (!$is_multicolumn && strpos($column, ': ', 1) !== FALSE) {
345
                list ($key, $column) = explode(': ', $column);
346
                $columns[$key] = $column;
347
              }
348
              else {
349
                $columns[] = $column;
350
              }
351
            }
352
          }
353
          // Use the column name if we are tracking a multicolumn field.
354
          if ($is_multicolumn) {
355
            $multicolumn_fields[$multicolumn_field][$key][$multicolumn_column] = $columns;
356
            unset($entity->$field);
357
          }
358
          else {
359
            $values[] = $columns;
360
          }
361
        }
362
        // Replace regular fields inline in the entity after parsing.
363
        if (!$is_multicolumn) {
364
          $entity->$field_name = $values;
365
        }
366
      }
367
    }
368
369
    // Add the multicolumn fields to the entity.
370
    foreach ($multicolumn_fields as $field_name => $columns) {
371
      $entity->$field_name = $columns;
372
    }
373
  }
374
375
  /**
376
   * Create a user.
377
   *
378
   * @return object
379
   *   The created user.
380
   */
381 View Code Duplication
  public function userCreate($user) {
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...
382
    $this->dispatchHooks('BeforeUserCreateScope', $user);
383
    $this->parseEntityFields('user', $user);
384
    $this->getDriver()->userCreate($user);
385
    $this->dispatchHooks('AfterUserCreateScope', $user);
386
    $this->users[$user->name] = $this->user = $user;
387
    return $user;
388
  }
389
390
  /**
391
   * Create a term.
392
   *
393
   * @return object
394
   *   The created term.
395
   */
396 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...
397
    $this->dispatchHooks('BeforeTermCreateScope', $term);
398
    $this->parseEntityFields('taxonomy_term', $term);
399
    $saved = $this->getDriver()->createTerm($term);
400
    $this->dispatchHooks('AfterTermCreateScope', $saved);
401
    $this->terms[] = $saved;
402
    return $saved;
403
  }
404
405
  /**
406
   * Creates a language.
407
   *
408
   * @param \stdClass $language
409
   *   An object with the following properties:
410
   *   - langcode: the langcode of the language to create.
411
   *
412
   * @return object|FALSE
413
   *   The created language, or FALSE if the language was already created.
414
   */
415
  public function languageCreate(\stdClass $language) {
416
    $this->dispatchHooks('BeforeLanguageCreateScope', $language);
417
    $language = $this->getDriver()->languageCreate($language);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Drupal\Driver\DriverInterface as the method languageCreate() does only exist in the following implementations of said interface: Drupal\Driver\DrupalDriver.

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...
418
    if ($language) {
419
      $this->dispatchHooks('AfterLanguageCreateScope', $language);
420
      $this->languages[$language->langcode] = $language;
421
    }
422
    return $language;
423
  }
424
425
  /**
426
   * Log-in the current user.
427
   */
428
  public function login() {
429
    // Check if logged in.
430
    if ($this->loggedIn()) {
431
      $this->logout();
432
    }
433
434
    if (!$this->user) {
435
      throw new \Exception('Tried to login without a user.');
436
    }
437
438
    $this->getSession()->visit($this->locatePath('/user'));
439
    $element = $this->getSession()->getPage();
440
    $element->fillField($this->getDrupalText('username_field'), $this->user->name);
441
    $element->fillField($this->getDrupalText('password_field'), $this->user->pass);
442
    $submit = $element->findButton($this->getDrupalText('log_in'));
443
    if (empty($submit)) {
444
      throw new \Exception(sprintf("No submit button at %s", $this->getSession()->getCurrentUrl()));
445
    }
446
447
    // Log in.
448
    $submit->click();
449
450
    if (!$this->loggedIn()) {
451
      if (isset($this->user->role)) {
452
        throw new \Exception(sprintf("Unable to determine if logged in because 'log_out' link cannot be found for user '%s' with role '%s'", $this->user->name, $this->user->role));
453
      }
454
      else {
455
        throw new \Exception(sprintf("Unable to determine if logged in because 'log_out' link cannot be found for user '%s'", $this->user->name));
456
      }
457
    }
458
  }
459
460
  /**
461
   * Logs the current user out.
462
   */
463
  public function logout() {
464
    $this->getSession()->visit($this->locatePath('/user/logout'));
465
  }
466
467
  /**
468
   * Determine if the a user is already logged in.
469
   *
470
   * @return boolean
471
   *   Returns TRUE if a user is logged in for this session.
472
   */
473
  public function loggedIn() {
474
    $session = $this->getSession();
475
    $session->visit($this->locatePath('/'));
476
477
    // If a logout link is found, we are logged in. While not perfect, this is
478
    // how Drupal SimpleTests currently work as well.
479
    $element = $session->getPage();
480
    return $element->findLink($this->getDrupalText('log_out'));
481
  }
482
483
  /**
484
   * User with a given role is already logged in.
485
   *
486
   * @param string $role
487
   *   A single role, or multiple comma-separated roles in a single string.
488
   *
489
   * @return boolean
490
   *   Returns TRUE if the current logged in user has this role (or roles).
491
   */
492
  public function loggedInWithRole($role) {
493
    return $this->loggedIn() && $this->user && isset($this->user->role) && $this->user->role == $role;
494
  }
495
496
}
497