View source
<?php
namespace Drupal\Tests\permissions_by_term\Behat\PermissionsByTermDrupalSubContext;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Drupal\DrupalExtension\Context\DrupalSubContextBase;
use Drupal\DrupalExtension\Context\DrupalSubContextInterface;
use Behat\Gherkin\Node\TableNode;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\user\Entity\Role;
class PermissionsByTermDrupalSubContext extends DrupalSubContextBase implements DrupalSubContextInterface {
private const MAX_DURATION_SECONDS = 1200;
private const MAX_SHORT_DURATION_SECONDS = 20;
public function createTerms($vocabulary, TableNode $termsTable) {
foreach ($termsTable
->getHash() as $termsHash) {
$term = (object) $termsHash;
$term->vocabulary_machine_name = $vocabulary;
$this
->termCreate($term);
$accessStorage = \Drupal::Service('permissions_by_term.access_storage');
if (!empty($termsHash['access_user'])) {
$userNames = explode(', ', $termsHash['access_user']);
foreach ($userNames as $userName) {
$accessStorage
->addTermPermissionsByUserIds([
$accessStorage
->getUserIdByName($userName)['uid'],
], $term->tid);
}
}
if (!empty($termsHash['access_role'])) {
$rolesIds = explode(', ', $termsHash['access_role']);
$accessStorage
->addTermPermissionsByRoleIds($rolesIds, $term->tid);
}
}
}
public function createVocabulary($name, $vid) {
$vocabulary = \Drupal::entityQuery('taxonomy_vocabulary')
->condition('vid', $vid)
->execute();
if (empty($vocabulary)) {
$vocabulary = Vocabulary::create([
'name' => $name,
'vid' => $vid,
]);
$vocabulary
->save();
}
}
public function iOpenOpenPermissionsByTermAdvancedInfo() {
$this
->getSession()
->evaluateScript("jQuery('#edit-permissions-by-term-info').attr('open', true);");
}
public function iCreateNodesOfType($number, $type) {
for ($i = 0; $i <= $number; $i++) {
$node = new \stdClass();
$node->type = $type;
$node->title = $this
->createRandomString();
$node->body = $this
->createRandomString();
$this
->nodeCreate($node);
}
}
private function createRandomString($length = 10) {
return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length);
}
public function nodeAccessRecordsAreRebuilt() : void {
node_access_rebuild();
}
public function nodeAccessRecordsAreDisabled() : void {
\Drupal::configFactory()
->getEditable('permissions_by_term.settings')
->set('disable_node_access_records', TRUE)
->save();
}
public function nodeAccessRecordsAreEnabled() : void {
\Drupal::configFactory()
->getEditable('permissions_by_term.settings')
->set('disable_node_access_records', FALSE)
->save();
}
public function waitSeconds($secondsNumber) {
$this
->getSession()
->wait($secondsNumber * 1000);
}
public function selectIndexInDropdown($index, $name) {
$this
->getSession()
->evaluateScript('document.getElementsByName("' . $name . '")[0].selectedIndex = ' . $index . ';');
}
public function openNodeEditFormByTitle($title) {
$query = \Drupal::service('database')
->select('node_field_data', 'nfd')
->fields('nfd', [
'nid',
])
->condition('nfd.title', $title);
$this
->visitPath('/node/' . $query
->execute()
->fetchField() . '/edit');
}
public function openNodeViewByTitle($title) {
$query = \Drupal::service('database')
->select('node_field_data', 'nfd')
->fields('nfd', [
'nid',
])
->condition('nfd.title', $title);
$this
->visitPath('/node/' . $query
->execute()
->fetchField());
}
public function iScrollToElementWithId($id) {
$this
->getSession()
->executeScript("\n var element = document.getElementById('" . $id . "');\n element.scrollIntoView( true );\n ");
}
public function checkCheckboxWithJS($id) {
$this
->getSession()
->executeScript("\n document.getElementById('" . $id . "').checked = true;\n ");
}
public function checkCheckbox($id) {
$page = $this
->getSession()
->getPage();
$selectElement = $page
->find('xpath', '//input[@id = "' . $id . '"]');
$selectElement
->check();
}
public function uncheckCheckbox($id) {
$page = $this
->getSession()
->getPage();
$selectElement = $page
->find('xpath', '//input[@id = "' . $id . '"]');
$selectElement
->uncheck();
}
public function selectOption($label, $id) {
$page = $this
->getSession()
->getPage();
$selectElement = $page
->find('xpath', '//select[@id = "' . $id . '"]');
$selectElement
->selectOption($label);
}
public function iShouldSeeTextAfterAWhile($text) {
try {
$startTime = time();
do {
$content = $this
->getSession()
->getPage()
->getText();
if (substr_count($content, $text) > 0) {
return true;
}
} while (time() - $startTime < self::MAX_DURATION_SECONDS);
throw new ResponseTextException(sprintf('Could not find text %s after %s seconds', $text, self::MAX_DURATION_SECONDS), $this
->getSession());
} catch (StaleElementReference $e) {
return true;
}
}
public function iShouldNotSeeTextAfterAWhile($text) {
$startTime = time();
do {
$content = $this
->getSession()
->getPage()
->getText();
if (substr_count($content, $text) === 0) {
return true;
}
} while (time() - $startTime < self::MAX_SHORT_DURATION_SECONDS);
throw new ResponseTextException(sprintf('Could find text %s after %s seconds', $text, self::MAX_SHORT_DURATION_SECONDS), $this
->getSession());
}
public function clickBySelector(string $selector) {
$this
->getSession()
->executeScript("document.querySelector('" . $selector . "').click()");
}
public function createEditorRole() {
if (!Role::load('editor')) {
$role = Role::create([
'id' => 'editor',
]);
$role
->grantPermission('edit any article content')
->save();
}
}
public function permissionModeIsSet() : void {
\Drupal::configFactory()
->getEditable('permissions_by_term.settings')
->set('permission_mode', TRUE)
->save();
}
public function iSubmitTheForm() {
$session = $this
->getSession();
$element = $session
->getPage()
->find('xpath', $session
->getSelectorsHandler()
->selectorToXpath('xpath', '//*[@type="submit"]'));
if (null === $element) {
throw new \InvalidArgumentException(sprintf('Could not evaluate XPath: "%s"', '//*[@type="submit"]'));
}
$element
->click();
}
public function dumpHTML() {
print_r($this
->getSession()
->getPage()
->getContent());
}
public function createMainMenuItemForNode(string $nodeTitle) : void {
$query = \Drupal::service('database')
->select('node_field_data', 'nfd')
->fields('nfd', [
'nid',
])
->condition('nfd.title', $nodeTitle);
$menuLink = MenuLinkContent::create([
'title' => $nodeTitle,
'link' => [
'uri' => 'internal:/node/' . $query
->execute()
->fetchField(),
],
'menu_name' => 'main',
'expanded' => TRUE,
]);
$menuLink
->save();
}
public function seeMenuItemMatchingText(string $text) : void {
$xpath = '//*/ul/li/a[text() = "' . $text . '"]';
$session = $this
->getSession();
$element = $session
->getPage()
->find('xpath', $session
->getSelectorsHandler()
->selectorToXpath('xpath', $xpath));
if ($element === NULL) {
throw new \InvalidArgumentException(sprintf('Could not evaluate XPath: "%s"', $xpath));
}
}
public function seeNotMenuItemMatchingText(string $text) : void {
$xpath = '//*/ul/li/a[text() = "' . $text . '"]';
$session = $this
->getSession();
$element = $session
->getPage()
->find('xpath', $session
->getSelectorsHandler()
->selectorToXpath('xpath', $xpath));
if ($element !== NULL) {
throw new \InvalidArgumentException(sprintf('Could not evaluate XPath: "%s"', $xpath));
}
}
public function iAmInstallingTheModule(string $moduleName) : void {
\Drupal::service('module_installer')
->install([
$moduleName,
]);
$batch =& batch_get();
if (empty($batch)) {
return;
}
$batch['progressive'] = FALSE;
batch_process();
}
public function openTaxonomyTermPageByTermName(string $termName) {
$query = \Drupal::service('database')
->select('taxonomy_term_field_data', 'ttfd')
->fields('ttfd', [
'tid',
])
->condition('ttfd.name', $termName);
$this
->visitPath('/taxonomy/term/' . $query
->execute()
->fetchField());
}
}