Security update for permissions_by_term
[yaffs-website] / vendor / drupal / drupal-extension / src / Drupal / DrupalExtension / Context / DrupalSubContextBase.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\DrupalExtension\Context\DrupalSubContextBase.
6  */
7
8 namespace Drupal\DrupalExtension\Context;
9
10 use Behat\Behat\Context\Environment\InitializedContextEnvironment;
11 use Drupal\DrupalDriverManager;
12
13 /**
14  * Base class for subcontexts that use the Drupal API.
15  */
16 abstract class DrupalSubContextBase extends RawDrupalContext implements DrupalSubContextInterface {
17
18   /**
19    * The Drupal Driver Manager.
20    *
21    * @var \Drupal\DrupalDriverManager $drupal
22    */
23   protected $drupal;
24
25   /**
26    * Constructs a DrupalSubContextBase object.
27    *
28    * @param \Drupal\DrupalDriverManager $drupal
29    *   The Drupal driver manager.
30    */
31   public function __construct(DrupalDriverManager $drupal) {
32     $this->drupal = $drupal;
33   }
34
35   /**
36    * Get the currently logged in user from DrupalContext.
37    */
38   protected function getUser() {
39     /** @var DrupalContext $context */
40     $context = $this->getContext('\Drupal\DrupalExtension\Context\DrupalContext');
41     if (empty($context->user)) {
42       throw new \Exception('No user is logged in.');
43     }
44
45     return $context->user;
46   }
47
48   /**
49    * Returns the Behat context that corresponds with the given class name.
50    *
51    * This is inspired by InitializedContextEnvironment::getContext() but also
52    * returns subclasses of the given class name. This allows us to retrieve for
53    * example DrupalContext even if it is overridden in a project.
54    *
55    * @param string $class
56    *   A fully namespaced class name.
57    *
58    * @return \Behat\Behat\Context\Context|false
59    *   The requested context, or FALSE if the context is not registered.
60    *
61    * @throws \Exception
62    *   Thrown when the environment is not yet initialized, meaning that contexts
63    *   cannot yet be retrieved.
64    */
65   protected function getContext($class) {
66     /** @var InitializedContextEnvironment $environment */
67     $environment = $this->drupal->getEnvironment();
68     // Throw an exception if the environment is not yet initialized. To make
69     // sure state doesn't leak between test scenarios, the environment is
70     // reinitialized at the start of every scenario. If this code is executed
71     // before a test scenario starts (e.g. in a `@BeforeScenario` hook) then the
72     // contexts cannot yet be retrieved.
73     if (!$environment instanceof InitializedContextEnvironment) {
74       throw new \Exception('Cannot retrieve contexts when the environment is not yet initialized.');
75     }
76     foreach ($environment->getContexts() as $context) {
77       if ($context instanceof $class) {
78         return $context;
79       }
80     }
81
82     return FALSE;
83   }
84
85 }