CommentLinkBuilderTest.php 10.7 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\comment\Unit;
4 5 6

use Drupal\comment\CommentLinkBuilder;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
7
use Drupal\Core\Url;
8
use Drupal\node\NodeInterface;
9
use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
10 11 12 13 14 15 16 17
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\comment\CommentLinkBuilder
 * @group comment
 */
class CommentLinkBuilderTest extends UnitTestCase {

18 19
  use GeneratePermutationsTrait;

20 21 22 23 24 25 26 27 28 29 30 31 32 33
  /**
   * Comment manager mock.
   *
   * @var \Drupal\comment\CommentManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $commentManager;

  /**
   * String translation mock.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $stringTranslation;

34 35 36 37 38 39 40
  /**
   * The entity manager service.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
  /**
   * Module handler mock.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $moduleHandler;

  /**
   * Current user proxy mock.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $currentUser;

  /**
   * Timestamp used in test.
   *
   * @var int
   */
  protected $timestamp;

  /**
63
   * @var \Drupal\comment\CommentLinkBuilderInterface
64 65 66 67 68 69
   */
  protected $commentLinkBuilder;

  /**
   * Prepares mocks for the test.
   */
70
  protected function setUp() {
71 72
    $this->commentManager = $this->getMock('\Drupal\comment\CommentManagerInterface');
    $this->stringTranslation = $this->getStringTranslationStub();
73
    $this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');
74 75
    $this->moduleHandler = $this->getMock('\Drupal\Core\Extension\ModuleHandlerInterface');
    $this->currentUser = $this->getMock('\Drupal\Core\Session\AccountProxyInterface');
76
    $this->commentLinkBuilder = new CommentLinkBuilder($this->currentUser, $this->commentManager, $this->moduleHandler, $this->stringTranslation, $this->entityManager);
77 78 79
    $this->commentManager->expects($this->any())
      ->method('getFields')
      ->with('node')
80 81 82
      ->willReturn([
        'comment' => [],
      ]);
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    $this->commentManager->expects($this->any())
      ->method('forbiddenMessage')
      ->willReturn("Can't let you do that Dave.");
    $this->stringTranslation->expects($this->any())
      ->method('formatPlural')
      ->willReturnArgument(1);
  }

  /**
   * Test the buildCommentedEntityLinks method.
   *
   * @param \Drupal\node\NodeInterface|\PHPUnit_Framework_MockObject_MockObject $node
   *   Mock node.
   * @param array $context
   *   Context for the links.
   * @param bool $has_access_comments
   *   TRUE if the user has 'access comments' permission.
   * @param bool $history_exists
   *   TRUE if the history module exists.
   * @param bool $has_post_comments
   *   TRUE if the use has 'post comments' permission.
   * @param bool $is_anonymous
   *   TRUE if the user is anonymous.
   * @param array $expected
   *   Array of expected links keyed by link ID. Can be either string (link
   *   title) or array of link properties.
   *
   * @dataProvider getLinkCombinations
   *
112
   * @covers ::buildCommentedEntityLinks
113 114 115 116 117 118 119 120
   */
  public function testCommentLinkBuilder(NodeInterface $node, $context, $has_access_comments, $history_exists, $has_post_comments, $is_anonymous, $expected) {
    $this->moduleHandler->expects($this->any())
      ->method('moduleExists')
      ->with('history')
      ->willReturn($history_exists);
    $this->currentUser->expects($this->any())
      ->method('hasPermission')
121 122 123 124
      ->willReturnMap([
        ['access comments', $has_access_comments],
        ['post comments', $has_post_comments],
      ]);
125 126 127 128 129 130 131 132 133 134 135 136 137
    $this->currentUser->expects($this->any())
      ->method('isAuthenticated')
      ->willReturn(!$is_anonymous);
    $this->currentUser->expects($this->any())
      ->method('isAnonymous')
      ->willReturn($is_anonymous);
    $links = $this->commentLinkBuilder->buildCommentedEntityLinks($node, $context);
    if (!empty($expected)) {
      if (!empty($links)) {
        foreach ($expected as $link => $detail) {
          if (is_array($detail)) {
            // Array of link attributes.
            foreach ($detail as $key => $value) {
138
              $this->assertEquals($value, $links['comment__comment']['#links'][$link][$key]);
139 140 141 142
            }
          }
          else {
            // Just the title.
143
            $this->assertEquals($detail, $links['comment__comment']['#links'][$link]['title']);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
          }
        }
      }
      else {
        $this->fail('Expected links but found none.');
      }
    }
    else {
      $this->assertSame($links, $expected);
    }
  }

  /**
   * Data provider for ::testCommentLinkBuilder.
   */
  public function getLinkCombinations() {
160
    $cases = [];
161
    // No links should be created if the entity doesn't have the field.
162
    $cases[] = [
163
      $this->getMockNode(FALSE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1),
164
      ['view_mode' => 'teaser'],
165 166 167 168
      TRUE,
      TRUE,
      TRUE,
      TRUE,
169 170 171
      [],
    ];
    foreach (['search_result', 'search_index', 'print'] as $view_mode) {
172
      // Nothing should be output in these view modes.
173
      $cases[] = [
174
        $this->getMockNode(TRUE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1),
175
        ['view_mode' => $view_mode],
176 177 178 179
        TRUE,
        TRUE,
        TRUE,
        TRUE,
180 181
        [],
      ];
182 183
    }
    // All other combinations.
184 185 186 187 188 189 190 191
    $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'        => [
192 193 194
        CommentItemInterface::OPEN,
        CommentItemInterface::CLOSED,
        CommentItemInterface::HIDDEN,
195 196
      ],
      'view_mode' => [
197
        'teaser', 'rss', 'full',
198 199
      ],
    ];
200
    $permutations = $this->generatePermutations($combinations);
201
    foreach ($permutations as $combination) {
202
      $case = [
203
        $this->getMockNode(TRUE, $combination['comments'], $combination['form_location'], $combination['comment_count']),
204
        ['view_mode' => $combination['view_mode']],
205 206 207 208
        $combination['has_access_comments'],
        $combination['history_exists'],
        $combination['has_post_comments'],
        $combination['is_anonymous'],
209 210
      ];
      $expected = [];
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
      // 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']) {
        $expected['comment-comments'] = '1 comment';
        // And if history module exists, we can show a 'new comments' link.
        if ($combination['history_exists']) {
          $expected['comment-new-comments'] = '';
        }
      }
      // All view modes other than RSS.
      if ($combination['view_mode'] != 'rss') {
        // Where commenting is open.
        if ($combination['comments'] == CommentItemInterface::OPEN) {
          // And the user has post-comments permission.
          if ($combination['has_post_comments']) {
            // If the view mode is teaser, or the user can access comments and
            // 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.
230
              $expected['comment-add'] = ['title' => 'Add new comment'];
231 232
              if ($combination['form_location'] == CommentItemInterface::FORM_BELOW) {
                // On the same page.
233
                $expected['comment-add']['url'] = Url::fromRoute('node.view');
234 235 236
              }
              else {
                // On a separate page.
237
                $expected['comment-add']['url'] = Url::fromRoute('comment.reply', ['entity_type' => 'node', 'entity' => 1, 'field_name' => 'comment']);
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
              }
            }
          }
          elseif ($combination['is_anonymous']) {
            // Anonymous users get the forbidden message if the can't post
            // comments.
            $expected['comment-forbidden'] = "Can't let you do that Dave.";
          }
        }
      }

      $case[] = $expected;
      $cases[] = $case;
    }
    return $cases;
  }

  /**
   * Builds a mock node based on given scenario.
   *
   * @param bool $has_field
   *   TRUE if the node has the 'comment' field.
   * @param int $comment_status
   *   One of CommentItemInterface::OPEN|HIDDEN|CLOSED
   * @param int $form_location
   *   One of CommentItemInterface::FORM_BELOW|FORM_SEPARATE_PAGE
   * @param int $comment_count
   *   Number of comments against the field.
   *
   * @return \Drupal\node\NodeInterface|\PHPUnit_Framework_MockObject_MockObject
   *   Mock node for testing.
   */
  protected function getMockNode($has_field, $comment_status, $form_location, $comment_count) {
    $node = $this->getMock('\Drupal\node\NodeInterface');
272
    $node->expects($this->any())
273 274 275 276 277 278
      ->method('hasField')
      ->willReturn($has_field);

    if (empty($this->timestamp)) {
      $this->timestamp = time();
    }
279
    $field_item = (object) [
280 281 282
      'status' => $comment_status,
      'comment_count' => $comment_count,
      'last_comment_timestamp' => $this->timestamp,
283
    ];
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    $node->expects($this->any())
      ->method('get')
      ->with('comment')
      ->willReturn($field_item);

    $field_definition = $this->getMock('\Drupal\Core\Field\FieldDefinitionInterface');
    $field_definition->expects($this->any())
      ->method('getSetting')
      ->with('form_location')
      ->willReturn($form_location);
    $node->expects($this->any())
      ->method('getFieldDefinition')
      ->with('comment')
      ->willReturn($field_definition);

    $node->expects($this->any())
      ->method('language')
      ->willReturn('und');

    $node->expects($this->any())
      ->method('getEntityTypeId')
      ->willReturn('node');

    $node->expects($this->any())
      ->method('id')
      ->willReturn(1);

311
    $url = Url::fromRoute('node.view');
312
    $node->expects($this->any())
313
      ->method('toUrl')
314 315 316
      ->willReturn($url);
    $node->expects($this->any())
      ->method('url')
317
      ->willReturn(['route_name' => 'node.view']);
318 319 320 321 322

    return $node;
  }

}
323

324
namespace Drupal\comment;
325

326
if (!function_exists('history_read')) {
327

328 329
  function history_read() {
    return 0;
330
  }
331

332
}