Skip to content

Instantly share code, notes, and snippets.

@nickopris
Created April 17, 2024 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickopris/82812ed29c1f14dd817da4f88925111f to your computer and use it in GitHub Desktop.
Save nickopris/82812ed29c1f14dd817da4f88925111f to your computer and use it in GitHub Desktop.
Behat get current user
<?php
declare(strict_types = 1);
use Drupal\DrupalExtension\Context\RawDrupalContext;
/**
* Defines step definitions that are generally useful for the project.
*/
class FeatureContext extends RawDrupalContext {
/**
* @return \Drupal\Core\Entity\EntityInterface|null
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function getCurrentUser() {
$this->getSession()->visit($this->locatePath($this->getDrupalText('login_url')));
$user_url = $this->getSession()->getCurrentUrl();
preg_match('/(?<=\/)\d+/', $user_url, $matches);
if ($matches) {
$user_id = reset($matches);
$user = \Drupal::entityTypeManager()
->getStorage('user')->load($user_id);
if ($user) {
return $user;
}
}
return NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment