knowledge-8.x-1.x-dev/tests/src/Functional/KnowledgeNonNodeTest.php
tests/src/Functional/KnowledgeNonNodeTest.php
<?php
namespace Drupal\Tests\knowledge\Functional;
use Drupal\Component\Utility\DeprecationHelper;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\EntityTestHelper;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\knowledge\Entity\Knowledge;
use Drupal\knowledge\Entity\KnowledgeType;
use Drupal\knowledge\KnowledgeInterface;
use Drupal\knowledge\Plugin\Field\FieldType\KnowledgeItemInterface;
use Drupal\knowledge\Tests\KnowledgeTestTrait;
use Drupal\user\RoleInterface;
/**
* Tests knowledge linking on a test entity.
*
* @group knowledge
*/
class KnowledgeNonNodeTest extends BrowserTestBase {
use FieldUiTestTrait;
use KnowledgeTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'knowledge',
'user',
'field_ui',
'entity_test',
'block',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* An administrative user with permission to configure knowledge settings.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* The entity to use within tests.
*
* @var \Drupal\entity_test\Entity\EntityTest
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('system_breadcrumb_block');
$this->drupalPlaceBlock('page_title_block');
// Create a bundle for entity_test.
DeprecationHelper::backwardsCompatibleCall(
currentVersion: \Drupal::VERSION,
deprecatedVersion: '11.2.0',
currentCallable: fn() => EntityTestHelper::createBundle('entity_test', 'Entity Test', 'entity_test'),
deprecatedCallable: fn() => entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test')
);
KnowledgeType::create([
'id' => 'knowledge',
'label' => 'Knowledge settings',
'description' => 'Knowledge settings',
'target_entity_type_id' => 'entity_test',
])->save();
// Create knowledge field on entity_test bundle.
$this->addDefaultKnowledgeField('entity_test', 'entity_test');
// Verify that bundles are defined correctly.
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('knowledge');
$this->assertEquals('Knowledge settings', $bundles['knowledge']['label']);
// Create test user.
$this->adminUser = $this->drupalCreateUser([
'administer knowledge',
'skip knowledge approval',
'post knowledge',
'access knowledge',
'view test entity',
'administer entity_test content',
]);
// Enable anonymous and authenticated user knowledge.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access knowledge',
'post knowledge',
'skip knowledge approval',
]);
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [
'access knowledge',
'post knowledge',
'skip knowledge approval',
]);
// Create a test entity.
$random_label = $this->randomMachineName();
$data = ['type' => 'entity_test', 'name' => $random_label];
$this->entity = EntityTest::create($data);
$this->entity->save();
}
/**
* Posts a knowledge.
*
* @param \Drupal\Core\Entity\EntityInterface|null $entity
* Entity to post knowledge or NULL to post to the previously loaded page.
* @param string $knowledge
* Knowledge body.
* @param string $subject
* Knowledge subject.
* @param mixed $contact
* Set to NULL for no contact info, TRUE to ignore success checking, and
* array of values to set contact info.
*
* @return \Drupal\knowledge\KnowledgeInterface
* The new knowledge entity.
*/
public function postKnowledge(EntityInterface $entity, $knowledge, $subject = '', $contact = NULL) {
$edit = [];
$edit['knowledge_body[0][value]'] = $knowledge;
/** @var \Drupal\field\FieldConfigInterface $field */
$field = FieldConfig::loadByName('entity_test', 'entity_test', 'knowledge');
$preview_mode = $field->getSetting('preview');
// Must get the page before we test for fields.
if ($entity !== NULL) {
$this->drupalGet('knowledge/reply/entity_test/' . $entity->id() . '/knowledge');
}
// Determine the visibility of subject form field.
$display_repository = $this->container->get('entity_display.repository');
if ($display_repository->getFormDisplay('knowledge', 'knowledge')->getComponent('subject')) {
// Subject input allowed.
$edit['subject[0][value]'] = $subject;
}
else {
$this->assertSession()->fieldValueNotEquals('subject[0][value]', '');
}
if ($contact !== NULL && is_array($contact)) {
$edit += $contact;
}
switch ($preview_mode) {
case DRUPAL_REQUIRED:
// Preview required so no save button should be found.
$this->assertSession()->buttonNotExists('Save');
$this->submitForm($edit, 'Preview');
// Don't break here so that we can test post-preview field presence and
// function below.
case DRUPAL_OPTIONAL:
$this->assertSession()->buttonExists('Preview');
$this->assertSession()->buttonExists('Save');
$this->submitForm($edit, 'Save');
break;
case DRUPAL_DISABLED:
$this->assertSession()->buttonNotExists('Preview');
$this->assertSession()->buttonExists('Save');
$this->submitForm($edit, 'Save');
break;
}
$match = [];
// Get knowledge ID.
preg_match('/#knowledge-([0-9]+)/', $this->getURL(), $match);
// Get knowledge.
if ($contact !== TRUE) {
// If true then attempting to find error message.
if ($subject) {
$this->assertSession()->pageTextContains($subject);
}
$this->assertSession()->pageTextContains($knowledge);
// Check the knowledge ID was extracted.
$this->assertArrayHasKey(1, $match);
}
if (isset($match[1])) {
return Knowledge::load($match[1]);
}
return NULL;
}
/**
* Checks current page for specified knowledge.
*
* @param \Drupal\knowledge\KnowledgeInterface $knowledge
* The knowledge object.
* @param bool $reply
* Boolean indicating whether the knowledge is a reply to another knowledge.
*
* @return bool
* Boolean indicating whether the knowledge was found.
*/
public function knowledgeExists(?KnowledgeInterface $knowledge = NULL, $reply = FALSE) {
if ($knowledge) {
$regex = '/' . ($reply ? '<div class="indented">(.*?)' : '');
$regex .= '<article(.*?)id="knowledge-' . $knowledge->id() . '"(.*?)';
$regex .= $knowledge->label() . '(.*?)';
$regex .= $knowledge->knowledge_body->value . '(.*?)';
$regex .= '/s';
return (boolean) preg_match($regex, $this->getSession()->getPage()->getContent());
}
else {
return FALSE;
}
}
/**
* Checks whether the knowledge linker's contact information is displayed.
*
* @return bool
* Contact info is available.
*/
public function knowledgeContactInfoAvailable() {
return (bool) preg_match('/(input).*?(name="name").*?(input).*?(name="mail")/s', $this->getSession()->getPage()->getContent());
}
/**
* Performs the specified operation on the specified knowledge.
*
* @param object $knowledge
* Knowledge to perform operation on.
* @param string $operation
* Operation to perform.
* @param bool $approval
* Operation is found on approval page.
*/
public function performKnowledgeOperation($knowledge, $operation, $approval = FALSE) {
$edit = [];
$edit['operation'] = $operation;
$edit['knowledge[' . $knowledge->id() . ']'] = TRUE;
$this->drupalGet('admin/content/knowledge' . ($approval ? '/approval' : ''));
$this->submitForm($edit, 'Update');
if ($operation == 'delete') {
$this->submitForm([], 'Delete');
$this->assertSession()->pageTextContains('Deleted 1 knowledge.');
}
else {
$this->assertSession()->pageTextContains('The update has been performed.');
}
}
/**
* Gets the knowledge ID for an unapproved knowledge.
*
* @param string $subject
* Knowledge subject to find.
*
* @return int
* Knowledge ID.
*/
public function getUnapprovedKnowledge($subject) {
$this->drupalGet('admin/content/knowledge/approval');
preg_match('/href="(.*?)#knowledge-([^"]+)"(.*?)>(' . $subject . ')/', $this->getSession()->getPage()->getContent(), $match);
return $match[2];
}
/**
* Tests anonymous knowledge functionality.
*/
public function testKnowledgeFunctionality() {
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
]);
$this->drupalLogin($limited_user);
// Test that default field exists.
$this->drupalGet('entity_test/structure/entity_test/fields');
$this->assertSession()->pageTextContains('Knowledge');
$this->assertSession()->linkByHrefExists('entity_test/structure/entity_test/fields/entity_test.entity_test.knowledge');
// Test widget hidden option is not visible when there's no knowledge.
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.knowledge');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->fieldNotExists('edit-default-value-input-knowledge-und-0-status-0');
// Test that field to change cardinality is not available.
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.knowledge/storage');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->fieldNotExists('cardinality_number');
$this->assertSession()->fieldNotExists('cardinality');
$this->drupalLogin($this->adminUser);
// Test breadcrumb on knowledge add page.
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge');
$xpath = '//nav[@aria-labelledby="system-breadcrumb"]/ol/li[last()]/a';
$this->assertEquals($this->entity->label(), current($this->xpath($xpath))->getText(), 'Last breadcrumb item is equal to node title on knowledge reply page.');
// Post a knowledge.
/** @var \Drupal\knowledge\KnowledgeInterface $knowledge1 */
$knowledge1 = $this->postKnowledge($this->entity, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->knowledgeExists($knowledge1), 'Knowledge on test entity exists.');
// Test breadcrumb on knowledge reply page.
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge/' . $knowledge1->id());
$xpath = '//nav[@aria-labelledby="system-breadcrumb"]/ol/li[last()]/a';
$this->assertEquals($knowledge1->label(), current($this->xpath($xpath))->getText(), 'Last breadcrumb item is equal to knowledge title on knowledge reply page.');
// Test breadcrumb on knowledge edit page.
$this->drupalGet('knowledge/' . $knowledge1->id() . '/edit');
$xpath = '//nav[@aria-labelledby="system-breadcrumb"]/ol/li[last()]/a';
$this->assertEquals($knowledge1->label(), current($this->xpath($xpath))->getText(), 'Last breadcrumb item is equal to knowledge subject on edit page.');
// Test breadcrumb on knowledge delete page.
$this->drupalGet('knowledge/' . $knowledge1->id() . '/delete');
$xpath = '//nav[@aria-labelledby="system-breadcrumb"]/ol/li[last()]/a';
$this->assertEquals($knowledge1->label(), current($this->xpath($xpath))->getText(), 'Last breadcrumb item is equal to knowledge subject on delete confirm page.');
// Unpublish the knowledge.
$this->performKnowledgeOperation($knowledge1, 'unpublish');
$this->drupalGet('admin/content/knowledge/approval');
$this->assertSession()->responseContains('knowledge[' . $knowledge1->id() . ']');
// Publish the knowledge.
$this->performKnowledgeOperation($knowledge1, 'publish', TRUE);
$this->drupalGet('admin/content/knowledge');
$this->assertSession()->responseContains('knowledge[' . $knowledge1->id() . ']');
// Delete the knowledge.
$this->performKnowledgeOperation($knowledge1, 'delete');
$this->drupalGet('admin/content/knowledge');
$this->assertSession()->responseNotContains('knowledge[' . $knowledge1->id() . ']');
// Post another knowledge.
$knowledge1 = $this->postKnowledge($this->entity, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($this->knowledgeExists($knowledge1), 'Knowledge on test entity exists.');
// Check that the knowledge was found.
$this->drupalGet('admin/content/knowledge');
$this->assertSession()->responseContains('knowledge[' . $knowledge1->id() . ']');
// Check that entity access applies to administrative page.
$this->assertSession()->pageTextContains($this->entity->label());
$limited_user = $this->drupalCreateUser([
'administer knowledge',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('admin/content/knowledge');
$this->assertSession()->pageTextNotContains($this->entity->label());
$this->drupalLogout();
// Deny anonymous users access to knowledge.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access knowledge' => FALSE,
'post knowledge' => FALSE,
'skip knowledge approval' => FALSE,
'view test entity' => TRUE,
]);
// Attempt to view knowledge while disallowed.
$this->drupalGet('entity-test/' . $this->entity->id());
// Verify that knowledge were not displayed.
$this->assertSession()->responseNotMatches('@<h2[^>]*>Knowledge</h2>@');
$this->assertSession()->linkNotExists('Add new knowledge', 'Link to add knowledge was found.');
// Attempt to view test entity knowledge form while disallowed.
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge');
$this->assertSession()->statusCodeEquals(403);
$this->assertSession()->fieldNotExists('subject[0][value]');
$this->assertSession()->fieldNotExists('knowledge_body[0][value]');
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access knowledge' => TRUE,
'post knowledge' => FALSE,
'view test entity' => TRUE,
'skip knowledge approval' => FALSE,
]);
$this->drupalGet('entity_test/' . $this->entity->id());
// Verify that the knowledge field title is displayed.
$this->assertSession()->responseMatches('@<h2[^>]*>Knowledge</h2>@');
$this->assertSession()->linkExists('Log in', 0, 'Link to login was found.');
$this->assertSession()->linkExists('register', 0, 'Link to register was found.');
$this->assertSession()->fieldNotExists('subject[0][value]');
$this->assertSession()->fieldNotExists('knowledge_body[0][value]');
// Test the combination of anonymous users being able to post, but not view
// knowledge, to ensure that access to post knowledge doesn't grant access
// to view them.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access knowledge' => FALSE,
'post knowledge' => TRUE,
'skip knowledge approval' => TRUE,
'view test entity' => TRUE,
]);
$this->drupalGet('entity_test/' . $this->entity->id());
// Verify that knowledge were not displayed.
$this->assertSession()->responseNotMatches('@<h2[^>]*>Knowledge</h2>@');
$this->assertSession()->fieldValueEquals('subject[0][value]', '');
$this->assertSession()->fieldValueEquals('knowledge_body[0][value]', '');
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge/' . $knowledge1->id());
$this->assertSession()->statusCodeEquals(403);
$this->assertSession()->pageTextNotContains($knowledge1->label());
// Test knowledge field widget changes.
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'view test entity',
'administer entity_test content',
'administer knowledge',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.knowledge');
$this->assertSession()->checkboxNotChecked('edit-default-value-input-knowledge-0-status-0');
$this->assertSession()->checkboxNotChecked('edit-default-value-input-knowledge-0-status-1');
$this->assertSession()->checkboxChecked('edit-default-value-input-knowledge-0-status-2');
// Test knowledge option change in field settings.
$edit = [
'default_value_input[knowledge][0][status]' => KnowledgeItemInterface::CLOSED,
'settings[anonymous]' => KnowledgeInterface::ANONYMOUS_MAY_CONTACT,
];
$this->submitForm($edit, 'Save settings');
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.knowledge');
$this->assertSession()->checkboxNotChecked('edit-default-value-input-knowledge-0-status-0');
$this->assertSession()->checkboxChecked('edit-default-value-input-knowledge-0-status-1');
$this->assertSession()->checkboxNotChecked('edit-default-value-input-knowledge-0-status-2');
$this->assertSession()->fieldValueEquals('settings[anonymous]', KnowledgeInterface::ANONYMOUS_MAY_CONTACT);
// Add a new knowledge-type.
$bundle = KnowledgeType::create([
'id' => 'foobar',
'label' => 'Foobar',
'description' => '',
'target_entity_type_id' => 'entity_test',
]);
$bundle->save();
// Add a new knowledge field.
$storage_edit = [
'settings[knowledge_type]' => 'foobar',
];
$this->fieldUIAddNewField('entity_test/structure/entity_test', 'foobar', 'Foobar', 'knowledge', $storage_edit);
// Add a third knowledge field.
$this->fieldUIAddNewField('entity_test/structure/entity_test', 'barfoo', 'BarFoo', 'knowledge', $storage_edit);
// Check the field contains the correct knowledge type.
$field_storage = FieldStorageConfig::load('entity_test.field_barfoo');
$this->assertInstanceOf(FieldStorageConfig::class, $field_storage);
$this->assertEquals('foobar', $field_storage->getSetting('knowledge_type'));
$this->assertEquals(1, $field_storage->getCardinality());
// Test the new entity knowledge linking inherits default.
$random_label = $this->randomMachineName();
$data = ['bundle' => 'entity_test', 'name' => $random_label];
$new_entity = EntityTest::create($data);
$new_entity->save();
$this->drupalGet('entity_test/manage/' . $new_entity->id() . '/edit');
$this->assertSession()->checkboxNotChecked('edit-field-foobar-0-status-1');
$this->assertSession()->checkboxChecked('edit-field-foobar-0-status-2');
$this->assertSession()->fieldNotExists('edit-field-foobar-0-status-0');
// @todo Check proper url and form https://www.drupal.org/node/2458323
$this->drupalGet('knowledge/reply/entity_test/knowledge/' . $new_entity->id());
$this->assertSession()->fieldNotExists('subject[0][value]');
$this->assertSession()->fieldNotExists('knowledge_body[0][value]');
// Test removal of knowledge_body field.
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'post knowledge',
'administer knowledge fields',
'administer knowledge types',
'view test entity',
]);
$this->drupalLogin($limited_user);
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge');
$this->assertSession()->fieldValueEquals('knowledge_body[0][value]', '');
$this->fieldUIDeleteField('admin/structure/knowledge/link/manage/knowledge', 'knowledge.knowledge.knowledge_body', 'Knowledge', 'Knowledge settings');
$this->drupalGet('knowledge/reply/entity_test/' . $this->entity->id() . '/knowledge');
$this->assertSession()->fieldNotExists('knowledge_body[0][value]');
// Set subject field to autogenerate it.
$edit = ['subject[0][value]' => ''];
$this->submitForm($edit, 'Save');
}
/**
* Tests knowledge fields cannot be added to entity types without integer IDs.
*/
public function testsNonIntegerIdEntities() {
// Create a bundle for entity_test_string_id.
DeprecationHelper::backwardsCompatibleCall(
currentVersion: \Drupal::VERSION,
deprecatedVersion: '11.2.0',
currentCallable: fn() => EntityTestHelper::createBundle('entity_test', 'Entity Test', 'entity_test_string_id'),
deprecatedCallable: fn() => entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_string_id')
);
$limited_user = $this->drupalCreateUser([
'administer entity_test_string_id fields',
'administer knowledge types',
]);
$this->drupalLogin($limited_user);
// Visit the Field UI field add page.
$this->drupalGet('entity_test_string_id/structure/entity_test/fields/add-field');
// Ensure field isn't shown for string IDs.
$this->assertSession()->optionNotExists('edit-new-storage-type', 'knowledge');
// Ensure a core field type shown.
$this->assertSession()->optionExists('edit-new-storage-type', 'boolean');
// Attempt to add a knowledge-type referencing this entity-type.
$this->drupalGet('admin/structure/knowledge/link/types/add');
$this->assertSession()->optionNotExists('edit-target-entity-type-id', 'entity_test_string_id');
$this->assertSession()->responseNotContains('Test entity with string_id');
// Create a bundle for entity_test_no_id.
DeprecationHelper::backwardsCompatibleCall(
currentVersion: \Drupal::VERSION,
deprecatedVersion: '11.2.0',
currentCallable: fn() => EntityTestHelper::createBundle('entity_test', 'Entity Test', 'entity_test_no_id'),
deprecatedCallable: fn() => entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_no_id')
);
$this->drupalLogin($this->drupalCreateUser([
'administer entity_test_no_id fields',
]));
// Visit the Field UI field add page.
$this->drupalGet('entity_test_no_id/structure/entity_test/fields/add-field');
// Ensure field isn't shown for empty IDs.
$this->assertSession()->optionNotExists('edit-new-storage-type', 'knowledge');
// Ensure a core field type shown.
$this->assertSession()->optionExists('edit-new-storage-type', 'boolean');
}
}
