5 * Contains \Drupal\DrupalExtension\Context\DrupalSubContextBase.
8 namespace Drupal\DrupalExtension\Context;
10 use Behat\Behat\Context\Environment\InitializedContextEnvironment;
11 use Drupal\DrupalDriverManager;
14 * Base class for subcontexts that use the Drupal API.
16 abstract class DrupalSubContextBase extends RawDrupalContext implements DrupalSubContextInterface {
19 * The Drupal Driver Manager.
21 * @var \Drupal\DrupalDriverManager $drupal
26 * Constructs a DrupalSubContextBase object.
28 * @param \Drupal\DrupalDriverManager $drupal
29 * The Drupal driver manager.
31 public function __construct(DrupalDriverManager $drupal) {
32 $this->drupal = $drupal;
36 * Get the currently logged in user from DrupalContext.
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.');
45 return $context->user;
49 * Returns the Behat context that corresponds with the given class name.
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.
55 * @param string $class
56 * A fully namespaced class name.
58 * @return \Behat\Behat\Context\Context|false
59 * The requested context, or FALSE if the context is not registered.
62 * Thrown when the environment is not yet initialized, meaning that contexts
63 * cannot yet be retrieved.
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.');
76 foreach ($environment->getContexts() as $context) {
77 if ($context instanceof $class) {