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

@ -31,16 +31,16 @@ use Drupal\Core\Url;
* @see \Drupal\comment\CommentViewBuilder::buildLinks()
*/
function hook_comment_links_alter(array &$links, CommentInterface $entity, array &$context) {
$links['mymodule'] = array(
$links['mymodule'] = [
'#theme' => 'links__comment__mymodule',
'#attributes' => array('class' => array('links', 'inline')),
'#links' => array(
'comment-report' => array(
'#attributes' => ['class' => ['links', 'inline']],
'#links' => [
'comment-report' => [
'title' => t('Report'),
'url' => Url::fromRoute('comment_test.report', ['comment' => $entity->id()], ['query' => ['token' => \Drupal::getContainer()->get('csrf_token')->get("comment/{$entity->id()}/report")]]),
),
),
);
],
],
];
}
/**

View file

@ -15,7 +15,7 @@ use Drupal\field\Entity\FieldStorageConfig;
*/
function comment_uninstall() {
// Remove the comment fields.
$fields = entity_load_multiple_by_properties('field_storage_config', array('type' => 'comment'));
$fields = entity_load_multiple_by_properties('field_storage_config', ['type' => 'comment']);
foreach ($fields as $field) {
$field->delete();
}
@ -37,87 +37,82 @@ function comment_install() {
* Implements hook_schema().
*/
function comment_schema() {
$schema['comment_entity_statistics'] = array(
$schema['comment_entity_statistics'] = [
'description' => 'Maintains statistics of entity and comments posts to show "new" and "updated" flags.',
'fields' => array(
'entity_id' => array(
'fields' => [
'entity_id' => [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'The entity_id of the entity for which the statistics are compiled.',
),
'entity_type' => array(
],
'entity_type' => [
'type' => 'varchar_ascii',
'not null' => TRUE,
'default' => 'node',
'length' => EntityTypeInterface::ID_MAX_LENGTH,
'description' => 'The entity_type of the entity to which this comment is a reply.',
),
'field_name' => array(
],
'field_name' => [
'type' => 'varchar_ascii',
'not null' => TRUE,
'default' => '',
'length' => FieldStorageConfig::NAME_MAX_LENGTH,
'description' => 'The field_name of the field that was used to add this comment.',
),
'cid' => array(
],
'cid' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The {comment}.cid of the last comment.',
),
'last_comment_timestamp' => array(
],
'last_comment_timestamp' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The Unix timestamp of the last comment that was posted within this node, from {comment}.changed.',
),
'last_comment_name' => array(
],
'last_comment_name' => [
'type' => 'varchar',
'length' => 60,
'not null' => FALSE,
'description' => 'The name of the latest author to post a comment on this node, from {comment}.name.',
),
'last_comment_uid' => array(
],
'last_comment_uid' => [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'The user ID of the latest author to post a comment on this node, from {comment}.uid.',
),
'comment_count' => array(
],
'comment_count' => [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'The total number of comments on this entity.',
),
),
'primary key' => array('entity_id', 'entity_type', 'field_name'),
'indexes' => array(
'last_comment_timestamp' => array('last_comment_timestamp'),
'comment_count' => array('comment_count'),
'last_comment_uid' => array('last_comment_uid'),
),
'foreign keys' => array(
'last_comment_author' => array(
],
],
'primary key' => ['entity_id', 'entity_type', 'field_name'],
'indexes' => [
'last_comment_timestamp' => ['last_comment_timestamp'],
'comment_count' => ['comment_count'],
'last_comment_uid' => ['last_comment_uid'],
],
'foreign keys' => [
'last_comment_author' => [
'table' => 'users',
'columns' => array(
'columns' => [
'last_comment_uid' => 'uid',
),
),
),
);
],
],
],
];
return $schema;
}
/**
* @addtogroup updates-8.0.0-rc
* @{
*/
/**
* Clear caches to fix Comment entity list builder and operations Views field.
*/
@ -126,10 +121,6 @@ function comment_update_8001() {
// information, so that comment operation links work.
}
/**
* @} End of "addtogroup updates-8.0.0-rc".
*/
/**
* Clear caches to fix Comment Views context filter.
*/
@ -137,11 +128,6 @@ function comment_update_8002() {
// Empty update to cause a cache flush.
}
/**
* @addtogroup updates-8.2.x
* @{
*/
/**
* Add the 'view_mode' setting to displays having 'comment_default' formatter.
*/
@ -177,5 +163,24 @@ function comment_update_8200() {
}
/**
* @} End of "addtogroup updates-8.2.x".
* Update status field.
*/
function comment_update_8300() {
$entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');
$field_definition = $entity_definition_update_manager->getFieldStorageDefinition('status', 'comment');
$field_definition->setDescription(new TranslatableMarkup('A boolean indicating the published state.'))
->setRevisionable(TRUE);
$entity_definition_update_manager->updateFieldStorageDefinition($field_definition);
}
/**
* Set the 'published' entity key.
*/
function comment_update_8301() {
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = $definition_update_manager->getEntityType('comment');
$keys = $entity_type->getKeys();
$keys['published'] = 'status';
$entity_type->set('entity_keys', $keys);
$definition_update_manager->updateEntityType($entity_type);
}

View file

@ -28,16 +28,25 @@ use Drupal\user\RoleInterface;
/**
* Anonymous posters cannot enter their contact information.
*
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
* Use \Drupal\comment\CommentInterface::ANONYMOUS_MAYNOT_CONTACT instead.
*/
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
/**
* Anonymous posters may leave their contact information.
*
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
* Use \Drupal\comment\CommentInterface::ANONYMOUS_MAY_CONTACT instead.
*/
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
/**
* Anonymous posters are required to leave their contact information.
*
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
* Use \Drupal\comment\CommentInterface::ANONYMOUS_MUST_CONTACT instead.
*/
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
@ -59,19 +68,19 @@ function comment_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.comment':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the <a href=":comment">online documentation for the Comment module</a>.', array(':comment' => 'https://www.drupal.org/documentation/modules/comment')) . '</p>';
$output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the <a href=":comment">online documentation for the Comment module</a>.', [':comment' => 'https://www.drupal.org/documentation/modules/comment']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Enabling commenting') . '</dt>';
$output .= '<dd>' . t('Comment functionality can be enabled for any entity sub-type (for example, a <a href=":content-type">content type</a>) by adding a <em>Comments</em> field on its <em>Manage fields page</em>. Adding or removing commenting for an entity through the user interface requires the <a href=":field_ui">Field UI</a> module to be enabled, even though the commenting functionality works without it. For more information on fields and entities, see the <a href=":field">Field module help page</a>.', array(':content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', ':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>';
$output .= '<dd>' . t('Comment functionality can be enabled for any entity sub-type (for example, a <a href=":content-type">content type</a>) by adding a <em>Comments</em> field on its <em>Manage fields page</em>. Adding or removing commenting for an entity through the user interface requires the <a href=":field_ui">Field UI</a> module to be enabled, even though the commenting functionality works without it. For more information on fields and entities, see the <a href=":field">Field module help page</a>.', [':content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', ':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '</dd>';
$output .= '<dt>' . t('Configuring commenting settings') . '</dt>';
$output .= '<dd>' . t('Commenting settings can be configured by editing the <em>Comments</em> field on the <em>Manage fields page</em> of an entity type if the <em>Field UI module</em> is enabled. Configuration includes the label of the comments field, the number of comments to be displayed, and whether they are shown in threaded list. Commenting can be be configured as: <em>Open</em> to allow new comments, <em>Closed</em> to view existing comments, but prevent new comments, or <em>Hidden</em> to hide existing comments and prevent new comments. Changing this configuration for an entity type will not change existing entity items.') . '</dd>';
$output .= '<dt>' . t('Overriding default settings') . '</dt>';
$output .= '<dd>' . t('Users with the appropriate permissions can override the default commenting settings of an entity type when they create an item of that type.') . '</dd>';
$output .= '<dt>' . t('Adding comment types') . '</dt>';
$output .= '<dd>' . t('Additional <em>comment types</em> can be created per entity sub-type and added on the <a href=":field">Comment types page</a>. If there are multiple comment types available you can select the appropriate one after adding a <em>Comments field</em>.', array(':field' => \Drupal::url('entity.comment_type.collection'))) . '</dd>';
$output .= '<dd>' . t('Additional <em>comment types</em> can be created per entity sub-type and added on the <a href=":field">Comment types page</a>. If there are multiple comment types available you can select the appropriate one after adding a <em>Comments field</em>.', [':field' => \Drupal::url('entity.comment_type.collection')]) . '</dd>';
$output .= '<dt>' . t('Approving and managing comments') . '</dt>';
$output .= '<dd>' . t('Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href=":comment-approval">Unapproved comments</a> queue, until a user who has permission to <em>Administer comments and comment settings</em> publishes or deletes them. Published comments can be bulk managed on the <a href=":admin-comment">Published comments</a> administration page. When a comment has no replies, it remains editable by its author, as long as the author has <em>Edit own comments</em> permission.', array(':comment-approval' => \Drupal::url('comment.admin_approval'), ':admin-comment' => \Drupal::url('comment.admin'))) . '</dd>';
$output .= '<dd>' . t('Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href=":comment-approval">Unapproved comments</a> queue, until a user who has permission to <em>Administer comments and comment settings</em> publishes or deletes them. Published comments can be bulk managed on the <a href=":admin-comment">Published comments</a> administration page. When a comment has no replies, it remains editable by its author, as long as the author has <em>Edit own comments</em> permission.', [':comment-approval' => \Drupal::url('comment.admin_approval'), ':admin-comment' => \Drupal::url('comment.admin')]) . '</dd>';
$output .= '</dl>';
return $output;
@ -87,10 +96,10 @@ function comment_help($route_name, RouteMatchInterface $route_match) {
function comment_uri(CommentInterface $comment) {
return new Url(
'entity.comment.canonical',
array(
[
'comment' => $comment->id(),
),
array('fragment' => 'comment-' . $comment->id())
],
['fragment' => 'comment-' . $comment->id()]
);
}
@ -98,23 +107,23 @@ function comment_uri(CommentInterface $comment) {
* Implements hook_entity_extra_field_info().
*/
function comment_entity_extra_field_info() {
$return = array();
$return = [];
foreach (CommentType::loadMultiple() as $comment_type) {
$return['comment'][$comment_type->id()] = array(
'form' => array(
'author' => array(
$return['comment'][$comment_type->id()] = [
'form' => [
'author' => [
'label' => t('Author'),
'description' => t('Author textfield'),
'weight' => -2,
),
),
);
$return['comment'][$comment_type->id()]['display']['links'] = array(
],
],
];
$return['comment'][$comment_type->id()]['display']['links'] = [
'label' => t('Links'),
'description' => t('Comment operation links'),
'weight' => 100,
'visible' => TRUE,
);
];
}
return $return;
@ -124,14 +133,14 @@ function comment_entity_extra_field_info() {
* Implements hook_theme().
*/
function comment_theme() {
return array(
'comment' => array(
return [
'comment' => [
'render element' => 'elements',
),
'field__comment' => array(
],
'field__comment' => [
'base hook' => 'field',
),
);
],
];
}
/**
@ -141,15 +150,15 @@ function comment_field_config_create(FieldConfigInterface $field) {
if ($field->getType() == 'comment' && !$field->isSyncing()) {
// Assign default values for the field.
$default_value = $field->getDefaultValueLiteral();
$default_value += array(array());
$default_value[0] += array(
$default_value += [[]];
$default_value[0] += [
'status' => CommentItemInterface::OPEN,
'cid' => 0,
'last_comment_timestamp' => 0,
'last_comment_name' => '',
'last_comment_uid' => 0,
'comment_count' => 0,
);
];
$field->setDefaultValue($default_value);
}
}
@ -218,14 +227,14 @@ function comment_entity_view(array &$build, EntityInterface $entity, EntityViewD
if ($entity->hasField($field_name) && $entity->get($field_name)->status != CommentItemInterface::HIDDEN) {
// Add a comments RSS element which is a URL to the comments of this
// entity.
$options = array(
$options = [
'fragment' => 'comments',
'absolute' => TRUE,
);
$entity->rss_elements[] = array(
];
$entity->rss_elements[] = [
'key' => 'comments',
'value' => $entity->url('canonical', $options),
);
];
}
}
}
@ -341,7 +350,7 @@ function comment_form_field_storage_config_edit_form_alter(&$form, FormStateInte
*/
function comment_entity_storage_load($entities, $entity_type) {
// Comments can only be attached to content entities, so skip others.
if (!\Drupal::entityManager()->getDefinition($entity_type)->isSubclassOf('Drupal\Core\Entity\FieldableEntityInterface')) {
if (!\Drupal::entityManager()->getDefinition($entity_type)->entityClassImplements(FieldableEntityInterface::class)) {
return;
}
// @todo Investigate in https://www.drupal.org/node/2527866 why we need that.
@ -448,7 +457,7 @@ function comment_node_update_index(EntityInterface $node) {
}
}
$build = array();
$build = [];
if ($index_comments) {
foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
@ -508,7 +517,7 @@ function comment_node_search_result(EntityInterface $node) {
// Do not make a string if there are no comment fields, or no comments exist
// or all comment fields are hidden.
if ($comments > 0 || $open) {
return array('comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments'));
return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')];
}
}
@ -518,7 +527,7 @@ function comment_node_search_result(EntityInterface $node) {
function comment_user_cancel($edit, $account, $method) {
switch ($method) {
case 'user_cancel_block_unpublish':
$comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id()));
$comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
foreach ($comments as $comment) {
$comment->setPublished(CommentInterface::NOT_PUBLISHED);
$comment->save();
@ -527,7 +536,7 @@ function comment_user_cancel($edit, $account, $method) {
case 'user_cancel_reassign':
/** @var \Drupal\comment\CommentInterface[] $comments */
$comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id()));
$comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
foreach ($comments as $comment) {
$comment->setOwnerId(0);
$comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
@ -559,7 +568,7 @@ function comment_user_predelete($account) {
* An array as expected by drupal_render().
*/
function comment_preview(CommentInterface $comment, FormStateInterface $form_state) {
$preview_build = array();
$preview_build = [];
$entity = $comment->getCommentedEntity();
if (!$form_state->getErrors()) {
@ -571,7 +580,7 @@ function comment_preview(CommentInterface $comment, FormStateInterface $form_sta
}
if ($comment->hasParentComment()) {
$build = array();
$build = [];
$parent = $comment->getParentComment();
if ($parent && $parent->isPublished()) {
$build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent);
@ -627,10 +636,10 @@ function template_preprocess_comment(&$variables) {
$variables['threaded'] = $variables['elements']['#comment_threaded'];
$account = $comment->getOwner();
$username = array(
$username = [
'#theme' => 'username',
'#account' => $account,
);
];
$variables['author'] = drupal_render($username);
$variables['author_id'] = $comment->getOwnerId();
$variables['new_indicator_timestamp'] = $comment->getChangedTime();
@ -649,7 +658,7 @@ function template_preprocess_comment(&$variables) {
$variables['user_picture'] = user_view($account, 'compact');
}
else {
$variables['user_picture'] = array();
$variables['user_picture'] = [];
}
if (isset($comment->in_preview)) {
@ -658,25 +667,25 @@ function template_preprocess_comment(&$variables) {
}
else {
$uri = $comment->permalink();
$attributes = $uri->getOption('attributes') ?: array();
$attributes += array('class' => array('permalink'), 'rel' => 'bookmark');
$attributes = $uri->getOption('attributes') ?: [];
$attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
$uri->setOption('attributes', $attributes);
$variables['title'] = \Drupal::l($comment->getSubject(), $uri);
$variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
}
$variables['submitted'] = t('Submitted by @username on @datetime', array('@username' => $variables['author'], '@datetime' => $variables['created']));
$variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
if ($comment->hasParentComment()) {
// Fetch and store the parent comment information for use in templates.
$comment_parent = $comment->getParentComment();
$account_parent = $comment_parent->getOwner();
$variables['parent_comment'] = $comment_parent;
$username = array(
$username = [
'#theme' => 'username',
'#account' => $account_parent,
);
];
$variables['parent_author'] = drupal_render($username);
$variables['parent_created'] = format_date($comment_parent->getCreatedTime());
// Avoid calling format_date() twice on the same timestamp.
@ -687,13 +696,13 @@ function template_preprocess_comment(&$variables) {
$variables['parent_changed'] = format_date($comment_parent->getChangedTime());
}
$permalink_uri_parent = $comment_parent->permalink();
$attributes = $permalink_uri_parent->getOption('attributes') ?: array();
$attributes += array('class' => array('permalink'), 'rel' => 'bookmark');
$attributes = $permalink_uri_parent->getOption('attributes') ?: [];
$attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
$permalink_uri_parent->setOption('attributes', $attributes);
$variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
$variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
$variables['parent'] = t('In reply to @parent_title by @parent_username',
array('@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']));
['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]);
}
else {
$variables['parent_comment'] = '';

View file

@ -7,7 +7,7 @@ services:
comment.manager:
class: Drupal\comment\CommentManager
arguments: ['@entity.manager', '@entity.query', '@config.factory', '@string_translation', '@url_generator', '@module_handler', '@current_user']
arguments: ['@entity.manager', '@config.factory', '@string_translation', '@url_generator', '@module_handler', '@current_user']
comment.statistics:
class: Drupal\comment\CommentStatistics

View file

@ -15,16 +15,16 @@ use Drupal\Core\Render\BubbleableMetadata;
* Implements hook_token_info().
*/
function comment_token_info() {
$type = array(
$type = [
'name' => t('Comments'),
'description' => t('Tokens for comments posted on the site.'),
'needs-data' => 'comment',
);
];
$tokens = [];
// Provide a integration for each entity type except comment.
foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_id => $entity_type) {
if ($entity_type_id == 'comment' || !$entity_type->isSubclassOf(ContentEntityInterface::class)) {
if ($entity_type_id == 'comment' || !$entity_type->entityClassImplements(ContentEntityInterface::class)) {
continue;
}
@ -45,76 +45,76 @@ function comment_token_info() {
}
// Core comment tokens
$comment['cid'] = array(
$comment['cid'] = [
'name' => t("Comment ID"),
'description' => t("The unique ID of the comment."),
);
$comment['hostname'] = array(
];
$comment['hostname'] = [
'name' => t("IP Address"),
'description' => t("The IP address of the computer the comment was posted from."),
);
$comment['mail'] = array(
];
$comment['mail'] = [
'name' => t("Email address"),
'description' => t("The email address left by the comment author."),
);
$comment['homepage'] = array(
];
$comment['homepage'] = [
'name' => t("Home page"),
'description' => t("The home page URL left by the comment author."),
);
$comment['title'] = array(
];
$comment['title'] = [
'name' => t("Title"),
'description' => t("The title of the comment."),
);
$comment['body'] = array(
];
$comment['body'] = [
'name' => t("Content"),
'description' => t("The formatted content of the comment itself."),
);
$comment['langcode'] = array(
];
$comment['langcode'] = [
'name' => t('Language code'),
'description' => t('The language code of the language the comment is written in.'),
);
$comment['url'] = array(
];
$comment['url'] = [
'name' => t("URL"),
'description' => t("The URL of the comment."),
);
$comment['edit-url'] = array(
];
$comment['edit-url'] = [
'name' => t("Edit URL"),
'description' => t("The URL of the comment's edit page."),
);
];
// Chained tokens for comments
$comment['created'] = array(
$comment['created'] = [
'name' => t("Date created"),
'description' => t("The date the comment was posted."),
'type' => 'date',
);
$comment['changed'] = array(
];
$comment['changed'] = [
'name' => t("Date changed"),
'description' => t("The date the comment was most recently updated."),
'type' => 'date',
);
$comment['parent'] = array(
];
$comment['parent'] = [
'name' => t("Parent"),
'description' => t("The comment's parent, if comment threading is active."),
'type' => 'comment',
);
$comment['entity'] = array(
];
$comment['entity'] = [
'name' => t("Entity"),
'description' => t("The entity the comment was posted to."),
'type' => 'entity',
);
$comment['author'] = array(
];
$comment['author'] = [
'name' => t("Author"),
'description' => t("The author name of the comment."),
'type' => 'user',
);
];
return array(
'types' => array('comment' => $type),
'tokens' => array(
return [
'types' => ['comment' => $type],
'tokens' => [
'comment' => $comment,
) + $tokens,
);
] + $tokens,
];
}
/**
@ -123,7 +123,7 @@ function comment_token_info() {
function comment_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
$url_options = ['absolute' => TRUE];
if (isset($options['langcode'])) {
$url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
$langcode = $options['langcode'];
@ -131,7 +131,7 @@ function comment_tokens($type, $tokens, array $data, array $options, BubbleableM
else {
$langcode = NULL;
}
$replacements = array();
$replacements = [];
if ($type == 'comment' && !empty($data['comment'])) {
/** @var \Drupal\comment\CommentInterface $comment */
@ -230,23 +230,23 @@ function comment_tokens($type, $tokens, array $data, array $options, BubbleableM
// Chained token relationships.
if ($entity_tokens = $token_service->findwithPrefix($tokens, 'entity')) {
$entity = $comment->getCommentedEntity();
$replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, array($comment->getCommentedEntityTypeId() => $entity), $options, $bubbleable_metadata);
$replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, [$comment->getCommentedEntityTypeId() => $entity], $options, $bubbleable_metadata);
}
if ($date_tokens = $token_service->findwithPrefix($tokens, 'created')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getCreatedTime()), $options, $bubbleable_metadata);
$replacements += $token_service->generate('date', $date_tokens, ['date' => $comment->getCreatedTime()], $options, $bubbleable_metadata);
}
if ($date_tokens = $token_service->findwithPrefix($tokens, 'changed')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getChangedTime()), $options, $bubbleable_metadata);
$replacements += $token_service->generate('date', $date_tokens, ['date' => $comment->getChangedTime()], $options, $bubbleable_metadata);
}
if (($parent_tokens = $token_service->findwithPrefix($tokens, 'parent')) && $parent = $comment->getParentComment()) {
$replacements += $token_service->generate('comment', $parent_tokens, array('comment' => $parent), $options, $bubbleable_metadata);
$replacements += $token_service->generate('comment', $parent_tokens, ['comment' => $parent], $options, $bubbleable_metadata);
}
if (($author_tokens = $token_service->findwithPrefix($tokens, 'author')) && $account = $comment->getOwner()) {
$replacements += $token_service->generate('user', $author_tokens, array('user' => $account), $options, $bubbleable_metadata);
$replacements += $token_service->generate('user', $author_tokens, ['user' => $account], $options, $bubbleable_metadata);
}
}
// Replacement tokens for any content entities that have comment field.

View file

@ -5,47 +5,49 @@
* Provide views data for comment.module.
*/
use Drupal\Core\Entity\ContentEntityInterface;
/**
* Implements hook_views_data_alter().
*/
function comment_views_data_alter(&$data) {
// New comments are only supported for node table because it requires the
// history table.
$data['node']['new_comments'] = array(
$data['node']['new_comments'] = [
'title' => t('New comments'),
'help' => t('The number of new comments on the node.'),
'field' => array(
'field' => [
'id' => 'node_new_comments',
'no group by' => TRUE,
),
);
],
];
// Provide a integration for each entity type except comment.
foreach (\Drupal::entityManager()->getDefinitions() as $entity_type_id => $entity_type) {
if ($entity_type_id == 'comment' || !$entity_type->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface') || !$entity_type->getBaseTable()) {
if ($entity_type_id == 'comment' || !$entity_type->entityClassImplements(ContentEntityInterface::class) || !$entity_type->getBaseTable()) {
continue;
}
$fields = \Drupal::service('comment.manager')->getFields($entity_type_id);
$base_table = $entity_type->getDataTable() ?: $entity_type->getBaseTable();
$args = array('@entity_type' => $entity_type_id);
$args = ['@entity_type' => $entity_type_id];
if ($fields) {
$data[$base_table]['comments_link'] = array(
'field' => array(
$data[$base_table]['comments_link'] = [
'field' => [
'title' => t('Add comment link'),
'help' => t('Display the standard add comment link used on regular @entity_type, which will only display if the viewing user has access to add a comment.', $args),
'id' => 'comment_entity_link',
),
);
],
];
// Multilingual properties are stored in data table.
if (!($table = $entity_type->getDataTable())) {
$table = $entity_type->getBaseTable();
}
$data[$table]['uid_touch'] = array(
$data[$table]['uid_touch'] = [
'title' => t('User posted or commented'),
'help' => t('Display nodes only if a user posted the @entity_type or commented on the @entity_type.', $args),
'argument' => array(
'argument' => [
'field' => 'uid',
'name table' => 'users_field_data',
'name field' => 'name',
@ -53,40 +55,40 @@ function comment_views_data_alter(&$data) {
'no group by' => TRUE,
'entity_type' => $entity_type_id,
'entity_id' => $entity_type->getKey('id'),
),
'filter' => array(
],
'filter' => [
'field' => 'uid',
'name table' => 'users_field_data',
'name field' => 'name',
'id' => 'comment_user_uid',
'entity_type' => $entity_type_id,
'entity_id' => $entity_type->getKey('id'),
),
);
],
];
foreach ($fields as $field_name => $field) {
$data[$base_table][$field_name . '_cid'] = array(
'title' => t('Comments of the @entity_type using field: @field_name', $args + array('@field_name' => $field_name)),
$data[$base_table][$field_name . '_cid'] = [
'title' => t('Comments of the @entity_type using field: @field_name', $args + ['@field_name' => $field_name]),
'help' => t('Relate all comments on the @entity_type. This will create 1 duplicate record for every comment. Usually if you need this it is better to create a comment view.', $args),
'relationship' => array(
'relationship' => [
'group' => t('Comment'),
'label' => t('Comments'),
'base' => 'comment_field_data',
'base field' => 'entity_id',
'relationship field' => $entity_type->getKey('id'),
'id' => 'standard',
'extra' => array(
array(
'extra' => [
[
'field' => 'entity_type',
'value' => $entity_type_id,
),
array(
],
[
'field' => 'field_name',
'value' => $field_name,
),
),
),
);
],
],
],
];
}
}
}

View file

@ -48,10 +48,6 @@ display:
type: fields
options:
default_field_elements: true
inline:
subject: subject
changed: changed
separator: ' '
hide_empty: false
relationships:
node:

View file

@ -36,8 +36,13 @@ class CommentAccessControlHandler extends EntityAccessControlHandler {
switch ($operation) {
case 'view':
return AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished())->cachePerPermissions()->addCacheableDependency($entity)
$access_result = AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished())->cachePerPermissions()->addCacheableDependency($entity)
->andIf($entity->getCommentedEntity()->access($operation, $account, TRUE));
if (!$access_result->isAllowed()) {
$access_result->setReason("The 'access comments' permission is required and the comment must be published.");
}
return $access_result;
case 'update':
return AccessResult::allowedIf($account->id() && $account->id() == $entity->getOwnerId() && $entity->isPublished() && $account->hasPermission('edit own comments'))->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
@ -62,23 +67,23 @@ class CommentAccessControlHandler extends EntityAccessControlHandler {
if ($operation == 'edit') {
// Only users with the "administer comments" permission can edit
// administrative fields.
$administrative_fields = array(
$administrative_fields = [
'uid',
'status',
'created',
'date',
);
];
if (in_array($field_definition->getName(), $administrative_fields, TRUE)) {
return AccessResult::allowedIfHasPermission($account, 'administer comments');
}
// No user can change read-only fields.
$read_only_fields = array(
$read_only_fields = [
'hostname',
'changed',
'cid',
'thread',
);
];
// These fields can be edited during comment creation.
$create_only_fields = [
'comment_type',

View file

@ -3,12 +3,14 @@
namespace Drupal\comment;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Session\AccountInterface;
@ -40,7 +42,9 @@ class CommentForm extends ContentEntityForm {
return new static(
$container->get('entity.manager'),
$container->get('current_user'),
$container->get('renderer')
$container->get('renderer'),
$container->get('entity_type.bundle.info'),
$container->get('datetime.time')
);
}
@ -53,9 +57,13 @@ class CommentForm extends ContentEntityForm {
* The current user.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer) {
parent::__construct($entity_manager);
public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
parent::__construct($entity_manager, $entity_type_bundle_info, $time);
$this->currentUser = $current_user;
$this->renderer = $renderer;
}
@ -83,7 +91,7 @@ class CommentForm extends ContentEntityForm {
// Use #comment-form as unique jump target, regardless of entity type.
$form['#id'] = Html::getUniqueId('comment_form');
$form['#theme'] = array('comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form');
$form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'];
$anonymous_contact = $field_definition->getSetting('anonymous');
$is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
@ -96,7 +104,7 @@ class CommentForm extends ContentEntityForm {
// If not replying to a comment, use our dedicated page callback for new
// Comments on entities.
if (!$comment->id() && !$comment->hasParentComment()) {
$form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));
$form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]);
}
$comment_preview = $form_state->get('comment_preview');
@ -104,13 +112,13 @@ class CommentForm extends ContentEntityForm {
$form += $comment_preview;
}
$form['author'] = array();
$form['author'] = [];
// Display author information in a details element for comment moderators.
if ($is_admin) {
$form['author'] += array(
$form['author'] += [
'#type' => 'details',
'#title' => $this->t('Administration'),
);
];
}
// Prepare default values for form elements.
@ -121,9 +129,9 @@ class CommentForm extends ContentEntityForm {
}
$status = $comment->getStatus();
if (empty($comment_preview)) {
$form['#title'] = $this->t('Edit comment %title', array(
$form['#title'] = $this->t('Edit comment %title', [
'%title' => $comment->getSubject(),
));
]);
}
}
else {
@ -154,7 +162,7 @@ class CommentForm extends ContentEntityForm {
// The name field is displayed when an anonymous user is adding a comment or
// when a user with the permission 'administer comments' is editing an
// existing comment from an anonymous user.
$form['author']['name'] = array(
$form['author']['name'] = [
'#type' => 'textfield',
'#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
'#default_value' => $author,
@ -165,20 +173,20 @@ class CommentForm extends ContentEntityForm {
'#attributes' => [
'data-drupal-default-value' => $config->get('anonymous'),
],
);
];
if ($is_admin) {
// When editing a comment only display the name textfield if the uid field
// is empty.
$form['author']['name']['#states'] = [
'visible' => [
':input[name="uid"]' => array('empty' => TRUE),
':input[name="uid"]' => ['empty' => TRUE],
],
];
}
// Add author email and homepage fields depending on the current user.
$form['author']['mail'] = array(
$form['author']['mail'] = [
'#type' => 'email',
'#title' => $this->t('Email'),
'#default_value' => $comment->getAuthorEmail(),
@ -187,36 +195,36 @@ class CommentForm extends ContentEntityForm {
'#size' => 30,
'#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
'#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
);
];
$form['author']['homepage'] = array(
$form['author']['homepage'] = [
'#type' => 'url',
'#title' => $this->t('Homepage'),
'#default_value' => $comment->getHomepage(),
'#maxlength' => 255,
'#size' => 30,
'#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
);
];
// Add administrative comment publishing options.
$form['author']['date'] = array(
$form['author']['date'] = [
'#type' => 'datetime',
'#title' => $this->t('Authored on'),
'#default_value' => $date,
'#size' => 20,
'#access' => $is_admin,
);
];
$form['author']['status'] = array(
$form['author']['status'] = [
'#type' => 'radios',
'#title' => $this->t('Status'),
'#default_value' => $status,
'#options' => array(
'#options' => [
CommentInterface::PUBLISHED => $this->t('Published'),
CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
),
],
'#access' => $is_admin,
);
];
return parent::form($form, $form_state, $comment);
}
@ -242,12 +250,12 @@ class CommentForm extends ContentEntityForm {
// already previewing the submission.
$element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
$element['preview'] = array(
$element['preview'] = [
'#type' => 'submit',
'#value' => $this->t('Preview'),
'#access' => $preview_mode != DRUPAL_DISABLED,
'#submit' => array('::submitForm', '::preview'),
);
'#submit' => ['::submitForm', '::preview'],
];
return $element;
}
@ -350,17 +358,17 @@ class CommentForm extends ContentEntityForm {
$entity = $comment->getCommentedEntity();
$field_name = $comment->getFieldName();
$uri = $entity->urlInfo();
$logger = $this->logger('content');
$logger = $this->logger('comment');
if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
$comment->save();
$form_state->setValue('cid', $comment->id());
// Add a log entry.
$logger->notice('Comment posted: %subject.', array(
$logger->notice('Comment posted: %subject.', [
'%subject' => $comment->getSubject(),
'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id()))
));
]);
// Explain the approval queue if necessary.
if (!$comment->isPublished()) {
@ -371,7 +379,7 @@ class CommentForm extends ContentEntityForm {
else {
drupal_set_message($this->t('Your comment has been posted.'));
}
$query = array();
$query = [];
// Find the current display page for this comment.
$field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
$page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
@ -383,8 +391,8 @@ class CommentForm extends ContentEntityForm {
$uri->setOption('fragment', 'comment-' . $comment->id());
}
else {
$logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject()));
drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject())), 'error');
$logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error');
// Redirect the user to the entity they are commenting on.
}
$form_state->setRedirectUrl($uri);

View file

@ -3,13 +3,14 @@
namespace Drupal\comment;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\user\EntityOwnerInterface;
use Drupal\Core\Entity\EntityChangedInterface;
/**
* Provides an interface defining a comment entity.
*/
interface CommentInterface extends ContentEntityInterface, EntityChangedInterface, EntityOwnerInterface {
interface CommentInterface extends ContentEntityInterface, EntityChangedInterface, EntityOwnerInterface, EntityPublishedInterface {
/**
* Comment is awaiting approval.
@ -21,6 +22,21 @@ interface CommentInterface extends ContentEntityInterface, EntityChangedInterfac
*/
const PUBLISHED = 1;
/**
* Anonymous posters cannot enter their contact information.
*/
const ANONYMOUS_MAYNOT_CONTACT = 0;
/**
* Anonymous posters may leave their contact information.
*/
const ANONYMOUS_MAY_CONTACT = 1;
/**
* Anonymous posters are required to leave their contact information.
*/
const ANONYMOUS_MUST_CONTACT = 2;
/**
* Determines if this comment is a reply to another comment.
*
@ -191,33 +207,17 @@ interface CommentInterface extends ContentEntityInterface, EntityChangedInterfac
*/
public function setCreatedTime($created);
/**
* Checks if the comment is published.
*
* @return bool
* TRUE if the comment is published.
*/
public function isPublished();
/**
* Returns the comment's status.
*
* @return int
* One of CommentInterface::PUBLISHED or CommentInterface::NOT_PUBLISHED
*
* @deprecated in Drupal 8.3.0, will be removed before Drupal 9.0.0. Use
* \Drupal\Core\Entity\EntityPublishedInterface::isPublished() instead.
*/
public function getStatus();
/**
* Sets the published status of the comment entity.
*
* @param bool $status
* Set to TRUE to publish the comment, FALSE to unpublish.
*
* @return \Drupal\comment\CommentInterface
* The class instance that this method is called on.
*/
public function setPublished($status);
/**
* Returns the alphadecimal representation of the comment's place in a thread.
*

View file

@ -99,13 +99,13 @@ class CommentLazyBuilders {
* A renderable array containing the comment form.
*/
public function renderForm($commented_entity_type_id, $commented_entity_id, $field_name, $comment_type_id) {
$values = array(
$values = [
'entity_type' => $commented_entity_type_id,
'entity_id' => $commented_entity_id,
'field_name' => $field_name,
'comment_type' => $comment_type_id,
'pid' => NULL,
);
];
$comment = $this->entityManager->getStorage('comment')->create($values);
return $this->entityFormBuilder->getForm($comment);
}
@ -126,11 +126,11 @@ class CommentLazyBuilders {
* A renderable array representing the comment links.
*/
public function renderLinks($comment_entity_id, $view_mode, $langcode, $is_in_preview) {
$links = array(
$links = [
'#theme' => 'links__comment',
'#pre_render' => array('drupal_pre_render_links'),
'#attributes' => array('class' => array('links', 'inline')),
);
'#pre_render' => ['drupal_pre_render_links'],
'#attributes' => ['class' => ['links', 'inline']],
];
if (!$is_in_preview) {
/** @var \Drupal\comment\CommentInterface $entity */
@ -140,11 +140,11 @@ class CommentLazyBuilders {
$links['comment'] = $this->buildLinks($entity, $commented_entity);
// Allow other modules to alter the comment links.
$hook_context = array(
$hook_context = [
'view_mode' => $view_mode,
'langcode' => $langcode,
'commented_entity' => $commented_entity,
);
];
$this->moduleHandler->alter('comment_links', $links, $entity, $hook_context);
}
return $links;
@ -162,25 +162,25 @@ class CommentLazyBuilders {
* An array that can be processed by drupal_pre_render_links().
*/
protected function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) {
$links = array();
$links = [];
$status = $commented_entity->get($entity->getFieldName())->status;
if ($status == CommentItemInterface::OPEN) {
if ($entity->access('delete')) {
$links['comment-delete'] = array(
$links['comment-delete'] = [
'title' => t('Delete'),
'url' => $entity->urlInfo('delete-form'),
);
];
}
if ($entity->access('update')) {
$links['comment-edit'] = array(
$links['comment-edit'] = [
'title' => t('Edit'),
'url' => $entity->urlInfo('edit-form'),
);
];
}
if ($entity->access('create')) {
$links['comment-reply'] = array(
$links['comment-reply'] = [
'title' => t('Reply'),
'url' => Url::fromRoute('comment.reply', [
'entity_type' => $entity->getCommentedEntityTypeId(),
@ -188,13 +188,13 @@ class CommentLazyBuilders {
'field_name' => $entity->getFieldName(),
'pid' => $entity->id(),
]),
);
];
}
if (!$entity->isPublished() && $entity->access('approve')) {
$links['comment-approve'] = array(
$links['comment-approve'] = [
'title' => t('Approve'),
'url' => Url::fromRoute('comment.approve', ['comment' => $entity->id()]),
);
];
}
if (empty($links) && $this->currentUser->isAnonymous()) {
$links['comment-forbidden']['title'] = $this->commentManager->forbiddenMessage($commented_entity, $entity->getFieldName());
@ -203,18 +203,18 @@ class CommentLazyBuilders {
// Add translations link for translation-enabled comment bundles.
if ($this->moduleHandler->moduleExists('content_translation') && $this->access($entity)->isAllowed()) {
$links['comment-translations'] = array(
$links['comment-translations'] = [
'title' => t('Translate'),
'url' => $entity->urlInfo('drupal:content-translation-overview'),
);
];
}
return array(
return [
'#theme' => 'links__comment__comment',
// The "entity" property is specified to be present, so no need to check.
'#links' => $links,
'#attributes' => array('class' => array('links', 'inline')),
);
'#attributes' => ['class' => ['links', 'inline']],
];
}
/**

View file

@ -75,7 +75,7 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
* {@inheritdoc}
*/
public function buildCommentedEntityLinks(FieldableEntityInterface $entity, array &$context) {
$entity_links = array();
$entity_links = [];
$view_mode = $context['view_mode'];
if ($view_mode == 'search_index' || $view_mode == 'search_result' || $view_mode == 'print' || $view_mode == 'rss') {
// Do not add any links if the entity is displayed for:
@ -83,7 +83,7 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
// - constructing a search result excerpt.
// - print.
// - rss.
return array();
return [];
}
$fields = $this->commentManager->getFields($entity->getEntityTypeId());
@ -92,7 +92,7 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
if (!$entity->hasField($field_name)) {
continue;
}
$links = array();
$links = [];
$commenting_status = $entity->get($field_name)->status;
if ($commenting_status != CommentItemInterface::HIDDEN) {
// Entity has commenting status open or closed.
@ -103,23 +103,23 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
// entity is open to new comments, and there currently are none.
if ($this->currentUser->hasPermission('access comments')) {
if (!empty($entity->get($field_name)->comment_count)) {
$links['comment-comments'] = array(
$links['comment-comments'] = [
'title' => $this->formatPlural($entity->get($field_name)->comment_count, '1 comment', '@count comments'),
'attributes' => array('title' => $this->t('Jump to the first comment.')),
'attributes' => ['title' => $this->t('Jump to the first comment.')],
'fragment' => 'comments',
'url' => $entity->urlInfo(),
);
];
if ($this->moduleHandler->moduleExists('history')) {
$links['comment-new-comments'] = array(
$links['comment-new-comments'] = [
'title' => '',
'url' => Url::fromRoute('<current>'),
'attributes' => array(
'attributes' => [
'class' => 'hidden',
'title' => $this->t('Jump to the first new comment.'),
'data-history-node-last-comment-timestamp' => $entity->get($field_name)->last_comment_timestamp,
'data-history-node-field-name' => $field_name,
),
);
],
];
}
}
}
@ -127,12 +127,12 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
if ($commenting_status == CommentItemInterface::OPEN) {
$comment_form_location = $field_definition->getSetting('form_location');
if ($this->currentUser->hasPermission('post comments')) {
$links['comment-add'] = array(
$links['comment-add'] = [
'title' => $this->t('Add new comment'),
'language' => $entity->language(),
'attributes' => array('title' => $this->t('Share your thoughts and opinions.')),
'attributes' => ['title' => $this->t('Share your thoughts and opinions.')],
'fragment' => 'comment-form',
);
];
if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) {
$links['comment-add']['url'] = Url::fromRoute('comment.reply', [
'entity_type' => $entity->getEntityTypeId(),
@ -145,9 +145,9 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
}
}
elseif ($this->currentUser->isAnonymous()) {
$links['comment-forbidden'] = array(
$links['comment-forbidden'] = [
'title' => $this->commentManager->forbiddenMessage($entity, $field_name),
);
];
}
}
}
@ -161,11 +161,11 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
// Show the "post comment" link if the form is on another page, or
// if there are existing comments that the link will skip past.
if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE || (!empty($entity->get($field_name)->comment_count) && $this->currentUser->hasPermission('access comments'))) {
$links['comment-add'] = array(
$links['comment-add'] = [
'title' => $this->t('Add new comment'),
'attributes' => array('title' => $this->t('Share your thoughts and opinions.')),
'attributes' => ['title' => $this->t('Share your thoughts and opinions.')],
'fragment' => 'comment-form',
);
];
if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) {
$links['comment-add']['url'] = Url::fromRoute('comment.reply', [
'entity_type' => $entity->getEntityTypeId(),
@ -179,20 +179,20 @@ class CommentLinkBuilder implements CommentLinkBuilderInterface {
}
}
elseif ($this->currentUser->isAnonymous()) {
$links['comment-forbidden'] = array(
$links['comment-forbidden'] = [
'title' => $this->commentManager->forbiddenMessage($entity, $field_name),
);
];
}
}
}
}
if (!empty($links)) {
$entity_links['comment__' . $field_name] = array(
$entity_links['comment__' . $field_name] = [
'#theme' => 'links__entity__comment__' . $field_name,
'#links' => $links,
'#attributes' => array('class' => array('links', 'inline')),
);
'#attributes' => ['class' => ['links', 'inline']],
];
if ($view_mode == 'teaser' && $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) {
$entity_links['comment__' . $field_name]['#cache']['contexts'][] = 'user';
$entity_links['comment__' . $field_name]['#attached']['library'][] = 'comment/drupal.node-new-comments-link';

View file

@ -6,7 +6,7 @@ use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Routing\UrlGeneratorTrait;
@ -31,13 +31,6 @@ class CommentManager implements CommentManagerInterface {
*/
protected $entityManager;
/**
* The entity query factory.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $queryFactory;
/**
* Whether the \Drupal\user\RoleInterface::AUTHENTICATED_ID can post comments.
*
@ -71,8 +64,6 @@ class CommentManager implements CommentManagerInterface {
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager service.
* @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
* The entity query factory.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
@ -84,9 +75,8 @@ class CommentManager implements CommentManagerInterface {
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(EntityManagerInterface $entity_manager, QueryFactory $query_factory, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
public function __construct(EntityManagerInterface $entity_manager, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
$this->entityManager = $entity_manager;
$this->queryFactory = $query_factory;
$this->userConfig = $config_factory->get('user.settings');
$this->stringTranslation = $string_translation;
$this->urlGenerator = $url_generator;
@ -99,12 +89,12 @@ class CommentManager implements CommentManagerInterface {
*/
public function getFields($entity_type_id) {
$entity_type = $this->entityManager->getDefinition($entity_type_id);
if (!$entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
return array();
if (!$entity_type->entityClassImplements(FieldableEntityInterface::class)) {
return [];
}
$map = $this->entityManager->getFieldMapByFieldType('comment');
return isset($map[$entity_type_id]) ? $map[$entity_type_id] : array();
return isset($map[$entity_type_id]) ? $map[$entity_type_id] : [];
}
/**
@ -113,28 +103,28 @@ class CommentManager implements CommentManagerInterface {
public function addBodyField($comment_type_id) {
if (!FieldConfig::loadByName('comment', $comment_type_id, 'comment_body')) {
// Attaches the body field by default.
$field = $this->entityManager->getStorage('field_config')->create(array(
$field = $this->entityManager->getStorage('field_config')->create([
'label' => 'Comment',
'bundle' => $comment_type_id,
'required' => TRUE,
'field_storage' => FieldStorageConfig::loadByName('comment', 'comment_body'),
));
]);
$field->save();
// Assign widget settings for the 'default' form mode.
entity_get_form_display('comment', $comment_type_id, 'default')
->setComponent('comment_body', array(
->setComponent('comment_body', [
'type' => 'text_textarea',
))
])
->save();
// Assign display settings for the 'default' view mode.
entity_get_display('comment', $comment_type_id, 'default')
->setComponent('comment_body', array(
->setComponent('comment_body', [
'label' => 'hidden',
'type' => 'text_default',
'weight' => 0,
))
])
->save();
}
}
@ -161,24 +151,24 @@ class CommentManager implements CommentManagerInterface {
'entity' => $entity->id(),
'field_name' => $field_name,
];
$destination = array('destination' => $this->url('comment.reply', $comment_reply_parameters, array('fragment' => 'comment-form')));
$destination = ['destination' => $this->url('comment.reply', $comment_reply_parameters, ['fragment' => 'comment-form'])];
}
else {
$destination = array('destination' => $entity->url('canonical', array('fragment' => 'comment-form')));
$destination = ['destination' => $entity->url('canonical', ['fragment' => 'comment-form'])];
}
if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
// Users can register themselves.
return $this->t('<a href=":login">Log in</a> or <a href=":register">register</a> to post comments', array(
':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)),
':register' => $this->urlGenerator->generateFromRoute('user.register', array(), array('query' => $destination)),
));
return $this->t('<a href=":login">Log in</a> or <a href=":register">register</a> to post comments', [
':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]),
':register' => $this->urlGenerator->generateFromRoute('user.register', [], ['query' => $destination]),
]);
}
else {
// Only admins can add new users, no public registration.
return $this->t('<a href=":login">Log in</a> to post comments', array(
':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)),
));
return $this->t('<a href=":login">Log in</a> to post comments', [
':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]),
]);
}
}
return '';
@ -211,7 +201,7 @@ class CommentManager implements CommentManagerInterface {
$timestamp = ($timestamp > HISTORY_READ_LIMIT ? $timestamp : HISTORY_READ_LIMIT);
// Use the timestamp to retrieve the number of new comments.
$query = $this->queryFactory->get('comment')
$query = $this->entityManager->getStorage('comment')->getQuery()
->condition('entity_type', $entity->getEntityTypeId())
->condition('entity_id', $entity->id())
->condition('created', $timestamp, '>')

View file

@ -65,14 +65,14 @@ class CommentStatistics implements CommentStatisticsInterface {
* {@inheritdoc}
*/
public function read($entities, $entity_type, $accurate = TRUE) {
$options = $accurate ? array() : array('target' => 'replica');
$options = $accurate ? [] : ['target' => 'replica'];
$stats = $this->database->select('comment_entity_statistics', 'ces', $options)
->fields('ces')
->condition('ces.entity_id', array_keys($entities), 'IN')
->condition('ces.entity_type', $entity_type)
->execute();
$statistics_records = array();
$statistics_records = [];
while ($entry = $stats->fetchObject()) {
$statistics_records[] = $entry;
}
@ -94,7 +94,7 @@ class CommentStatistics implements CommentStatisticsInterface {
*/
public function create(FieldableEntityInterface $entity, $fields) {
$query = $this->database->insert('comment_entity_statistics')
->fields(array(
->fields([
'entity_id',
'entity_type',
'field_name',
@ -103,7 +103,7 @@ class CommentStatistics implements CommentStatisticsInterface {
'last_comment_name',
'last_comment_uid',
'comment_count',
));
]);
foreach ($fields as $field_name => $detail) {
// Skip fields that entity does not have.
if (!$entity->hasField($field_name)) {
@ -127,7 +127,7 @@ class CommentStatistics implements CommentStatisticsInterface {
if ($entity instanceof EntityChangedInterface) {
$last_comment_timestamp = $entity->getChangedTimeAcrossTranslations();
}
$query->values(array(
$query->values([
'entity_id' => $entity->id(),
'entity_type' => $entity->getEntityTypeId(),
'field_name' => $field_name,
@ -136,7 +136,7 @@ class CommentStatistics implements CommentStatisticsInterface {
'last_comment_name' => NULL,
'last_comment_uid' => $last_comment_uid,
'comment_count' => 0,
));
]);
}
$query->execute();
}
@ -145,24 +145,24 @@ class CommentStatistics implements CommentStatisticsInterface {
* {@inheritdoc}
*/
public function getMaximumCount($entity_type) {
return $this->database->query('SELECT MAX(comment_count) FROM {comment_entity_statistics} WHERE entity_type = :entity_type', array(':entity_type' => $entity_type))->fetchField();
return $this->database->query('SELECT MAX(comment_count) FROM {comment_entity_statistics} WHERE entity_type = :entity_type', [':entity_type' => $entity_type])->fetchField();
}
/**
* {@inheritdoc}
*/
public function getRankingInfo() {
return array(
'comments' => array(
return [
'comments' => [
'title' => t('Number of comments'),
'join' => array(
'join' => [
'type' => 'LEFT',
'table' => 'comment_entity_statistics',
'alias' => 'ces',
// Default to comment field as this is the most common use case for
// nodes.
'on' => "ces.entity_id = i.sid AND ces.entity_type = 'node' AND ces.field_name = 'comment'",
),
],
// Inverse law that maps the highest view count on the site to 1 and 0
// to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite
// in order to ensure that the :comment_scale argument is treated as
@ -170,9 +170,9 @@ class CommentStatistics implements CommentStatisticsInterface {
// values in as strings instead of numbers in complex expressions like
// this.
'score' => '2.0 - 2.0 / (1.0 + ces.comment_count * (ROUND(:comment_scale, 4)))',
'arguments' => array(':comment_scale' => \Drupal::state()->get('comment.node_comment_statistics_scale') ?: 0),
),
);
'arguments' => [':comment_scale' => \Drupal::state()->get('comment.node_comment_statistics_scale') ?: 0],
],
];
}
/**
@ -198,7 +198,7 @@ class CommentStatistics implements CommentStatisticsInterface {
if ($count > 0) {
// Comments exist.
$last_reply = $this->database->select('comment_field_data', 'c')
->fields('c', array('cid', 'name', 'changed', 'uid'))
->fields('c', ['cid', 'name', 'changed', 'uid'])
->condition('c.entity_id', $comment->getCommentedEntityId())
->condition('c.entity_type', $comment->getCommentedEntityTypeId())
->condition('c.field_name', $comment->getFieldName())
@ -210,18 +210,18 @@ class CommentStatistics implements CommentStatisticsInterface {
->fetchObject();
// Use merge here because entity could be created before comment field.
$this->database->merge('comment_entity_statistics')
->fields(array(
->fields([
'cid' => $last_reply->cid,
'comment_count' => $count,
'last_comment_timestamp' => $last_reply->changed,
'last_comment_name' => $last_reply->uid ? '' : $last_reply->name,
'last_comment_uid' => $last_reply->uid,
))
->keys(array(
])
->keys([
'entity_id' => $comment->getCommentedEntityId(),
'entity_type' => $comment->getCommentedEntityTypeId(),
'field_name' => $comment->getFieldName(),
))
])
->execute();
}
else {
@ -238,7 +238,7 @@ class CommentStatistics implements CommentStatisticsInterface {
$last_comment_uid = $this->currentUser->id();
}
$this->database->update('comment_entity_statistics')
->fields(array(
->fields([
'cid' => 0,
'comment_count' => 0,
// Use the changed date of the entity if it's set, or default to
@ -246,7 +246,7 @@ class CommentStatistics implements CommentStatisticsInterface {
'last_comment_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : REQUEST_TIME,
'last_comment_name' => '',
'last_comment_uid' => $last_comment_uid,
))
])
->condition('entity_id', $comment->getCommentedEntityId())
->condition('entity_type', $comment->getCommentedEntityTypeId())
->condition('field_name', $comment->getFieldName())
@ -255,7 +255,7 @@ class CommentStatistics implements CommentStatisticsInterface {
// Reset the cache of the commented entity so that when the entity is loaded
// the next time, the statistics will be loaded again.
$this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId()));
$this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache([$comment->getCommentedEntityId()]);
}
}

View file

@ -147,7 +147,7 @@ class CommentStorage extends SqlContentEntityStorage implements CommentStorageIn
// 1. Find all the threads with a new comment.
$unread_threads_query = $this->database->select('comment_field_data', 'comment')
->fields('comment', array('thread'))
->fields('comment', ['thread'])
->condition('entity_id', $entity->id())
->condition('entity_type', $entity->getEntityTypeId())
->condition('field_name', $field_name)
@ -161,7 +161,7 @@ class CommentStorage extends SqlContentEntityStorage implements CommentStorageIn
$first_thread_query = $this->database->select($unread_threads_query, 'thread');
$first_thread_query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'torder');
$first_thread = $first_thread_query
->fields('thread', array('thread'))
->fields('thread', ['thread'])
->orderBy('torder')
->range(0, 1)
->execute()
@ -176,13 +176,13 @@ class CommentStorage extends SqlContentEntityStorage implements CommentStorageIn
AND field_name = :field_name
AND status = :status
AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread
AND default_langcode = 1', array(
AND default_langcode = 1', [
':status' => CommentInterface::PUBLISHED,
':entity_id' => $entity->id(),
':field_name' => $field_name,
':entity_type' => $entity->getEntityTypeId(),
':thread' => $first_thread,
))->fetchField();
])->fetchField();
}
return $comments_per_page > 0 ? (int) ($count / $comments_per_page) : 0;
@ -193,7 +193,7 @@ class CommentStorage extends SqlContentEntityStorage implements CommentStorageIn
*/
public function getChildCids(array $comments) {
return $this->database->select('comment_field_data', 'c')
->fields('c', array('cid'))
->fields('c', ['cid'])
->condition('pid', array_keys($comments), 'IN')
->condition('default_langcode', 1)
->execute()
@ -312,7 +312,7 @@ class CommentStorage extends SqlContentEntityStorage implements CommentStorageIn
$cids = $query->execute()->fetchCol();
$comments = array();
$comments = [];
if ($cids) {
$comments = $this->loadMultiple($cids);
}

View file

@ -17,9 +17,9 @@ class CommentStorageSchema extends SqlContentEntityStorageSchema {
protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
$schema = parent::getEntitySchema($entity_type, $reset);
$schema['comment_field_data']['indexes'] += array(
'comment__status_pid' => array('pid', 'status'),
'comment__num_new' => array(
$schema['comment_field_data']['indexes'] += [
'comment__status_pid' => ['pid', 'status'],
'comment__num_new' => [
'entity_id',
'entity_type',
'comment_type',
@ -27,14 +27,14 @@ class CommentStorageSchema extends SqlContentEntityStorageSchema {
'created',
'cid',
'thread',
),
'comment__entity_langcode' => array(
],
'comment__entity_langcode' => [
'entity_id',
'entity_type',
'comment_type',
'default_langcode',
),
);
],
];
return $schema;
}

View file

@ -30,7 +30,7 @@ class CommentTranslationHandler extends ContentTranslationHandler {
* {@inheritdoc}
*/
protected function entityFormTitle(EntityInterface $entity) {
return t('Edit comment @subject', array('@subject' => $entity->label()));
return t('Edit comment @subject', ['@subject' => $entity->label()]);
}
/**

View file

@ -71,32 +71,32 @@ class CommentTypeForm extends EntityForm {
$comment_type = $this->entity;
$form['label'] = array(
$form['label'] = [
'#type' => 'textfield',
'#title' => t('Label'),
'#maxlength' => 255,
'#default_value' => $comment_type->label(),
'#required' => TRUE,
);
$form['id'] = array(
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $comment_type->id(),
'#machine_name' => array(
'#machine_name' => [
'exists' => '\Drupal\comment\Entity\CommentType::load',
),
],
'#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
'#disabled' => !$comment_type->isNew(),
);
];
$form['description'] = array(
$form['description'] = [
'#type' => 'textarea',
'#default_value' => $comment_type->getDescription(),
'#description' => t('Describe this comment type. The text will be displayed on the <em>Comment types</em> administration overview page.'),
'#title' => t('Description'),
);
];
if ($comment_type->isNew()) {
$options = array();
$options = [];
foreach ($this->entityManager->getDefinitions() as $entity_type) {
// Only expose entities that have field UI enabled, only those can
// get comment fields added in the UI.
@ -104,47 +104,47 @@ class CommentTypeForm extends EntityForm {
$options[$entity_type->id()] = $entity_type->getLabel();
}
}
$form['target_entity_type_id'] = array(
$form['target_entity_type_id'] = [
'#type' => 'select',
'#default_value' => $comment_type->getTargetEntityTypeId(),
'#title' => t('Target entity type'),
'#options' => $options,
'#description' => t('The target entity type can not be changed after the comment type has been created.')
);
];
}
else {
$form['target_entity_type_id_display'] = array(
$form['target_entity_type_id_display'] = [
'#type' => 'item',
'#markup' => $this->entityManager->getDefinition($comment_type->getTargetEntityTypeId())->getLabel(),
'#title' => t('Target entity type'),
);
];
}
if ($this->moduleHandler->moduleExists('content_translation')) {
$form['language'] = array(
$form['language'] = [
'#type' => 'details',
'#title' => t('Language settings'),
'#group' => 'additional_settings',
);
];
$language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('comment', $comment_type->id());
$form['language']['language_configuration'] = array(
$form['language']['language_configuration'] = [
'#type' => 'language_configuration',
'#entity_information' => array(
'#entity_information' => [
'entity_type' => 'comment',
'bundle' => $comment_type->id(),
),
],
'#default_value' => $language_configuration,
);
];
$form['#submit'][] = 'language_configuration_element_submit';
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => t('Save'),
);
];
return $form;
}
@ -158,13 +158,13 @@ class CommentTypeForm extends EntityForm {
$edit_link = $this->entity->link($this->t('Edit'));
if ($status == SAVED_UPDATED) {
drupal_set_message(t('Comment type %label has been updated.', array('%label' => $comment_type->label())));
$this->logger->notice('Comment type %label has been updated.', array('%label' => $comment_type->label(), 'link' => $edit_link));
drupal_set_message(t('Comment type %label has been updated.', ['%label' => $comment_type->label()]));
$this->logger->notice('Comment type %label has been updated.', ['%label' => $comment_type->label(), 'link' => $edit_link]);
}
else {
$this->commentManager->addBodyField($comment_type->id());
drupal_set_message(t('Comment type %label has been added.', array('%label' => $comment_type->label())));
$this->logger->notice('Comment type %label has been added.', array('%label' => $comment_type->label(), 'link' => $edit_link));
drupal_set_message(t('Comment type %label has been added.', ['%label' => $comment_type->label()]));
$this->logger->notice('Comment type %label has been added.', ['%label' => $comment_type->label(), 'link' => $edit_link]);
}
$form_state->setRedirectUrl($comment_type->urlInfo('collection'));

View file

@ -88,7 +88,7 @@ class CommentViewBuilder extends EntityViewBuilder {
}
// Pre-load associated users into cache to leverage multiple loading.
$uids = array();
$uids = [];
foreach ($entities as $entity) {
$uids[] = $entity->getOwnerId();
}
@ -125,7 +125,7 @@ class CommentViewBuilder extends EntityViewBuilder {
$display = $displays[$entity->bundle()];
if ($display->getComponent('links')) {
$build[$id]['links'] = array(
$build[$id]['links'] = [
'#lazy_builder' => ['comment.lazy_builders:renderLinks', [
$entity->id(),
$view_mode,
@ -133,11 +133,11 @@ class CommentViewBuilder extends EntityViewBuilder {
!empty($entity->in_preview),
]],
'#create_placeholder' => TRUE,
);
];
}
if (!isset($build[$id]['#attached'])) {
$build[$id]['#attached'] = array();
$build[$id]['#attached'] = [];
}
$build[$id]['#attached']['library'][] = 'comment/drupal.comment-by-viewer';
if ($this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) {

View file

@ -2,6 +2,7 @@
namespace Drupal\comment;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\views\EntityViewsData;
/**
@ -35,148 +36,148 @@ class CommentViewsData extends EntityViewsData {
$data['comment_field_data']['created']['title'] = $this->t('Post date');
$data['comment_field_data']['created']['help'] = $this->t('Date and time of when the comment was created.');
$data['comment_field_data']['created_fulldata'] = array(
$data['comment_field_data']['created_fulldata'] = [
'title' => $this->t('Created date'),
'help' => $this->t('Date in the form of CCYYMMDD.'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_fulldate',
),
);
],
];
$data['comment_field_data']['created_year_month'] = array(
$data['comment_field_data']['created_year_month'] = [
'title' => $this->t('Created year + month'),
'help' => $this->t('Date in the form of YYYYMM.'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_year_month',
),
);
],
];
$data['comment_field_data']['created_year'] = array(
$data['comment_field_data']['created_year'] = [
'title' => $this->t('Created year'),
'help' => $this->t('Date in the form of YYYY.'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_year',
),
);
],
];
$data['comment_field_data']['created_month'] = array(
$data['comment_field_data']['created_month'] = [
'title' => $this->t('Created month'),
'help' => $this->t('Date in the form of MM (01 - 12).'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_month',
),
);
],
];
$data['comment_field_data']['created_day'] = array(
$data['comment_field_data']['created_day'] = [
'title' => $this->t('Created day'),
'help' => $this->t('Date in the form of DD (01 - 31).'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_day',
),
);
],
];
$data['comment_field_data']['created_week'] = array(
$data['comment_field_data']['created_week'] = [
'title' => $this->t('Created week'),
'help' => $this->t('Date in the form of WW (01 - 53).'),
'argument' => array(
'argument' => [
'field' => 'created',
'id' => 'date_week',
),
);
],
];
$data['comment_field_data']['changed']['title'] = $this->t('Updated date');
$data['comment_field_data']['changed']['help'] = $this->t('Date and time of when the comment was last updated.');
$data['comment_field_data']['changed_fulldata'] = array(
$data['comment_field_data']['changed_fulldata'] = [
'title' => $this->t('Changed date'),
'help' => $this->t('Date in the form of CCYYMMDD.'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_fulldate',
),
);
],
];
$data['comment_field_data']['changed_year_month'] = array(
$data['comment_field_data']['changed_year_month'] = [
'title' => $this->t('Changed year + month'),
'help' => $this->t('Date in the form of YYYYMM.'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_year_month',
),
);
],
];
$data['comment_field_data']['changed_year'] = array(
$data['comment_field_data']['changed_year'] = [
'title' => $this->t('Changed year'),
'help' => $this->t('Date in the form of YYYY.'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_year',
),
);
],
];
$data['comment_field_data']['changed_month'] = array(
$data['comment_field_data']['changed_month'] = [
'title' => $this->t('Changed month'),
'help' => $this->t('Date in the form of MM (01 - 12).'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_month',
),
);
],
];
$data['comment_field_data']['changed_day'] = array(
$data['comment_field_data']['changed_day'] = [
'title' => $this->t('Changed day'),
'help' => $this->t('Date in the form of DD (01 - 31).'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_day',
),
);
],
];
$data['comment_field_data']['changed_week'] = array(
$data['comment_field_data']['changed_week'] = [
'title' => $this->t('Changed week'),
'help' => $this->t('Date in the form of WW (01 - 53).'),
'argument' => array(
'argument' => [
'field' => 'changed',
'id' => 'date_week',
),
);
],
];
$data['comment_field_data']['status']['title'] = $this->t('Approved status');
$data['comment_field_data']['status']['help'] = $this->t('Whether the comment is approved (or still in the moderation queue).');
$data['comment_field_data']['status']['filter']['label'] = $this->t('Approved comment status');
$data['comment_field_data']['status']['filter']['type'] = 'yes-no';
$data['comment']['approve_comment'] = array(
'field' => array(
$data['comment']['approve_comment'] = [
'field' => [
'title' => $this->t('Link to approve comment'),
'help' => $this->t('Provide a simple link to approve the comment.'),
'id' => 'comment_link_approve',
),
);
],
];
$data['comment']['replyto_comment'] = array(
'field' => array(
$data['comment']['replyto_comment'] = [
'field' => [
'title' => $this->t('Link to reply-to comment'),
'help' => $this->t('Provide a simple link to reply to the comment.'),
'id' => 'comment_link_reply',
),
);
],
];
$data['comment_field_data']['thread']['field'] = array(
$data['comment_field_data']['thread']['field'] = [
'title' => $this->t('Depth'),
'help' => $this->t('Display the depth of the comment if it is threaded.'),
'id' => 'comment_depth',
);
$data['comment_field_data']['thread']['sort'] = array(
];
$data['comment_field_data']['thread']['sort'] = [
'title' => $this->t('Thread'),
'help' => $this->t('Sort by the threaded order. This will keep child comments together with their parents.'),
'id' => 'comment_thread',
);
];
unset($data['comment_field_data']['thread']['filter']);
unset($data['comment_field_data']['thread']['argument']);
@ -184,28 +185,28 @@ class CommentViewsData extends EntityViewsData {
// Provide a relationship for each entity type except comment.
foreach ($entities_types as $type => $entity_type) {
if ($type == 'comment' || !$entity_type->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface') || !$entity_type->getBaseTable()) {
if ($type == 'comment' || !$entity_type->entityClassImplements(ContentEntityInterface::class) || !$entity_type->getBaseTable()) {
continue;
}
if ($fields = \Drupal::service('comment.manager')->getFields($type)) {
$data['comment_field_data'][$type] = array(
'relationship' => array(
$data['comment_field_data'][$type] = [
'relationship' => [
'title' => $entity_type->getLabel(),
'help' => $this->t('The @entity_type to which the comment is a reply to.', array('@entity_type' => $entity_type->getLabel())),
'help' => $this->t('The @entity_type to which the comment is a reply to.', ['@entity_type' => $entity_type->getLabel()]),
'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(),
'base field' => $entity_type->getKey('id'),
'relationship field' => 'entity_id',
'id' => 'standard',
'label' => $entity_type->getLabel(),
'extra' => array(
array(
'extra' => [
[
'field' => 'entity_type',
'value' => $type,
'table' => 'comment_field_data'
),
),
),
);
],
],
],
];
}
}
@ -226,7 +227,7 @@ class CommentViewsData extends EntityViewsData {
// Provide a relationship for each entity type except comment.
foreach ($entities_types as $type => $entity_type) {
if ($type == 'comment' || !$entity_type->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface') || !$entity_type->getBaseTable()) {
if ($type == 'comment' || !$entity_type->entityClassImplements(ContentEntityInterface::class) || !$entity_type->getBaseTable()) {
continue;
}
// This relationship does not use the 'field id' column, if the entity has
@ -236,84 +237,84 @@ class CommentViewsData extends EntityViewsData {
// {comment_entity_statistics} for each field as multiple joins between
// the same two tables is not supported.
if (\Drupal::service('comment.manager')->getFields($type)) {
$data['comment_entity_statistics']['table']['join'][$entity_type->getDataTable() ?: $entity_type->getBaseTable()] = array(
$data['comment_entity_statistics']['table']['join'][$entity_type->getDataTable() ?: $entity_type->getBaseTable()] = [
'type' => 'INNER',
'left_field' => $entity_type->getKey('id'),
'field' => 'entity_id',
'extra' => array(
array(
'extra' => [
[
'field' => 'entity_type',
'value' => $type,
),
),
);
],
],
];
}
}
$data['comment_entity_statistics']['last_comment_timestamp'] = array(
$data['comment_entity_statistics']['last_comment_timestamp'] = [
'title' => $this->t('Last comment time'),
'help' => $this->t('Date and time of when the last comment was posted.'),
'field' => array(
'field' => [
'id' => 'comment_last_timestamp',
),
'sort' => array(
],
'sort' => [
'id' => 'date',
),
'filter' => array(
],
'filter' => [
'id' => 'date',
),
);
],
];
$data['comment_entity_statistics']['last_comment_name'] = array(
$data['comment_entity_statistics']['last_comment_name'] = [
'title' => $this->t("Last comment author"),
'help' => $this->t('The name of the author of the last posted comment.'),
'field' => array(
'field' => [
'id' => 'comment_ces_last_comment_name',
'no group by' => TRUE,
),
'sort' => array(
],
'sort' => [
'id' => 'comment_ces_last_comment_name',
'no group by' => TRUE,
),
);
],
];
$data['comment_entity_statistics']['comment_count'] = array(
$data['comment_entity_statistics']['comment_count'] = [
'title' => $this->t('Comment count'),
'help' => $this->t('The number of comments an entity has.'),
'field' => array(
'field' => [
'id' => 'numeric',
),
'filter' => array(
],
'filter' => [
'id' => 'numeric',
),
'sort' => array(
],
'sort' => [
'id' => 'standard',
),
'argument' => array(
],
'argument' => [
'id' => 'standard',
),
);
],
];
$data['comment_entity_statistics']['last_updated'] = array(
$data['comment_entity_statistics']['last_updated'] = [
'title' => $this->t('Updated/commented date'),
'help' => $this->t('The most recent of last comment posted or entity updated time.'),
'field' => array(
'field' => [
'id' => 'comment_ces_last_updated',
'no group by' => TRUE,
),
'sort' => array(
],
'sort' => [
'id' => 'comment_ces_last_updated',
'no group by' => TRUE,
),
'filter' => array(
],
'filter' => [
'id' => 'comment_ces_last_updated',
),
);
],
];
$data['comment_entity_statistics']['cid'] = array(
$data['comment_entity_statistics']['cid'] = [
'title' => $this->t('Last comment CID'),
'help' => $this->t('Display the last comment of an entity'),
'relationship' => array(
'relationship' => [
'title' => $this->t('Last comment'),
'help' => $this->t('The last comment of an entity.'),
'group' => $this->t('Comment'),
@ -321,62 +322,62 @@ class CommentViewsData extends EntityViewsData {
'base field' => 'cid',
'id' => 'standard',
'label' => $this->t('Last Comment'),
),
);
],
];
$data['comment_entity_statistics']['last_comment_uid'] = array(
$data['comment_entity_statistics']['last_comment_uid'] = [
'title' => $this->t('Last comment uid'),
'help' => $this->t('The User ID of the author of the last comment of an entity.'),
'relationship' => array(
'relationship' => [
'title' => $this->t('Last comment author'),
'base' => 'users',
'base field' => 'uid',
'id' => 'standard',
'label' => $this->t('Last comment author'),
),
'filter' => array(
],
'filter' => [
'id' => 'numeric',
),
'argument' => array(
],
'argument' => [
'id' => 'numeric',
),
'field' => array(
],
'field' => [
'id' => 'numeric',
),
);
],
];
$data['comment_entity_statistics']['entity_type'] = array(
$data['comment_entity_statistics']['entity_type'] = [
'title' => $this->t('Entity type'),
'help' => $this->t('The entity type to which the comment is a reply to.'),
'field' => array(
'field' => [
'id' => 'standard',
),
'filter' => array(
],
'filter' => [
'id' => 'string',
),
'argument' => array(
],
'argument' => [
'id' => 'string',
),
'sort' => array(
],
'sort' => [
'id' => 'standard',
),
);
$data['comment_entity_statistics']['field_name'] = array(
],
];
$data['comment_entity_statistics']['field_name'] = [
'title' => $this->t('Comment field name'),
'help' => $this->t('The field name from which the comment originated.'),
'field' => array(
'field' => [
'id' => 'standard',
),
'filter' => array(
],
'filter' => [
'id' => 'string',
),
'argument' => array(
],
'argument' => [
'id' => 'string',
),
'sort' => array(
],
'sort' => [
'id' => 'standard',
),
);
],
];
return $data;
}

View file

@ -125,7 +125,7 @@ class CommentController extends ControllerBase {
$page = $this->entityManager()->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
// @todo: Cleaner sub request handling.
$subrequest_url = $entity->urlInfo()->setOption('query', ['page' => $page])->toString(TRUE);
$redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), array(), $request->server->all());
$redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), [], $request->server->all());
// Carry over the session to the subrequest.
if ($session = $request->getSession()) {
$redirect_request->setSession($session);
@ -174,11 +174,11 @@ class CommentController extends ControllerBase {
// Legacy nodes only had a single comment field, so use the first comment
// field on the entity.
if (!empty($fields) && ($field_names = array_keys($fields)) && ($field_name = reset($field_names))) {
return $this->redirect('comment.reply', array(
return $this->redirect('comment.reply', [
'entity_type' => 'node',
'entity' => $node->id(),
'field_name' => $field_name,
));
]);
}
throw new NotFoundHttpException();
}
@ -211,7 +211,7 @@ class CommentController extends ControllerBase {
*/
public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) {
$account = $this->currentUser();
$build = array();
$build = [];
// The user is not just previewing a comment.
if ($request->request->get('op') != $this->t('Preview')) {
@ -240,12 +240,12 @@ class CommentController extends ControllerBase {
}
// Show the actual reply box.
$comment = $this->entityManager()->getStorage('comment')->create(array(
$comment = $this->entityManager()->getStorage('comment')->create([
'entity_id' => $entity->id(),
'pid' => $pid,
'entity_type' => $entity->getEntityTypeId(),
'field_name' => $field_name,
));
]);
$build['comment_form'] = $this->entityFormBuilder()->getForm($comment);
return $build;
@ -324,17 +324,17 @@ class CommentController extends ControllerBase {
// Only handle up to 100 nodes.
$nids = array_slice($nids, 0, 100);
$links = array();
$links = [];
foreach ($nids as $nid) {
$node = $this->entityManager->getStorage('node')->load($nid);
$new = $this->commentManager->getCountNewComments($node);
$page_number = $this->entityManager()->getStorage('comment')
->getNewCommentPageNumber($node->{$field_name}->comment_count, $new, $node, $field_name);
$query = $page_number ? array('page' => $page_number) : NULL;
$links[$nid] = array(
$query = $page_number ? ['page' => $page_number] : NULL;
$links[$nid] = [
'new_comment_count' => (int) $new,
'first_new_comment_link' => $this->getUrlGenerator()->generateFromRoute('entity.node.canonical', array('node' => $node->id()), array('query' => $query, 'fragment' => 'new')),
);
'first_new_comment_link' => $this->getUrlGenerator()->generateFromRoute('entity.node.canonical', ['node' => $node->id()], ['query' => $query, 'fragment' => 'new']),
];
}
return new JsonResponse($links);

View file

@ -7,6 +7,7 @@ use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\comment\CommentInterface;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
@ -20,6 +21,12 @@ use Drupal\user\UserInterface;
* @ContentEntityType(
* id = "comment",
* label = @Translation("Comment"),
* label_singular = @Translation("comment"),
* label_plural = @Translation("comments"),
* label_count = @PluralTranslation(
* singular = "@count comment",
* plural = "@count comments",
* ),
* bundle_label = @Translation("Comment type"),
* handlers = {
* "storage" = "Drupal\comment\CommentStorage",
@ -43,7 +50,8 @@ use Drupal\user\UserInterface;
* "bundle" = "comment_type",
* "label" = "subject",
* "langcode" = "langcode",
* "uuid" = "uuid"
* "uuid" = "uuid",
* "published" = "status",
* },
* links = {
* "canonical" = "/comment/{comment}",
@ -60,6 +68,7 @@ use Drupal\user\UserInterface;
class Comment extends ContentEntityBase implements CommentInterface {
use EntityChangedTrait;
use EntityPublishedTrait;
/**
* The thread for which a lock was acquired.
@ -73,8 +82,12 @@ class Comment extends ContentEntityBase implements CommentInterface {
parent::preSave($storage);
if (is_null($this->get('status')->value)) {
$published = \Drupal::currentUser()->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
$this->setPublished($published);
if (\Drupal::currentUser()->hasPermission('skip comment approval')) {
$this->setPublished();
}
else {
$this->setUnpublished();
}
}
if ($this->isNew()) {
// Add the comment to database. This next section builds the thread field.
@ -138,9 +151,11 @@ class Comment extends ContentEntityBase implements CommentInterface {
if ($this->getOwnerId() === \Drupal::currentUser()->id() && \Drupal::currentUser()->isAuthenticated()) {
$this->setAuthorName(\Drupal::currentUser()->getUsername());
}
// Add the values which aren't passed into the function.
$this->setThread($thread);
$this->setHostname(\Drupal::request()->getClientIP());
if (!$this->getHostname()) {
// Ensure a client host from the current request.
$this->setHostname(\Drupal::request()->getClientIP());
}
}
}
@ -210,6 +225,7 @@ class Comment extends ContentEntityBase implements CommentInterface {
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::publishedBaseFieldDefinitions($entity_type);
$fields['cid']->setLabel(t('Comment ID'))
->setDescription(t('The comment ID.'));
@ -235,11 +251,11 @@ class Comment extends ContentEntityBase implements CommentInterface {
->setLabel(t('Subject'))
->setTranslatable(TRUE)
->setSetting('max_length', 64)
->setDisplayOptions('form', array(
->setDisplayOptions('form', [
'type' => 'string_textfield',
// Default comment body field has weight 20.
'weight' => 10,
))
])
->setDisplayConfigurable('form', TRUE);
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
@ -285,12 +301,6 @@ class Comment extends ContentEntityBase implements CommentInterface {
->setDescription(t('The time that the comment was last edited.'))
->setTranslatable(TRUE);
$fields['status'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Publishing status'))
->setDescription(t('A boolean indicating whether the comment is published.'))
->setTranslatable(TRUE)
->setDefaultValue(TRUE);
$fields['thread'] = BaseFieldDefinition::create('string')
->setLabel(t('Thread place'))
->setDescription(t("The alphadecimal representation of the comment's place in a thread, consisting of a base 36 string prefixed by an integer indicating its length."))
@ -320,7 +330,7 @@ class Comment extends ContentEntityBase implements CommentInterface {
$fields['entity_id']->setSetting('target_type', $comment_type->getTargetEntityTypeId());
return $fields;
}
return array();
return [];
}
/**
@ -467,13 +477,6 @@ class Comment extends ContentEntityBase implements CommentInterface {
return $this;
}
/**
* {@inheritdoc}
*/
public function isPublished() {
return $this->get('status')->value == CommentInterface::PUBLISHED;
}
/**
* {@inheritdoc}
*/
@ -481,14 +484,6 @@ class Comment extends ContentEntityBase implements CommentInterface {
return $this->get('status')->value;
}
/**
* {@inheritdoc}
*/
public function setPublished($status) {
$this->set('status', $status ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
return $this;
}
/**
* {@inheritdoc}
*/

View file

@ -11,6 +11,12 @@ use Drupal\comment\CommentTypeInterface;
* @ConfigEntityType(
* id = "comment_type",
* label = @Translation("Comment type"),
* label_singular = @Translation("comment type"),
* label_plural = @Translation("comment types"),
* label_count = @PluralTranslation(
* singular = "@count comment type",
* plural = "@count comment types",
* ),
* handlers = {
* "form" = {
* "default" = "Drupal\comment\CommentTypeForm",

View file

@ -99,12 +99,12 @@ class CommentAdminOverview extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') {
// Build an 'Update options' form.
$form['options'] = array(
$form['options'] = [
'#type' => 'details',
'#title' => $this->t('Update options'),
'#open' => TRUE,
'#attributes' => array('class' => array('container-inline')),
);
'#attributes' => ['class' => ['container-inline']],
];
if ($type == 'approval') {
$options['publish'] = $this->t('Publish the selected comments');
@ -114,42 +114,42 @@ class CommentAdminOverview extends FormBase {
}
$options['delete'] = $this->t('Delete the selected comments');
$form['options']['operation'] = array(
$form['options']['operation'] = [
'#type' => 'select',
'#title' => $this->t('Action'),
'#title_display' => 'invisible',
'#options' => $options,
'#default_value' => 'publish',
);
$form['options']['submit'] = array(
];
$form['options']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Update'),
);
];
// Load the comments that need to be displayed.
$status = ($type == 'approval') ? CommentInterface::NOT_PUBLISHED : CommentInterface::PUBLISHED;
$header = array(
'subject' => array(
$header = [
'subject' => [
'data' => $this->t('Subject'),
'specifier' => 'subject',
),
'author' => array(
],
'author' => [
'data' => $this->t('Author'),
'specifier' => 'name',
'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
),
'posted_in' => array(
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
],
'posted_in' => [
'data' => $this->t('Posted in'),
'class' => array(RESPONSIVE_PRIORITY_LOW),
),
'changed' => array(
'class' => [RESPONSIVE_PRIORITY_LOW],
],
'changed' => [
'data' => $this->t('Updated'),
'specifier' => 'changed',
'sort' => 'desc',
'class' => array(RESPONSIVE_PRIORITY_LOW),
),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
'operations' => $this->t('Operations'),
);
];
$cids = $this->commentStorage->getQuery()
->condition('status', $status)
->tableSort($header)
@ -160,11 +160,11 @@ class CommentAdminOverview extends FormBase {
$comments = $this->commentStorage->loadMultiple($cids);
// Build a table listing the appropriate comments.
$options = array();
$options = [];
$destination = $this->getDestinationArray();
$commented_entity_ids = array();
$commented_entities = array();
$commented_entity_ids = [];
$commented_entities = [];
foreach ($comments as $comment) {
$commented_entity_ids[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId();
@ -179,61 +179,61 @@ class CommentAdminOverview extends FormBase {
$commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()];
$comment_permalink = $comment->permalink();
if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) {
$attributes = $comment_permalink->getOption('attributes') ?: array();
$attributes += array('title' => Unicode::truncate($body, 128));
$attributes = $comment_permalink->getOption('attributes') ?: [];
$attributes += ['title' => Unicode::truncate($body, 128)];
$comment_permalink->setOption('attributes', $attributes);
}
$options[$comment->id()] = array(
'title' => array('data' => array('#title' => $comment->getSubject() ?: $comment->id())),
'subject' => array(
'data' => array(
$options[$comment->id()] = [
'title' => ['data' => ['#title' => $comment->getSubject() ?: $comment->id()]],
'subject' => [
'data' => [
'#type' => 'link',
'#title' => $comment->getSubject(),
'#url' => $comment_permalink,
),
),
'author' => array(
'data' => array(
],
],
'author' => [
'data' => [
'#theme' => 'username',
'#account' => $comment->getOwner(),
),
),
'posted_in' => array(
'data' => array(
],
],
'posted_in' => [
'data' => [
'#type' => 'link',
'#title' => $commented_entity->label(),
'#access' => $commented_entity->access('view'),
'#url' => $commented_entity->urlInfo(),
),
),
],
],
'changed' => $this->dateFormatter->format($comment->getChangedTimeAcrossTranslations(), 'short'),
);
];
$comment_uri_options = $comment->urlInfo()->getOptions() + ['query' => $destination];
$links = array();
$links['edit'] = array(
$links = [];
$links['edit'] = [
'title' => $this->t('Edit'),
'url' => $comment->urlInfo('edit-form', $comment_uri_options),
);
if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', array($comment))->isAllowed()) {
$links['translate'] = array(
];
if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', [$comment])->isAllowed()) {
$links['translate'] = [
'title' => $this->t('Translate'),
'url' => $comment->urlInfo('drupal:content-translation-overview', $comment_uri_options),
);
];
}
$options[$comment->id()]['operations']['data'] = array(
$options[$comment->id()]['operations']['data'] = [
'#type' => 'operations',
'#links' => $links,
);
];
}
$form['comments'] = array(
$form['comments'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#empty' => $this->t('No comments available.'),
);
];
$form['pager'] = array('#type' => 'pager');
$form['pager'] = ['#type' => 'pager'];
return $form;
}
@ -242,7 +242,7 @@ class CommentAdminOverview extends FormBase {
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$form_state->setValue('comments', array_diff($form_state->getValue('comments'), array(0)));
$form_state->setValue('comments', array_diff($form_state->getValue('comments'), [0]));
// We can't execute any 'Update options' if no comments were selected.
if (count($form_state->getValue('comments')) == 0) {
$form_state->setErrorByName('', $this->t('Select one or more comments to perform the update on.'));

View file

@ -5,7 +5,6 @@ namespace Drupal\comment\Form;
use Drupal\comment\CommentManagerInterface;
use Drupal\Core\Entity\EntityDeleteForm;
use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Psr\Log\LoggerInterface;
@ -16,13 +15,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*/
class CommentTypeDeleteForm extends EntityDeleteForm {
/**
* The query factory to create entity queries.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
public $queryFactory;
/**
* The comment manager service.
*
@ -54,8 +46,6 @@ class CommentTypeDeleteForm extends EntityDeleteForm {
/**
* Constructs a query factory object.
*
* @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
* The entity query object.
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Entity\EntityManager $entity_manager
@ -63,8 +53,7 @@ class CommentTypeDeleteForm extends EntityDeleteForm {
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(QueryFactory $query_factory, CommentManagerInterface $comment_manager, EntityManager $entity_manager, LoggerInterface $logger) {
$this->queryFactory = $query_factory;
public function __construct(CommentManagerInterface $comment_manager, EntityManager $entity_manager, LoggerInterface $logger) {
$this->commentManager = $comment_manager;
$this->entityManager = $entity_manager;
$this->logger = $logger;
@ -75,7 +64,6 @@ class CommentTypeDeleteForm extends EntityDeleteForm {
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.query'),
$container->get('comment.manager'),
$container->get('entity.manager'),
$container->get('logger.factory')->get('comment')
@ -86,24 +74,26 @@ class CommentTypeDeleteForm extends EntityDeleteForm {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$comments = $this->queryFactory->get('comment')->condition('comment_type', $this->entity->id())->execute();
$comments = $this->entityTypeManager->getStorage('comment')->getQuery()
->condition('comment_type', $this->entity->id())
->execute();
$entity_type = $this->entity->getTargetEntityTypeId();
$caption = '';
foreach (array_keys($this->commentManager->getFields($entity_type)) as $field_name) {
/** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
if (($field_storage = FieldStorageConfig::loadByName($entity_type, $field_name)) && $field_storage->getSetting('comment_type') == $this->entity->id() && !$field_storage->isDeleted()) {
$caption .= '<p>' . $this->t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', array(
$caption .= '<p>' . $this->t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [
'%label' => $this->entity->label(),
'%field' => $field_storage->label(),
)) . '</p>';
]) . '</p>';
}
}
if (!empty($comments)) {
$caption .= '<p>' . $this->formatPlural(count($comments), '%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', '%label is used by @count comments on your site. You may not remove %label until you have removed all of the %label comments.', array('%label' => $this->entity->label())) . '</p>';
$caption .= '<p>' . $this->formatPlural(count($comments), '%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', '%label is used by @count comments on your site. You may not remove %label until you have removed all of the %label comments.', ['%label' => $this->entity->label()]) . '</p>';
}
if ($caption) {
$form['description'] = array('#markup' => $caption);
$form['description'] = ['#markup' => $caption];
return $form;
}
else {

View file

@ -81,25 +81,25 @@ class ConfirmDeleteMultiple extends ConfirmFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$edit = $form_state->getUserInput();
$form['comments'] = array(
$form['comments'] = [
'#prefix' => '<ul>',
'#suffix' => '</ul>',
'#tree' => TRUE,
);
];
// array_filter() returns only elements with actual values.
$comment_counter = 0;
$this->comments = $this->commentStorage->loadMultiple(array_keys(array_filter($edit['comments'])));
foreach ($this->comments as $comment) {
$cid = $comment->id();
$form['comments'][$cid] = array(
$form['comments'][$cid] = [
'#type' => 'hidden',
'#value' => $cid,
'#prefix' => '<li>',
'#suffix' => Html::escape($comment->label()) . '</li>'
);
];
$comment_counter++;
}
$form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
$form['operation'] = ['#type' => 'hidden', '#value' => 'delete'];
if (!$comment_counter) {
drupal_set_message($this->t('There do not appear to be any comments to delete, or your selected comment was deleted by another administrator.'));
@ -116,7 +116,7 @@ class ConfirmDeleteMultiple extends ConfirmFormBase {
if ($form_state->getValue('confirm')) {
$this->commentStorage->delete($this->comments);
$count = count($form_state->getValue('comments'));
$this->logger('content')->notice('Deleted @count comments.', array('@count' => $count));
$this->logger('comment')->notice('Deleted @count comments.', ['@count' => $count]);
drupal_set_message($this->formatPlural($count, 'Deleted 1 comment.', 'Deleted @count comments.'));
}
$form_state->setRedirectUrl($this->getCancelUrl());

View file

@ -42,7 +42,7 @@ class DeleteForm extends ContentEntityDeleteForm {
* {@inheritdoc}
*/
public function logDeletionMessage() {
$this->logger('content')->notice('Deleted comment @cid and its replies.', array('@cid' => $this->entity->id()));
$this->logger('comment')->notice('Deleted comment @cid and its replies.', ['@cid' => $this->entity->id()]);
}
}

View file

@ -89,21 +89,21 @@ class UnpublishByKeywordComment extends ConfigurableActionBase implements Contai
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
'keywords' => array(),
);
return [
'keywords' => [],
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['keywords'] = array(
$form['keywords'] = [
'#title' => $this->t('Keywords'),
'#type' => 'textarea',
'#description' => $this->t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
'#default_value' => Tags::implode($this->configuration['keywords']),
);
];
return $form;
}

View file

@ -24,19 +24,19 @@ class AuthorNameFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
/** @var $comment \Drupal\comment\CommentInterface */
$comment = $item->getEntity();
$account = $comment->getOwner();
$elements[$delta] = array(
$elements[$delta] = [
'#theme' => 'username',
'#account' => $account,
'#cache' => array(
'#cache' => [
'tags' => $account->getCacheTags() + $comment->getCacheTags(),
),
);
],
];
}
return $elements;

View file

@ -36,10 +36,10 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'view_mode' => 'default',
'pager_id' => 0,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@ -141,8 +141,8 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$output = array();
$elements = [];
$output = [];
$field_name = $this->fieldDefinition->getName();
$entity = $items->getEntity();
@ -153,7 +153,7 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
// Comments are added to the search results and search index by
// comment_node_update_index() instead of by this formatter, so don't
// return anything if the view mode is search_index or search_result.
!in_array($this->viewMode, array('search_result', 'search_index'))) {
!in_array($this->viewMode, ['search_result', 'search_index'])) {
$comment_settings = $this->getFieldSettings();
// Only attempt to render comments if the entity has visible comments.
@ -203,12 +203,12 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
}
}
$elements[] = $output + array(
$elements[] = $output + [
'#comment_type' => $this->getFieldSetting('comment_type'),
'#comment_display_mode' => $this->getFieldSetting('default_mode'),
'comments' => array(),
'comment_form' => array(),
);
'comments' => [],
'comment_form' => [],
];
}
return $elements;
@ -218,7 +218,7 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element = array();
$element = [];
$view_modes = $this->getViewModes();
$element['view_mode'] = [
'#type' => 'select',
@ -229,13 +229,13 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP
// Only show the select element when there are more than one options.
'#access' => count($view_modes) > 1,
];
$element['pager_id'] = array(
$element['pager_id'] = [
'#type' => 'select',
'#title' => $this->t('Pager ID'),
'#options' => range(0, 10),
'#default_value' => $this->getSetting('pager_id'),
'#description' => $this->t("Unless you're experiencing problems with pagers related to this field, you should leave this at 0. If using multiple pagers on one page you may need to set this number to a higher value so as not to conflict within the ?page= array. Large values will add a lot of commas to your URLs, so avoid if possible."),
);
];
return $element;
}

View file

@ -31,22 +31,22 @@ class CommentItem extends FieldItemBase implements CommentItemInterface {
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return array(
return [
'comment_type' => '',
) + parent::defaultStorageSettings();
] + parent::defaultStorageSettings();
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
return [
'default_mode' => CommentManagerInterface::COMMENT_MODE_THREADED,
'per_page' => 50,
'form_location' => CommentItemInterface::FORM_BELOW,
'anonymous' => COMMENT_ANONYMOUS_MAYNOT_CONTACT,
'preview' => DRUPAL_OPTIONAL,
) + parent::defaultFieldSettings();
] + parent::defaultFieldSettings();
}
/**
@ -82,36 +82,36 @@ class CommentItem extends FieldItemBase implements CommentItemInterface {
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'status' => array(
return [
'columns' => [
'status' => [
'description' => 'Whether comments are allowed on this entity: 0 = no, 1 = closed (read only), 2 = open (read/write).',
'type' => 'int',
'default' => 0,
),
),
'indexes' => array(),
'foreign keys' => array(),
);
],
],
'indexes' => [],
'foreign keys' => [],
];
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = array();
$element = [];
$settings = $this->getSettings();
$anonymous_user = new AnonymousUserSession();
$element['default_mode'] = array(
$element['default_mode'] = [
'#type' => 'checkbox',
'#title' => t('Threading'),
'#default_value' => $settings['default_mode'],
'#description' => t('Show comment replies in a threaded list.'),
);
$element['per_page'] = array(
];
$element['per_page'] = [
'#type' => 'number',
'#title' => t('Comments per page'),
'#default_value' => $settings['per_page'],
@ -119,33 +119,33 @@ class CommentItem extends FieldItemBase implements CommentItemInterface {
'#min' => 10,
'#max' => 1000,
'#step' => 10,
);
$element['anonymous'] = array(
];
$element['anonymous'] = [
'#type' => 'select',
'#title' => t('Anonymous commenting'),
'#default_value' => $settings['anonymous'],
'#options' => array(
'#options' => [
COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
),
],
'#access' => $anonymous_user->hasPermission('post comments'),
);
$element['form_location'] = array(
];
$element['form_location'] = [
'#type' => 'checkbox',
'#title' => t('Show reply form on the same page as comments'),
'#default_value' => $settings['form_location'],
);
$element['preview'] = array(
];
$element['preview'] = [
'#type' => 'radios',
'#title' => t('Preview comment'),
'#default_value' => $settings['preview'],
'#options' => array(
'#options' => [
DRUPAL_DISABLED => t('Disabled'),
DRUPAL_OPTIONAL => t('Optional'),
DRUPAL_REQUIRED => t('Required'),
),
);
],
];
return $element;
}
@ -171,27 +171,27 @@ class CommentItem extends FieldItemBase implements CommentItemInterface {
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = array();
$element = [];
// @todo Inject entity storage once typed-data supports container injection.
// See https://www.drupal.org/node/2053415 for more details.
$comment_types = CommentType::loadMultiple();
$options = array();
$options = [];
$entity_type = $this->getEntity()->getEntityTypeId();
foreach ($comment_types as $comment_type) {
if ($comment_type->getTargetEntityTypeId() == $entity_type) {
$options[$comment_type->id()] = $comment_type->label();
}
}
$element['comment_type'] = array(
$element['comment_type'] = [
'#type' => 'select',
'#title' => t('Comment type'),
'#options' => $options,
'#required' => TRUE,
'#description' => $this->t('Select the Comment type to use for this comment field. Manage the comment types from the <a href=":url">administration overview page</a>.', array(':url' => $this->url('entity.comment_type.collection'))),
'#description' => $this->t('Select the Comment type to use for this comment field. Manage the comment types from the <a href=":url">administration overview page</a>.', [':url' => $this->url('entity.comment_type.collection')]),
'#default_value' => $this->getSetting('comment_type'),
'#disabled' => $has_data,
);
];
return $element;
}

View file

@ -27,26 +27,26 @@ class CommentWidget extends WidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$entity = $items->getEntity();
$element['status'] = array(
$element['status'] = [
'#type' => 'radios',
'#title' => t('Comments'),
'#title_display' => 'invisible',
'#default_value' => $items->status,
'#options' => array(
'#options' => [
CommentItemInterface::OPEN => t('Open'),
CommentItemInterface::CLOSED => t('Closed'),
CommentItemInterface::HIDDEN => t('Hidden'),
),
CommentItemInterface::OPEN => array(
],
CommentItemInterface::OPEN => [
'#description' => t('Users with the "Post comments" permission can post comments.'),
),
CommentItemInterface::CLOSED => array(
],
CommentItemInterface::CLOSED => [
'#description' => t('Users cannot post comments, but existing comments will be displayed.'),
),
CommentItemInterface::HIDDEN => array(
],
CommentItemInterface::HIDDEN => [
'#description' => t('Comments are hidden from view.'),
),
);
],
];
// If the entity doesn't have any comments, the "hidden" option makes no
// sense, so don't even bother presenting it to the user unless this is the
// default value widget on the field settings form.
@ -65,19 +65,19 @@ class CommentWidget extends WidgetBase {
// Override widget title to be helpful for end users.
$element['#title'] = $this->t('Comment settings');
$element += array(
$element += [
'#type' => 'details',
// Open the details when the selected value is different to the stored
// default values for the field.
'#open' => ($items->status != $field_default_values[0]['status']),
'#group' => 'advanced',
'#attributes' => array(
'class' => array('comment-' . Html::getClass($entity->getEntityTypeId()) . '-settings-form'),
),
'#attached' => array(
'library' => array('comment/drupal.comment'),
),
);
'#attributes' => [
'class' => ['comment-' . Html::getClass($entity->getEntityTypeId()) . '-settings-form'],
],
'#attached' => [
'library' => ['comment/drupal.comment'],
],
];
}
return $element;
@ -90,13 +90,13 @@ class CommentWidget extends WidgetBase {
// Add default values for statistics properties because we don't want to
// have them in form.
foreach ($values as &$value) {
$value += array(
$value += [
'cid' => 0,
'last_comment_timestamp' => 0,
'last_comment_name' => '',
'last_comment_uid' => 0,
'comment_count' => 0,
);
];
}
return $values;
}

View file

@ -54,7 +54,7 @@ class UnapprovedComments extends LocalTaskDefault implements ContainerFactoryPlu
* {@inheritdoc}
*/
public function getTitle() {
return $this->t('Unapproved comments (@count)', array('@count' => $this->commentStorage->getUnapprovedCount()));
return $this->t('Unapproved comments (@count)', ['@count' => $this->commentStorage->getUnapprovedCount()]);
}
}

View file

@ -55,9 +55,9 @@ class CommentNameConstraintValidator extends ConstraintValidator implements Cont
// Do not allow unauthenticated comment authors to use a name that is
// taken by a registered user.
if (isset($author_name) && $author_name !== '' && $owner_id === 0) {
$users = $this->userStorage->loadByProperties(array('name' => $author_name));
$users = $this->userStorage->loadByProperties(['name' => $author_name]);
if (!empty($users)) {
$this->context->buildViolation($constraint->messageNameTaken, array('%name' => $author_name))
$this->context->buildViolation($constraint->messageNameTaken, ['%name' => $author_name])
->atPath('name')
->addViolation();
}

View file

@ -4,7 +4,6 @@ namespace Drupal\comment\Plugin\migrate\destination;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\State\StateInterface;
use Drupal\migrate\Plugin\MigrationInterface;
@ -26,13 +25,6 @@ class EntityComment extends EntityContentBase {
*/
protected $state;
/**
* The entity query object.
*
* @var \Drupal\Core\Entity\Query\QueryInterface
*/
protected $entityQuery;
/**
* An array of entity IDs for the 'commented entity' keyed by entity type.
*
@ -61,13 +53,10 @@ class EntityComment extends EntityContentBase {
* The field type plugin manager service.
* @param \Drupal\Core\State\StateInterface $state
* The state storage object.
* @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
* The query object that can query the given entity type.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, EntityStorageInterface $storage, array $bundles, EntityManagerInterface $entity_manager, FieldTypePluginManagerInterface $field_type_manager, StateInterface $state, QueryFactory $entity_query) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, EntityStorageInterface $storage, array $bundles, EntityManagerInterface $entity_manager, FieldTypePluginManagerInterface $field_type_manager, StateInterface $state) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration, $storage, $bundles, $entity_manager, $field_type_manager);
$this->state = $state;
$this->entityQuery = $entity_query;
}
/**
@ -84,15 +73,14 @@ class EntityComment extends EntityContentBase {
array_keys($container->get('entity.manager')->getBundleInfo($entity_type)),
$container->get('entity.manager'),
$container->get('plugin.manager.field.field_type'),
$container->get('state'),
$container->get('entity.query')
$container->get('state')
);
}
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
if ($row->isStub() && ($state = $this->state->get('comment.maintain_entity_statistics', 0))) {
$this->state->set('comment.maintain_entity_statistics', 0);
}

View file

@ -15,7 +15,7 @@ class EntityCommentType extends EntityConfigBase {
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
$entity_ids = parent::import($row, $old_destination_id_values);
\Drupal::service('comment.manager')->addBodyField(reset($entity_ids));
return $entity_ids;

View file

@ -20,11 +20,11 @@ class Comment extends DrupalSqlBase {
*/
public function query() {
$query = $this->select('comments', 'c')
->fields('c', array('cid', 'pid', 'nid', 'uid', 'subject',
->fields('c', ['cid', 'pid', 'nid', 'uid', 'subject',
'comment', 'hostname', 'timestamp', 'status', 'thread', 'name',
'mail', 'homepage', 'format'));
'mail', 'homepage', 'format']);
$query->innerJoin('node', 'n', 'c.nid = n.nid');
$query->fields('n', array('type'));
$query->fields('n', ['type']);
$query->orderBy('c.timestamp');
return $query;
}
@ -52,7 +52,7 @@ class Comment extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'cid' => $this->t('Comment ID.'),
'pid' => $this->t('Parent comment ID. If set to 0, this comment is not a reply to an existing comment.'),
'nid' => $this->t('The {node}.nid to which this comment is a reply.'),
@ -68,7 +68,7 @@ class Comment extends DrupalSqlBase {
'mail' => $this->t("The comment author's email address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."),
'homepage' => $this->t("The comment author's home page address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."),
'type' => $this->t("The {node}.type to which this comment is a reply."),
);
];
}
/**

View file

@ -35,7 +35,7 @@ class CommentVariable extends DrupalSqlBase {
*/
protected function getCommentVariables() {
$comment_prefixes = array_keys($this->commentPrefixes());
$variables = array();
$variables = [];
$node_types = $this->select('node_type', 'nt')
->fields('nt', ['type'])
->execute()
@ -45,7 +45,7 @@ class CommentVariable extends DrupalSqlBase {
$variables[] = $prefix . '_' . $node_type;
}
}
$return = array();
$return = [];
$values = $this->select('variable', 'v')
->fields('v', ['name', 'value'])
->condition('name', $variables, 'IN')
@ -74,17 +74,17 @@ class CommentVariable extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return $this->commentPrefixes() + array(
return $this->commentPrefixes() + [
'node_type' => $this->t('The node type'),
'comment_type' => $this->t('The comment type'),
);
];
}
/**
* Comment related data for fields.
*/
protected function commentPrefixes() {
return array(
return [
'comment' => $this->t('Default comment setting'),
'comment_default_mode' => $this->t('Default display mode'),
'comment_default_order' => $this->t('Default display order'),
@ -94,7 +94,7 @@ class CommentVariable extends DrupalSqlBase {
'comment_subject_field' => $this->t('Comment subject field'),
'comment_preview' => $this->t('Preview comment'),
'comment_form_location' => $this->t('Location of comment submission form'),
);
];
}
/**

View file

@ -17,24 +17,24 @@ class CommentVariablePerCommentType extends CommentVariable {
protected function getCommentVariables() {
$node_types = parent::getCommentVariables();
// The return key used to separate comment types with hidden subject field.
$return = array();
$return = [];
foreach ($node_types as $node_type => $data) {
// Only 2 comment types depending on subject field visibility.
if (!empty($data['comment_subject_field'])) {
// Default label and description should be set in migration.
$return['comment'] = array(
$return['comment'] = [
'comment_type' => 'comment',
'label' => $this->t('Default comments'),
'description' => $this->t('Allows commenting on content')
);
];
}
else {
// Provide a special comment type with hidden subject field.
$return['comment_no_subject'] = array(
$return['comment_no_subject'] = [
'comment_type' => 'comment_no_subject',
'label' => $this->t('Comments without subject field'),
'description' => $this->t('Allows commenting on content, comments without subject field')
);
];
}
}
return $return;
@ -44,11 +44,11 @@ class CommentVariablePerCommentType extends CommentVariable {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'comment_type' => $this->t('The comment type'),
'label' => $this->t('The comment type label'),
'description' => $this->t('The comment type description'),
);
];
}
/**

View file

@ -47,7 +47,7 @@ class Comment extends FieldableEntity {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'cid' => $this->t('Comment ID.'),
'pid' => $this->t('Parent comment ID. If set to 0, this comment is not a reply to an existing comment.'),
'nid' => $this->t('The {node}.nid to which this comment is a reply.'),
@ -64,7 +64,7 @@ class Comment extends FieldableEntity {
'mail' => $this->t("The comment author's email address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."),
'homepage' => $this->t("The comment author's home page address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."),
'type' => $this->t("The {node}.type to which this comment is a reply."),
);
];
}
/**

View file

@ -21,7 +21,7 @@ class CommentType extends DrupalSqlBase {
*
* @var string[]
*/
protected $nodeTypes = array();
protected $nodeTypes = [];
/**
* {@inheritdoc}
@ -29,7 +29,7 @@ class CommentType extends DrupalSqlBase {
public function query() {
return $this->select('field_config_instance', 'fci')
->distinct()
->fields('fci', array('bundle'))
->fields('fci', ['bundle'])
->condition('fci.entity_type', 'comment');
}
@ -38,7 +38,7 @@ class CommentType extends DrupalSqlBase {
*/
protected function initializeIterator() {
$this->nodeTypes = $this->select('node_type', 'nt')
->fields('nt', array('type', 'name'))
->fields('nt', ['type', 'name'])
->execute()
->fetchAllKeyed();
@ -71,7 +71,7 @@ class CommentType extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'label' => $this->t('The label of the comment type.'),
'bundle' => $this->t('Bundle ID of the comment type.'),
'node_type' => $this->t('The node type to which this comment type is attached.'),
@ -81,18 +81,18 @@ class CommentType extends DrupalSqlBase {
'form_location' => $this->t('Location of the comment form.'),
'preview' => $this->t('Whether previews are enabled for the comment type.'),
'subject' => $this->t('Whether a subject field is enabled for the comment type.'),
);
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
return array(
'bundle' => array(
return [
'bundle' => [
'type' => 'string',
),
);
],
];
}
}

View file

@ -48,12 +48,12 @@ class UserUid extends ArgumentPluginBase {
return new static($configuration, $plugin_id, $plugin_definition, $container->get('database'));
}
function title() {
public function title() {
if (!$this->argument) {
$title = \Drupal::config('user.settings')->get('anonymous');
}
else {
$title = $this->database->query('SELECT name FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', array(':uid' => $this->argument))->fetchField();
$title = $this->database->query('SELECT name FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', [':uid' => $this->argument])->fetchField();
}
if (empty($title)) {
return $this->t('No user');
@ -102,7 +102,7 @@ class UserUid extends ArgumentPluginBase {
* {@inheritdoc}
*/
public function getSortName() {
return $this->t('Numerical', array(), array('context' => 'Sort order'));
return $this->t('Numerical', [], ['context' => 'Sort order']);
}
}

View file

@ -2,7 +2,7 @@
namespace Drupal\comment\Plugin\views\field;
use Drupal\views\Plugin\views\field\Field;
use Drupal\views\Plugin\views\field\EntityField;
use Drupal\views\ResultRow;
/**
@ -12,7 +12,7 @@ use Drupal\views\ResultRow;
*
* @ViewsField("comment_depth")
*/
class Depth extends Field {
class Depth extends EntityField {
/**
* {@inheritdoc}

View file

@ -27,7 +27,7 @@ class EntityLink extends FieldPluginBase {
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['teaser'] = array('default' => FALSE);
$options['teaser'] = ['default' => FALSE];
return $options;
}
@ -35,12 +35,12 @@ class EntityLink extends FieldPluginBase {
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['teaser'] = array(
$form['teaser'] = [
'#type' => 'checkbox',
'#title' => $this->t('Show teaser-style link'),
'#default_value' => $this->options['teaser'],
'#description' => $this->t('Show the comment link in the form used on standard entity teasers, rather than the full entity form.'),
);
];
parent::buildOptionsForm($form, $form_state);
}
@ -55,7 +55,7 @@ class EntityLink extends FieldPluginBase {
*/
public function preRender(&$values) {
// Render all nodes, so you can grep the comment links.
$entities = array();
$entities = [];
foreach ($values as $row) {
$entity = $row->_entity;
$entities[$entity->id()] = $entity;

View file

@ -68,7 +68,7 @@ class NodeNewComments extends NumericField {
$this->additional_fields['entity_id'] = 'nid';
$this->additional_fields['type'] = 'type';
$this->additional_fields['comment_count'] = array('table' => 'comment_entity_statistics', 'field' => 'comment_count');
$this->additional_fields['comment_count'] = ['table' => 'comment_entity_statistics', 'field' => 'comment_count'];
}
/**
@ -77,7 +77,7 @@ class NodeNewComments extends NumericField {
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_comment'] = array('default' => TRUE);
$options['link_to_comment'] = ['default' => TRUE];
return $options;
}
@ -86,12 +86,12 @@ class NodeNewComments extends NumericField {
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['link_to_comment'] = array(
$form['link_to_comment'] = [
'#title' => $this->t('Link this field to new comments'),
'#description' => $this->t("Enable to override this field's links."),
'#type' => 'checkbox',
'#default_value' => $this->options['link_to_comment'],
);
];
parent::buildOptionsForm($form, $form_state);
}
@ -114,14 +114,14 @@ class NodeNewComments extends NumericField {
return;
}
$nids = array();
$ids = array();
$nids = [];
$ids = [];
foreach ($values as $id => $result) {
$nids[] = $result->{$this->aliases['nid']};
$values[$id]->{$this->field_alias} = 0;
// Create a reference so we can find this record in the values again.
if (empty($ids[$result->{$this->aliases['nid']}])) {
$ids[$result->{$this->aliases['nid']}] = array();
$ids[$result->{$this->aliases['nid']}] = [];
}
$ids[$result->{$this->aliases['nid']}][] = $id;
}
@ -129,13 +129,13 @@ class NodeNewComments extends NumericField {
if ($nids) {
$result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n INNER JOIN {comment_field_data} c ON n.nid = c.entity_id AND c.entity_type = 'node' AND c.default_langcode = 1
LEFT JOIN {history} h ON h.nid = n.nid AND h.uid = :h_uid WHERE n.nid IN ( :nids[] )
AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", array(
AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", [
':status' => CommentInterface::PUBLISHED,
':h_uid' => $user->id(),
':nids[]' => $nids,
':timestamp1' => HISTORY_READ_LIMIT,
':timestamp2' => HISTORY_READ_LIMIT,
));
]);
foreach ($result as $node) {
foreach ($ids[$node->nid] as $id) {
$values[$id]->{$this->field_alias} = $node->num_comments;
@ -181,7 +181,7 @@ class NodeNewComments extends NumericField {
->getNewCommentPageNumber($this->getValue($values, 'comment_count'), $this->getValue($values), $node, $comment_field_name);
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['url'] = $node->urlInfo();
$this->options['alter']['query'] = $page_number ? array('page' => $page_number) : NULL;
$this->options['alter']['query'] = $page_number ? ['page' => $page_number] : NULL;
$this->options['alter']['fragment'] = 'new';
}

View file

@ -23,19 +23,19 @@ class StatisticsLastCommentName extends FieldPluginBase {
// have to join in a specially related user table.
$this->ensureMyTable();
// join 'users' to this table via vid
$definition = array(
$definition = [
'table' => 'users_field_data',
'field' => 'uid',
'left_table' => 'comment_entity_statistics',
'left_field' => 'last_comment_uid',
'extra' => array(
array(
'extra' => [
[
'field' => 'uid',
'operator' => '!=',
'value' => '0'
)
)
);
]
]
];
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
// nes_user alias so this can work with the sort handler, below.
@ -53,7 +53,7 @@ class StatisticsLastCommentName extends FieldPluginBase {
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_user'] = array('default' => TRUE);
$options['link_to_user'] = ['default' => TRUE];
return $options;
}
@ -66,10 +66,10 @@ class StatisticsLastCommentName extends FieldPluginBase {
$account = User::create();
$account->name = $this->getValue($values);
$account->uid = $values->{$this->uid};
$username = array(
$username = [
'#theme' => 'username',
'#account' => $account,
);
];
return drupal_render($username);
}
else {

View file

@ -15,11 +15,11 @@ use Drupal\views\Plugin\views\filter\InOperator;
class NodeComment extends InOperator {
public function getValueOptions() {
$this->valueOptions = array(
$this->valueOptions = [
CommentItemInterface::HIDDEN => $this->t('Hidden'),
CommentItemInterface::CLOSED => $this->t('Closed'),
CommentItemInterface::OPEN => $this->t('Open'),
);
];
return $this->valueOptions;
}

View file

@ -40,7 +40,7 @@ class Rss extends RssPluginBase {
protected $entityTypeId = 'comment';
public function preRender($result) {
$cids = array();
$cids = [];
foreach ($result as $row) {
$cids[] = $row->cid;
@ -79,23 +79,23 @@ class Rss extends RssPluginBase {
return;
}
$comment->link = $comment->url('canonical', array('absolute' => TRUE));
$comment->rss_namespaces = array();
$comment->rss_elements = array(
array(
$comment->link = $comment->url('canonical', ['absolute' => TRUE]);
$comment->rss_namespaces = [];
$comment->rss_elements = [
[
'key' => 'pubDate',
'value' => gmdate('r', $comment->getCreatedTime()),
),
array(
],
[
'key' => 'dc:creator',
'value' => $comment->getAuthorName(),
),
array(
],
[
'key' => 'guid',
'value' => 'comment ' . $comment->id() . ' at ' . $base_url,
'attributes' => array('isPermaLink' => 'false'),
),
);
'attributes' => ['isPermaLink' => 'false'],
],
];
// The comment gets built and modules add to or modify
// $comment->rss_elements and $comment->rss_namespaces.
@ -118,12 +118,12 @@ class Rss extends RssPluginBase {
$item->elements = &$comment->rss_elements;
$item->cid = $comment->id();
$build = array(
$build = [
'#theme' => $this->themeFunctions(),
'#view' => $this->view,
'#options' => $this->options,
'#row' => $item,
);
];
return $build;
}

View file

@ -16,12 +16,12 @@ class StatisticsLastCommentName extends SortPluginBase {
public function query() {
$this->ensureMyTable();
$definition = array(
$definition = [
'table' => 'users_field_data',
'field' => 'uid',
'left_table' => 'comment_entity_statistics',
'left_field' => 'last_comment_uid',
);
];
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
// @todo this might be safer if we had an ensure_relationship rather than guessing

View file

@ -27,16 +27,16 @@ class Comment extends WizardPluginBase {
/**
* Set default values for the filters.
*/
protected $filters = array(
'status' => array(
protected $filters = [
'status' => [
'value' => TRUE,
'table' => 'comment_field_data',
'field' => 'status',
'plugin_id' => 'boolean',
'entity_type' => 'comment',
'entity_field' => 'status',
),
'status_node' => array(
],
'status_node' => [
'value' => TRUE,
'table' => 'node_field_data',
'field' => 'status',
@ -44,14 +44,14 @@ class Comment extends WizardPluginBase {
'relationship' => 'node',
'entity_type' => 'node',
'entity_field' => 'status',
),
);
],
];
/**
* {@inheritdoc}
*/
protected function rowStyleOptions() {
$options = array();
$options = [];
$options['entity:comment'] = $this->t('comments');
$options['fields'] = $this->t('fields');
return $options;

View file

@ -17,12 +17,12 @@ class CommentActionsTest extends CommentTestBase {
*
* @var array
*/
public static $modules = array('dblog', 'action');
public static $modules = ['dblog', 'action'];
/**
* Tests comment publish and unpublish actions.
*/
function testCommentPublishUnpublishActions() {
public function testCommentPublishUnpublishActions() {
$this->drupalLogin($this->webUser);
$comment_text = $this->randomMachineName();
$subject = $this->randomMachineName();
@ -30,31 +30,31 @@ class CommentActionsTest extends CommentTestBase {
// Unpublish a comment.
$action = Action::load('comment_unpublish_action');
$action->execute(array($comment));
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === FALSE, 'Comment was unpublished');
// Publish a comment.
$action = Action::load('comment_publish_action');
$action->execute(array($comment));
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === TRUE, 'Comment was published');
}
/**
* Tests the unpublish comment by keyword action.
*/
function testCommentUnpublishByKeyword() {
public function testCommentUnpublishByKeyword() {
$this->drupalLogin($this->adminUser);
$keyword_1 = $this->randomMachineName();
$keyword_2 = $this->randomMachineName();
$action = Action::create(array(
$action = Action::create([
'id' => 'comment_unpublish_by_keyword_action',
'label' => $this->randomMachineName(),
'type' => 'comment',
'configuration' => array(
'keywords' => array($keyword_1, $keyword_2),
),
'configuration' => [
'keywords' => [$keyword_1, $keyword_2],
],
'plugin' => 'comment_unpublish_by_keyword_action',
));
]);
$action->save();
$comment = $this->postComment($this->node, $keyword_2, $this->randomMachineName());
@ -64,7 +64,7 @@ class CommentActionsTest extends CommentTestBase {
$this->assertTrue($comment->isPublished() === TRUE, 'The comment status was set to published.');
$action->execute(array($comment));
$action->execute([$comment]);
$this->assertTrue($comment->isPublished() === FALSE, 'The comment status was set to not published.');
}

View file

@ -21,13 +21,13 @@ class CommentAdminTest extends CommentTestBase {
/**
* Test comment approval functionality through admin/content/comment.
*/
function testApprovalAdminInterface() {
public function testApprovalAdminInterface() {
// Set anonymous comments to require approval.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
));
]);
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous('0'); // Ensure that doesn't require contact info.
@ -46,14 +46,14 @@ class CommentAdminTest extends CommentTestBase {
// Get unapproved comment id.
$this->drupalLogin($this->adminUser);
$anonymous_comment4 = $this->getUnapprovedComment($subject);
$anonymous_comment4 = Comment::create(array(
$anonymous_comment4 = Comment::create([
'cid' => $anonymous_comment4,
'subject' => $subject,
'comment_body' => $body,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment'
));
]);
$this->drupalLogout();
$this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
@ -73,29 +73,29 @@ class CommentAdminTest extends CommentTestBase {
// Publish multiple comments in one operation.
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/content/comment/approval');
$this->assertText(t('Unapproved comments (@count)', array('@count' => 2)), 'Two unapproved comments waiting for approval.');
$edit = array(
$this->assertText(t('Unapproved comments (@count)', ['@count' => 2]), 'Two unapproved comments waiting for approval.');
$edit = [
"comments[{$comments[0]->id()}]" => 1,
"comments[{$comments[1]->id()}]" => 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Unapproved comments (@count)', array('@count' => 0)), 'All comments were approved.');
$this->assertText(t('Unapproved comments (@count)', ['@count' => 0]), 'All comments were approved.');
// Delete multiple comments in one operation.
$edit = array(
$edit = [
'operation' => 'delete',
"comments[{$comments[0]->id()}]" => 1,
"comments[{$comments[1]->id()}]" => 1,
"comments[{$anonymous_comment4->id()}]" => 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Are you sure you want to delete these comments and all their children?'), 'Confirmation required.');
$this->drupalPostForm(NULL, $edit, t('Delete comments'));
$this->assertText(t('No comments available.'), 'All comments were deleted.');
// Test message when no comments selected.
$edit = array(
$edit = [
'operation' => 'delete',
);
];
$this->drupalPostForm(NULL, $edit, t('Update'));
$this->assertText(t('Select one or more comments to perform the update on.'));
}
@ -103,13 +103,13 @@ class CommentAdminTest extends CommentTestBase {
/**
* Tests comment approval functionality through the node interface.
*/
function testApprovalNodeInterface() {
public function testApprovalNodeInterface() {
// Set anonymous comments to require approval.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
));
]);
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous('0'); // Ensure that doesn't require contact info.
$this->drupalLogout();
@ -123,14 +123,14 @@ class CommentAdminTest extends CommentTestBase {
// Get unapproved comment id.
$this->drupalLogin($this->adminUser);
$anonymous_comment4 = $this->getUnapprovedComment($subject);
$anonymous_comment4 = Comment::create(array(
$anonymous_comment4 = Comment::create([
'cid' => $anonymous_comment4,
'subject' => $subject,
'comment_body' => $body,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
'field_name' => 'comment'
));
]);
$this->drupalLogout();
$this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
@ -139,7 +139,7 @@ class CommentAdminTest extends CommentTestBase {
$this->drupalLogin($this->adminUser);
$this->drupalGet('comment/1/approve');
$this->assertResponse(403, 'Forged comment approval was denied.');
$this->drupalGet('comment/1/approve', array('query' => array('token' => 'forged')));
$this->drupalGet('comment/1/approve', ['query' => ['token' => 'forged']]);
$this->assertResponse(403, 'Forged comment approval was denied.');
$this->drupalGet('comment/1/edit');
$this->assertFieldChecked('edit-status-0');
@ -178,11 +178,11 @@ class CommentAdminTest extends CommentTestBase {
*/
public function testEditComment() {
// Enable anonymous user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
));
]);
// Log in as a web user.
$this->drupalLogin($this->webUser);
@ -199,7 +199,7 @@ class CommentAdminTest extends CommentTestBase {
// Post comment with contact info (required).
$author_name = $this->randomMachineName();
$author_mail = $this->randomMachineName() . '@example.com';
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), array('name' => $author_name, 'mail' => $author_mail));
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]);
// Log in as an admin user.
$this->drupalLogin($this->adminUser);

View file

@ -15,22 +15,22 @@ class CommentAnonymousTest extends CommentTestBase {
parent::setUp();
// Enable anonymous and authenticated user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
));
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array(
]);
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [
'access comments',
'post comments',
'skip comment approval',
));
]);
}
/**
* Tests anonymous comment functionality.
*/
function testAnonymous() {
public function testAnonymous() {
$this->drupalLogin($this->adminUser);
$this->setCommentAnonymous(COMMENT_ANONYMOUS_MAYNOT_CONTACT);
$this->drupalLogout();
@ -66,10 +66,10 @@ class CommentAnonymousTest extends CommentTestBase {
$this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.');
// Ensure anonymous users cannot post in the name of registered users.
$edit = array(
$edit = [
'name' => $this->adminUser->getUsername(),
'comment_body[0][value]' => $this->randomMachineName(),
);
];
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertRaw(t('The name you used (%name) belongs to a registered user.', [
'%name' => $this->adminUser->getUsername(),
@ -97,12 +97,12 @@ class CommentAnonymousTest extends CommentTestBase {
$this->assertTrue($this->commentExists($anonymous_comment2), 'Anonymous comment with contact info (optional) found.');
// Ensure anonymous users cannot post in the name of registered users.
$edit = array(
$edit = [
'name' => $this->adminUser->getUsername(),
'mail' => $this->randomMachineName() . '@example.com',
'subject[0][value]' => $this->randomMachineName(),
'comment_body[0][value]' => $this->randomMachineName(),
);
];
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertRaw(t('The name you used (%name) belongs to a registered user.', [
'%name' => $this->adminUser->getUsername(),
@ -125,7 +125,7 @@ class CommentAnonymousTest extends CommentTestBase {
// Post comment with contact info (required).
$author_name = $this->randomMachineName();
$author_mail = $this->randomMachineName() . '@example.com';
$anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), array('name' => $author_name, 'mail' => $author_mail));
$anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]);
$this->assertTrue($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) found.');
// Make sure the user data appears correctly when editing the comment.
@ -159,11 +159,11 @@ class CommentAnonymousTest extends CommentTestBase {
$this->assertResponse(403);
// Reset.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
));
]);
// Attempt to view comments while disallowed.
// NOTE: if authenticated user has permission to post comments, then a
@ -176,21 +176,21 @@ class CommentAnonymousTest extends CommentTestBase {
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
));
]);
$this->drupalGet('node/' . $this->node->id());
$this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
$this->assertLink('Log in', 1, 'Link to login was found.');
$this->assertLink('register', 1, 'Link to register was found.');
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
));
]);
$this->drupalGet('node/' . $this->node->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertFieldByName('subject[0][value]', '', 'Subject field found.');

View file

@ -17,12 +17,12 @@ class CommentBlockTest extends CommentTestBase {
*
* @var array
*/
public static $modules = array('block', 'views');
public static $modules = ['block', 'views'];
protected function setUp() {
parent::setUp();
// Update admin user to have the 'administer blocks' permission.
$this->adminUser = $this->drupalCreateUser(array(
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer comments',
'skip comment approval',
@ -30,13 +30,13 @@ class CommentBlockTest extends CommentTestBase {
'access comments',
'access content',
'administer blocks',
));
]);
}
/**
* Tests the recent comments block.
*/
function testRecentCommentBlock() {
public function testRecentCommentBlock() {
$this->drupalLogin($this->adminUser);
$block = $this->drupalPlaceBlock('views_block:comments_recent-block_1');
@ -54,10 +54,10 @@ class CommentBlockTest extends CommentTestBase {
// Test that a user without the 'access comments' permission cannot see the
// block.
$this->drupalLogout();
user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
$this->drupalGet('');
$this->assertNoText(t('Recent comments'));
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
// Test that a user with the 'access comments' permission can see the
// block.
@ -68,11 +68,11 @@ class CommentBlockTest extends CommentTestBase {
// Test the only the 10 latest comments are shown and in the proper order.
$this->assertNoText($comments[10]->getSubject(), 'Comment 11 not found in block.');
for ($i = 0; $i < 10; $i++) {
$this->assertText($comments[$i]->getSubject(), SafeMarkup::format('Comment @number found in block.', array('@number' => 10 - $i)));
$this->assertText($comments[$i]->getSubject(), SafeMarkup::format('Comment @number found in block.', ['@number' => 10 - $i]));
if ($i > 1) {
$previous_position = $position;
$position = strpos($this->getRawContent(), $comments[$i]->getSubject());
$this->assertTrue($position > $previous_position, SafeMarkup::format('Comment @a appears after comment @b', array('@a' => 10 - $i, '@b' => 11 - $i)));
$this->assertTrue($position > $previous_position, SafeMarkup::format('Comment @a appears after comment @b', ['@a' => 10 - $i, '@b' => 11 - $i]));
}
$position = strpos($this->getRawContent(), $comments[$i]->getSubject());
}

View file

@ -21,7 +21,7 @@ class CommentBookTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('book', 'comment');
public static $modules = ['book', 'comment'];
protected function setUp() {
parent::setUp();
@ -44,17 +44,17 @@ class CommentBookTest extends WebTestBase {
$comment_subject = $this->randomMachineName(8);
$comment_body = $this->randomMachineName(8);
$comment = Comment::create(array(
$comment = Comment::create([
'subject' => $comment_subject,
'comment_body' => $comment_body,
'entity_id' => $book_node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
));
]);
$comment->save();
$commenting_user = $this->drupalCreateUser(array('access printer-friendly version', 'access comments', 'post comments'));
$commenting_user = $this->drupalCreateUser(['access printer-friendly version', 'access comments', 'post comments']);
$this->drupalLogin($commenting_user);
$this->drupalGet('node/' . $book_node->id());

View file

@ -18,32 +18,32 @@ class CommentCSSTest extends CommentTestBase {
parent::setUp();
// Allow anonymous users to see comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'access content'
));
]);
}
/**
* Tests CSS classes on comments.
*/
function testCommentClasses() {
public function testCommentClasses() {
// Create all permutations for comments, users, and nodes.
$parameters = array(
'node_uid' => array(0, $this->webUser->id()),
'comment_uid' => array(0, $this->webUser->id(), $this->adminUser->id()),
'comment_status' => array(CommentInterface::PUBLISHED, CommentInterface::NOT_PUBLISHED),
'user' => array('anonymous', 'authenticated', 'admin'),
);
$parameters = [
'node_uid' => [0, $this->webUser->id()],
'comment_uid' => [0, $this->webUser->id(), $this->adminUser->id()],
'comment_status' => [CommentInterface::PUBLISHED, CommentInterface::NOT_PUBLISHED],
'user' => ['anonymous', 'authenticated', 'admin'],
];
$permutations = $this->generatePermutations($parameters);
foreach ($permutations as $case) {
// Create a new node.
$node = $this->drupalCreateNode(array('type' => 'article', 'uid' => $case['node_uid']));
$node = $this->drupalCreateNode(['type' => 'article', 'uid' => $case['node_uid']]);
// Add a comment.
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create(array(
$comment = Comment::create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
@ -51,8 +51,8 @@ class CommentCSSTest extends CommentTestBase {
'status' => $case['comment_status'],
'subject' => $this->randomMachineName(),
'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => array(LanguageInterface::LANGCODE_NOT_SPECIFIED => array($this->randomMachineName())),
));
'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
]);
$comment->save();
// Adjust the current/viewing user.

View file

@ -24,7 +24,7 @@ class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('comment');
public static $modules = ['comment'];
/**
* @var \Drupal\entity_test\Entity\EntityTest
@ -66,24 +66,24 @@ class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase {
$field->save();
// Create a "Camelids" test entity that the comment will be assigned to.
$this->entityTestCamelid = EntityTest::create(array(
$this->entityTestCamelid = EntityTest::create([
'name' => 'Camelids',
'type' => 'bar',
));
]);
$this->entityTestCamelid->save();
// Create a "Llama" comment.
$comment = Comment::create(array(
$comment = Comment::create([
'subject' => 'Llama',
'comment_body' => array(
'comment_body' => [
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
),
],
'entity_id' => $this->entityTestCamelid->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
));
]);
$comment->save();
return $comment;
@ -97,26 +97,26 @@ class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase {
$this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'HIT');
// Create a "Hippopotamus" comment.
$this->entityTestHippopotamidae = EntityTest::create(array(
$this->entityTestHippopotamidae = EntityTest::create([
'name' => 'Hippopotamus',
'type' => 'bar',
));
]);
$this->entityTestHippopotamidae->save();
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'MISS');
$this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'HIT');
$hippo_comment = Comment::create(array(
$hippo_comment = Comment::create([
'subject' => 'Hippopotamus',
'comment_body' => array(
'comment_body' => [
'value' => 'The common hippopotamus (Hippopotamus amphibius), or hippo, is a large, mostly herbivorous mammal in sub-Saharan Africa',
'format' => 'plain_text',
),
],
'entity_id' => $this->entityTestHippopotamidae->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
));
]);
$hippo_comment->save();
// Ensure that a new comment only invalidates the commented entity.
@ -145,11 +145,11 @@ class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase {
*/
protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) {
/** @var \Drupal\comment\CommentInterface $entity */
return array(
return [
'config:filter.format.plain_text',
'user:' . $entity->getOwnerId(),
'user_view',
);
];
}
}

View file

@ -19,15 +19,15 @@ class CommentFieldsTest extends CommentTestBase {
*
* @var array
*/
public static $modules = array('field_ui');
public static $modules = ['field_ui'];
/**
* Tests that the default 'comment_body' field is correctly added.
*/
function testCommentDefaultFields() {
public function testCommentDefaultFields() {
// Do not make assumptions on default node types created by the test
// installation profile, and create our own.
$this->drupalCreateContentType(array('type' => 'test_node_type'));
$this->drupalCreateContentType(['type' => 'test_node_type']);
$this->addDefaultCommentField('node', 'test_node_type');
// Check that the 'comment_body' field is present on the comment bundle.
@ -43,7 +43,7 @@ class CommentFieldsTest extends CommentTestBase {
// Create a new content type.
$type_name = 'test_node_type_2';
$this->drupalCreateContentType(array('type' => $type_name));
$this->drupalCreateContentType(['type' => $type_name]);
$this->addDefaultCommentField('node', $type_name);
// Check that the 'comment_body' field exists and has an instance on the
@ -51,7 +51,7 @@ class CommentFieldsTest extends CommentTestBase {
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertTrue($field_storage, 'The comment_body field exists');
$field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
$this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', array('@type' => $type_name)));
$this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', ['@type' => $type_name]));
// Test adding a field that defaults to CommentItemInterface::CLOSED.
$this->addDefaultCommentField('node', 'test_node_type', 'who_likes_ponies', CommentItemInterface::CLOSED, 'who_likes_ponies');
@ -63,7 +63,7 @@ class CommentFieldsTest extends CommentTestBase {
* Tests that you can remove a comment field.
*/
public function testCommentFieldDelete() {
$this->drupalCreateContentType(array('type' => 'test_node_type'));
$this->drupalCreateContentType(['type' => 'test_node_type']);
$this->addDefaultCommentField('node', 'test_node_type');
// We want to test the handling of removing the primary comment field, so we
// ensure there is at least one other comment field attached to a node type
@ -71,10 +71,10 @@ class CommentFieldsTest extends CommentTestBase {
$this->addDefaultCommentField('node', 'test_node_type', 'comment2');
// Create a sample node.
$node = $this->drupalCreateNode(array(
$node = $this->drupalCreateNode([
'title' => 'Baloney',
'type' => 'test_node_type',
));
]);
$this->drupalLogin($this->webUser);
@ -143,38 +143,38 @@ class CommentFieldsTest extends CommentTestBase {
*/
public function testCommentFieldCreate() {
// Create user who can administer user fields.
$user = $this->drupalCreateUser(array(
$user = $this->drupalCreateUser([
'administer user fields',
));
]);
$this->drupalLogin($user);
// Create comment field in account settings.
$edit = array(
$edit = [
'new_storage_type' => 'comment',
'label' => 'User comment',
'field_name' => 'user_comment',
);
];
$this->drupalPostForm('admin/config/people/accounts/fields/add-field', $edit, 'Save and continue');
// Try to save the comment field without selecting a comment type.
$edit = array();
$edit = [];
$this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings'));
// We should get an error message.
$this->assertText(t('An illegal choice has been detected. Please contact the site administrator.'));
// Create a comment type for users.
$bundle = CommentType::create(array(
$bundle = CommentType::create([
'id' => 'user_comment_type',
'label' => 'user_comment_type',
'description' => '',
'target_entity_type_id' => 'user',
));
]);
$bundle->save();
// Select a comment type and try to save again.
$edit = array(
$edit = [
'settings[comment_type]' => 'user_comment_type',
);
];
$this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings'));
// We shouldn't get an error message.
$this->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));
@ -183,9 +183,9 @@ class CommentFieldsTest extends CommentTestBase {
/**
* Tests that comment module works when installed after a content module.
*/
function testCommentInstallAfterContentModule() {
public function testCommentInstallAfterContentModule() {
// Create a user to do module administration.
$this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
$this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer modules']);
$this->drupalLogin($this->adminUser);
// Drop default comment field added in CommentTestBase::setup().
@ -199,35 +199,35 @@ class CommentFieldsTest extends CommentTestBase {
field_purge_batch(10);
// Uninstall the comment module.
$edit = array();
$edit = [];
$edit['uninstall[comment]'] = TRUE;
$this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
$this->drupalPostForm(NULL, array(), t('Uninstall'));
$this->drupalPostForm(NULL, [], t('Uninstall'));
$this->rebuildContainer();
$this->assertFalse($this->container->get('module_handler')->moduleExists('comment'), 'Comment module uninstalled.');
// Install core content type module (book).
$edit = array();
$edit['modules[Core][book][enable]'] = 'book';
$edit = [];
$edit['modules[book][enable]'] = 'book';
$this->drupalPostForm('admin/modules', $edit, t('Install'));
// Now install the comment module.
$edit = array();
$edit['modules[Core][comment][enable]'] = 'comment';
$edit = [];
$edit['modules[comment][enable]'] = 'comment';
$this->drupalPostForm('admin/modules', $edit, t('Install'));
$this->rebuildContainer();
$this->assertTrue($this->container->get('module_handler')->moduleExists('comment'), 'Comment module enabled.');
// Create nodes of each type.
$this->addDefaultCommentField('node', 'book');
$book_node = $this->drupalCreateNode(array('type' => 'book'));
$book_node = $this->drupalCreateNode(['type' => 'book']);
$this->drupalLogout();
// Try to post a comment on each node. A failure will be triggered if the
// comment body is missing on one of these forms, due to postComment()
// asserting that the body is actually posted correctly.
$this->webUser = $this->drupalCreateUser(array('access content', 'access comments', 'post comments', 'skip comment approval'));
$this->webUser = $this->drupalCreateUser(['access content', 'access comments', 'post comments', 'skip comment approval']);
$this->drupalLogin($this->webUser);
$this->postComment($book_node, $this->randomMachineName(), $this->randomMachineName());
}

View file

@ -68,7 +68,7 @@ class CommentInterfaceTest extends CommentTestBase {
// Comment as anonymous with preview required.
$this->drupalLogout();
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access content', 'access comments', 'post comments', 'skip comment approval'));
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access content', 'access comments', 'post comments', 'skip comment approval']);
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($anonymous_comment), 'Comment found.');
$anonymous_comment->delete();
@ -92,24 +92,24 @@ class CommentInterfaceTest extends CommentTestBase {
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->drupalGet('comment/' . $comment->id() . '/edit');
$this->assertTitle(t('Edit comment @title | Drupal', array(
$this->assertTitle(t('Edit comment @title | Drupal', [
'@title' => $comment->getSubject(),
)));
]));
// Test changing the comment author to "Anonymous".
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('uid' => ''));
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => '']);
$this->assertTrue($comment->getAuthorName() == t('Anonymous') && $comment->getOwnerId() == 0, 'Comment author successfully changed to anonymous.');
// Test changing the comment author to an unverified user.
$random_name = $this->randomMachineName();
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('name' => $random_name));
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['name' => $random_name]);
$this->drupalGet('node/' . $this->node->id());
$this->assertText($random_name . ' (' . t('not verified') . ')', 'Comment author successfully changed to an unverified user.');
// Test changing the comment author to a verified user.
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('uid' => $this->webUser->getUsername() . ' (' . $this->webUser->id() . ')'));
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => $this->webUser->getUsername() . ' (' . $this->webUser->id() . ')']);
$this->assertTrue($comment->getAuthorName() == $this->webUser->getUsername() && $comment->getOwnerId() == $this->webUser->id(), 'Comment author successfully changed to a registered user.');
$this->drupalLogout();
@ -121,7 +121,7 @@ class CommentInterfaceTest extends CommentTestBase {
// \Drupal\comment\Controller\CommentController::redirectNode().
$this->drupalGet('comment/' . $this->node->id() . '/reply');
// Verify we were correctly redirected.
$this->assertUrl(\Drupal::url('comment.reply', array('entity_type' => 'node', 'entity' => $this->node->id(), 'field_name' => 'comment'), array('absolute' => TRUE)));
$this->assertUrl(\Drupal::url('comment.reply', ['entity_type' => 'node', 'entity' => $this->node->id(), 'field_name' => 'comment'], ['absolute' => TRUE]));
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment->id());
$this->assertText($subject_text, 'Individual comment-reply subject found.');
$this->assertText($comment_text, 'Individual comment-reply body found.');
@ -161,7 +161,7 @@ class CommentInterfaceTest extends CommentTestBase {
$this->setCommentsPerPage(2);
$comment_new_page = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->assertTrue($this->commentExists($comment_new_page), 'Page one exists. %s');
$this->drupalGet('node/' . $this->node->id(), array('query' => array('page' => 2)));
$this->drupalGet('node/' . $this->node->id(), ['query' => ['page' => 2]]);
$this->assertTrue($this->commentExists($reply, TRUE), 'Page two exists. %s');
$this->setCommentsPerPage(50);
@ -172,21 +172,21 @@ class CommentInterfaceTest extends CommentTestBase {
$this->assertResponse(403);
// Attempt to post to node with comments disabled.
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::HIDDEN))));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::HIDDEN]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
$this->assertNoField('edit-comment', 'Comment body field found.');
// Attempt to post to node with read-only comments.
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::CLOSED))));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::CLOSED]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertResponse(403);
$this->assertNoField('edit-comment', 'Comment body field found.');
// Attempt to post to node with comments enabled (check field names etc).
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::OPEN))));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::OPEN]]]);
$this->assertTrue($this->node, 'Article node created.');
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertNoText('This discussion is closed', 'Posting to node with comments enabled');
@ -254,17 +254,17 @@ class CommentInterfaceTest extends CommentTestBase {
// can select one of them. Then create a user that can use these formats,
// log the user in, and then GET the node page on which to test the
// comments.
$filtered_html_format = FilterFormat::create(array(
$filtered_html_format = FilterFormat::create([
'format' => 'filtered_html',
'name' => 'Filtered HTML',
));
]);
$filtered_html_format->save();
$full_html_format = FilterFormat::create(array(
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
));
]);
$full_html_format->save();
$html_user = $this->drupalCreateUser(array(
$html_user = $this->drupalCreateUser([
'access comments',
'post comments',
'edit own comments',
@ -272,25 +272,25 @@ class CommentInterfaceTest extends CommentTestBase {
'access content',
$filtered_html_format->getPermissionName(),
$full_html_format->getPermissionName(),
));
]);
$this->drupalLogin($html_user);
$this->drupalGet('node/' . $this->node->id());
// HTML should not be included in the character count.
$body_text1 = '<span></span><strong> </strong><span> </span><strong></strong>Hello World<br />';
$edit1 = array(
$edit1 = [
'comment_body[0][value]' => $body_text1,
'comment_body[0][format]' => 'filtered_html',
);
];
$this->drupalPostForm(NULL, $edit1, t('Save'));
$this->assertEqual('Hello World', Comment::load(1)->getSubject());
// If there's nothing other than HTML, the subject should be '(No subject)'.
$body_text2 = '<span></span><strong> </strong><span> </span><strong></strong> <br />';
$edit2 = array(
$edit2 = [
'comment_body[0][value]' => $body_text2,
'comment_body[0][format]' => 'filtered_html',
);
];
$this->drupalPostForm(NULL, $edit2, t('Save'));
$this->assertEqual('(No subject)', Comment::load(2)->getSubject());
}

View file

@ -25,23 +25,23 @@ class CommentLanguageTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'language', 'language_test', 'comment_test');
public static $modules = ['node', 'language', 'language_test', 'comment_test'];
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
// Create and log in user.
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval'));
$admin_user = $this->drupalCreateUser(['administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval']);
$this->drupalLogin($admin_user);
// Add language.
$edit = array('predefined_langcode' => 'fr');
$edit = ['predefined_langcode' => 'fr'];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Set "Article" content type to use multilingual support.
$edit = array('language_configuration[language_alterable]' => TRUE);
$edit = ['language_configuration[language_alterable]' => TRUE];
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Enable content language negotiation UI.
@ -51,16 +51,16 @@ class CommentLanguageTest extends WebTestBase {
// to URL. Disable inheritance from interface language to ensure content
// language will fall back to the default language if no URL language can be
// detected.
$edit = array(
$edit = [
'language_interface[enabled][language-user]' => TRUE,
'language_content[enabled][language-url]' => TRUE,
'language_content[enabled][language-interface]' => FALSE,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Change user language preference, this way interface language is always
// French no matter what path prefix the URLs have.
$edit = array('preferred_langcode' => 'fr');
$edit = ['preferred_langcode' => 'fr'];
$this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save'));
// Create comment field on article.
@ -76,7 +76,7 @@ class CommentLanguageTest extends WebTestBase {
/**
* Test that comment language is properly set.
*/
function testCommentLanguage() {
public function testCommentLanguage() {
// Create two nodes, one for english and one for french, and comment each
// node using both english and french as content language by changing URL
@ -87,12 +87,12 @@ class CommentLanguageTest extends WebTestBase {
foreach ($this->container->get('language_manager')->getLanguages() as $node_langcode => $node_language) {
// Create "Article" content.
$title = $this->randomMachineName();
$edit = array(
$edit = [
'title[0][value]' => $title,
'body[0][value]' => $this->randomMachineName(),
'langcode[0][value]' => $node_langcode,
'comment[0][status]' => CommentItemInterface::OPEN,
);
];
$this->drupalPostForm("node/add/article", $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($title);
@ -101,10 +101,10 @@ class CommentLanguageTest extends WebTestBase {
// Post a comment with content language $langcode.
$prefix = empty($prefixes[$langcode]) ? '' : $prefixes[$langcode] . '/';
$comment_values[$node_langcode][$langcode] = $this->randomMachineName();
$edit = array(
$edit = [
'subject[0][value]' => $this->randomMachineName(),
'comment_body[0][value]' => $comment_values[$node_langcode][$langcode],
);
];
$this->drupalPostForm($prefix . 'node/' . $node->id(), $edit, t('Preview'));
$this->drupalPostForm(NULL, $edit, t('Save'));
@ -117,7 +117,7 @@ class CommentLanguageTest extends WebTestBase {
->range(0, 1)
->execute();
$comment = Comment::load(reset($cids));
$args = array('%node_language' => $node_langcode, '%comment_language' => $comment->langcode->value, '%langcode' => $langcode);
$args = ['%node_language' => $node_langcode, '%comment_language' => $comment->langcode->value, '%langcode' => $langcode];
$this->assertEqual($comment->langcode->value, $langcode, format_string('The comment posted with content language %langcode and belonging to the node with language %node_language has language %comment_language', $args));
$this->assertEqual($comment->comment_body->value, $comment_values[$node_langcode][$langcode], 'Comment body correctly stored.');
}

View file

@ -9,7 +9,7 @@ namespace Drupal\comment\Tests;
*/
class CommentLinksAlterTest extends CommentTestBase {
public static $modules = array('comment_test');
public static $modules = ['comment_test'];
protected function setUp() {
parent::setUp();

View file

@ -27,7 +27,7 @@ class CommentLinksTest extends CommentTestBase {
*
* @var array
*/
protected $seen = array();
protected $seen = [];
/**
* Use the main node listing to test rendering on teasers.
@ -36,14 +36,14 @@ class CommentLinksTest extends CommentTestBase {
*
* @todo Remove this dependency.
*/
public static $modules = array('views');
public static $modules = ['views'];
/**
* Tests that comment links are output and can be hidden.
*/
public function testCommentLinks() {
// Bartik theme alters comment links, so use a different theme.
\Drupal::service('theme_handler')->install(array('stark'));
\Drupal::service('theme_handler')->install(['stark']);
$this->config('system.theme')
->set('default', 'stark')
->save();
@ -51,11 +51,11 @@ class CommentLinksTest extends CommentTestBase {
// Remove additional user permissions from $this->webUser added by setUp(),
// since this test is limited to anonymous and authenticated roles only.
$roles = $this->webUser->getRoles();
entity_delete_multiple('user_role', array(reset($roles)));
entity_delete_multiple('user_role', [reset($roles)]);
// Create a comment via CRUD API functionality, since
// $this->postComment() relies on actual user permissions.
$comment = Comment::create(array(
$comment = Comment::create([
'cid' => NULL,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
@ -66,8 +66,8 @@ class CommentLinksTest extends CommentTestBase {
'subject' => $this->randomMachineName(),
'hostname' => '127.0.0.1',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => array(array('value' => $this->randomMachineName())),
));
'comment_body' => [['value' => $this->randomMachineName()]],
]);
$comment->save();
$this->comment = $comment;
@ -78,19 +78,19 @@ class CommentLinksTest extends CommentTestBase {
$this->node->save();
// Change user permissions.
$perms = array(
$perms = [
'access comments' => 1,
'post comments' => 1,
'skip comment approval' => 1,
'edit own comments' => 1,
);
];
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, $perms);
$nid = $this->node->id();
// Assert basic link is output, actual functionality is unit-tested in
// \Drupal\comment\Tests\CommentLinkBuilderTest.
foreach (array('node', "node/$nid") as $path) {
foreach (['node', "node/$nid"] as $path) {
$this->drupalGet($path);
// In teaser view, a link containing the comment count is always
@ -103,7 +103,7 @@ class CommentLinksTest extends CommentTestBase {
// Change weight to make links go before comment body.
entity_get_display('comment', 'comment', 'default')
->setComponent('links', array('weight' => -100))
->setComponent('links', ['weight' => -100])
->save();
$this->drupalGet($this->node->urlInfo());
$element = $this->cssSelect('article.js-comment > div');
@ -113,7 +113,7 @@ class CommentLinksTest extends CommentTestBase {
// Change weight to make links go after comment body.
entity_get_display('comment', 'comment', 'default')
->setComponent('links', array('weight' => 100))
->setComponent('links', ['weight' => 100])
->save();
$this->drupalGet($this->node->urlInfo());
$element = $this->cssSelect('article.js-comment > div');

View file

@ -22,7 +22,7 @@ class CommentNewIndicatorTest extends CommentTestBase {
*
* @todo Remove this dependency.
*/
public static $modules = array('views');
public static $modules = ['views'];
/**
* Get node "x new comments" metadata from the server for the current user.
@ -35,7 +35,7 @@ class CommentNewIndicatorTest extends CommentTestBase {
*/
protected function renderNewCommentsNodeLinks(array $node_ids) {
// Build POST values.
$post = array();
$post = [];
for ($i = 0; $i < count($node_ids); $i++) {
$post['node_ids[' . $i . ']'] = $node_ids[$i];
}
@ -51,15 +51,15 @@ class CommentNewIndicatorTest extends CommentTestBase {
$post = implode('&', $post);
// Perform HTTP request.
return $this->curlExec(array(
CURLOPT_URL => \Drupal::url('comment.new_comments_node_links', array(), array('absolute' => TRUE)),
return $this->curlExec([
CURLOPT_URL => \Drupal::url('comment.new_comments_node_links', [], ['absolute' => TRUE]),
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => array(
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
));
],
]);
}
/**
@ -70,7 +70,7 @@ class CommentNewIndicatorTest extends CommentTestBase {
// node.
$this->drupalLogin($this->adminUser);
$this->drupalGet('node');
$this->assertNoLink(t('@count comments', array('@count' => 0)));
$this->assertNoLink(t('@count comments', ['@count' => 0]));
$this->assertLink(t('Read more'));
// Verify the data-history-node-last-comment-timestamp attribute, which is
// used by the drupal.node-new-comments-link library to determine whether
@ -81,7 +81,7 @@ class CommentNewIndicatorTest extends CommentTestBase {
// Create a new comment. This helper function may be run with different
// comment settings so use $comment->save() to avoid complex setup.
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create(array(
$comment = Comment::create([
'cid' => NULL,
'entity_id' => $this->node->id(),
'entity_type' => 'node',
@ -92,8 +92,8 @@ class CommentNewIndicatorTest extends CommentTestBase {
'subject' => $this->randomMachineName(),
'hostname' => '127.0.0.1',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'comment_body' => array(LanguageInterface::LANGCODE_NOT_SPECIFIED => array($this->randomMachineName())),
));
'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
]);
$comment->save();
$this->drupalLogout();
@ -126,24 +126,24 @@ class CommentNewIndicatorTest extends CommentTestBase {
]);
// Pretend the data was not present in drupalSettings, i.e. test the
// separate request to the server.
$response = $this->renderNewCommentsNodeLinks(array($this->node->id()));
$response = $this->renderNewCommentsNodeLinks([$this->node->id()]);
$this->assertResponse(200);
$json = Json::decode($response);
$expected = array($this->node->id() => array(
$expected = [$this->node->id() => [
'new_comment_count' => 1,
'first_new_comment_link' => $this->node->url('canonical', array('fragment' => 'new')),
));
'first_new_comment_link' => $this->node->url('canonical', ['fragment' => 'new']),
]];
$this->assertIdentical($expected, $json);
// Failing to specify node IDs for the endpoint should return a 404.
$this->renderNewCommentsNodeLinks(array());
$this->renderNewCommentsNodeLinks([]);
$this->assertResponse(404);
// Accessing the endpoint as the anonymous user should return a 403.
$this->drupalLogout();
$this->renderNewCommentsNodeLinks(array($this->node->id()));
$this->renderNewCommentsNodeLinks([$this->node->id()]);
$this->assertResponse(403);
$this->renderNewCommentsNodeLinks(array());
$this->renderNewCommentsNodeLinks([]);
$this->assertResponse(403);
}

View file

@ -19,7 +19,7 @@ class CommentNodeAccessTest extends CommentTestBase {
*
* @var array
*/
public static $modules = array('node_access_test');
public static $modules = ['node_access_test'];
protected function setUp() {
parent::setUp();
@ -27,14 +27,14 @@ class CommentNodeAccessTest extends CommentTestBase {
node_access_rebuild();
// Re-create user.
$this->webUser = $this->drupalCreateUser(array(
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'edit own comments',
'node test view',
'skip comment approval',
));
]);
// Set the author of the created node to the web_user uid.
$this->node->setOwnerId($this->webUser->id())->save();
@ -43,7 +43,7 @@ class CommentNodeAccessTest extends CommentTestBase {
/**
* Test that threaded comments can be viewed.
*/
function testThreadedCommentView() {
public function testThreadedCommentView() {
// Set comments to have subject required and preview disabled.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_DISABLED);

View file

@ -16,7 +16,7 @@ class CommentNodeChangesTest extends CommentTestBase {
/**
* Tests that comments are deleted with the node.
*/
function testNodeDeletion() {
public function testNodeDeletion() {
$this->drupalLogin($this->webUser);
$comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
$this->assertTrue($comment->id(), 'The comment could be loaded.');
@ -27,7 +27,7 @@ class CommentNodeChangesTest extends CommentTestBase {
$this->assertNotNull(FieldStorageConfig::load('node.comment'), 'Comment field storage exists');
$this->assertNotNull(FieldConfig::load('node.article.comment'), 'Comment field exists');
// Delete the node type.
entity_delete_multiple('node_type', array($this->node->bundle()));
entity_delete_multiple('node_type', [$this->node->bundle()]);
$this->assertNull(FieldStorageConfig::load('node.comment'), 'Comment field storage deleted');
$this->assertNull(FieldConfig::load('node.article.comment'), 'Comment field deleted');
}

View file

@ -24,7 +24,7 @@ class CommentNonNodeTest extends WebTestBase {
use FieldUiTestTrait;
use CommentTestTrait;
public static $modules = array('comment', 'user', 'field_ui', 'entity_test', 'block');
public static $modules = ['comment', 'user', 'field_ui', 'entity_test', 'block'];
/**
* An administrative user with permission to configure comment settings.
@ -50,12 +50,12 @@ class CommentNonNodeTest extends WebTestBase {
// Create a bundle for entity_test.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test');
CommentType::create(array(
CommentType::create([
'id' => 'comment',
'label' => 'Comment settings',
'description' => 'Comment settings',
'target_entity_type_id' => 'entity_test',
))->save();
])->save();
// Create comment field on entity_test bundle.
$this->addDefaultCommentField('entity_test', 'entity_test');
@ -64,30 +64,30 @@ class CommentNonNodeTest extends WebTestBase {
$this->assertEqual($bundles['comment']['label'], 'Comment settings');
// Create test user.
$this->adminUser = $this->drupalCreateUser(array(
$this->adminUser = $this->drupalCreateUser([
'administer comments',
'skip comment approval',
'post comments',
'access comments',
'view test entity',
'administer entity_test content',
));
]);
// Enable anonymous and authenticated user comments.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments',
'post comments',
'skip comment approval',
));
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array(
]);
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [
'access comments',
'post comments',
'skip comment approval',
));
]);
// Create a test entity.
$random_label = $this->randomMachineName();
$data = array('type' => 'entity_test', 'name' => $random_label);
$data = ['type' => 'entity_test', 'name' => $random_label];
$this->entity = EntityTest::create($data);
$this->entity->save();
}
@ -108,8 +108,8 @@ class CommentNonNodeTest extends WebTestBase {
* @return \Drupal\comment\CommentInterface
* The new comment entity.
*/
function postComment(EntityInterface $entity, $comment, $subject = '', $contact = NULL) {
$edit = array();
public function postComment(EntityInterface $entity, $comment, $subject = '', $contact = NULL) {
$edit = [];
$edit['comment_body[0][value]'] = $comment;
$field = FieldConfig::loadByName('entity_test', 'entity_test', 'comment');
@ -151,7 +151,7 @@ class CommentNonNodeTest extends WebTestBase {
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
}
$match = array();
$match = [];
// Get comment ID
preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
@ -180,7 +180,7 @@ class CommentNonNodeTest extends WebTestBase {
* @return bool
* Boolean indicating whether the comment was found.
*/
function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
public function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
if ($comment) {
$regex = '/' . ($reply ? '<div class="indented">(.*?)' : '');
$regex .= '<a id="comment-' . $comment->id() . '"(.*?)';
@ -201,7 +201,7 @@ class CommentNonNodeTest extends WebTestBase {
* @return bool
* Contact info is available.
*/
function commentContactInfoAvailable() {
public function commentContactInfoAvailable() {
return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->getRawContent());
}
@ -215,18 +215,18 @@ class CommentNonNodeTest extends WebTestBase {
* @param bool $approval
* Operation is found on approval page.
*/
function performCommentOperation($comment, $operation, $approval = FALSE) {
$edit = array();
public function performCommentOperation($comment, $operation, $approval = FALSE) {
$edit = [];
$edit['operation'] = $operation;
$edit['comments[' . $comment->id() . ']'] = TRUE;
$this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
if ($operation == 'delete') {
$this->drupalPostForm(NULL, array(), t('Delete comments'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation)));
$this->drupalPostForm(NULL, [], t('Delete comments'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
else {
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation)));
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
}
@ -239,7 +239,7 @@ class CommentNonNodeTest extends WebTestBase {
* @return int
* Comment ID.
*/
function getUnapprovedComment($subject) {
public function getUnapprovedComment($subject) {
$this->drupalGet('admin/content/comment/approval');
preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->getRawContent(), $match);
@ -249,10 +249,10 @@ class CommentNonNodeTest extends WebTestBase {
/**
* Tests anonymous comment functionality.
*/
function testCommentFunctionality() {
$limited_user = $this->drupalCreateUser(array(
public function testCommentFunctionality() {
$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');
@ -320,9 +320,9 @@ class CommentNonNodeTest extends WebTestBase {
// Check that entity access applies to administrative page.
$this->assertText($this->entity->label(), 'Name of commented account found.');
$limited_user = $this->drupalCreateUser(array(
$limited_user = $this->drupalCreateUser([
'administer comments',
));
]);
$this->drupalLogin($limited_user);
$this->drupalGet('admin/content/comment');
$this->assertNoText($this->entity->label(), 'No commented account name found.');
@ -330,12 +330,12 @@ class CommentNonNodeTest extends WebTestBase {
$this->drupalLogout();
// Deny anonymous users access to comments.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => FALSE,
'skip comment approval' => FALSE,
'view test entity' => TRUE,
));
]);
// Attempt to view comments while disallowed.
$this->drupalGet('entity-test/' . $this->entity->id());
@ -348,12 +348,12 @@ class CommentNonNodeTest extends WebTestBase {
$this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.');
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field not found.');
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => FALSE,
'view test entity' => TRUE,
'skip comment approval' => FALSE,
));
]);
$this->drupalGet('entity_test/' . $this->entity->id());
$this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
$this->assertLink('Log in', 0, 'Link to login was found.');
@ -364,12 +364,12 @@ class CommentNonNodeTest extends WebTestBase {
// Test the combination of anonymous users being able to post, but not view
// comments, to ensure that access to post comments doesn't grant access to
// view them.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => FALSE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
'view test entity' => TRUE,
));
]);
$this->drupalGet('entity_test/' . $this->entity->id());
$this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
$this->assertFieldByName('subject[0][value]', '', 'Subject field found.');
@ -380,22 +380,22 @@ class CommentNonNodeTest extends WebTestBase {
$this->assertNoText($comment1->getSubject(), 'Comment not displayed.');
// Test comment field widget changes.
$limited_user = $this->drupalCreateUser(array(
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'view test entity',
'administer entity_test content',
'administer comments',
));
]);
$this->drupalLogin($limited_user);
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-1');
$this->assertFieldChecked('edit-default-value-input-comment-0-status-2');
// Test comment option change in field settings.
$edit = array(
$edit = [
'default_value_input[comment][0][status]' => CommentItemInterface::CLOSED,
'settings[anonymous]' => COMMENT_ANONYMOUS_MAY_CONTACT,
);
];
$this->drupalPostForm(NULL, $edit, t('Save settings'));
$this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment');
$this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0');
@ -404,18 +404,18 @@ class CommentNonNodeTest extends WebTestBase {
$this->assertFieldByName('settings[anonymous]', COMMENT_ANONYMOUS_MAY_CONTACT);
// Add a new comment-type.
$bundle = CommentType::create(array(
$bundle = CommentType::create([
'id' => 'foobar',
'label' => 'Foobar',
'description' => '',
'target_entity_type_id' => 'entity_test',
));
]);
$bundle->save();
// Add a new comment field.
$storage_edit = array(
$storage_edit = [
'settings[comment_type]' => 'foobar',
);
];
$this->fieldUIAddNewField('entity_test/structure/entity_test', 'foobar', 'Foobar', 'comment', $storage_edit);
// Add a third comment field.
@ -429,7 +429,7 @@ class CommentNonNodeTest extends WebTestBase {
// Test the new entity commenting inherits default.
$random_label = $this->randomMachineName();
$data = array('bundle' => 'entity_test', 'name' => $random_label);
$data = ['bundle' => 'entity_test', 'name' => $random_label];
$new_entity = EntityTest::create($data);
$new_entity->save();
$this->drupalGet('entity_test/manage/' . $new_entity->id() . '/edit');
@ -443,12 +443,12 @@ class CommentNonNodeTest extends WebTestBase {
$this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field found.');
// Test removal of comment_body field.
$limited_user = $this->drupalCreateUser(array(
$limited_user = $this->drupalCreateUser([
'administer entity_test fields',
'post comments',
'administer comment fields',
'administer comment types',
));
]);
$this->drupalLogin($limited_user);
$this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment');
@ -467,9 +467,9 @@ class CommentNonNodeTest extends WebTestBase {
public function testsNonIntegerIdEntities() {
// Create a bundle for entity_test_string_id.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_string_id');
$limited_user = $this->drupalCreateUser(array(
$limited_user = $this->drupalCreateUser([
'administer entity_test_string_id fields',
));
]);
$this->drupalLogin($limited_user);
// Visit the Field UI field add page.
$this->drupalGet('entity_test_string_id/structure/entity_test/fields/add-field');
@ -480,9 +480,9 @@ class CommentNonNodeTest extends WebTestBase {
// Create a bundle for entity_test_no_id.
entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_no_id');
$this->drupalLogin($this->drupalCreateUser(array(
$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.

View file

@ -15,7 +15,7 @@ class CommentPagerTest extends CommentTestBase {
/**
* Confirms comment paging works correctly with flat and threaded comments.
*/
function testCommentPaging() {
public function testCommentPaging() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
@ -24,8 +24,8 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentPreview(DRUPAL_DISABLED);
// Create a node and three comments.
$node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
$comments = array();
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
@ -45,13 +45,13 @@ class CommentPagerTest extends CommentTestBase {
$this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 1.');
// Check the second page.
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 1)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 1]]);
$this->assertTrue($this->commentExists($comments[1]), 'Comment 2 appears on page 2.');
$this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 2.');
$this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 2.');
// Check the third page.
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 2)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 2]]);
$this->assertTrue($this->commentExists($comments[2]), 'Comment 3 appears on page 3.');
$this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 3.');
$this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 3.');
@ -64,27 +64,27 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentsPerPage(2);
// We are still in flat view - the replies should not be on the first page,
// even though they are replies to the oldest comment.
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply, TRUE), 'In flat mode, reply does not appear on page 1.');
// If we switch to threaded mode, the replies on the oldest comment
// should be bumped to the first page and comment 6 should be bumped
// to the second page.
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertTrue($this->commentExists($reply, TRUE), 'In threaded mode, reply appears on page 1.');
$this->assertFalse($this->commentExists($comments[1]), 'In threaded mode, comment 2 has been bumped off of page 1.');
// If (# replies > # comments per page) in threaded expanded view,
// the overage should be bumped.
$reply2 = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply2, TRUE), 'In threaded mode where # replies > # comments per page, the newest reply does not appear on page 1.');
// Test that the page build process does not somehow generate errors when
// # comments per page is set to 0.
$this->setCommentsPerPage(0);
$this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0)));
$this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]);
$this->assertFalse($this->commentExists($reply2, TRUE), 'Threaded mode works correctly when comments per page is 0.');
$this->drupalLogout();
@ -93,7 +93,7 @@ class CommentPagerTest extends CommentTestBase {
/**
* Confirms comment paging works correctly with flat and threaded comments.
*/
function testCommentPermalink() {
public function testCommentPermalink() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
@ -102,8 +102,8 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentPreview(DRUPAL_DISABLED);
// Create a node and three comments.
$node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
$comments = array();
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, 'comment 1: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, 'comment 2: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, 'comment 3: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE);
@ -125,7 +125,7 @@ class CommentPagerTest extends CommentTestBase {
/**
* Tests comment ordering and threading.
*/
function testCommentOrderingThreading() {
public function testCommentOrderingThreading() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
@ -137,8 +137,8 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentsPerPage(1000);
// Create a node and three comments.
$node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
$comments = array();
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
@ -170,7 +170,7 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
$expected_order = array(
$expected_order = [
0,
1,
2,
@ -178,13 +178,13 @@ class CommentPagerTest extends CommentTestBase {
4,
5,
6,
);
];
$this->drupalGet('node/' . $node->id());
$this->assertCommentOrder($comments, $expected_order);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$expected_order = array(
$expected_order = [
0,
4,
1,
@ -192,7 +192,7 @@ class CommentPagerTest extends CommentTestBase {
6,
2,
5,
);
];
$this->drupalGet('node/' . $node->id());
$this->assertCommentOrder($comments, $expected_order);
}
@ -205,8 +205,8 @@ class CommentPagerTest extends CommentTestBase {
* @param array $expected_order
* An array of keys from $comments describing the expected order.
*/
function assertCommentOrder(array $comments, array $expected_order) {
$expected_cids = array();
public function assertCommentOrder(array $comments, array $expected_order) {
$expected_cids = [];
// First, rekey the expected order by cid.
foreach ($expected_order as $key) {
@ -214,17 +214,17 @@ class CommentPagerTest extends CommentTestBase {
}
$comment_anchors = $this->xpath('//a[starts-with(@id,"comment-")]');
$result_order = array();
$result_order = [];
foreach ($comment_anchors as $anchor) {
$result_order[] = substr($anchor['id'], 8);
}
return $this->assertEqual($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', array('@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order))));
return $this->assertEqual($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', ['@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order)]));
}
/**
* Tests calculation of first page with new comment.
*/
function testCommentNewPageIndicator() {
public function testCommentNewPageIndicator() {
$this->drupalLogin($this->adminUser);
// Set comment variables.
@ -237,8 +237,8 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentsPerPage(1);
// Create a node and three comments.
$node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
$comments = array();
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$comments = [];
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
$comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
@ -265,83 +265,83 @@ class CommentPagerTest extends CommentTestBase {
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.');
$expected_pages = array(
$expected_pages = [
1 => 5, // Page of comment 5
2 => 4, // Page of comment 4
3 => 3, // Page of comment 3
4 => 2, // Page of comment 2
5 => 1, // Page of comment 1
6 => 0, // Page of comment 0
);
];
$node = Node::load($node->id());
foreach ($expected_pages as $new_replies => $expected_page) {
$returned_page = \Drupal::entityManager()->getStorage('comment')
->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment');
$this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page)));
$this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page]));
}
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.');
$expected_pages = array(
$expected_pages = [
1 => 5, // Page of comment 5
2 => 1, // Page of comment 4
3 => 1, // Page of comment 4
4 => 1, // Page of comment 4
5 => 1, // Page of comment 4
6 => 0, // Page of comment 0
);
];
\Drupal::entityManager()->getStorage('node')->resetCache(array($node->id()));
\Drupal::entityManager()->getStorage('node')->resetCache([$node->id()]);
$node = Node::load($node->id());
foreach ($expected_pages as $new_replies => $expected_page) {
$returned_page = \Drupal::entityManager()->getStorage('comment')
->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment');
$this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page)));
$this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page]));
}
}
/**
* Confirms comment paging works correctly with two pagers.
*/
function testTwoPagers() {
public function testTwoPagers() {
// Add another field to article content-type.
$this->addDefaultCommentField('node', 'article', 'comment_2');
// Set default to display comment list with unique pager id.
entity_get_display('node', 'article', 'default')
->setComponent('comment_2', array(
->setComponent('comment_2', [
'label' => 'hidden',
'type' => 'comment_default',
'weight' => 30,
'settings' => array(
'settings' => [
'pager_id' => 1,
'view_mode' => 'default',
)
))
]
])
->save();
// Make sure pager appears in formatter summary and settings form.
$account = $this->drupalCreateUser(array('administer node display'));
$account = $this->drupalCreateUser(['administer node display']);
$this->drupalLogin($account);
$this->drupalGet('admin/structure/types/manage/article/display');
$this->assertNoText(t('Pager ID: @id', array('@id' => 0)), 'No summary for standard pager');
$this->assertText(t('Pager ID: @id', array('@id' => 1)));
$this->drupalPostAjaxForm(NULL, array(), 'comment_settings_edit');
$this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager');
$this->assertText(t('Pager ID: @id', ['@id' => 1]));
$this->drupalPostAjaxForm(NULL, [], 'comment_settings_edit');
// Change default pager to 2.
$this->drupalPostForm(NULL, array('fields[comment][settings_edit_form][settings][pager_id]' => 2), t('Save'));
$this->assertText(t('Pager ID: @id', array('@id' => 2)));
$this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 2], t('Save'));
$this->assertText(t('Pager ID: @id', ['@id' => 2]));
// Revert the changes.
$this->drupalPostAjaxForm(NULL, array(), 'comment_settings_edit');
$this->drupalPostForm(NULL, array('fields[comment][settings_edit_form][settings][pager_id]' => 0), t('Save'));
$this->assertNoText(t('Pager ID: @id', array('@id' => 0)), 'No summary for standard pager');
$this->drupalPostAjaxForm(NULL, [], 'comment_settings_edit');
$this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 0], t('Save'));
$this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager');
$this->drupalLogin($this->adminUser);
// Add a new node with both comment fields open.
$node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()));
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Set comment options.
$comments = array();
foreach (array('comment', 'comment_2') as $field_name) {
$comments = [];
foreach (['comment', 'comment_2'] as $field_name) {
$this->setCommentForm(TRUE, $field_name);
$this->setCommentPreview(DRUPAL_OPTIONAL, $field_name);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.', $field_name);
@ -350,10 +350,10 @@ class CommentPagerTest extends CommentTestBase {
// needing to insert large numbers of comments.
$this->setCommentsPerPage(1, $field_name);
for ($i = 0; $i < 3; $i++) {
$comment = t('Comment @count on field @field', array(
$comment = t('Comment @count on field @field', [
'@count' => $i + 1,
'@field' => $field_name,
));
]);
$comments[] = $this->postComment($node, $comment, $comment, TRUE, $field_name);
}
}
@ -365,19 +365,19 @@ class CommentPagerTest extends CommentTestBase {
$this->assertRaw('Comment 1 on field comment');
$this->assertRaw('Comment 1 on field comment_2');
// Navigate to next page of field 1.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment'));
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']);
// Check only one pager updated.
$this->assertRaw('Comment 2 on field comment');
$this->assertRaw('Comment 1 on field comment_2');
// Return to page 1.
$this->drupalGet('node/' . $node->id());
// Navigate to next page of field 2.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment_2'));
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment_2']);
// Check only one pager updated.
$this->assertRaw('Comment 1 on field comment');
$this->assertRaw('Comment 2 on field comment_2');
// Navigate to next page of field 1.
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment'));
$this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']);
// Check only one pager updated.
$this->assertRaw('Comment 2 on field comment');
$this->assertRaw('Comment 2 on field comment_2');
@ -405,15 +405,15 @@ class CommentPagerTest extends CommentTestBase {
*
* @see WebTestBase::clickLink()
*/
protected function clickLinkWithXPath($xpath, $arguments = array(), $index = 0) {
protected function clickLinkWithXPath($xpath, $arguments = [], $index = 0) {
$url_before = $this->getUrl();
$urls = $this->xpath($xpath, $arguments);
if (isset($urls[$index])) {
$url_target = $this->getAbsoluteUrl($urls[$index]['href']);
$this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', array('%label' => $xpath, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
$this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', ['%label' => $xpath, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
return $this->drupalGet($url_target);
}
$this->fail(SafeMarkup::format('Link %label does not exist on @url_before', array('%label' => $xpath, '@url_before' => $url_before)), 'Browser');
$this->fail(SafeMarkup::format('Link %label does not exist on @url_before', ['%label' => $xpath, '@url_before' => $url_before]), 'Browser');
return FALSE;
}

View file

@ -26,7 +26,7 @@ class CommentPreviewTest extends CommentTestBase {
/**
* Tests comment preview.
*/
function testCommentPreview() {
public function testCommentPreview() {
// As admin user, configure comment settings.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_OPTIONAL);
@ -41,7 +41,7 @@ class CommentPreviewTest extends CommentTestBase {
// Test escaping of the username on the preview form.
\Drupal::service('module_installer')->install(['user_hooks_test']);
\Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
$edit = array();
$edit = [];
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
@ -90,7 +90,7 @@ class CommentPreviewTest extends CommentTestBase {
$this->drupalLogin($this->webUser);
// As the web user, fill in the comment form and preview the comment.
$edit = array();
$edit = [];
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview'));
@ -123,15 +123,15 @@ class CommentPreviewTest extends CommentTestBase {
/**
* Tests comment edit, preview, and save.
*/
function testCommentEditPreviewSave() {
$web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'skip comment approval', 'edit own comments'));
public function testCommentEditPreviewSave() {
$web_user = $this->drupalCreateUser(['access comments', 'post comments', 'skip comment approval', 'edit own comments']);
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
$edit = array();
$edit = [];
$date = new DrupalDateTime('2008-03-02 17:23');
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
@ -172,7 +172,7 @@ class CommentPreviewTest extends CommentTestBase {
$this->assertFieldByName('date[time]', $expected_form_time, 'Time field displayed.');
// Submit the form using the displayed values.
$displayed = array();
$displayed = [];
$displayed['subject[0][value]'] = (string) current($this->xpath("//input[@id='edit-subject-0-value']/@value"));
$displayed['comment_body[0][value]'] = (string) current($this->xpath("//textarea[@id='edit-comment-body-0-value']"));
$displayed['uid'] = (string) current($this->xpath("//input[@id='edit-uid']/@value"));
@ -182,7 +182,7 @@ class CommentPreviewTest extends CommentTestBase {
// Check that the saved comment is still correct.
$comment_storage = \Drupal::entityManager()->getStorage('comment');
$comment_storage->resetCache(array($comment->id()));
$comment_storage->resetCache([$comment->id()]);
/** @var \Drupal\comment\CommentInterface $comment_loaded */
$comment_loaded = Comment::load($comment->id());
$this->assertEqual($comment_loaded->getSubject(), $edit['subject[0][value]'], 'Subject loaded.');
@ -193,13 +193,13 @@ class CommentPreviewTest extends CommentTestBase {
// Check that the date and time of the comment are correct when edited by
// non-admin users.
$user_edit = array();
$user_edit = [];
$expected_created_time = $comment_loaded->getCreatedTime();
$this->drupalLogin($web_user);
// Web user cannot change the comment author.
unset($edit['uid']);
$this->drupalPostForm('comment/' . $comment->id() . '/edit', $user_edit, t('Save'));
$comment_storage->resetCache(array($comment->id()));
$comment_storage->resetCache([$comment->id()]);
$comment_loaded = Comment::load($comment->id());
$this->assertEqual($comment_loaded->getCreatedTime(), $expected_created_time, 'Expected date and time for comment edited.');
$this->drupalLogout();

View file

@ -21,7 +21,7 @@ class CommentRssTest extends CommentTestBase {
*
* @var array
*/
public static $modules = array('views');
public static $modules = ['views'];
/**
* {@inheritdoc}
@ -42,7 +42,7 @@ class CommentRssTest extends CommentTestBase {
/**
* Tests comments as part of an RSS feed.
*/
function testCommentRss() {
public function testCommentRss() {
// Find comment in RSS feed.
$this->drupalLogin($this->webUser);
$this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
@ -66,7 +66,7 @@ class CommentRssTest extends CommentTestBase {
'user:3',
]));
$raw = '<comments>' . $this->node->url('canonical', array('fragment' => 'comments', 'absolute' => TRUE)) . '</comments>';
$raw = '<comments>' . $this->node->url('canonical', ['fragment' => 'comments', 'absolute' => TRUE]) . '</comments>';
$this->assertRaw($raw, 'Comments as part of RSS feed.');
// Hide comments from RSS feed and check presence.

View file

@ -24,7 +24,7 @@ class CommentStatisticsTest extends CommentTestBase {
parent::setUp();
// Create a second user to post comments.
$this->webUser2 = $this->drupalCreateUser(array(
$this->webUser2 = $this->drupalCreateUser([
'post comments',
'create article content',
'edit own comments',
@ -32,13 +32,13 @@ class CommentStatisticsTest extends CommentTestBase {
'skip comment approval',
'access comments',
'access content',
));
]);
}
/**
* Tests the node comment statistics.
*/
function testCommentNodeCommentStatistics() {
public function testCommentNodeCommentStatistics() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
// Set comments to have subject and preview disabled.
$this->drupalLogin($this->adminUser);
@ -62,7 +62,7 @@ class CommentStatisticsTest extends CommentTestBase {
// Checks the new values of node comment statistics with comment #1.
// The node cache needs to be reset before reload.
$node_storage->resetCache(array($this->node->id()));
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is NULL.');
$this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is the comment #1 uid.');
@ -70,11 +70,11 @@ class CommentStatisticsTest extends CommentTestBase {
// Prepare for anonymous comment submission (comment approval enabled).
$this->drupalLogin($this->adminUser);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => FALSE,
));
]);
// Ensure that the poster can leave some contact info.
$this->setCommentAnonymous('1');
$this->drupalLogout();
@ -86,7 +86,7 @@ class CommentStatisticsTest extends CommentTestBase {
// Checks the new values of node comment statistics with comment #2 and
// ensure they haven't changed since the comment has not been moderated.
// The node needs to be reloaded with the cache reset.
$node_storage->resetCache(array($this->node->id()));
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.');
$this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is still the comment #1 uid.');
@ -94,21 +94,21 @@ class CommentStatisticsTest extends CommentTestBase {
// Prepare for anonymous comment submission (no approval required).
$this->drupalLogin($this->adminUser);
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
));
]);
$this->drupalLogout();
// Post comment #3 as anonymous.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', array('name' => $this->randomMachineName()));
$anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', ['name' => $this->randomMachineName()]);
$comment_loaded = Comment::load($anonymous_comment->id());
// Checks the new values of node comment statistics with comment #3.
// The node needs to be reloaded with the cache reset.
$node_storage->resetCache(array($this->node->id()));
$node_storage->resetCache([$this->node->id()]);
$node = $node_storage->load($this->node->id());
$this->assertEqual($node->get('comment')->last_comment_name, $comment_loaded->getAuthorName(), 'The value of node last_comment_name is the name of the anonymous user.');
$this->assertEqual($node->get('comment')->last_comment_uid, 0, 'The value of node last_comment_uid is zero.');

View file

@ -52,11 +52,11 @@ abstract class CommentTestBase extends WebTestBase {
// child classes may specify the standard profile.
$types = NodeType::loadMultiple();
if (empty($types['article'])) {
$this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article')));
$this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
}
// Create two test users.
$this->adminUser = $this->drupalCreateUser(array(
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer comments',
'administer comment types',
@ -69,21 +69,21 @@ abstract class CommentTestBase extends WebTestBase {
// permission is granted.
'access user profiles',
'access content',
));
$this->webUser = $this->drupalCreateUser(array(
]);
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'edit own comments',
'skip comment approval',
'access content',
));
]);
// Create comment field on article.
$this->addDefaultCommentField('node', 'article');
// Create a test node authored by the web user.
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
$this->drupalPlaceBlock('local_tasks_block');
}
@ -107,7 +107,7 @@ abstract class CommentTestBase extends WebTestBase {
* The posted comment or NULL when posted comment was not found.
*/
public function postComment($entity, $comment, $subject = '', $contact = NULL, $field_name = 'comment') {
$edit = array();
$edit = [];
$edit['comment_body[0][value]'] = $comment;
if ($entity !== NULL) {
@ -154,7 +154,7 @@ abstract class CommentTestBase extends WebTestBase {
$this->drupalPostForm(NULL, $edit, t('Save'));
break;
}
$match = array();
$match = [];
// Get comment ID
preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
@ -168,7 +168,7 @@ abstract class CommentTestBase extends WebTestBase {
}
if (isset($match[1])) {
\Drupal::entityManager()->getStorage('comment')->resetCache(array($match[1]));
\Drupal::entityManager()->getStorage('comment')->resetCache([$match[1]]);
return Comment::load($match[1]);
}
}
@ -184,7 +184,7 @@ abstract class CommentTestBase extends WebTestBase {
* @return bool
* Boolean indicating whether the comment was found.
*/
function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
public function commentExists(CommentInterface $comment = NULL, $reply = FALSE) {
if ($comment) {
$comment_element = $this->cssSelect('.comment-wrapper ' . ($reply ? '.indented ' : '') . '#comment-' . $comment->id() . ' ~ article');
if (empty($comment_element)) {
@ -214,8 +214,8 @@ abstract class CommentTestBase extends WebTestBase {
* @param \Drupal\comment\CommentInterface $comment
* Comment to delete.
*/
function deleteComment(CommentInterface $comment) {
$this->drupalPostForm('comment/' . $comment->id() . '/delete', array(), t('Delete'));
public function deleteComment(CommentInterface $comment) {
$this->drupalPostForm('comment/' . $comment->id() . '/delete', [], t('Delete'));
$this->assertText(t('The comment and all its replies have been deleted.'), 'Comment deleted.');
}
@ -228,9 +228,9 @@ abstract class CommentTestBase extends WebTestBase {
public function setCommentSubject($enabled) {
$form_display = entity_get_form_display('comment', 'comment', 'default');
if ($enabled) {
$form_display->setComponent('subject', array(
$form_display->setComponent('subject', [
'type' => 'string_textfield',
));
]);
}
else {
$form_display->removeComponent('subject');
@ -263,7 +263,7 @@ abstract class CommentTestBase extends WebTestBase {
$mode_text = 'required';
break;
}
$this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', array('@mode_text' => $mode_text)), $field_name);
$this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', ['@mode_text' => $mode_text]), $field_name);
}
/**
@ -289,8 +289,8 @@ abstract class CommentTestBase extends WebTestBase {
* - 1: Contact information allowed but not required.
* - 2: Contact information required.
*/
function setCommentAnonymous($level) {
$this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', array('@level' => $level)));
public function setCommentAnonymous($level) {
$this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', ['@level' => $level]));
}
/**
@ -303,7 +303,7 @@ abstract class CommentTestBase extends WebTestBase {
* Defaults to 'comment'.
*/
public function setCommentsPerPage($number, $field_name = 'comment') {
$this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', array('@number' => $number)), $field_name);
$this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', ['@number' => $number]), $field_name);
}
/**
@ -333,7 +333,7 @@ abstract class CommentTestBase extends WebTestBase {
* @return bool
* Contact info is available.
*/
function commentContactInfoAvailable() {
public function commentContactInfoAvailable() {
return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->getRawContent());
}
@ -347,18 +347,18 @@ abstract class CommentTestBase extends WebTestBase {
* @param bool $approval
* Operation is found on approval page.
*/
function performCommentOperation(CommentInterface $comment, $operation, $approval = FALSE) {
$edit = array();
public function performCommentOperation(CommentInterface $comment, $operation, $approval = FALSE) {
$edit = [];
$edit['operation'] = $operation;
$edit['comments[' . $comment->id() . ']'] = TRUE;
$this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
if ($operation == 'delete') {
$this->drupalPostForm(NULL, array(), t('Delete comments'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation)));
$this->drupalPostForm(NULL, [], t('Delete comments'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
else {
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation)));
$this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation]));
}
}
@ -371,7 +371,7 @@ abstract class CommentTestBase extends WebTestBase {
* @return int
* Comment id.
*/
function getUnapprovedComment($subject) {
public function getUnapprovedComment($subject) {
$this->drupalGet('admin/content/comment/approval');
preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->getRawContent(), $match);
@ -388,12 +388,12 @@ abstract class CommentTestBase extends WebTestBase {
* Created comment type.
*/
protected function createCommentType($label) {
$bundle = CommentType::create(array(
$bundle = CommentType::create([
'id' => $label,
'label' => $label,
'description' => '',
'target_entity_type_id' => 'node',
));
]);
$bundle->save();
return $bundle;
}

View file

@ -43,12 +43,12 @@ trait CommentTestTrait {
}
}
else {
$comment_type_storage->create(array(
$comment_type_storage->create([
'id' => $comment_type_id,
'label' => Unicode::ucfirst($comment_type_id),
'target_entity_type_id' => $entity_type,
'description' => 'Default comment field',
))->save();
])->save();
}
// Add a body field to the comment type.
\Drupal::service('comment.manager')->addBodyField($comment_type_id);
@ -56,43 +56,43 @@ trait CommentTestTrait {
// Add a comment field to the host entity type. Create the field storage if
// needed.
if (!array_key_exists($field_name, $entity_manager->getFieldStorageDefinitions($entity_type))) {
$entity_manager->getStorage('field_storage_config')->create(array(
$entity_manager->getStorage('field_storage_config')->create([
'entity_type' => $entity_type,
'field_name' => $field_name,
'type' => 'comment',
'translatable' => TRUE,
'settings' => array(
'settings' => [
'comment_type' => $comment_type_id,
),
))->save();
],
])->save();
}
// Create the field if needed, and configure its form and view displays.
if (!array_key_exists($field_name, $entity_manager->getFieldDefinitions($entity_type, $bundle))) {
$entity_manager->getStorage('field_config')->create(array(
$entity_manager->getStorage('field_config')->create([
'label' => 'Comments',
'description' => '',
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'required' => 1,
'default_value' => array(
array(
'default_value' => [
[
'status' => $default_value,
'cid' => 0,
'last_comment_name' => '',
'last_comment_timestamp' => 0,
'last_comment_uid' => 0,
),
),
))->save();
],
],
])->save();
// Entity form displays: assign widget settings for the 'default' form
// mode, and hide the field in all other form modes.
entity_get_form_display($entity_type, $bundle, 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'comment_default',
'weight' => 20,
))
])
->save();
foreach ($entity_manager->getFormModes($entity_type) as $id => $form_mode) {
$display = entity_get_form_display($entity_type, $bundle, $id);
@ -105,12 +105,12 @@ trait CommentTestTrait {
// Entity view displays: assign widget settings for the 'default' view
// mode, and hide the field in all other view modes.
entity_get_display($entity_type, $bundle, 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'label' => 'above',
'type' => 'comment_default',
'weight' => 20,
'settings' => array('view_mode' => $comment_view_mode),
))
'settings' => ['view_mode' => $comment_view_mode],
])
->save();
foreach ($entity_manager->getViewModes($entity_type) as $id => $view_mode) {
$display = entity_get_display($entity_type, $bundle, $id);

View file

@ -13,7 +13,7 @@ class CommentThreadingTest extends CommentTestBase {
/**
* Tests the comment threading.
*/
function testCommentThreading() {
public function testCommentThreading() {
// Set comments to have a subject with preview disabled.
$this->drupalLogin($this->adminUser);
$this->setCommentPreview(DRUPAL_DISABLED);
@ -24,7 +24,7 @@ class CommentThreadingTest extends CommentTestBase {
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1.
$this->drupalLogin($this->webUser);
@ -139,10 +139,10 @@ class CommentThreadingTest extends CommentTestBase {
$this->assertFieldByXpath($pattern, NULL, format_string(
'Comment %cid has a link to parent %pid.',
array(
[
'%cid' => $cid,
'%pid' => $pid,
)
]
));
}
@ -162,9 +162,9 @@ class CommentThreadingTest extends CommentTestBase {
$pattern = "//a[@id='comment-$cid']/following-sibling::article//p[contains(@class, 'parent')]";
$this->assertNoFieldByXpath($pattern, NULL, format_string(
'Comment %cid does not have a link to a parent.',
array(
[
'%cid' => $cid,
)
]
));
}

View file

@ -14,7 +14,7 @@ class CommentTitleTest extends CommentTestBase {
*/
public function testCommentEmptyTitles() {
// Installs module that sets comments to an empty string.
\Drupal::service('module_installer')->install(array('comment_empty_title_test'));
\Drupal::service('module_installer')->install(['comment_empty_title_test']);
// Set comments to have a subject with preview disabled.
$this->setCommentPreview(DRUPAL_DISABLED);
@ -23,7 +23,7 @@ class CommentTitleTest extends CommentTestBase {
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1 and verify that h3's are not rendered.
$subject_text = $this->randomMachineName();
@ -49,7 +49,7 @@ class CommentTitleTest extends CommentTestBase {
// Create a node.
$this->drupalLogin($this->webUser);
$this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()));
$this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]);
// Post comment #1 and verify that title is rendered in h3.
$subject_text = $this->randomMachineName();

View file

@ -29,13 +29,13 @@ class CommentTokenReplaceTest extends CommentTestBase {
/**
* Creates a comment, then tests the tokens generated from it.
*/
function testCommentTokenReplacement() {
public function testCommentTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$url_options = array(
$url_options = [
'absolute' => TRUE,
'language' => $language_interface,
);
];
// Setup vocabulary.
Vocabulary::create([
@ -65,7 +65,7 @@ class CommentTokenReplaceTest extends CommentTestBase {
$comment->setSubject('<blink>Blinking Comment</blink>');
// Generate and test tokens.
$tests = array();
$tests = [];
$tests['[comment:cid]'] = $comment->id();
$tests['[comment:hostname]'] = $comment->getHostname();
$tests['[comment:author]'] = Html::escape($comment->getAuthorName());
@ -74,11 +74,11 @@ class CommentTokenReplaceTest extends CommentTestBase {
$tests['[comment:title]'] = Html::escape($comment->getSubject());
$tests['[comment:body]'] = $comment->comment_body->processed;
$tests['[comment:langcode]'] = $comment->language()->getId();
$tests['[comment:url]'] = $comment->url('canonical', $url_options + array('fragment' => 'comment-' . $comment->id()));
$tests['[comment:url]'] = $comment->url('canonical', $url_options + ['fragment' => 'comment-' . $comment->id()]);
$tests['[comment:edit-url]'] = $comment->url('edit-form', $url_options);
$tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', array('langcode' => $language_interface->getId()));
$tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), array('langcode' => $language_interface->getId()));
$tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), array('langcode' => $language_interface->getId()));
$tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', ['langcode' => $language_interface->getId()]);
$tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), ['langcode' => $language_interface->getId()]);
$tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), ['langcode' => $language_interface->getId()]);
$tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
$tests['[comment:parent:title]'] = $parent_comment->getSubject();
$tests['[comment:entity]'] = Html::escape($node->getTitle());
@ -127,7 +127,7 @@ class CommentTokenReplaceTest extends CommentTestBase {
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
$output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()], $bubbleable_metadata);
$this->assertEqual($output, $expected, new FormattableMarkup('Comment token %token replaced.', ['%token' => $input]));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
@ -136,8 +136,8 @@ class CommentTokenReplaceTest extends CommentTestBase {
$author_name = 'This is a random & " > string';
$comment->setOwnerId(0)->setAuthorName($author_name);
$input = '[comment:author]';
$output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()));
$this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', array('%token' => $input)));
$output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()]);
$this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', ['%token' => $input]));
// Add comment field to user and term entities.
$this->addDefaultCommentField('user', 'user', 'comment', CommentItemInterface::OPEN, 'comment_user');
$this->addDefaultCommentField('taxonomy_term', 'tags', 'comment', CommentItemInterface::OPEN, 'comment_term');
@ -162,7 +162,7 @@ class CommentTokenReplaceTest extends CommentTestBase {
// Generate comment tokens for node (it has 2 comments, both new),
// user and term.
$tests = array();
$tests = [];
$tests['[entity:comment-count]'] = 2;
$tests['[entity:comment-count-new]'] = 2;
$tests['[node:comment-count]'] = 2;

View file

@ -46,7 +46,7 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
*
* @var array
*/
public static $modules = array('language', 'content_translation', 'node', 'comment');
public static $modules = ['language', 'content_translation', 'node', 'comment'];
protected function setUp() {
$this->entityTypeId = 'comment';
@ -60,13 +60,13 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
/**
* {@inheritdoc}
*/
function setupBundle() {
public function setupBundle() {
parent::setupBundle();
$this->drupalCreateContentType(array('type' => $this->nodeBundle, 'name' => $this->nodeBundle));
$this->drupalCreateContentType(['type' => $this->nodeBundle, 'name' => $this->nodeBundle]);
// Add a comment field to the article content type.
$this->addDefaultCommentField('node', 'article', 'comment_article', CommentItemInterface::OPEN, 'comment_article');
// Create a page content type.
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'page'));
$this->drupalCreateContentType(['type' => 'page', 'name' => 'page']);
// Add a comment field to the page content type - this one won't be
// translatable.
$this->addDefaultCommentField('node', 'page', 'comment');
@ -78,7 +78,7 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
* {@inheritdoc}
*/
protected function getTranslatorPermissions() {
return array_merge(parent::getTranslatorPermissions(), array('post comments', 'administer comments', 'access comments'));
return array_merge(parent::getTranslatorPermissions(), ['post comments', 'administer comments', 'access comments']);
}
/**
@ -95,12 +95,12 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
$node_type = 'page';
$field_name = 'comment';
}
$node = $this->drupalCreateNode(array(
$node = $this->drupalCreateNode([
'type' => $node_type,
$field_name => array(
array('status' => CommentItemInterface::OPEN)
),
));
$field_name => [
['status' => CommentItemInterface::OPEN]
],
]);
$values['entity_id'] = $node->id();
$values['entity_type'] = 'node';
$values['field_name'] = $field_name;
@ -113,10 +113,10 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
*/
protected function getNewEntityValues($langcode) {
// Comment subject is not translatable hence we use a fixed value.
return array(
'subject' => array(array('value' => $this->subject)),
'comment_body' => array(array('value' => $this->randomMachineName(16))),
) + parent::getNewEntityValues($langcode);
return [
'subject' => [['value' => $this->subject]],
'comment_body' => [['value' => $this->randomMachineName(16)]],
] + parent::getNewEntityValues($langcode);
}
/**
@ -132,8 +132,8 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
// Unpublish translations.
foreach ($this->langcodes as $index => $langcode) {
if ($index > 0) {
$edit = array('status' => 0);
$url = $entity->urlInfo('edit-form', array('language' => ConfigurableLanguage::load($langcode)));
$edit = ['status' => 0];
$url = $entity->urlInfo('edit-form', ['language' => ConfigurableLanguage::load($langcode)]);
$this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode));
$storage->resetCache();
$entity = $storage->load($this->entityId);
@ -151,21 +151,21 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
$storage->resetCache([$this->entityId]);
$entity = $storage->load($this->entityId);
$languages = $this->container->get('language_manager')->getLanguages();
$values = array();
$values = [];
// Post different authoring information for each translation.
foreach ($this->langcodes as $langcode) {
$url = $entity->urlInfo('edit-form', ['language' => $languages[$langcode]]);
$user = $this->drupalCreateUser();
$values[$langcode] = array(
$values[$langcode] = [
'uid' => $user->id(),
'created' => REQUEST_TIME - mt_rand(0, 1000),
);
$edit = array(
];
$edit = [
'uid' => $user->getUsername() . ' (' . $user->id() . ')',
'date[date]' => format_date($values[$langcode]['created'], 'custom', 'Y-m-d'),
'date[time]' => format_date($values[$langcode]['created'], 'custom', 'H:i:s'),
);
];
$this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode));
}
@ -181,12 +181,12 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
/**
* Tests translate link on comment content admin page.
*/
function testTranslateLinkCommentAdminPage() {
$this->adminUser = $this->drupalCreateUser(array_merge(parent::getTranslatorPermissions(), array('access administration pages', 'administer comments', 'skip comment approval')));
public function testTranslateLinkCommentAdminPage() {
$this->adminUser = $this->drupalCreateUser(array_merge(parent::getTranslatorPermissions(), ['access administration pages', 'administer comments', 'skip comment approval']));
$this->drupalLogin($this->adminUser);
$cid_translatable = $this->createEntity(array(), $this->langcodes[0]);
$cid_untranslatable = $this->createEntity(array(), $this->langcodes[0], 'comment');
$cid_translatable = $this->createEntity([], $this->langcodes[0]);
$cid_untranslatable = $this->createEntity([], $this->langcodes[0], 'comment');
// Verify translation links.
$this->drupalGet('admin/content/comment');
@ -208,15 +208,15 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
foreach ($this->langcodes as $langcode) {
// We only want to test the title for non-english translations.
if ($langcode != 'en') {
$options = array('language' => $languages[$langcode]);
$options = ['language' => $languages[$langcode]];
$url = $entity->urlInfo('edit-form', $options);
$this->drupalGet($url);
$title = t('Edit @type @title [%language translation]', array(
$title = t('Edit @type @title [%language translation]', [
'@type' => $this->entityTypeId,
'@title' => $entity->getTranslation($langcode)->label(),
'%language' => $languages[$langcode]->getName(),
));
]);
$this->assertRaw($title);
}
}

View file

@ -27,11 +27,11 @@ class CommentTypeTest extends CommentTestBase {
*
* @var array
*/
protected $permissions = array(
protected $permissions = [
'administer comments',
'administer comment fields',
'administer comment types',
);
];
/**
* Sets the test up.
@ -61,12 +61,12 @@ class CommentTypeTest extends CommentTestBase {
$this->assertResponse(200, 'The new comment type can be accessed at the edit form.');
// Create a comment type via the user interface.
$edit = array(
$edit = [
'id' => 'foo',
'label' => 'title for foo',
'description' => '',
'target_entity_type_id' => 'node',
);
];
$this->drupalPostForm('admin/structure/comment/types/add', $edit, t('Save'));
$comment_type = CommentType::load('foo');
$this->assertTrue($comment_type, 'The new comment type has been created.');
@ -81,8 +81,8 @@ class CommentTypeTest extends CommentTestBase {
$this->assertText(t('Target entity type'));
// Save the form and ensure the entity-type value is preserved even though
// the field isn't present.
$this->drupalPostForm(NULL, array(), t('Save'));
\Drupal::entityManager()->getStorage('comment_type')->resetCache(array('foo'));
$this->drupalPostForm(NULL, [], t('Save'));
\Drupal::entityManager()->getStorage('comment_type')->resetCache(['foo']);
$comment_type = CommentType::load('foo');
$this->assertEqual($comment_type->getTargetEntityTypeId(), 'node');
}
@ -98,9 +98,9 @@ class CommentTypeTest extends CommentTestBase {
// Change the comment type name.
$this->drupalGet('admin/structure/comment');
$edit = array(
$edit = [
'label' => 'Bar',
);
];
$this->drupalPostForm('admin/structure/comment/manage/comment', $edit, t('Save'));
$this->drupalGet('admin/structure/comment');
@ -110,9 +110,9 @@ class CommentTypeTest extends CommentTestBase {
$this->assertTrue($this->cssSelect('tr#comment-body'), 'Body field exists.');
// Remove the body field.
$this->drupalPostForm('admin/structure/comment/manage/comment/fields/comment.comment.comment_body/delete', array(), t('Delete'));
$this->drupalPostForm('admin/structure/comment/manage/comment/fields/comment.comment.comment_body/delete', [], t('Delete'));
// Resave the settings for this type.
$this->drupalPostForm('admin/structure/comment/manage/comment', array(), t('Save'));
$this->drupalPostForm('admin/structure/comment/manage/comment', [], t('Save'));
// Check that the body field doesn't exist.
$this->drupalGet('admin/structure/comment/manage/comment/fields');
$this->assertFalse($this->cssSelect('tr#comment-body'), 'Body field does not exist.');
@ -124,39 +124,39 @@ class CommentTypeTest extends CommentTestBase {
public function testCommentTypeDeletion() {
// Create a comment type programmatically.
$type = $this->createCommentType('foo');
$this->drupalCreateContentType(array('type' => 'page'));
$this->drupalCreateContentType(['type' => 'page']);
$this->addDefaultCommentField('node', 'page', 'foo', CommentItemInterface::OPEN, 'foo');
$field_storage = FieldStorageConfig::loadByName('node', 'foo');
$this->drupalLogin($this->adminUser);
// Create a node.
$node = Node::create(array(
$node = Node::create([
'type' => 'page',
'title' => 'foo',
));
]);
$node->save();
// Add a new comment of this type.
$comment = Comment::create(array(
$comment = Comment::create([
'comment_type' => 'foo',
'entity_type' => 'node',
'field_name' => 'foo',
'entity_id' => $node->id(),
));
]);
$comment->save();
// Attempt to delete the comment type, which should not be allowed.
$this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete');
$this->assertRaw(
t('%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', array('%label' => $type->label())),
t('%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', ['%label' => $type->label()]),
'The comment type will not be deleted until all comments of that type are removed.'
);
$this->assertRaw(
t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', array(
t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [
'%label' => 'foo',
'%field' => 'node.foo',
)),
]),
'The comment type will not be deleted until all fields of that type are removed.'
);
$this->assertNoText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is not available.');
@ -167,7 +167,7 @@ class CommentTypeTest extends CommentTestBase {
// Attempt to delete the comment type, which should now be allowed.
$this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete');
$this->assertRaw(
t('Are you sure you want to delete the comment type %type?', array('%type' => $type->id())),
t('Are you sure you want to delete the comment type %type?', ['%type' => $type->id()]),
'The comment type is available for deletion.'
);
$this->assertText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is available.');
@ -182,9 +182,9 @@ class CommentTypeTest extends CommentTestBase {
}
// Delete the comment type.
$this->drupalPostForm('admin/structure/comment/manage/' . $type->id() . '/delete', array(), t('Delete'));
$this->drupalPostForm('admin/structure/comment/manage/' . $type->id() . '/delete', [], t('Delete'));
$this->assertNull(CommentType::load($type->id()), 'Comment type deleted.');
$this->assertRaw(t('The comment type %label has been deleted.', array('%label' => $type->label())));
$this->assertRaw(t('The comment type %label has been deleted.', ['%label' => $type->label()]));
}
}

View file

@ -20,13 +20,13 @@ class CommentUninstallTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('comment', 'node');
public static $modules = ['comment', 'node'];
protected function setUp() {
parent::setup();
// Create an article content type.
$this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article')));
$this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
// Create comment field on article so that adds 'comment_body' field.
$this->addDefaultCommentField('node', 'article');
}
@ -36,14 +36,14 @@ class CommentUninstallTest extends WebTestBase {
*
* @throws \Drupal\Core\Extension\ModuleUninstallValidatorException
*/
function testCommentUninstallWithField() {
public function testCommentUninstallWithField() {
// Ensure that the field exists before uninstallation.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertNotNull($field_storage, 'The comment_body field exists.');
// Uninstall the comment module which should trigger an exception.
try {
$this->container->get('module_installer')->uninstall(array('comment'));
$this->container->get('module_installer')->uninstall(['comment']);
$this->fail("Expected an exception when uninstall was attempted.");
}
catch (ModuleUninstallValidatorException $e) {
@ -55,7 +55,7 @@ class CommentUninstallTest extends WebTestBase {
/**
* Tests if uninstallation succeeds if the field has been deleted beforehand.
*/
function testCommentUninstallWithoutField() {
public function testCommentUninstallWithoutField() {
// Manually delete the comment_body field before module uninstallation.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$this->assertNotNull($field_storage, 'The comment_body field exists.');
@ -77,7 +77,7 @@ class CommentUninstallTest extends WebTestBase {
field_purge_batch(10);
// Ensure that uninstallation succeeds even if the field has already been
// deleted manually beforehand.
$this->container->get('module_installer')->uninstall(array('comment'));
$this->container->get('module_installer')->uninstall(['comment']);
}
}

View file

@ -50,4 +50,25 @@ class CommentUpdateTest extends UpdatePathTestBase {
$this->assertIdentical($config->get('content.comment_forum.settings.view_mode'), 'default');
}
/**
* Tests that the comment entity type has a 'published' entity key.
*
* @see comment_update_8301()
*/
public function testPublishedEntityKey() {
// Check that the 'published' entity key does not exist prior to the update.
$entity_type = \Drupal::entityDefinitionUpdateManager()->getEntityType('comment');
$this->assertFalse($entity_type->getKey('published'));
// Run updates.
$this->runUpdates();
// Check that the entity key exists and it has the correct value.
$entity_type = \Drupal::entityDefinitionUpdateManager()->getEntityType('comment');
$this->assertEqual('status', $entity_type->getKey('published'));
// Check that the {comment_field_data} table status index has been created.
$this->assertTrue(\Drupal::database()->schema()->indexExists('comment_field_data', 'comment__status_comment_type'));
}
}

View file

@ -18,9 +18,9 @@ class ArgumentUserUIDTest extends CommentTestBase {
*
* @var array
*/
public static $testViews = array('test_comment_user_uid');
public static $testViews = ['test_comment_user_uid'];
function testCommentUserUIDTest() {
public function testCommentUserUIDTest() {
// Add an additional comment which is not created by the user.
$new_user = User::create(['name' => 'new user']);
$new_user->save();
@ -35,16 +35,16 @@ class ArgumentUserUIDTest extends CommentTestBase {
$comment->save();
$view = Views::getView('test_comment_user_uid');
$this->executeView($view, array($this->account->id()));
$result_set = array(
array(
$this->executeView($view, [$this->account->id()]);
$result_set = [
[
'nid' => $this->nodeUserPosted->id(),
),
array(
],
[
'nid' => $this->nodeUserCommented->id(),
),
);
$column_map = array('nid' => 'nid');
],
];
$column_map = ['nid' => 'nid'];
$this->assertIdenticalResultset($view, $result_set, $column_map);
}

View file

@ -15,23 +15,23 @@ class CommentFieldFilterTest extends CommentTestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_field_filters');
public static $testViews = ['test_field_filters'];
/**
* List of comment titles by language.
*
* @var array
*/
public $commentTitles = array();
public $commentTitles = [];
function setUp() {
public function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(['access comments']));
@ -40,15 +40,15 @@ class CommentFieldFilterTest extends CommentTestBase {
ConfigurableLanguage::createFromLangcode('es')->save();
// Set up comment titles.
$this->commentTitles = array(
$this->commentTitles = [
'en' => 'Food in Paris',
'es' => 'Comida en Paris',
'fr' => 'Nouriture en Paris',
);
];
// Create a new comment. Using the one created earlier will not work,
// as it predates the language set-up.
$comment = array(
$comment = [
'uid' => $this->loggedInUser->id(),
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
@ -56,7 +56,7 @@ class CommentFieldFilterTest extends CommentTestBase {
'cid' => '',
'pid' => '',
'node_type' => '',
);
];
$this->comment = Comment::create($comment);
// Add field values and translate the comment.
@ -64,8 +64,8 @@ class CommentFieldFilterTest extends CommentTestBase {
$this->comment->comment_body->value = $this->commentTitles['en'];
$this->comment->langcode = 'en';
$this->comment->save();
foreach (array('es', 'fr') as $langcode) {
$translation = $this->comment->addTranslation($langcode, array());
foreach (['es', 'fr'] as $langcode) {
$translation = $this->comment->addTranslation($langcode, []);
$translation->comment_body->value = $this->commentTitles[$langcode];
$translation->subject->value = $this->commentTitles[$langcode];
}
@ -78,19 +78,19 @@ class CommentFieldFilterTest extends CommentTestBase {
public function testFilters() {
// Test the title filter page, which filters for title contains 'Comida'.
// Should show just the Spanish translation, once.
$this->assertPageCounts('test-title-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida title filter');
$this->assertPageCounts('test-title-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida title filter');
// Test the body filter page, which filters for body contains 'Comida'.
// Should show just the Spanish translation, once.
$this->assertPageCounts('test-body-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida body filter');
$this->assertPageCounts('test-body-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida body filter');
// Test the title Paris filter page, which filters for title contains
// 'Paris'. Should show each translation once.
$this->assertPageCounts('test-title-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris title filter');
$this->assertPageCounts('test-title-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris title filter');
// Test the body Paris filter page, which filters for body contains
// 'Paris'. Should show each translation once.
$this->assertPageCounts('test-body-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris body filter');
$this->assertPageCounts('test-body-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris body filter');
}
/**

View file

@ -27,7 +27,7 @@ class CommentRestExportTest extends CommentTestBase {
protected function setUp() {
parent::setUp();
// Add another anonymous comment.
$comment = array(
$comment = [
'uid' => 0,
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
@ -38,7 +38,7 @@ class CommentRestExportTest extends CommentTestBase {
'mail' => 'someone@example.com',
'name' => 'bobby tables',
'hostname' => 'public.example.com',
);
];
$this->comment = Comment::create($comment);
$this->comment->save();

View file

@ -14,7 +14,7 @@ class CommentRowTest extends CommentTestBase {
*
* @var array
*/
public static $testViews = array('test_comment_row');
public static $testViews = ['test_comment_row'];
/**
* Test comment row.

View file

@ -19,7 +19,7 @@ abstract class CommentTestBase extends ViewTestBase {
*
* @var array
*/
public static $modules = array('node', 'comment', 'comment_test_views');
public static $modules = ['node', 'comment', 'comment_test_views'];
/**
* A normal user with permission to post comments (without approval).
@ -59,21 +59,21 @@ abstract class CommentTestBase extends ViewTestBase {
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('comment_test_views'));
ViewTestData::createTestViews(get_class($this), ['comment_test_views']);
// Add two users, create a node with the user1 as author and another node
// with user2 as author. For the second node add a comment from user1.
$this->account = $this->drupalCreateUser(array('skip comment approval'));
$this->account = $this->drupalCreateUser(['skip comment approval']);
$this->account2 = $this->drupalCreateUser();
$this->drupalLogin($this->account);
$this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page')));
$this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
$this->addDefaultCommentField('node', 'page');
$this->nodeUserPosted = $this->drupalCreateNode();
$this->nodeUserCommented = $this->drupalCreateNode(array('uid' => $this->account2->id()));
$this->nodeUserCommented = $this->drupalCreateNode(['uid' => $this->account2->id()]);
$comment = array(
$comment = [
'uid' => $this->loggedInUser->id(),
'entity_id' => $this->nodeUserCommented->id(),
'entity_type' => 'node',
@ -82,7 +82,7 @@ abstract class CommentTestBase extends ViewTestBase {
'cid' => '',
'pid' => '',
'mail' => 'someone@example.com',
);
];
$this->comment = Comment::create($comment);
$this->comment->save();
}

View file

@ -22,7 +22,7 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
*
* @var array
*/
public static $modules = array('node', 'comment', 'block');
public static $modules = ['node', 'comment', 'block'];
/**
* Number of results for the Master display.
@ -50,7 +50,7 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
*
* @var array
*/
protected $commentsCreated = array();
protected $commentsCreated = [];
/**
* Contains the node object used for comments of this test.
@ -66,9 +66,9 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
$content_type = $this->drupalCreateContentType();
// Add a node of the new content type.
$node_data = array(
$node_data = [
'type' => $content_type->id(),
);
];
$this->addDefaultCommentField('node', $content_type->id());
$this->node = $this->drupalCreateNode($node_data);
@ -79,12 +79,12 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
// Create some comments and attach them to the created node.
for ($i = 0; $i < $this->masterDisplayResults; $i++) {
/** @var \Drupal\comment\CommentInterface $comment */
$comment = Comment::create(array(
$comment = Comment::create([
'status' => CommentInterface::PUBLISHED,
'field_name' => 'comment',
'entity_type' => 'node',
'entity_id' => $this->node->id(),
));
]);
$comment->setOwnerId(0);
$comment->setSubject('Test comment ' . $i);
$comment->comment_body->value = 'Test body ' . $i;
@ -116,12 +116,12 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
$view->setDisplay('block_1');
$this->executeView($view);
$map = array(
$map = [
'subject' => 'subject',
'cid' => 'cid',
'comment_field_data_created' => 'created'
);
$expected_result = array();
];
$expected_result = [];
foreach (array_values($this->commentsCreated) as $key => $comment) {
$expected_result[$key]['subject'] = $comment->getSubject();
$expected_result[$key]['cid'] = $comment->id();
@ -132,7 +132,7 @@ class DefaultViewRecentCommentsTest extends ViewTestBase {
// Check the number of results given by the display is the expected.
$this->assertEqual(sizeof($view->result), $this->blockDisplayResults,
format_string('There are exactly @results comments. Expected @expected',
array('@results' => count($view->result), '@expected' => $this->blockDisplayResults)
['@results' => count($view->result), '@expected' => $this->blockDisplayResults]
)
);
}

View file

@ -20,9 +20,9 @@ class FilterUserUIDTest extends CommentTestBase {
*
* @var array
*/
public static $testViews = array('test_comment_user_uid');
public static $testViews = ['test_comment_user_uid'];
function testCommentUserUIDTest() {
public function testCommentUserUIDTest() {
$view = Views::getView('test_comment_user_uid');
$view->setDisplay();
$view->removeHandler('default', 'argument', 'uid_touch');
@ -40,23 +40,23 @@ class FilterUserUIDTest extends CommentTestBase {
]);
$comment->save();
$options = array(
$options = [
'id' => 'uid_touch',
'table' => 'node_field_data',
'field' => 'uid_touch',
'value' => array($this->loggedInUser->id()),
);
'value' => [$this->loggedInUser->id()],
];
$view->addHandler('default', 'filter', 'node_field_data', 'uid_touch', $options);
$this->executeView($view, array($this->account->id()));
$result_set = array(
array(
$this->executeView($view, [$this->account->id()]);
$result_set = [
[
'nid' => $this->nodeUserPosted->id(),
),
array(
],
[
'nid' => $this->nodeUserCommented->id(),
),
);
$column_map = array('nid' => 'nid');
],
];
$column_map = ['nid' => 'nid'];
$this->assertIdenticalResultset($view, $result_set, $column_map);
}

View file

@ -15,7 +15,7 @@ class RowRssTest extends CommentTestBase {
*
* @var array
*/
public static $testViews = array('test_comment_rss');
public static $testViews = ['test_comment_rss'];
/**
* Test comment rss output.

View file

@ -21,7 +21,7 @@ class WizardTest extends WizardTestBase {
*
* @var array
*/
public static $modules = array('node', 'comment');
public static $modules = ['node', 'comment'];
/**
@ -29,7 +29,7 @@ class WizardTest extends WizardTestBase {
*/
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page')));
$this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
// Add comment field to page node type.
$this->addDefaultCommentField('node', 'page');
}
@ -38,7 +38,7 @@ class WizardTest extends WizardTestBase {
* Tests adding a view of comments.
*/
public function testCommentWizard() {
$view = array();
$view = [];
$view['label'] = $this->randomMachineName(16);
$view['id'] = strtolower($this->randomMachineName(16));
$view['show[wizard_key]'] = 'comment';
@ -48,7 +48,7 @@ class WizardTest extends WizardTestBase {
// Just triggering the saving should automatically choose a proper row
// plugin.
$this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit'));
$this->assertUrl('admin/structure/views/view/' . $view['id'], array(), 'Make sure the view saving was successful and the browser got redirected to the edit page.');
$this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.');
// If we update the type first we should get a selection of comment valid
// row plugins as the select field.
@ -59,19 +59,19 @@ class WizardTest extends WizardTestBase {
// Check for available options of the row plugin.
$xpath = $this->constructFieldXpath('name', 'page[style][row_plugin]');
$fields = $this->xpath($xpath);
$options = array();
$options = [];
foreach ($fields as $field) {
$items = $this->getAllOptions($field);
foreach ($items as $item) {
$options[] = $item->attributes()->value;
}
}
$expected_options = array('entity:comment', 'fields');
$expected_options = ['entity:comment', 'fields'];
$this->assertEqual($options, $expected_options);
$view['id'] = strtolower($this->randomMachineName(16));
$this->drupalPostForm(NULL, $view, t('Save and edit'));
$this->assertUrl('admin/structure/views/view/' . $view['id'], array(), 'Make sure the view saving was successful and the browser got redirected to the edit page.');
$this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.');
$user = $this->drupalCreateUser(['access comments']);
$this->drupalLogin($user);

View file

@ -31,14 +31,14 @@ function comment_test_comment_links_alter(array &$links, CommentInterface &$enti
return;
}
$links['comment_test'] = array(
$links['comment_test'] = [
'#theme' => 'links__comment__comment_test',
'#attributes' => array('class' => array('links', 'inline')),
'#links' => array(
'comment-report' => array(
'#attributes' => ['class' => ['links', 'inline']],
'#links' => [
'comment-report' => [
'title' => t('Report'),
'url' => Url::fromRoute('comment_test.report', ['comment' => $entity->id()], ['query' => ['token' => \Drupal::getContainer()->get('csrf_token')->get("comment/{$entity->id()}/report")]]),
),
),
);
],
],
];
}

View file

@ -26,7 +26,7 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase {
*
* @var array
*/
public static $modules = array('entity_test', 'comment');
public static $modules = ['entity_test', 'comment'];
/**
* {@inheritdoc}
@ -48,11 +48,11 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase {
// user does not have access to the 'administer comments' permission, to
// ensure only published comments are visible to the end user.
$current_user = $this->container->get('current_user');
$current_user->setAccount($this->createUser(array(), array('access comments')));
$current_user->setAccount($this->createUser([], ['access comments']));
// Install tables and config needed to render comments.
$this->installSchema('comment', array('comment_entity_statistics'));
$this->installConfig(array('system', 'filter', 'comment'));
$this->installSchema('comment', ['comment_entity_statistics']);
$this->installConfig(['system', 'filter', 'comment']);
// Comment rendering generates links, so build the router.
$this->container->get('router.builder')->rebuild();
@ -70,7 +70,7 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase {
$renderer = $this->container->get('renderer');
// Create the entity that will be commented upon.
$commented_entity = EntityTest::create(array('name' => $this->randomMachineName()));
$commented_entity = EntityTest::create(['name' => $this->randomMachineName()]);
$commented_entity->save();
// Verify cache tags on the rendered entity before it has comments.
@ -94,19 +94,19 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase {
// also exists in the {users} table.
$user = $this->createUser();
$user->save();
$comment = Comment::create(array(
$comment = Comment::create([
'subject' => 'Llama',
'comment_body' => array(
'comment_body' => [
'value' => 'Llamas are cool!',
'format' => 'plain_text',
),
],
'entity_id' => $commented_entity->id(),
'entity_type' => 'entity_test',
'field_name' => 'comment',
'comment_type' => 'comment',
'status' => CommentInterface::PUBLISHED,
'uid' => $user->id(),
));
]);
$comment->save();
// Load commented entity so comment_count gets computed.

View file

@ -29,30 +29,30 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
*
* @var array
*/
public static $modules = array('comment', 'entity_test', 'user');
public static $modules = ['comment', 'entity_test', 'user'];
/**
* Fields that only users with administer comments permissions can change.
*
* @var array
*/
protected $administrativeFields = array(
protected $administrativeFields = [
'uid',
'status',
'created',
);
];
/**
* These fields are automatically managed and can not be changed by any user.
*
* @var array
*/
protected $readOnlyFields = array(
protected $readOnlyFields = [
'changed',
'hostname',
'cid',
'thread',
);
];
/**
* These fields can be edited on create only.
@ -73,19 +73,19 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
*
* @var array
*/
protected $contactFields = array(
protected $contactFields = [
'name',
'mail',
'homepage',
);
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(array('user', 'comment'));
$this->installSchema('comment', array('comment_entity_statistics'));
$this->installConfig(['user', 'comment']);
$this->installSchema('comment', ['comment_entity_statistics']);
}
/**

View file

@ -18,21 +18,21 @@ class CommentStringIdEntitiesTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'comment',
'user',
'field',
'field_ui',
'entity_test',
'text',
);
];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('comment');
$this->installSchema('comment', array('comment_entity_statistics'));
$this->installSchema('comment', ['comment_entity_statistics']);
// Create the comment body field storage.
$this->installConfig(array('field'));
$this->installConfig(['field']);
}
/**
@ -40,21 +40,21 @@ class CommentStringIdEntitiesTest extends KernelTestBase {
*/
public function testCommentFieldNonStringId() {
try {
$bundle = CommentType::create(array(
$bundle = CommentType::create([
'id' => 'foo',
'label' => 'foo',
'description' => '',
'target_entity_type_id' => 'entity_test_string_id',
));
]);
$bundle->save();
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'foo',
'entity_type' => 'entity_test_string_id',
'settings' => array(
'settings' => [
'comment_type' => 'entity_test_string_id',
),
],
'type' => 'comment',
));
]);
$field_storage->save();
$this->fail('Did not throw an exception as expected.');
}

View file

@ -19,14 +19,14 @@ class CommentValidationTest extends EntityKernelTestBase {
*
* @var array
*/
public static $modules = array('comment', 'node');
public static $modules = ['comment', 'node'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('comment', array('comment_entity_statistics'));
$this->installSchema('comment', ['comment_entity_statistics']);
}
/**
@ -34,54 +34,54 @@ class CommentValidationTest extends EntityKernelTestBase {
*/
public function testValidation() {
// Add a user.
$user = User::create(array('name' => 'test', 'status' => TRUE));
$user = User::create(['name' => 'test', 'status' => TRUE]);
$user->save();
// Add comment type.
$this->entityManager->getStorage('comment_type')->create(array(
$this->entityManager->getStorage('comment_type')->create([
'id' => 'comment',
'label' => 'comment',
'target_entity_type_id' => 'node',
))->save();
])->save();
// Add comment field to content.
$this->entityManager->getStorage('field_storage_config')->create(array(
$this->entityManager->getStorage('field_storage_config')->create([
'entity_type' => 'node',
'field_name' => 'comment',
'type' => 'comment',
'settings' => array(
'settings' => [
'comment_type' => 'comment',
)
))->save();
]
])->save();
// Create a page node type.
$this->entityManager->getStorage('node_type')->create(array(
$this->entityManager->getStorage('node_type')->create([
'type' => 'page',
'name' => 'page',
))->save();
])->save();
// Add comment field to page content.
/** @var \Drupal\field\FieldConfigInterface $field */
$field = $this->entityManager->getStorage('field_config')->create(array(
$field = $this->entityManager->getStorage('field_config')->create([
'field_name' => 'comment',
'entity_type' => 'node',
'bundle' => 'page',
'label' => 'Comment settings',
));
]);
$field->save();
$node = $this->entityManager->getStorage('node')->create(array(
$node = $this->entityManager->getStorage('node')->create([
'type' => 'page',
'title' => 'test',
));
]);
$node->save();
$comment = $this->entityManager->getStorage('comment')->create(array(
$comment = $this->entityManager->getStorage('comment')->create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'comment_body' => $this->randomMachineName(),
));
]);
$violations = $comment->validate();
$this->assertEqual(count($violations), 0, 'No violations when validating a default comment.');
@ -101,7 +101,7 @@ class CommentValidationTest extends EntityKernelTestBase {
$violations = $comment->validate();
$this->assertEqual(count($violations), 1, "Violation found on author name collision");
$this->assertEqual($violations[0]->getPropertyPath(), "name");
$this->assertEqual($violations[0]->getMessage(), t('The name you used (%name) belongs to a registered user.', array('%name' => 'test')));
$this->assertEqual($violations[0]->getMessage(), t('The name you used (%name) belongs to a registered user.', ['%name' => 'test']));
// Make the name valid.
$comment->set('name', 'valid unused name');
@ -141,39 +141,39 @@ class CommentValidationTest extends EntityKernelTestBase {
\Drupal::entityManager()->getStorage('node')->resetCache([$node->id()]);
$node = Node::load($node->id());
// Create a new comment with the new field.
$comment = $this->entityManager->getStorage('comment')->create(array(
$comment = $this->entityManager->getStorage('comment')->create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'comment_body' => $this->randomMachineName(),
'uid' => 0,
'name' => '',
));
]);
$violations = $comment->validate();
$this->assertEqual(count($violations), 1, 'Violation found when name is required, but empty and UID is anonymous.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name');
$this->assertEqual($violations[0]->getMessage(), t('You have to specify a valid author.'));
// Test creating a default comment with a given user id works.
$comment = $this->entityManager->getStorage('comment')->create(array(
$comment = $this->entityManager->getStorage('comment')->create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'comment_body' => $this->randomMachineName(),
'uid' => $user->id(),
));
]);
$violations = $comment->validate();
$this->assertEqual(count($violations), 0, 'No violations when validating a default comment with an author.');
// Test specifying a wrong author name does not work.
$comment = $this->entityManager->getStorage('comment')->create(array(
$comment = $this->entityManager->getStorage('comment')->create([
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'comment_body' => $this->randomMachineName(),
'uid' => $user->id(),
'name' => 'not-test',
));
]);
$violations = $comment->validate();
$this->assertEqual(count($violations), 1, 'Violation found when author name and comment author do not match.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name');
@ -195,7 +195,7 @@ class CommentValidationTest extends EntityKernelTestBase {
$this->assertEqual(count($violations), 1, "Violation found when $field_name is too long.");
$this->assertEqual($violations[0]->getPropertyPath(), "$field_name.0.value");
$field_label = $comment->get($field_name)->getFieldDefinition()->getLabel();
$this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', array('%name' => $field_label, '@max' => $length)));
$this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => $field_label, '@max' => $length]));
}
}

View file

@ -33,11 +33,11 @@ class MigrateCommentStubTest extends MigrateDrupalTestBase {
$storage = \Drupal::entityManager()->getStorage('user');
// Insert a row for the anonymous user.
$storage
->create(array(
->create([
'uid' => 0,
'status' => 0,
'name' => '',
))
])
->save();
// Need at least one node type and comment type present.
NodeType::create([

View file

@ -61,14 +61,17 @@ class MigrateCommentTest extends MigrateDrupal6TestBase {
$this->assertIdentical('node', $comment->getCommentedEntityTypeId());
$this->assertIdentical('en', $comment->language()->getId());
$this->assertIdentical('comment_no_subject', $comment->getTypeId());
$this->assertEquals('203.0.113.1', $comment->getHostname());
$comment = $comment_storage->load(2);
$this->assertIdentical('The response to the second comment.', $comment->subject->value);
$this->assertIdentical('3', $comment->pid->target_id);
$this->assertEquals('203.0.113.2', $comment->getHostname());
$comment = $comment_storage->load(3);
$this->assertIdentical('The second comment.', $comment->subject->value);
$this->assertIdentical(NULL, $comment->pid->target_id);
$this->assertEquals('203.0.113.3', $comment->getHostname());
}
}

View file

@ -34,11 +34,11 @@ class MigrateCommentTest extends MigrateDrupal7TestBase {
$this->executeMigration('d7_node_type');
// We only need the test_content_type node migration to run for real, so
// mock all the others.
$this->prepareMigrations(array(
'd7_node' => array(
array(array(0), array(0)),
),
));
$this->prepareMigrations([
'd7_node' => [
[[0], [0]],
],
]);
$this->executeMigrations([
'd7_node',
'd7_comment_type',
@ -61,6 +61,7 @@ class MigrateCommentTest extends MigrateDrupal7TestBase {
$this->assertIdentical('admin@local.host', $comment->getAuthorEmail());
$this->assertIdentical('This is a comment', $comment->comment_body->value);
$this->assertIdentical('filtered_html', $comment->comment_body->format);
$this->assertEquals('2001:db8:ffff:ffff:ffff:ffff:ffff:ffff', $comment->getHostname());
$node = $comment->getCommentedEntity();
$this->assertTrue($node instanceof NodeInterface);

View file

@ -43,11 +43,11 @@ class CommentUserNameTest extends ViewsKernelTestBase {
$storage = \Drupal::entityManager()->getStorage('user');
// Insert a row for the anonymous user.
$storage
->create(array(
->create([
'uid' => 0,
'name' => '',
'status' => 0,
))
])
->save();
$admin_role = Role::create([

View file

@ -75,9 +75,9 @@ class CommentLinkBuilderTest extends UnitTestCase {
$this->commentManager->expects($this->any())
->method('getFields')
->with('node')
->willReturn(array(
'comment' => array(),
));
->willReturn([
'comment' => [],
]);
$this->commentManager->expects($this->any())
->method('forbiddenMessage')
->willReturn("Can't let you do that Dave.");
@ -116,10 +116,10 @@ class CommentLinkBuilderTest extends UnitTestCase {
->willReturn($history_exists);
$this->currentUser->expects($this->any())
->method('hasPermission')
->willReturnMap(array(
array('access comments', $has_access_comments),
array('post comments', $has_post_comments),
));
->willReturnMap([
['access comments', $has_access_comments],
['post comments', $has_post_comments],
]);
$this->currentUser->expects($this->any())
->method('isAuthenticated')
->willReturn(!$is_anonymous);
@ -155,57 +155,57 @@ class CommentLinkBuilderTest extends UnitTestCase {
* Data provider for ::testCommentLinkBuilder.
*/
public function getLinkCombinations() {
$cases = array();
$cases = [];
// No links should be created if the entity doesn't have the field.
$cases[] = array(
$cases[] = [
$this->getMockNode(FALSE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1),
array('view_mode' => 'teaser'),
['view_mode' => 'teaser'],
TRUE,
TRUE,
TRUE,
TRUE,
array(),
);
foreach (array('search_result', 'search_index', 'print') as $view_mode) {
[],
];
foreach (['search_result', 'search_index', 'print'] as $view_mode) {
// Nothing should be output in these view modes.
$cases[] = array(
$cases[] = [
$this->getMockNode(TRUE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1),
array('view_mode' => $view_mode),
['view_mode' => $view_mode],
TRUE,
TRUE,
TRUE,
TRUE,
array(),
);
[],
];
}
// All other combinations.
$combinations = array(
'is_anonymous' => array(FALSE, TRUE),
'comment_count' => array(0, 1),
'has_access_comments' => array(0, 1),
'history_exists' => array(FALSE, TRUE),
'has_post_comments' => array(0, 1),
'form_location' => array(CommentItemInterface::FORM_BELOW, CommentItemInterface::FORM_SEPARATE_PAGE),
'comments' => array(
$combinations = [
'is_anonymous' => [FALSE, TRUE],
'comment_count' => [0, 1],
'has_access_comments' => [0, 1],
'history_exists' => [FALSE, TRUE],
'has_post_comments' => [0, 1],
'form_location' => [CommentItemInterface::FORM_BELOW, CommentItemInterface::FORM_SEPARATE_PAGE],
'comments' => [
CommentItemInterface::OPEN,
CommentItemInterface::CLOSED,
CommentItemInterface::HIDDEN,
),
'view_mode' => array(
],
'view_mode' => [
'teaser', 'rss', 'full',
),
);
],
];
$permutations = TestBase::generatePermutations($combinations);
foreach ($permutations as $combination) {
$case = array(
$case = [
$this->getMockNode(TRUE, $combination['comments'], $combination['form_location'], $combination['comment_count']),
array('view_mode' => $combination['view_mode']),
['view_mode' => $combination['view_mode']],
$combination['has_access_comments'],
$combination['history_exists'],
$combination['has_post_comments'],
$combination['is_anonymous'],
);
$expected = array();
];
$expected = [];
// When comments are enabled in teaser mode, and comments exist, and the
// user has access - we can output the comment count.
if ($combination['comments'] && $combination['view_mode'] == 'teaser' && $combination['comment_count'] && $combination['has_access_comments']) {
@ -225,7 +225,7 @@ class CommentLinkBuilderTest extends UnitTestCase {
// comments exist or the form is on a separate page.
if ($combination['view_mode'] == 'teaser' || ($combination['has_access_comments'] && $combination['comment_count']) || $combination['form_location'] == CommentItemInterface::FORM_SEPARATE_PAGE) {
// There should be a add comment link.
$expected['comment-add'] = array('title' => 'Add new comment');
$expected['comment-add'] = ['title' => 'Add new comment'];
if ($combination['form_location'] == CommentItemInterface::FORM_BELOW) {
// On the same page.
$expected['comment-add']['url'] = Url::fromRoute('node.view');
@ -274,11 +274,11 @@ class CommentLinkBuilderTest extends UnitTestCase {
if (empty($this->timestamp)) {
$this->timestamp = time();
}
$field_item = (object) array(
$field_item = (object) [
'status' => $comment_status,
'comment_count' => $comment_count,
'last_comment_timestamp' => $this->timestamp,
);
];
$node->expects($this->any())
->method('get')
->with('comment')
@ -312,7 +312,7 @@ class CommentLinkBuilderTest extends UnitTestCase {
->willReturn($url);
$node->expects($this->any())
->method('url')
->willReturn(array('route_name' => 'node.view'));
->willReturn(['route_name' => 'node.view']);
return $node;
}

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\comment\Unit;
use Drupal\comment\CommentManager;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Tests\UnitTestCase;
/**
@ -23,21 +24,21 @@ class CommentManagerTest extends UnitTestCase {
->method('getClass')
->will($this->returnValue('Node'));
$entity_type->expects($this->any())
->method('isSubclassOf')
->with('\Drupal\Core\Entity\FieldableEntityInterface')
->method('entityClassImplements')
->with(FieldableEntityInterface::class)
->will($this->returnValue(TRUE));
$entity_manager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$entity_manager->expects($this->once())
->method('getFieldMapByFieldType')
->will($this->returnValue(array(
'node' => array(
'field_foobar' => array(
->will($this->returnValue([
'node' => [
'field_foobar' => [
'type' => 'comment',
),
),
)));
],
],
]));
$entity_manager->expects($this->any())
->method('getDefinition')
@ -45,7 +46,6 @@ class CommentManagerTest extends UnitTestCase {
$comment_manager = new CommentManager(
$entity_manager,
$this->getMockBuilder('Drupal\Core\Entity\Query\QueryFactory')->disableOriginalConstructor()->getMock(),
$this->getMock('Drupal\Core\Config\ConfigFactoryInterface'),
$this->getMock('Drupal\Core\StringTranslation\TranslationInterface'),
$this->getMock('Drupal\Core\Routing\UrlGeneratorInterface'),

View file

@ -56,7 +56,7 @@ class CommentStatisticsUnitTest extends UnitTestCase {
$this->statement->expects($this->any())
->method('fetchObject')
->will($this->returnCallback(array($this, 'fetchObjectCallback')));
->will($this->returnCallback([$this, 'fetchObjectCallback']));
$this->select = $this->getMockBuilder('Drupal\Core\Database\Query\Select')
->disableOriginalConstructor()
@ -95,8 +95,8 @@ class CommentStatisticsUnitTest extends UnitTestCase {
*/
public function testRead() {
$this->calls_to_fetch = 0;
$results = $this->commentStatistics->read(array('1' => 'boo', '2' => 'foo'), 'snafoos');
$this->assertEquals($results, array('something', 'something-else'));
$results = $this->commentStatistics->read(['1' => 'boo', '2' => 'foo'], 'snafoos');
$this->assertEquals($results, ['something', 'something-else']);
}
/**

Some files were not shown because too many files have changed in this diff Show more