Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -32,9 +32,9 @@ class ForumNodeBreadcrumbBuilder extends ForumBreadcrumbBuilderBase {
foreach ($parents as $parent) {
$breadcrumb->addCacheableDependency($parent);
$breadcrumb->addLink(Link::createFromRoute($parent->label(), 'forum.page',
array(
[
'taxonomy_term' => $parent->id(),
)
]
));
}
}

View file

@ -207,9 +207,9 @@ class ForumController extends ControllerBase {
* @return array
* A render array.
*/
protected function build($forums, TermInterface $term, $topics = array(), $parents = array(), $header = array()) {
protected function build($forums, TermInterface $term, $topics = [], $parents = [], $header = []) {
$config = $this->config('forum.settings');
$build = array(
$build = [
'#theme' => 'forums',
'#forums' => $forums,
'#topics' => $topics,
@ -218,9 +218,9 @@ class ForumController extends ControllerBase {
'#term' => $term,
'#sortby' => $config->get('topics.order'),
'#forums_per_page' => $config->get('topics.page_limit'),
);
];
if (empty($term->forum_container->value)) {
$build['#attached']['feed'][] = array('taxonomy/term/' . $term->id() . '/feed', 'RSS - ' . $term->getName());
$build['#attached']['feed'][] = ['taxonomy/term/' . $term->id() . '/feed', 'RSS - ' . $term->getName()];
}
$this->renderer->addCacheableDependency($build, $config);
@ -252,10 +252,10 @@ class ForumController extends ControllerBase {
*/
public function addForum() {
$vid = $this->config('forum.settings')->get('vocabulary');
$taxonomy_term = $this->termStorage->create(array(
$taxonomy_term = $this->termStorage->create([
'vid' => $vid,
'forum_controller' => 0,
));
]);
return $this->entityFormBuilder()->getForm($taxonomy_term, 'forum');
}
@ -267,10 +267,10 @@ class ForumController extends ControllerBase {
*/
public function addContainer() {
$vid = $this->config('forum.settings')->get('vocabulary');
$taxonomy_term = $this->termStorage->create(array(
$taxonomy_term = $this->termStorage->create([
'vid' => $vid,
'forum_container' => 1,
));
]);
return $this->entityFormBuilder()->getForm($taxonomy_term, 'container');
}
@ -325,10 +325,10 @@ class ForumController extends ControllerBase {
$links['login'] = [
'#attributes' => ['class' => ['action-links']],
'#theme' => 'menu_local_action',
'#link' => array(
'#link' => [
'title' => $this->t('Log in to post new content in the forum.'),
'url' => Url::fromRoute('user.login', [], ['query' => $this->getDestinationArray()]),
),
],
];
}
}

View file

@ -30,7 +30,7 @@ class DeleteForm extends ConfirmFormBase {
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the forum %label?', array('%label' => $this->taxonomyTerm->label()));
return $this->t('Are you sure you want to delete the forum %label?', ['%label' => $this->taxonomyTerm->label()]);
}
/**
@ -61,8 +61,8 @@ class DeleteForm extends ConfirmFormBase {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->taxonomyTerm->delete();
drupal_set_message($this->t('The forum %label and all sub-forums have been deleted.', array('%label' => $this->taxonomyTerm->label())));
$this->logger('forum')->notice('forum: deleted %label and all its sub-forums.', array('%label' => $this->taxonomyTerm->label()));
drupal_set_message($this->t('The forum %label and all sub-forums have been deleted.', ['%label' => $this->taxonomyTerm->label()]));
$this->logger('forum')->notice('forum: deleted %label and all its sub-forums.', ['%label' => $this->taxonomyTerm->label()]);
$form_state->setRedirectUrl($this->getCancelUrl());
}

View file

@ -50,7 +50,7 @@ class ForumForm extends TermForm {
$form['parent']['#tree'] = TRUE;
$form['parent'][0] = $this->forumParentSelect($taxonomy_term->id(), $this->t('Parent'));
$form['#theme_wrappers'] = array('form__forum');
$form['#theme_wrappers'] = ['form__forum'];
$this->forumFormType = $this->t('forum');
return $form;
}
@ -62,7 +62,7 @@ class ForumForm extends TermForm {
$term = parent::buildEntity($form, $form_state);
// Assign parents from forum parent select field.
$term->parent = array($form_state->getValue(array('parent', 0)));
$term->parent = [$form_state->getValue(['parent', 0])];
return $term;
}
@ -81,14 +81,14 @@ class ForumForm extends TermForm {
$view_link = $term->link($term->getName());
switch ($status) {
case SAVED_NEW:
drupal_set_message($this->t('Created new @type %term.', array('%term' => $view_link, '@type' => $this->forumFormType)));
$this->logger('forum')->notice('Created new @type %term.', array('%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link));
drupal_set_message($this->t('Created new @type %term.', ['%term' => $view_link, '@type' => $this->forumFormType]));
$this->logger('forum')->notice('Created new @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
$form_state->setValue('tid', $term->id());
break;
case SAVED_UPDATED:
drupal_set_message($this->t('The @type %term has been updated.', array('%term' => $term->getName(), '@type' => $this->forumFormType)));
$this->logger('forum')->notice('Updated @type %term.', array('%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link));
drupal_set_message($this->t('The @type %term has been updated.', ['%term' => $term->getName(), '@type' => $this->forumFormType]));
$this->logger('forum')->notice('Updated @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
break;
}
@ -155,14 +155,14 @@ class ForumForm extends TermForm {
$description = $this->t('Forums may be placed at the top (root) level, or inside another container or forum.');
return array(
return [
'#type' => 'select',
'#title' => $title,
'#default_value' => $parent,
'#options' => $options,
'#description' => $description,
'#required' => TRUE,
);
];
}
}

View file

@ -80,10 +80,10 @@ class Overview extends OverviewTerms {
unset($form['actions']['reset_alphabetical']);
// Use the existing taxonomy overview submit handler.
$form['terms']['#empty'] = $this->t('No containers or forums available. <a href=":container">Add container</a> or <a href=":forum">Add forum</a>.', array(
$form['terms']['#empty'] = $this->t('No containers or forums available. <a href=":container">Add container</a> or <a href=":forum">Add forum</a>.', [
':container' => $this->url('forum.add_container'),
':forum' => $this->url('forum.add_forum')
));
]);
return $form;
}

View file

@ -23,7 +23,7 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
* @param \Drupal\Core\Database\Connection $database
* The current database connection.
*/
function __construct(Connection $database) {
public function __construct(Connection $database) {
$this->database = $database;
}
@ -31,7 +31,7 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
* {@inheritdoc}
*/
public function getOriginalTermId(NodeInterface $node) {
return $this->database->queryRange("SELECT f.tid FROM {forum} f INNER JOIN {node} n ON f.vid = n.vid WHERE n.nid = :nid ORDER BY f.vid DESC", 0, 1, array(':nid' => $node->id()))->fetchField();
return $this->database->queryRange("SELECT f.tid FROM {forum} f INNER JOIN {node} n ON f.vid = n.vid WHERE n.nid = :nid ORDER BY f.vid DESC", 0, 1, [':nid' => $node->id()])->fetchField();
}
/**
@ -39,11 +39,11 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
*/
public function create(NodeInterface $node) {
$this->database->insert('forum')
->fields(array(
->fields([
'tid' => $node->forum_tid,
'vid' => $node->getRevisionId(),
'nid' => $node->id(),
))
])
->execute();
}
@ -52,7 +52,7 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
*/
public function read(array $vids) {
return $this->database->select('forum', 'f')
->fields('f', array('nid', 'tid'))
->fields('f', ['nid', 'tid'])
->condition('f.vid', $vids, 'IN')
->execute();
}
@ -81,7 +81,7 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
*/
public function update(NodeInterface $node) {
$this->database->update('forum')
->fields(array('tid' => $node->forum_tid))
->fields(['tid' => $node->forum_tid])
->condition('vid', $node->getRevisionId())
->execute();
}
@ -91,22 +91,22 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
*/
public function updateIndex(NodeInterface $node) {
$nid = $node->id();
$count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {forum_index} i ON c.entity_id = i.nid WHERE c.entity_id = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", array(
$count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {forum_index} i ON c.entity_id = i.nid WHERE c.entity_id = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", [
':nid' => $nid,
':status' => CommentInterface::PUBLISHED,
))->fetchField();
])->fetchField();
if ($count > 0) {
// Comments exist.
$last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} WHERE entity_id = :nid AND field_name = 'comment_forum' AND entity_type = 'node' AND status = :status AND default_langcode = 1 ORDER BY cid DESC", 0, 1, array(
$last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} WHERE entity_id = :nid AND field_name = 'comment_forum' AND entity_type = 'node' AND status = :status AND default_langcode = 1 ORDER BY cid DESC", 0, 1, [
':nid' => $nid,
':status' => CommentInterface::PUBLISHED,
))->fetchObject();
])->fetchObject();
$this->database->update('forum_index')
->fields( array(
->fields( [
'comment_count' => $count,
'last_comment_timestamp' => $last_reply->created,
))
])
->condition('nid', $nid)
->execute();
}
@ -114,10 +114,10 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
// Comments do not exist.
// @todo This should be actually filtering on the desired node language
$this->database->update('forum_index')
->fields( array(
->fields( [
'comment_count' => 0,
'last_comment_timestamp' => $node->getCreatedTime(),
))
])
->condition('nid', $nid)
->execute();
}
@ -128,11 +128,11 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
*/
public function createIndex(NodeInterface $node) {
$query = $this->database->insert('forum_index')
->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
->fields(['nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp']);
foreach ($node->getTranslationLanguages() as $langcode => $language) {
$translation = $node->getTranslation($langcode);
foreach ($translation->taxonomy_forums as $item) {
$query->values(array(
$query->values([
'nid' => $node->id(),
'title' => $translation->label(),
'tid' => $item->target_id,
@ -140,7 +140,7 @@ class ForumIndexStorage implements ForumIndexStorageInterface {
'created' => $node->getCreatedTime(),
'comment_count' => 0,
'last_comment_timestamp' => $node->getCreatedTime(),
));
]);
}
}
$query->execute();

View file

@ -75,28 +75,28 @@ class ForumManager implements ForumManagerInterface {
*
* @var array
*/
protected $lastPostData = array();
protected $lastPostData = [];
/**
* Array of forum statistics keyed by forum (term) id.
*
* @var array
*/
protected $forumStatistics = array();
protected $forumStatistics = [];
/**
* Array of forum children keyed by parent forum (term) id.
*
* @var array
*/
protected $forumChildren = array();
protected $forumChildren = [];
/**
* Array of history keyed by nid.
*
* @var array
*/
protected $history = array();
protected $history = [];
/**
* Cached forum index.
@ -135,11 +135,11 @@ class ForumManager implements ForumManagerInterface {
$forum_per_page = $config->get('topics.page_limit');
$sortby = $config->get('topics.order');
$header = array(
array('data' => $this->t('Topic'), 'field' => 'f.title'),
array('data' => $this->t('Replies'), 'field' => 'f.comment_count'),
array('data' => $this->t('Last reply'), 'field' => 'f.last_comment_timestamp'),
);
$header = [
['data' => $this->t('Topic'), 'field' => 'f.title'],
['data' => $this->t('Replies'), 'field' => 'f.comment_count'],
['data' => $this->t('Last reply'), 'field' => 'f.last_comment_timestamp'],
];
$order = $this->getTopicOrder($sortby);
for ($i = 0; $i < count($header); $i++) {
@ -168,7 +168,7 @@ class ForumManager implements ForumManagerInterface {
$query->setCountQuery($count_query);
$result = $query->execute();
$nids = array();
$nids = [];
foreach ($result as $record) {
$nids[] = $record->nid;
}
@ -177,15 +177,15 @@ class ForumManager implements ForumManagerInterface {
$query = $this->connection->select('node_field_data', 'n')
->extend('Drupal\Core\Database\Query\TableSortExtender');
$query->fields('n', array('nid'));
$query->fields('n', ['nid']);
$query->join('comment_entity_statistics', 'ces', "n.nid = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
$query->fields('ces', array(
$query->fields('ces', [
'cid',
'last_comment_uid',
'last_comment_timestamp',
'comment_count'
));
]);
$query->join('forum_index', 'f', 'f.nid = n.nid');
$query->addField('f', 'tid', 'forum_tid');
@ -205,7 +205,7 @@ class ForumManager implements ForumManagerInterface {
// and just fall back to the default language.
->condition('n.default_langcode', 1);
$result = array();
$result = [];
foreach ($query->execute() as $row) {
$topic = $nodes[$row->nid];
$topic->comment_mode = $topic->comment_forum->status;
@ -217,10 +217,10 @@ class ForumManager implements ForumManagerInterface {
}
}
else {
$result = array();
$result = [];
}
$topics = array();
$topics = [];
$first_new_found = FALSE;
foreach ($result as $topic) {
if ($account->isAuthenticated()) {
@ -258,7 +258,7 @@ class ForumManager implements ForumManagerInterface {
$topics[$topic->id()] = $topic;
}
return array('topics' => $topics, 'header' => $header);
return ['topics' => $topics, 'header' => $header];
}
@ -280,16 +280,16 @@ class ForumManager implements ForumManagerInterface {
protected function getTopicOrder($sortby) {
switch ($sortby) {
case static::NEWEST_FIRST:
return array('field' => 'f.last_comment_timestamp', 'sort' => 'desc');
return ['field' => 'f.last_comment_timestamp', 'sort' => 'desc'];
case static::OLDEST_FIRST:
return array('field' => 'f.last_comment_timestamp', 'sort' => 'asc');
return ['field' => 'f.last_comment_timestamp', 'sort' => 'asc'];
case static::MOST_POPULAR_FIRST:
return array('field' => 'f.comment_count', 'sort' => 'desc');
return ['field' => 'f.comment_count', 'sort' => 'desc'];
case static::LEAST_POPULAR_FIRST:
return array('field' => 'f.comment_count', 'sort' => 'asc');
return ['field' => 'f.comment_count', 'sort' => 'asc'];
}
}
@ -309,7 +309,7 @@ class ForumManager implements ForumManagerInterface {
protected function lastVisit($nid, AccountInterface $account) {
if (empty($this->history[$nid])) {
$result = $this->connection->select('history', 'h')
->fields('h', array('nid', 'timestamp'))
->fields('h', ['nid', 'timestamp'])
->condition('uid', $account->id())
->execute();
foreach ($result as $t) {
@ -334,13 +334,13 @@ class ForumManager implements ForumManagerInterface {
}
// Query "Last Post" information for this forum.
$query = $this->connection->select('node_field_data', 'n');
$query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $tid));
$query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', [':tid' => $tid]);
$query->join('comment_entity_statistics', 'ces', "n.nid = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
$query->join('users_field_data', 'u', 'ces.last_comment_uid = u.uid AND u.default_langcode = 1');
$query->addExpression('CASE ces.last_comment_uid WHEN 0 THEN ces.last_comment_name ELSE u.name END', 'last_comment_name');
$topic = $query
->fields('ces', array('last_comment_timestamp', 'last_comment_uid'))
->fields('ces', ['last_comment_timestamp', 'last_comment_uid'])
->condition('n.status', 1)
->orderBy('last_comment_timestamp', 'DESC')
->range(0, 1)
@ -378,7 +378,7 @@ class ForumManager implements ForumManagerInterface {
$query->addExpression('COUNT(n.nid)', 'topic_count');
$query->addExpression('SUM(ces.comment_count)', 'comment_count');
$this->forumStatistics = $query
->fields('f', array('tid'))
->fields('f', ['tid'])
->condition('n.status', 1)
->condition('n.default_langcode', 1)
->groupBy('tid')
@ -399,7 +399,7 @@ class ForumManager implements ForumManagerInterface {
if (!empty($this->forumChildren[$tid])) {
return $this->forumChildren[$tid];
}
$forums = array();
$forums = [];
$_forums = $this->entityManager->getStorage('taxonomy_term')->loadTree($vid, $tid, NULL, TRUE);
foreach ($_forums as $forum) {
// Merge in the topic and post counters.
@ -430,13 +430,13 @@ class ForumManager implements ForumManagerInterface {
}
$vid = $this->configFactory->get('forum.settings')->get('vocabulary');
$index = $this->entityManager->getStorage('taxonomy_term')->create(array(
$index = $this->entityManager->getStorage('taxonomy_term')->create([
'tid' => 0,
'container' => 1,
'parents' => array(),
'parents' => [],
'isIndex' => TRUE,
'vid' => $vid
));
]);
// Load the tree below.
$index->forums = $this->getChildren($vid, 0);
@ -451,7 +451,7 @@ class ForumManager implements ForumManagerInterface {
// Reset the index.
$this->index = NULL;
// Reset history.
$this->history = array();
$this->history = [];
}
/**
@ -475,8 +475,8 @@ class ForumManager implements ForumManagerInterface {
*/
public function unreadTopics($term, $uid) {
$query = $this->connection->select('node_field_data', 'n');
$query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $term));
$query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', array(':uid' => $uid));
$query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', [':tid' => $term]);
$query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', [':uid' => $uid]);
$query->addExpression('COUNT(n.nid)', 'count');
return $query
->condition('status', 1)
@ -506,10 +506,10 @@ class ForumManager implements ForumManagerInterface {
public function __wakeup() {
$this->defaultWakeup();
// Initialize static cache.
$this->history = array();
$this->lastPostData = array();
$this->forumChildren = array();
$this->forumStatistics = array();
$this->history = [];
$this->lastPostData = [];
$this->forumChildren = [];
$this->forumStatistics = [];
$this->index = NULL;
}

View file

@ -30,35 +30,35 @@ class ForumSettingsForm extends ConfigFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('forum.settings');
$options = array(5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100, 150, 200, 250, 300, 350, 400, 500);
$form['forum_hot_topic'] = array(
$options = [5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100, 150, 200, 250, 300, 350, 400, 500];
$form['forum_hot_topic'] = [
'#type' => 'select',
'#title' => $this->t('Hot topic threshold'),
'#default_value' => $config->get('topics.hot_threshold'),
'#options' => array_combine($options, $options),
'#description' => $this->t('The number of replies a topic must have to be considered "hot".'),
);
$options = array(10, 25, 50, 75, 100);
$form['forum_per_page'] = array(
];
$options = [10, 25, 50, 75, 100];
$form['forum_per_page'] = [
'#type' => 'select',
'#title' => $this->t('Topics per page'),
'#default_value' => $config->get('topics.page_limit'),
'#options' => array_combine($options, $options),
'#description' => $this->t('Default number of forum topics displayed per page.'),
);
$forder = array(
];
$forder = [
1 => $this->t('Date - newest first'),
2 => $this->t('Date - oldest first'),
3 => $this->t('Posts - most active first'),
4 => $this->t('Posts - least active first')
);
$form['forum_order'] = array(
];
$form['forum_order'] = [
'#type' => 'radios',
'#title' => $this->t('Default order'),
'#default_value' => $config->get('topics.order'),
'#options' => $forder,
'#description' => $this->t('Default display order for topics.'),
);
];
return parent::buildForm($form, $form_state);
}

View file

@ -3,8 +3,7 @@
namespace Drupal\forum;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
@ -19,18 +18,11 @@ class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
use StringTranslationTrait;
/**
* The field storage config storage.
* The entity type manager.
*
* @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $vocabularyStorage;
/**
* The entity query factory.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $queryFactory;
protected $entityTypeManager;
/**
* The config factory.
@ -42,18 +34,15 @@ class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
/**
* Constructs a new ForumUninstallValidator.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
* The entity query factory.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(EntityManagerInterface $entity_manager, QueryFactory $query_factory, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation) {
$this->vocabularyStorage = $entity_manager->getStorage('taxonomy_vocabulary');
$this->queryFactory = $query_factory;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->configFactory = $config_factory;
$this->stringTranslation = $string_translation;
}
@ -94,7 +83,7 @@ class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
* TRUE if there are forum nodes, FALSE otherwise.
*/
protected function hasForumNodes() {
$nodes = $this->queryFactory->get('node')
$nodes = $this->entityTypeManager->getStorage('node')->getQuery()
->condition('type', 'forum')
->accessCheck(FALSE)
->range(0, 1)
@ -112,7 +101,7 @@ class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
* TRUE if there are terms for this vocabulary, FALSE otherwise.
*/
protected function hasTermsForVocabulary(VocabularyInterface $vocabulary) {
$terms = $this->queryFactory->get('taxonomy_term')
$terms = $this->entityTypeManager->getStorage('taxonomy_term')->getQuery()
->condition('vid', $vocabulary->id())
->accessCheck(FALSE)
->range(0, 1)
@ -128,7 +117,7 @@ class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
*/
protected function getForumVocabulary() {
$vid = $this->configFactory->get('forum.settings')->get('vocabulary');
return $this->vocabularyStorage->load($vid);
return $this->entityTypeManager->getStorage('taxonomy_vocabulary')->load($vid);
}
}

View file

@ -19,14 +19,14 @@ abstract class ForumBlockBase extends BlockBase {
*/
public function build() {
$result = $this->buildForumQuery()->execute();
$elements = array();
$elements = [];
if ($node_title_list = node_title_list($result)) {
$elements['forum_list'] = $node_title_list;
$elements['forum_more'] = array(
$elements['forum_more'] = [
'#type' => 'more_link',
'#url' => Url::fromRoute('forum.index'),
'#attributes' => array('title' => $this->t('Read the latest forum topics.')),
);
'#attributes' => ['title' => $this->t('Read the latest forum topics.')],
];
}
return $elements;
}
@ -43,12 +43,12 @@ abstract class ForumBlockBase extends BlockBase {
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
'properties' => array(
return [
'properties' => [
'administrative' => TRUE,
),
],
'block_count' => 5,
);
];
}
/**
@ -63,12 +63,12 @@ abstract class ForumBlockBase extends BlockBase {
*/
public function blockForm($form, FormStateInterface $form_state) {
$range = range(2, 20);
$form['block_count'] = array(
$form['block_count'] = [
'#type' => 'select',
'#title' => $this->t('Number of topics'),
'#default_value' => $this->configuration['block_count'],
'#options' => array_combine($range, $range),
);
];
return $form;
}

View file

@ -26,7 +26,7 @@ class ForumLeafConstraintValidator extends ConstraintValidator {
// The forum_container flag must not be set.
if (!empty($item->entity->forum_container->value)) {
$this->context->addViolation($constraint->noLeafMessage, array('%forum' => $item->entity->getName()));
$this->context->addViolation($constraint->noLeafMessage, ['%forum' => $item->entity->getName()]);
}
}

View file

@ -1,180 +0,0 @@
<?php
namespace Drupal\forum\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\comment\Entity\Comment;
/**
* Tests the forum blocks.
*
* @group forum
*/
class ForumBlockTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('forum', 'block');
/**
* A user with various administrative privileges.
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
// Create users.
$this->adminUser = $this->drupalCreateUser(array(
'access administration pages',
'administer blocks',
'administer nodes',
'create forum content',
'post comments',
'skip comment approval',
));
}
/**
* Tests the "New forum topics" block.
*/
public function testNewForumTopicsBlock() {
$this->drupalLogin($this->adminUser);
// Enable the new forum topics block.
$block = $this->drupalPlaceBlock('forum_new_block');
$this->drupalGet('');
// Create 5 forum topics.
$topics = $this->createForumTopics();
$this->assertLink(t('More'), 0, 'New forum topics block has a "more"-link.');
$this->assertLinkByHref('forum', 0, 'New forum topics block has a "more"-link.');
// We expect all 5 forum topics to appear in the "New forum topics" block.
foreach ($topics as $topic) {
$this->assertLink($topic, 0, format_string('Forum topic @topic found in the "New forum topics" block.', array('@topic' => $topic)));
}
// Configure the new forum topics block to only show 2 topics.
$block->getPlugin()->setConfigurationValue('block_count', 2);
$block->save();
$this->drupalGet('');
// We expect only the 2 most recent forum topics to appear in the "New forum
// topics" block.
for ($index = 0; $index < 5; $index++) {
if (in_array($index, array(3, 4))) {
$this->assertLink($topics[$index], 0, format_string('Forum topic @topic found in the "New forum topics" block.', array('@topic' => $topics[$index])));
}
else {
$this->assertNoText($topics[$index], format_string('Forum topic @topic not found in the "New forum topics" block.', array('@topic' => $topics[$index])));
}
}
}
/**
* Tests the "Active forum topics" block.
*/
public function testActiveForumTopicsBlock() {
$this->drupalLogin($this->adminUser);
// Create 10 forum topics.
$topics = $this->createForumTopics(10);
// Comment on the first 5 topics.
$date = new DrupalDateTime();
for ($index = 0; $index < 5; $index++) {
// Get the node from the topic title.
$node = $this->drupalGetNodeByTitle($topics[$index]);
$date->modify('+1 minute');
$comment = Comment::create(array(
'entity_id' => $node->id(),
'field_name' => 'comment_forum',
'entity_type' => 'node',
'node_type' => 'node_type_' . $node->bundle(),
'subject' => $this->randomString(20),
'comment_body' => $this->randomString(256),
'created' => $date->getTimestamp(),
));
$comment->save();
}
// Enable the block.
$block = $this->drupalPlaceBlock('forum_active_block');
$this->drupalGet('');
$this->assertLink(t('More'), 0, 'Active forum topics block has a "more"-link.');
$this->assertLinkByHref('forum', 0, 'Active forum topics block has a "more"-link.');
// We expect the first 5 forum topics to appear in the "Active forum topics"
// block.
$this->drupalGet('<front>');
for ($index = 0; $index < 10; $index++) {
if ($index < 5) {
$this->assertLink($topics[$index], 0, format_string('Forum topic @topic found in the "Active forum topics" block.', array('@topic' => $topics[$index])));
}
else {
$this->assertNoText($topics[$index], format_string('Forum topic @topic not found in the "Active forum topics" block.', array('@topic' => $topics[$index])));
}
}
// Configure the active forum block to only show 2 topics.
$block->getPlugin()->setConfigurationValue('block_count', 2);
$block->save();
$this->drupalGet('');
// We expect only the 2 forum topics with most recent comments to appear in
// the "Active forum topics" block.
for ($index = 0; $index < 10; $index++) {
if (in_array($index, array(3, 4))) {
$this->assertLink($topics[$index], 0, 'Forum topic found in the "Active forum topics" block.');
}
else {
$this->assertNoText($topics[$index], 'Forum topic not found in the "Active forum topics" block.');
}
}
}
/**
* Creates a forum topic.
*
* @return string
* The title of the newly generated topic.
*/
protected function createForumTopics($count = 5) {
$topics = array();
$date = new DrupalDateTime();
$date->modify('-24 hours');
for ($index = 0; $index < $count; $index++) {
// Generate a random subject/body.
$title = $this->randomMachineName(20);
$body = $this->randomMachineName(200);
// Forum posts are ordered by timestamp, so force a unique timestamp by
// changing the date.
$date->modify('+1 minute');
$edit = array(
'title[0][value]' => $title,
'body[0][value]' => $body,
// Forum posts are ordered by timestamp, so force a unique timestamp by
// adding the index.
'created[0][value][date]' => $date->format('Y-m-d'),
'created[0][value][time]' => $date->format('H:i:s'),
);
// Create the forum topic, preselecting the forum ID via a URL parameter.
$this->drupalPostForm('node/add/forum', $edit, t('Save and publish'), array('query' => array('forum_id' => 1)));
$topics[] = $title;
}
return $topics;
}
}

View file

@ -1,83 +0,0 @@
<?php
namespace Drupal\forum\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the forum index listing.
*
* @group forum
*/
class ForumIndexTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('taxonomy', 'comment', 'forum');
protected function setUp() {
parent::setUp();
// Create a test user.
$web_user = $this->drupalCreateUser(['create forum content', 'edit own forum content', 'edit any forum content', 'administer nodes', 'administer forums']);
$this->drupalLogin($web_user);
}
/**
* Tests the forum index for published and unpublished nodes.
*/
function testForumIndexStatus() {
// The forum ID to use.
$tid = 1;
// Create a test node.
$title = $this->randomMachineName(20);
$edit = array(
'title[0][value]' => $title,
'body[0][value]' => $this->randomMachineName(200),
);
// Create the forum topic, preselecting the forum ID via a URL parameter.
$this->drupalGet("forum/$tid");
$this->clickLink(t('Add new @node_type', array('@node_type' => 'Forum topic')));
$this->assertUrl('node/add/forum', array('query' => array('forum_id' => $tid)));
$this->drupalPostForm(NULL, $edit, t('Save and publish'));
// Check that the node exists in the database.
$node = $this->drupalGetNodeByTitle($title);
$this->assertTrue(!empty($node), 'New forum node found in database.');
// Create a child forum.
$edit = array(
'name[0][value]' => $this->randomMachineName(20),
'description[0][value]' => $this->randomMachineName(200),
'parent[0]' => $tid,
);
$this->drupalPostForm('admin/structure/forum/add/forum', $edit, t('Save'));
$tid_child = $tid + 1;
// Verify that the node appears on the index.
$this->drupalGet('forum/' . $tid);
$this->assertText($title, 'Published forum topic appears on index.');
$this->assertCacheTag('node_list');
$this->assertCacheTag('config:node.type.forum');
$this->assertCacheTag('comment_list');
$this->assertCacheTag('node:' . $node->id());
$this->assertCacheTag('taxonomy_term:' . $tid);
$this->assertCacheTag('taxonomy_term:' . $tid_child);
// Unpublish the node.
$this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save and unpublish'));
$this->drupalGet('node/' . $node->id());
$this->assertText(t('Access denied'), 'Unpublished node is no longer accessible.');
// Verify that the node no longer appears on the index.
$this->drupalGet('forum/' . $tid);
$this->assertNoText($title, 'Unpublished forum topic no longer appears on index.');
}
}

View file

@ -1,86 +0,0 @@
<?php
namespace Drupal\forum\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\node\Entity\NodeType;
/**
* Tests forum block view for private node access.
*
* @group forum
*/
class ForumNodeAccessTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'comment', 'forum', 'taxonomy', 'tracker', 'node_access_test', 'block');
protected function setUp() {
parent::setUp();
node_access_rebuild();
node_access_test_add_field(NodeType::load('forum'));
\Drupal::state()->set('node_access_test.private', TRUE);
}
/**
* Creates some users and creates a public node and a private node.
*
* Adds both active forum topics and new forum topics blocks to the sidebar.
* Tests to ensure private node/public node access is respected on blocks.
*/
function testForumNodeAccess() {
// Create some users.
$access_user = $this->drupalCreateUser(array('node test view'));
$no_access_user = $this->drupalCreateUser();
$admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules', 'administer blocks', 'create forum content'));
$this->drupalLogin($admin_user);
// Create a private node.
$private_node_title = $this->randomMachineName(20);
$edit = array(
'title[0][value]' => $private_node_title,
'body[0][value]' => $this->randomMachineName(200),
'private[0][value]' => TRUE,
);
$this->drupalPostForm('node/add/forum', $edit, t('Save'), array('query' => array('forum_id' => 1)));
$private_node = $this->drupalGetNodeByTitle($private_node_title);
$this->assertTrue(!empty($private_node), 'New private forum node found in database.');
// Create a public node.
$public_node_title = $this->randomMachineName(20);
$edit = array(
'title[0][value]' => $public_node_title,
'body[0][value]' => $this->randomMachineName(200),
);
$this->drupalPostForm('node/add/forum', $edit, t('Save'), array('query' => array('forum_id' => 1)));
$public_node = $this->drupalGetNodeByTitle($public_node_title);
$this->assertTrue(!empty($public_node), 'New public forum node found in database.');
// Enable the new and active forum blocks.
$this->drupalPlaceBlock('forum_active_block');
$this->drupalPlaceBlock('forum_new_block');
// Test for $access_user.
$this->drupalLogin($access_user);
$this->drupalGet('');
// Ensure private node and public node are found.
$this->assertText($private_node->getTitle(), 'Private node found in block by $access_user');
$this->assertText($public_node->getTitle(), 'Public node found in block by $access_user');
// Test for $no_access_user.
$this->drupalLogin($no_access_user);
$this->drupalGet('');
// Ensure private node is not found but public is found.
$this->assertNoText($private_node->getTitle(), 'Private node not found in block by $no_access_user');
$this->assertText($public_node->getTitle(), 'Public node found in block by $no_access_user');
}
}

View file

@ -1,689 +0,0 @@
<?php
namespace Drupal\forum\Tests;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Link;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Url;
use Drupal\taxonomy\Entity\Vocabulary;
/**
* Tests for forum.module.
*
* Create, view, edit, delete, and change forum entries and verify its
* consistency in the database.
*
* @group forum
*/
class ForumTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('taxonomy', 'comment', 'forum', 'node', 'block', 'menu_ui', 'help');
/**
* A user with various administrative privileges.
*/
protected $adminUser;
/**
* A user that can create forum topics and edit its own topics.
*/
protected $editOwnTopicsUser;
/**
* A user that can create, edit, and delete forum topics.
*/
protected $editAnyTopicsUser;
/**
* A user with no special privileges.
*/
protected $webUser;
/**
* An administrative user who can bypass comment approval.
*/
protected $postCommentUser;
/**
* An array representing a forum container.
*/
protected $forumContainer;
/**
* An array representing a forum.
*/
protected $forum;
/**
* An array representing a root forum.
*/
protected $rootForum;
/**
* An array of forum topic node IDs.
*/
protected $nids;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalPlaceBlock('system_breadcrumb_block');
$this->drupalPlaceBlock('page_title_block');
// Create users.
$this->adminUser = $this->drupalCreateUser(array(
'access administration pages',
'administer modules',
'administer blocks',
'administer forums',
'administer menu',
'administer taxonomy',
'create forum content',
'access comments',
));
$this->editAnyTopicsUser = $this->drupalCreateUser(array(
'access administration pages',
'create forum content',
'edit any forum content',
'delete any forum content',
));
$this->editOwnTopicsUser = $this->drupalCreateUser(array(
'create forum content',
'edit own forum content',
'delete own forum content',
));
$this->webUser = $this->drupalCreateUser();
$this->postCommentUser = $this->drupalCreateUser(array(
'administer content types',
'create forum content',
'post comments',
'skip comment approval',
'access comments',
));
$this->drupalPlaceBlock('help_block', array('region' => 'help'));
$this->drupalPlaceBlock('local_actions_block');
}
/**
* Tests forum functionality through the admin and user interfaces.
*/
function testForum() {
//Check that the basic forum install creates a default forum topic
$this->drupalGet('/forum');
// Look for the "General discussion" default forum
$this->assertRaw(Link::createFromRoute(t('General discussion'), 'forum.page', ['taxonomy_term' => 1])->toString(), "Found the default forum at the /forum listing");
// Check the presence of expected cache tags.
$this->assertCacheTag('config:forum.settings');
$this->drupalGet(Url::fromRoute('forum.page', ['taxonomy_term' => 1]));
$this->assertCacheTag('config:forum.settings');
// Do the admin tests.
$this->doAdminTests($this->adminUser);
// Check display order.
$display = EntityViewDisplay::load('node.forum.default');
$body = $display->getComponent('body');
$comment = $display->getComponent('comment_forum');
$taxonomy = $display->getComponent('taxonomy_forums');
// Assert field order is body » taxonomy » comments.
$this->assertTrue($taxonomy['weight'] < $body['weight']);
$this->assertTrue($body['weight'] < $comment['weight']);
// Check form order.
$display = EntityFormDisplay::load('node.forum.default');
$body = $display->getComponent('body');
$comment = $display->getComponent('comment_forum');
$taxonomy = $display->getComponent('taxonomy_forums');
// Assert category comes before body in order.
$this->assertTrue($taxonomy['weight'] < $body['weight']);
$this->generateForumTopics();
// Log in an unprivileged user to view the forum topics and generate an
// active forum topics list.
$this->drupalLogin($this->webUser);
// Verify that this user is shown a message that they may not post content.
$this->drupalGet('forum/' . $this->forum['tid']);
$this->assertText(t('You are not allowed to post new content in the forum'), "Authenticated user without permission to post forum content is shown message in local tasks to that effect.");
// Log in, and do basic tests for a user with permission to edit any forum
// content.
$this->doBasicTests($this->editAnyTopicsUser, TRUE);
// Create a forum node authored by this user.
$any_topics_user_node = $this->createForumTopic($this->forum, FALSE);
// Log in, and do basic tests for a user with permission to edit only its
// own forum content.
$this->doBasicTests($this->editOwnTopicsUser, FALSE);
// Create a forum node authored by this user.
$own_topics_user_node = $this->createForumTopic($this->forum, FALSE);
// Verify that this user cannot edit forum content authored by another user.
$this->verifyForums($any_topics_user_node, FALSE, 403);
// Verify that this user is shown a local task to add new forum content.
$this->drupalGet('forum');
$this->assertLink(t('Add new Forum topic'));
$this->drupalGet('forum/' . $this->forum['tid']);
$this->assertLink(t('Add new Forum topic'));
// Log in a user with permission to edit any forum content.
$this->drupalLogin($this->editAnyTopicsUser);
// Verify that this user can edit forum content authored by another user.
$this->verifyForums($own_topics_user_node, TRUE);
// Verify the topic and post counts on the forum page.
$this->drupalGet('forum');
// Verify row for testing forum.
$forum_arg = array(':forum' => 'forum-list-' . $this->forum['tid']);
// Topics cell contains number of topics and number of unread topics.
$xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__topics"]', $forum_arg);
$topics = $this->xpath($xpath);
$topics = trim($topics[0]);
$this->assertEqual($topics, '6', 'Number of topics found.');
// Verify the number of unread topics.
$unread_topics = $this->container->get('forum_manager')->unreadTopics($this->forum['tid'], $this->editAnyTopicsUser->id());
$unread_topics = \Drupal::translation()->formatPlural($unread_topics, '1 new post', '@count new posts');
$xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__topics"]//a', $forum_arg);
$this->assertFieldByXPath($xpath, $unread_topics, 'Number of unread topics found.');
// Verify that the forum name is in the unread topics text.
$xpath = $this->buildXPathQuery('//tr[@id=:forum]//em[@class="placeholder"]', $forum_arg);
$this->assertFieldByXpath($xpath, $this->forum['name'], 'Forum name found in unread topics text.');
// Verify total number of posts in forum.
$xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__posts"]', $forum_arg);
$this->assertFieldByXPath($xpath, '6', 'Number of posts found.');
// Test loading multiple forum nodes on the front page.
$this->drupalLogin($this->drupalCreateUser(array('administer content types', 'create forum content', 'post comments')));
$this->drupalPostForm('admin/structure/types/manage/forum', array('options[promote]' => 'promote'), t('Save content type'));
$this->createForumTopic($this->forum, FALSE);
$this->createForumTopic($this->forum, FALSE);
$this->drupalGet('node');
// Test adding a comment to a forum topic.
$node = $this->createForumTopic($this->forum, FALSE);
$edit = array();
$edit['comment_body[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
$this->assertResponse(200);
// Test editing a forum topic that has a comment.
$this->drupalLogin($this->editAnyTopicsUser);
$this->drupalGet('forum/' . $this->forum['tid']);
$this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save'));
$this->assertResponse(200);
// Test the root forum page title change.
$this->drupalGet('forum');
$this->assertCacheTag('config:taxonomy.vocabulary.' . $this->forum['vid']);
$this->assertTitle(t('Forums | Drupal'));
$vocabulary = Vocabulary::load($this->forum['vid']);
$vocabulary->set('name', 'Discussions');
$vocabulary->save();
$this->drupalGet('forum');
$this->assertTitle(t('Discussions | Drupal'));
// Test anonymous action link.
$this->drupalLogout();
$this->drupalGet('forum/' . $this->forum['tid']);
$this->assertLink(t('Log in to post new content in the forum.'));
}
/**
* Tests that forum nodes can't be added without a parent.
*
* Verifies that forum nodes are not created without choosing "forum" from the
* select list.
*/
function testAddOrphanTopic() {
// Must remove forum topics to test creating orphan topics.
$vid = $this->config('forum.settings')->get('vocabulary');
$tids = \Drupal::entityQuery('taxonomy_term')
->condition('vid', $vid)
->execute();
entity_delete_multiple('taxonomy_term', $tids);
// Create an orphan forum item.
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName(10);
$edit['body[0][value]'] = $this->randomMachineName(120);
$this->drupalLogin($this->adminUser);
$this->drupalPostForm('node/add/forum', $edit, t('Save'));
$nid_count = db_query('SELECT COUNT(nid) FROM {node}')->fetchField();
$this->assertEqual(0, $nid_count, 'A forum node was not created when missing a forum vocabulary.');
// Reset the defaults for future tests.
\Drupal::service('module_installer')->install(array('forum'));
}
/**
* Runs admin tests on the admin user.
*
* @param object $user
* The logged-in user.
*/
private function doAdminTests($user) {
// Log in the user.
$this->drupalLogin($user);
// Add forum to the Tools menu.
$edit = array();
$this->drupalPostForm('admin/structure/menu/manage/tools', $edit, t('Save'));
$this->assertResponse(200);
// Edit forum taxonomy.
// Restoration of the settings fails and causes subsequent tests to fail.
$this->editForumVocabulary();
// Create forum container.
$this->forumContainer = $this->createForum('container');
// Verify "edit container" link exists and functions correctly.
$this->drupalGet('admin/structure/forum');
// Verify help text is shown.
$this->assertText(t('Forums contain forum topics. Use containers to group related forums'));
// Verify action links are there.
$this->assertLink('Add forum');
$this->assertLink('Add container');
$this->clickLink('edit container');
$this->assertRaw('Edit container', 'Followed the link to edit the container');
// Create forum inside the forum container.
$this->forum = $this->createForum('forum', $this->forumContainer['tid']);
// Verify the "edit forum" link exists and functions correctly.
$this->drupalGet('admin/structure/forum');
$this->clickLink('edit forum');
$this->assertRaw('Edit forum', 'Followed the link to edit the forum');
// Navigate back to forum structure page.
$this->drupalGet('admin/structure/forum');
// Create second forum in container, destined to be deleted below.
$delete_forum = $this->createForum('forum', $this->forumContainer['tid']);
// Save forum overview.
$this->drupalPostForm('admin/structure/forum/', array(), t('Save'));
$this->assertRaw(t('The configuration options have been saved.'));
// Delete this second forum.
$this->deleteForum($delete_forum['tid']);
// Create forum at the top (root) level.
$this->rootForum = $this->createForum('forum');
// Test vocabulary form alterations.
$this->drupalGet('admin/structure/taxonomy/manage/forums');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->assertNoFieldByName('op', t('Delete'), 'Delete button not found.');
// Test term edit form alterations.
$this->drupalGet('taxonomy/term/' . $this->forumContainer['tid'] . '/edit');
// Test parent field been hidden by forum module.
$this->assertNoField('parent[]', 'Parent field not found.');
// Create a default vocabulary named "Tags".
$description = 'Use tags to group articles on similar topics into categories.';
$help = 'Enter a comma-separated list of words to describe your content.';
$vocabulary = Vocabulary::create([
'name' => 'Tags',
'description' => $description,
'vid' => 'tags',
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'help' => $help,
]);
$vocabulary->save();
// Test tags vocabulary form is not affected.
$this->drupalGet('admin/structure/taxonomy/manage/tags');
$this->assertFieldByName('op', t('Save'), 'Save button found.');
$this->assertLink(t('Delete'));
// Test tags vocabulary term form is not affected.
$this->drupalGet('admin/structure/taxonomy/manage/tags/add');
$this->assertField('parent[]', 'Parent field found.');
// Test relations widget exists.
$relations_widget = $this->xpath("//details[@id='edit-relations']");
$this->assertTrue(isset($relations_widget[0]), 'Relations widget element found.');
}
/**
* Edits the forum taxonomy.
*/
function editForumVocabulary() {
// Backup forum taxonomy.
$vid = $this->config('forum.settings')->get('vocabulary');
$original_vocabulary = Vocabulary::load($vid);
// Generate a random name and description.
$edit = array(
'name' => $this->randomMachineName(10),
'description' => $this->randomMachineName(100),
);
// Edit the vocabulary.
$this->drupalPostForm('admin/structure/taxonomy/manage/' . $original_vocabulary->id(), $edit, t('Save'));
$this->assertResponse(200);
$this->assertRaw(t('Updated vocabulary %name.', array('%name' => $edit['name'])), 'Vocabulary was edited');
// Grab the newly edited vocabulary.
$current_vocabulary = Vocabulary::load($vid);
// Make sure we actually edited the vocabulary properly.
$this->assertEqual($current_vocabulary->label(), $edit['name'], 'The name was updated');
$this->assertEqual($current_vocabulary->getDescription(), $edit['description'], 'The description was updated');
// Restore the original vocabulary's name and description.
$current_vocabulary->set('name', $original_vocabulary->label());
$current_vocabulary->set('description', $original_vocabulary->getDescription());
$current_vocabulary->save();
// Reload vocabulary to make sure changes are saved.
$current_vocabulary = Vocabulary::load($vid);
$this->assertEqual($current_vocabulary->label(), $original_vocabulary->label(), 'The original vocabulary settings were restored');
}
/**
* Creates a forum container or a forum.
*
* @param string $type
* The forum type (forum container or forum).
* @param int $parent
* The forum parent. This defaults to 0, indicating a root forum.
*
* @return \Drupal\Core\Database\StatementInterface
* The created taxonomy term data.
*/
function createForum($type, $parent = 0) {
// Generate a random name/description.
$name = $this->randomMachineName(10);
$description = $this->randomMachineName(100);
$edit = array(
'name[0][value]' => $name,
'description[0][value]' => $description,
'parent[0]' => $parent,
'weight' => '0',
);
// Create forum.
$this->drupalPostForm('admin/structure/forum/add/' . $type, $edit, t('Save'));
$this->assertResponse(200);
$type = ($type == 'container') ? 'forum container' : 'forum';
$this->assertText(
t(
'Created new @type @term.',
array('@term' => $name, '@type' => t($type))
),
format_string('@type was created', array('@type' => ucfirst($type)))
);
// Verify that the creation message contains a link to a term.
$view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'term/'));
$this->assert(isset($view_link), 'The message area contains a link to a term');
// Verify forum.
$term = db_query("SELECT * FROM {taxonomy_term_field_data} t WHERE t.vid = :vid AND t.name = :name AND t.description__value = :desc AND t.default_langcode = 1", array(':vid' => $this->config('forum.settings')->get('vocabulary'), ':name' => $name, ':desc' => $description))->fetchAssoc();
$this->assertTrue(!empty($term), 'The ' . $type . ' exists in the database');
// Verify forum hierarchy.
$tid = $term['tid'];
$parent_tid = db_query("SELECT t.parent FROM {taxonomy_term_hierarchy} t WHERE t.tid = :tid", array(':tid' => $tid))->fetchField();
$this->assertTrue($parent == $parent_tid, 'The ' . $type . ' is linked to its container');
$forum = $this->container->get('entity.manager')->getStorage('taxonomy_term')->load($tid);
$this->assertEqual(($type == 'forum container'), (bool) $forum->forum_container->value);
return $term;
}
/**
* Deletes a forum.
*
* @param int $tid
* The forum ID.
*/
function deleteForum($tid) {
// Delete the forum.
$this->drupalGet('admin/structure/forum/edit/forum/' . $tid);
$this->clickLink(t('Delete'));
$this->assertText('Are you sure you want to delete the forum');
$this->assertNoText('Add forum');
$this->assertNoText('Add forum container');
$this->drupalPostForm(NULL, array(), t('Delete'));
// Assert that the forum no longer exists.
$this->drupalGet('forum/' . $tid);
$this->assertResponse(404, 'The forum was not found');
}
/**
* Runs basic tests on the indicated user.
*
* @param \Drupal\Core\Session\AccountInterface $user
* The logged in user.
* @param bool $admin
* User has 'access administration pages' privilege.
*/
private function doBasicTests($user, $admin) {
// Log in the user.
$this->drupalLogin($user);
// Attempt to create forum topic under a container.
$this->createForumTopic($this->forumContainer, TRUE);
// Create forum node.
$node = $this->createForumTopic($this->forum, FALSE);
// Verify the user has access to all the forum nodes.
$this->verifyForums($node, $admin);
}
/**
* Tests a forum with a new post displays properly.
*/
function testForumWithNewPost() {
// Log in as the first user.
$this->drupalLogin($this->adminUser);
// Create a forum container.
$this->forumContainer = $this->createForum('container');
// Create a forum.
$this->forum = $this->createForum('forum');
// Create a topic.
$node = $this->createForumTopic($this->forum, FALSE);
// Log in as a second user.
$this->drupalLogin($this->postCommentUser);
// Post a reply to the topic.
$edit = array();
$edit['subject[0][value]'] = $this->randomMachineName();
$edit['comment_body[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
$this->assertResponse(200);
// Test replying to a comment.
$this->clickLink('Reply');
$this->assertResponse(200);
$this->assertFieldByName('comment_body[0][value]');
// Log in as the first user.
$this->drupalLogin($this->adminUser);
// Check that forum renders properly.
$this->drupalGet("forum/{$this->forum['tid']}");
$this->assertResponse(200);
// Verify there is no unintentional HTML tag escaping.
$this->assertNoEscaped('<', '');
}
/**
* Creates a forum topic.
*
* @param array $forum
* A forum array.
* @param bool $container
* TRUE if $forum is a container; FALSE otherwise.
*
* @return object
* The created topic node.
*/
function createForumTopic($forum, $container = FALSE) {
// Generate a random subject/body.
$title = $this->randomMachineName(20);
$body = $this->randomMachineName(200);
$edit = array(
'title[0][value]' => $title,
'body[0][value]' => $body,
);
$tid = $forum['tid'];
// Create the forum topic, preselecting the forum ID via a URL parameter.
$this->drupalPostForm('node/add/forum', $edit, t('Save'), array('query' => array('forum_id' => $tid)));
$type = t('Forum topic');
if ($container) {
$this->assertNoText(t('@type @title has been created.', array('@type' => $type, '@title' => $title)), 'Forum topic was not created');
$this->assertRaw(t('The item %title is a forum container, not a forum.', array('%title' => $forum['name'])), 'Error message was shown');
return;
}
else {
$this->assertText(t('@type @title has been created.', array('@type' => $type, '@title' => $title)), 'Forum topic was created');
$this->assertNoRaw(t('The item %title is a forum container, not a forum.', array('%title' => $forum['name'])), 'No error message was shown');
// Verify that the creation message contains a link to a term.
$view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'term/'));
$this->assert(isset($view_link), 'The message area contains a link to a term');
}
// Retrieve node object, ensure that the topic was created and in the proper forum.
$node = $this->drupalGetNodeByTitle($title);
$this->assertTrue($node != NULL, format_string('Node @title was loaded', array('@title' => $title)));
$this->assertEqual($node->taxonomy_forums->target_id, $tid, 'Saved forum topic was in the expected forum');
// View forum topic.
$this->drupalGet('node/' . $node->id());
$this->assertRaw($title, 'Subject was found');
$this->assertRaw($body, 'Body was found');
return $node;
}
/**
* Verifies that the logged in user has access to a forum node.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* The node being checked.
* @param bool $admin
* Boolean to indicate whether the user can 'access administration pages'.
* @param int $response
* The expected HTTP response code.
*/
private function verifyForums(EntityInterface $node, $admin, $response = 200) {
$response2 = ($admin) ? 200 : 403;
// View forum help node.
$this->drupalGet('admin/help/forum');
$this->assertResponse($response2);
if ($response2 == 200) {
$this->assertTitle(t('Forum | Drupal'), 'Forum help title was displayed');
$this->assertText(t('Forum'), 'Forum help node was displayed');
}
// View forum container page.
$this->verifyForumView($this->forumContainer);
// View forum page.
$this->verifyForumView($this->forum, $this->forumContainer);
// View root forum page.
$this->verifyForumView($this->rootForum);
// View forum node.
$this->drupalGet('node/' . $node->id());
$this->assertResponse(200);
$this->assertTitle($node->label() . ' | Drupal', 'Forum node was displayed');
$breadcrumb_build = array(
Link::createFromRoute(t('Home'), '<front>'),
Link::createFromRoute(t('Forums'), 'forum.index'),
Link::createFromRoute($this->forumContainer['name'], 'forum.page', array('taxonomy_term' => $this->forumContainer['tid'])),
Link::createFromRoute($this->forum['name'], 'forum.page', array('taxonomy_term' => $this->forum['tid'])),
);
$breadcrumb = array(
'#theme' => 'breadcrumb',
'#links' => $breadcrumb_build,
);
$this->assertRaw(\Drupal::service('renderer')->renderRoot($breadcrumb), 'Breadcrumbs were displayed');
// View forum edit node.
$this->drupalGet('node/' . $node->id() . '/edit');
$this->assertResponse($response);
if ($response == 200) {
$this->assertTitle('Edit Forum topic ' . $node->label() . ' | Drupal', 'Forum edit node was displayed');
}
if ($response == 200) {
// Edit forum node (including moving it to another forum).
$edit = array();
$edit['title[0][value]'] = 'node/' . $node->id();
$edit['body[0][value]'] = $this->randomMachineName(256);
// Assume the topic is initially associated with $forum.
$edit['taxonomy_forums'] = $this->rootForum['tid'];
$edit['shadow'] = TRUE;
$this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
$this->assertText(t('Forum topic @title has been updated.', array('@title' => $edit['title[0][value]'])), 'Forum node was edited');
// Verify topic was moved to a different forum.
$forum_tid = db_query("SELECT tid FROM {forum} WHERE nid = :nid AND vid = :vid", array(
':nid' => $node->id(),
':vid' => $node->getRevisionId(),
))->fetchField();
$this->assertTrue($forum_tid == $this->rootForum['tid'], 'The forum topic is linked to a different forum');
// Delete forum node.
$this->drupalPostForm('node/' . $node->id() . '/delete', array(), t('Delete'));
$this->assertResponse($response);
$this->assertRaw(t('Forum topic %title has been deleted.', array('%title' => $edit['title[0][value]'])), 'Forum node was deleted');
}
}
/**
* Verifies the display of a forum page.
*
* @param array $forum
* A row from the taxonomy_term_data table in an array.
* @param array $parent
* (optional) An array representing the forum's parent.
*/
private function verifyForumView($forum, $parent = NULL) {
// View forum page.
$this->drupalGet('forum/' . $forum['tid']);
$this->assertResponse(200);
$this->assertTitle($forum['name'] . ' | Drupal');
$breadcrumb_build = array(
Link::createFromRoute(t('Home'), '<front>'),
Link::createFromRoute(t('Forums'), 'forum.index'),
);
if (isset($parent)) {
$breadcrumb_build[] = Link::createFromRoute($parent['name'], 'forum.page', array('taxonomy_term' => $parent['tid']));
}
$breadcrumb = array(
'#theme' => 'breadcrumb',
'#links' => $breadcrumb_build,
);
$this->assertRaw(\Drupal::service('renderer')->renderRoot($breadcrumb), 'Breadcrumbs were displayed');
}
/**
* Generates forum topics.
*/
private function generateForumTopics() {
$this->nids = array();
for ($i = 0; $i < 5; $i++) {
$node = $this->createForumTopic($this->forum, FALSE);
$this->nids[] = $node->id();
}
}
}

View file

@ -1,150 +0,0 @@
<?php
namespace Drupal\forum\Tests;
use Drupal\comment\CommentInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\NodeType;
use Drupal\simpletest\WebTestBase;
use Drupal\comment\Entity\Comment;
use Drupal\taxonomy\Entity\Term;
/**
* Tests forum module uninstallation.
*
* @group forum
*/
class ForumUninstallTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('forum');
/**
* Tests if forum module uninstallation properly deletes the field.
*/
public function testForumUninstallWithField() {
$this->drupalLogin($this->drupalCreateUser(['administer taxonomy', 'administer nodes', 'administer modules', 'delete any forum content', 'administer content types']));
// Ensure that the field exists before uninstallation.
$field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums');
$this->assertNotNull($field_storage, 'The taxonomy_forums field storage exists.');
// Create a taxonomy term.
$term = Term::create([
'name' => t('A term'),
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'description' => '',
'parent' => array(0),
'vid' => 'forums',
'forum_container' => 0,
]);
$term->save();
// Create a forum node.
$node = $this->drupalCreateNode(array(
'title' => 'A forum post',
'type' => 'forum',
'taxonomy_forums' => array(array('target_id' => $term->id())),
));
// Create at least one comment against the forum node.
$comment = Comment::create(array(
'entity_id' => $node->nid->value,
'entity_type' => 'node',
'field_name' => 'comment_forum',
'pid' => 0,
'uid' => 0,
'status' => CommentInterface::PUBLISHED,
'subject' => $this->randomMachineName(),
'hostname' => '127.0.0.1',
));
$comment->save();
// Attempt to uninstall forum.
$this->drupalGet('admin/modules/uninstall');
// Assert forum is required.
$this->assertNoFieldByName('uninstall[forum]');
$this->assertText('To uninstall Forum, first delete all Forum content');
// Delete the node.
$this->drupalPostForm('node/' . $node->id() . '/delete', array(), t('Delete'));
// Attempt to uninstall forum.
$this->drupalGet('admin/modules/uninstall');
// Assert forum is still required.
$this->assertNoFieldByName('uninstall[forum]');
$this->assertText('To uninstall Forum, first delete all Forums terms');
// Delete any forum terms.
$vid = $this->config('forum.settings')->get('vocabulary');
$terms = entity_load_multiple_by_properties('taxonomy_term', ['vid' => $vid]);
foreach ($terms as $term) {
$term->delete();
}
// Ensure that the forum node type can not be deleted.
$this->drupalGet('admin/structure/types/manage/forum');
$this->assertNoLink(t('Delete'));
// Now attempt to uninstall forum.
$this->drupalGet('admin/modules/uninstall');
// Assert forum is no longer required.
$this->assertFieldByName('uninstall[forum]');
$this->drupalPostForm('admin/modules/uninstall', array(
'uninstall[forum]' => 1,
), t('Uninstall'));
$this->drupalPostForm(NULL, [], t('Uninstall'));
// Check that the field is now deleted.
$field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums');
$this->assertNull($field_storage, 'The taxonomy_forums field storage has been deleted.');
// Check that a node type with a machine name of forum can be created after
// uninstalling the forum module and the node type is not locked.
$edit = array(
'name' => 'Forum',
'title_label' => 'title for forum',
'type' => 'forum',
);
$this->drupalPostForm('admin/structure/types/add', $edit, t('Save content type'));
$this->assertTrue((bool) NodeType::load('forum'), 'Node type with machine forum created.');
$this->drupalGet('admin/structure/types/manage/forum');
$this->clickLink(t('Delete'));
$this->drupalPostForm(NULL, array(), t('Delete'));
$this->assertResponse(200);
$this->assertFalse((bool) NodeType::load('forum'), 'Node type with machine forum deleted.');
// Double check everything by reinstalling the forum module again.
$this->drupalPostForm('admin/modules', ['modules[Core][forum][enable]' => 1], 'Install');
$this->assertText('Module Forum has been enabled.');
}
/**
* Tests uninstallation if the field storage has been deleted beforehand.
*/
public function testForumUninstallWithoutFieldStorage() {
// Manually delete the taxonomy_forums field before module uninstallation.
$field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums');
$this->assertNotNull($field_storage, 'The taxonomy_forums field storage exists.');
$field_storage->delete();
// Check that the field is now deleted.
$field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums');
$this->assertNull($field_storage, 'The taxonomy_forums field storage has been deleted.');
// Delete all terms in the Forums vocabulary. Uninstalling the forum module
// will fail unless this is done.
$terms = entity_load_multiple_by_properties('taxonomy_term', array('vid' => 'forums'));
foreach ($terms as $term) {
$term->delete();
}
// Ensure that uninstallation succeeds even if the field has already been
// deleted manually beforehand.
$this->container->get('module_installer')->uninstall(array('forum'));
}
}

View file

@ -2,6 +2,7 @@
namespace Drupal\forum\Tests\Views;
use Drupal\node\NodeInterface;
use Drupal\views\Views;
use Drupal\views\Tests\ViewTestBase;
use Drupal\views\Tests\ViewTestData;
@ -18,19 +19,19 @@ class ForumIntegrationTest extends ViewTestBase {
*
* @var array
*/
public static $modules = array('forum_test_views');
public static $modules = ['forum_test_views'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_forum_index');
public static $testViews = ['test_forum_index'];
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('forum_test_views'));
ViewTestData::createTestViews(get_class($this), ['forum_test_views']);
}
@ -40,25 +41,25 @@ class ForumIntegrationTest extends ViewTestBase {
public function testForumIntegration() {
// Create a forum.
$entity_manager = $this->container->get('entity.manager');
$term = $entity_manager->getStorage('taxonomy_term')->create(array('vid' => 'forums', 'name' => $this->randomMachineName()));
$term = $entity_manager->getStorage('taxonomy_term')->create(['vid' => 'forums', 'name' => $this->randomMachineName()]);
$term->save();
$comment_storage = $entity_manager->getStorage('comment');
// Create some nodes which are part of this forum with some comments.
$nodes = array();
$nodes = [];
for ($i = 0; $i < 3; $i++) {
$node = $this->drupalCreateNode(array('type' => 'forum', 'taxonomy_forums' => array($term->id()), 'sticky' => $i == 0 ? NODE_STICKY : NODE_NOT_STICKY));
$node = $this->drupalCreateNode(['type' => 'forum', 'taxonomy_forums' => [$term->id()], 'sticky' => $i == 0 ? NodeInterface::STICKY : NodeInterface::NOT_STICKY]);
$nodes[] = $node;
}
$account = $this->drupalCreateUser(array('skip comment approval'));
$account = $this->drupalCreateUser(['skip comment approval']);
$this->drupalLogin($account);
$comments = array();
$comments = [];
foreach ($nodes as $index => $node) {
for ($i = 0; $i <= $index; $i++) {
$comment = $comment_storage->create(array('entity_type' => 'node', 'entity_id' => $node->id(), 'field_name' => 'comment_forum'));
$comment = $comment_storage->create(['entity_type' => 'node', 'entity_id' => $node->id(), 'field_name' => 'comment_forum']);
$comment->save();
$comments[$comment->get('entity_id')->target_id][$comment->id()] = $comment;
}
@ -67,27 +68,27 @@ class ForumIntegrationTest extends ViewTestBase {
$view = Views::getView('test_forum_index');
$this->executeView($view);
$expected_result = array();
$expected_result[] = array(
$expected_result = [];
$expected_result[] = [
'nid' => $nodes[0]->id(),
'sticky' => NODE_STICKY,
'sticky' => NodeInterface::STICKY,
'comment_count' => 1.
);
$expected_result[] = array(
];
$expected_result[] = [
'nid' => $nodes[1]->id(),
'sticky' => NODE_NOT_STICKY,
'sticky' => NodeInterface::NOT_STICKY,
'comment_count' => 2.
);
$expected_result[] = array(
];
$expected_result[] = [
'nid' => $nodes[2]->id(),
'sticky' => NODE_NOT_STICKY,
'sticky' => NodeInterface::NOT_STICKY,
'comment_count' => 3.
);
$column_map = array(
];
$column_map = [
'nid' => 'nid',
'forum_index_sticky' => 'sticky',
'forum_index_comment_count' => 'comment_count',
);
];
$this->assertIdenticalResultset($view, $expected_result, $column_map);
}