FieldWebTest.php 28.8 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2
<?php

3
namespace Drupal\Tests\views\Functional\Handler;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Component\Utility\UrlHelper;
8
use Drupal\Core\Render\RenderContext;
9
use Drupal\Core\Url;
10
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
11
use Drupal\Tests\views\Functional\ViewTestBase;
12 13
use Drupal\views\Views;

merlinofchaos's avatar
merlinofchaos committed
14
/**
15
 * Tests fields from within a UI.
merlinofchaos's avatar
merlinofchaos committed
16
 *
17
 * @group views
18
 * @see \Drupal\views\Plugin\views\field\FieldPluginBase
merlinofchaos's avatar
merlinofchaos committed
19
 */
20
class FieldWebTest extends ViewTestBase {
21

22 23
  use AssertPageCacheContextsAndTagsTrait;

24 25 26 27 28
  /**
   * Views used by this test.
   *
   * @var array
   */
29
  public static $testViews = ['test_view', 'test_field_classes', 'test_field_output', 'test_click_sort'];
30

31 32 33 34 35
  /**
   * {@inheritdoc}
   */
  public static $modules = ['node'];

36 37 38 39 40
  /**
   * Maps between the key in the expected result and the query result.
   *
   * @var array
   */
41
  protected $columnMap = [
42
    'views_test_data_name' => 'name',
43
  ];
44

45 46
  protected function setUp($import_test_views = TRUE) {
    parent::setUp($import_test_views);
47 48

    $this->enableViewsTestModule();
merlinofchaos's avatar
merlinofchaos committed
49 50
  }

51
  /**
52
   * {@inheritdoc}
53 54 55
   */
  protected function viewsData() {
    $data = parent::viewsData();
56
    $data['views_test_data']['job']['field']['id'] = 'test_field';
57 58 59 60 61 62 63 64
    return $data;
  }

  /**
   * Tests the click sorting functionality.
   */
  public function testClickSorting() {
    $this->drupalGet('test_click_sort');
65
    $this->assertResponse(200);
66

67
    // Only the id and name should be click sortable, but not the name.
68 69 70
    $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'id', 'sort' => 'asc']]));
    $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'name', 'sort' => 'desc']]));
    $this->assertNoLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'created']]));
71

72 73 74 75
    // Check that the view returns the click sorting cache contexts.
    $expected_contexts = [
      'languages:language_interface',
      'theme',
76
      'url.query_args',
77 78 79
    ];
    $this->assertCacheContexts($expected_contexts);

80 81
    // Clicking a click sort should change the order.
    $this->clickLink(t('ID'));
82
    $this->assertLinkByHref(\Drupal::url('<none>', [], ['query' => ['order' => 'id', 'sort' => 'desc']]));
83 84 85 86
    // Check that the output has the expected order (asc).
    $ids = $this->clickSortLoadIdsFromOutput();
    $this->assertEqual($ids, range(1, 5));

87
    $this->clickLink(t('ID Sort descending'));
88 89 90 91 92 93 94 95 96 97 98 99 100
    // Check that the output has the expected order (desc).
    $ids = $this->clickSortLoadIdsFromOutput();
    $this->assertEqual($ids, range(5, 1, -1));
  }

  /**
   * Small helper function to get all ids in the output.
   *
   * @return array
   *   A list of beatle ids.
   */
  protected function clickSortLoadIdsFromOutput() {
    $fields = $this->xpath("//td[contains(@class, 'views-field-id')]");
101
    $ids = [];
102
    foreach ($fields as $field) {
103
      $ids[] = (int) $field->getText();
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    }
    return $ids;
  }

  /**
   * Assertion helper which checks whether a string is part of another string.
   *
   * @param string $haystack
   *   The value to search in.
   * @param string $needle
   *   The value to search for.
   * @param string $message
   *   The message to display along with the assertion.
   * @param string $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return bool
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertSubString($haystack, $needle, $message = '', $group = 'Other') {
    return $this->assertTrue(strpos($haystack, $needle) !== FALSE, $message, $group);
  }

  /**
   * Assertion helper which checks whether a string is not part of another string.
   *
   * @param string $haystack
   *   The value to search in.
   * @param string $needle
   *   The value to search for.
   * @param string $message
   *   The message to display along with the assertion.
   * @param string $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return bool
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertNotSubString($haystack, $needle, $message = '', $group = 'Other') {
    return $this->assertTrue(strpos($haystack, $needle) === FALSE, $message, $group);
  }

  /**
   * Parse a content and return the html element.
   *
   * @param string $content
   *   The html to parse.
   *
   * @return array
   *   An array containing simplexml objects.
   */
  protected function parseContent($content) {
154
    $htmlDom = new \DOMDocument();
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    @$htmlDom->loadHTML('<?xml encoding="UTF-8">' . $content);
    $elements = simplexml_import_dom($htmlDom);

    return $elements;
  }

  /**
   * Performs an xpath search on a certain content.
   *
   * The search is relative to the root element of the $content variable.
   *
   * @param string $content
   *   The html to parse.
   * @param string $xpath
   *   The xpath string to use in the search.
   * @param array $arguments
   *   Some arguments for the xpath.
   *
173
   * @return array|false
174 175 176 177
   *   The return value of the xpath search. For details on the xpath string
   *   format and return values see the SimpleXML documentation,
   *   http://php.net/manual/function.simplexml-element-xpath.php.
   */
178
  protected function xpathContent($content, $xpath, array $arguments = []) {
179 180 181 182 183 184
    if ($elements = $this->parseContent($content)) {
      $xpath = $this->buildXPathQuery($xpath, $arguments);
      $result = $elements->xpath($xpath);
      // Some combinations of PHP / libxml versions return an empty array
      // instead of the documented FALSE. Forcefully convert any falsish values
      // to an empty array to allow foreach(...) constructions.
185
      return $result ? $result : [];
186 187 188 189 190 191 192 193 194 195
    }
    else {
      return FALSE;
    }
  }

  /**
   * Tests rewriting the output to a link.
   */
  public function testAlterUrl() {
196 197 198
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

199
    $view = Views::getView('test_view');
200
    $view->setDisplay();
201 202 203 204 205 206 207
    $view->initHandlers();
    $this->executeView($view);
    $row = $view->result[0];
    $id_field = $view->field['id'];

    // Setup the general settings required to build a link.
    $id_field->options['alter']['make_link'] = TRUE;
208
    $id_field->options['alter']['path'] = $path = $this->randomMachineName();
209 210

    // Tests that the suffix/prefix appears on the output.
211 212
    $id_field->options['alter']['prefix'] = $prefix = $this->randomMachineName();
    $id_field->options['alter']['suffix'] = $suffix = $this->randomMachineName();
213 214 215
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
216 217 218 219 220
    $this->assertSubString($output, $prefix);
    $this->assertSubString($output, $suffix);
    unset($id_field->options['alter']['prefix']);
    unset($id_field->options['alter']['suffix']);

221 222 223
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
224 225 226 227
    $this->assertSubString($output, $path, 'Make sure that the path is part of the output');

    // Some generic test code adapted from the UrlTest class, which tests
    // mostly the different options for the path.
228
    foreach ([FALSE, TRUE] as $absolute) {
229
      $alter = &$id_field->options['alter'];
230 231
      $alter['path'] = 'node/123';

232
      $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['absolute' => $absolute]);
233
      $alter['absolute'] = $absolute;
234 235 236
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
237 238
      $this->assertSubString($result, $expected_result);

239
      $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['fragment' => 'foo', 'absolute' => $absolute]);
240
      $alter['path'] = 'node/123#foo';
241 242 243
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
244 245
      $this->assertSubString($result, $expected_result);

246
      $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'absolute' => $absolute]);
247
      $alter['path'] = 'node/123?foo';
248 249 250
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
251 252
      $this->assertSubString($result, $expected_result);

253
      $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => 'bar', 'bar' => 'baz'], 'absolute' => $absolute]);
254
      $alter['path'] = 'node/123?foo=bar&bar=baz';
255 256 257
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
258
      $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
259

260 261
      // @todo The route-based URL generator strips out NULL attributes.
      // $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute]);
262
      $expected_result = Url::fromUserInput('/node/123', ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute])->toString();
263
      $alter['path'] = 'node/123?foo#bar';
264 265 266
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
267
      $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
268

269
      $expected_result = \Drupal::url('<front>', [], ['absolute' => $absolute]);
270
      $alter['path'] = '<front>';
271 272 273
      $result = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
        return $id_field->theme($row);
      });
274 275 276 277 278
      $this->assertSubString($result, $expected_result);
    }

    // Tests the replace spaces with dashes feature.
    $id_field->options['alter']['replace_spaces'] = TRUE;
279
    $id_field->options['alter']['path'] = $path = $this->randomMachineName() . ' ' . $this->randomMachineName();
280 281 282
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
283 284
    $this->assertSubString($output, str_replace(' ', '-', $path));
    $id_field->options['alter']['replace_spaces'] = FALSE;
285 286 287
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
288 289 290 291 292 293
    // The url has a space in it, so to check we have to decode the url output.
    $this->assertSubString(urldecode($output), $path);

    // Tests the external flag.
    // Switch on the external flag should output an external url as well.
    $id_field->options['alter']['external'] = TRUE;
294
    $id_field->options['alter']['path'] = $path = 'www.drupal.org';
295 296 297
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
298
    $this->assertSubString($output, 'http://www.drupal.org');
299 300 301

    // Setup a not external url, which shouldn't lead to an external url.
    $id_field->options['alter']['external'] = FALSE;
302
    $id_field->options['alter']['path'] = $path = 'www.drupal.org';
303 304 305
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
306
    $this->assertNotSubString($output, 'http://www.drupal.org');
307 308

    // Tests the transforming of the case setting.
309
    $id_field->options['alter']['path'] = $path = $this->randomMachineName();
310
    $id_field->options['alter']['path_case'] = 'none';
311 312 313
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
314 315 316 317
    $this->assertSubString($output, $path);

    // Switch to uppercase and lowercase.
    $id_field->options['alter']['path_case'] = 'upper';
318 319 320
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
321 322
    $this->assertSubString($output, strtoupper($path));
    $id_field->options['alter']['path_case'] = 'lower';
323 324 325
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
326 327 328 329 330
    $this->assertSubString($output, strtolower($path));

    // Switch to ucfirst and ucwords.
    $id_field->options['alter']['path_case'] = 'ucfirst';
    $id_field->options['alter']['path'] = 'drupal has a great community';
331 332 333
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
334
    $this->assertSubString($output, UrlHelper::encodePath('Drupal has a great community'));
335 336

    $id_field->options['alter']['path_case'] = 'ucwords';
337 338 339
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
340
    $this->assertSubString($output, UrlHelper::encodePath('Drupal Has A Great Community'));
341 342
    unset($id_field->options['alter']['path_case']);

343 344
    // Tests the linkclass setting and see whether it actually exists in the
    // output.
345
    $id_field->options['alter']['link_class'] = $class = $this->randomMachineName();
346 347 348
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
349
    $elements = $this->xpathContent($output, '//a[contains(@class, :class)]', [':class' => $class]);
350 351 352 353 354
    $this->assertTrue($elements);
    // @fixme link_class, alt, rel cannot be unset, which should be fixed.
    $id_field->options['alter']['link_class'] = '';

    // Tests the alt setting.
355
    $id_field->options['alter']['alt'] = $rel = $this->randomMachineName();
356 357 358
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
359
    $elements = $this->xpathContent($output, '//a[contains(@title, :alt)]', [':alt' => $rel]);
360 361 362 363
    $this->assertTrue($elements);
    $id_field->options['alter']['alt'] = '';

    // Tests the rel setting.
364
    $id_field->options['alter']['rel'] = $rel = $this->randomMachineName();
365 366 367
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
368
    $elements = $this->xpathContent($output, '//a[contains(@rel, :rel)]', [':rel' => $rel]);
369 370 371 372
    $this->assertTrue($elements);
    $id_field->options['alter']['rel'] = '';

    // Tests the target setting.
373
    $id_field->options['alter']['target'] = $target = $this->randomMachineName();
374 375 376
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($id_field, $row) {
      return $id_field->theme($row);
    });
377
    $elements = $this->xpathContent($output, '//a[contains(@target, :target)]', [':target' => $target]);
378 379 380 381 382 383 384 385
    $this->assertTrue($elements);
    unset($id_field->options['alter']['target']);
  }

  /**
   * Tests the field/label/wrapper classes.
   */
  public function testFieldClasses() {
386 387
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');
388
    $view = Views::getView('test_field_classes');
389 390 391 392 393 394
    $view->initHandlers();

    // Tests whether the default field classes are added.
    $id_field = $view->field['id'];

    $id_field->options['element_default_classes'] = FALSE;
395 396
    // Setup some kind of label by default.
    $id_field->options['label'] = $this->randomMachineName();
397
    $output = $view->preview();
398
    $output = $renderer->renderRoot($output);
399 400
    $this->assertFalse($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field-content']));
    $this->assertFalse($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field__label']));
401 402 403

    $id_field->options['element_default_classes'] = TRUE;
    $output = $view->preview();
404
    $output = $renderer->renderRoot($output);
405
    // Per default the label and the element of the field are spans.
406 407 408
    $this->assertTrue($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'field-content']));
    $this->assertTrue($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'views-label']));
    $this->assertTrue($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'views-field']));
409 410

    // Tests the element wrapper classes/element.
411
    $random_class = $this->randomMachineName();
412 413

    // Set some common wrapper element types and see whether they appear with and without a custom class set.
414
    foreach (['h1', 'span', 'p', 'div'] as $element_type) {
415 416 417 418 419
      $id_field->options['element_wrapper_type'] = $element_type;

      // Set a custom wrapper element css class.
      $id_field->options['element_wrapper_class'] = $random_class;
      $output = $view->preview();
420
      $output = $renderer->renderRoot($output);
421
      $this->assertTrue($this->xpathContent($output, "//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
422 423 424 425

      // Set no custom css class.
      $id_field->options['element_wrapper_class'] = '';
      $output = $view->preview();
426
      $output = $renderer->renderRoot($output);
427
      $this->assertFalse($this->xpathContent($output, "//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
428 429 430 431 432 433
      $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]/{$element_type}"));
    }

    // Tests the label class/element.

    // Set some common label element types and see whether they appear with and without a custom class set.
434
    foreach (['h1', 'span', 'p', 'div'] as $element_type) {
435 436 437 438 439
      $id_field->options['element_label_type'] = $element_type;

      // Set a custom label element css class.
      $id_field->options['element_label_class'] = $random_class;
      $output = $view->preview();
440
      $output = $renderer->renderRoot($output);
441
      $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
442 443 444 445

      // Set no custom css class.
      $id_field->options['element_label_class'] = '';
      $output = $view->preview();
446
      $output = $renderer->renderRoot($output);
447
      $this->assertFalse($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
448 449 450 451 452 453
      $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//{$element_type}"));
    }

    // Tests the element classes/element.

    // Set some common element element types and see whether they appear with and without a custom class set.
454
    foreach (['h1', 'span', 'p', 'div'] as $element_type) {
455 456 457 458 459
      $id_field->options['element_type'] = $element_type;

      // Set a custom label element css class.
      $id_field->options['element_class'] = $random_class;
      $output = $view->preview();
460
      $output = $renderer->renderRoot($output);
461
      $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
462 463 464 465

      // Set no custom css class.
      $id_field->options['element_class'] = '';
      $output = $view->preview();
466
      $output = $renderer->renderRoot($output);
467
      $this->assertFalse($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}[contains(@class, :class)]", [':class' => $random_class]));
468 469 470 471
      $this->assertTrue($this->xpathContent($output, "//li[contains(@class, views-row)]//div[contains(@class, views-field)]//{$element_type}"));
    }

    // Tests the available html elements.
472
    $element_types = $id_field->getElements();
473
    $expected_elements = [
474
      '',
475
      0,
476 477 478 479 480 481 482 483 484 485 486 487
      'div',
      'span',
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6',
      'p',
      'strong',
      'em',
      'marquee'
488
    ];
489

490 491 492 493 494 495 496
    $this->assertEqual(array_keys($element_types), $expected_elements);
  }

  /**
   * Tests trimming/read-more/ellipses.
   */
  public function testTextRendering() {
497 498 499
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

500
    $view = Views::getView('test_field_output');
501 502 503 504 505
    $view->initHandlers();
    $name_field = $view->field['name'];

    // Tests stripping of html elements.
    $this->executeView($view);
506
    $random_text = $this->randomMachineName();
507 508 509 510 511
    $name_field->options['alter']['alter_text'] = TRUE;
    $name_field->options['alter']['text'] = $html_text = '<div class="views-test">' . $random_text . '</div>';
    $row = $view->result[0];

    $name_field->options['alter']['strip_tags'] = TRUE;
512 513 514
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
515 516 517 518 519
    $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is enabled.');
    $this->assertNotSubString($output, $html_text, 'Find no text with the html if stripping of views field output is enabled.');

    // Tests preserving of html tags.
    $name_field->options['alter']['preserve_tags'] = '<div>';
520 521 522
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
523 524 525 526
    $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is enabled but a div is allowed.');
    $this->assertSubString($output, $html_text, 'Find text with the html if stripping of views field output is enabled but a div is allowed.');

    $name_field->options['alter']['strip_tags'] = FALSE;
527 528 529
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
530 531 532 533 534
    $this->assertSubString($output, $random_text, 'Find text without html if stripping of views field output is disabled.');
    $this->assertSubString($output, $html_text, 'Find text with the html if stripping of views field output is disabled.');

    // Tests for removing whitespace and the beginning and the end.
    $name_field->options['alter']['alter_text'] = FALSE;
535 536
    $views_test_data_name = $row->views_test_data_name;
    $row->views_test_data_name = '  ' . $views_test_data_name . '     ';
537
    $name_field->options['alter']['trim_whitespace'] = TRUE;
538 539 540
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
541

542 543
    $this->assertSubString($output, $views_test_data_name, 'Make sure the trimmed text can be found if trimming is enabled.');
    $this->assertNotSubString($output, $row->views_test_data_name, 'Make sure the untrimmed text can be found if trimming is enabled.');
544 545

    $name_field->options['alter']['trim_whitespace'] = FALSE;
546 547 548
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
549 550
    $this->assertSubString($output, $views_test_data_name, 'Make sure the trimmed text can be found if trimming is disabled.');
    $this->assertSubString($output, $row->views_test_data_name, 'Make sure the untrimmed text can be found  if trimming is disabled.');
551 552 553 554 555 556

    // Tests for trimming to a maximum length.
    $name_field->options['alter']['trim'] = TRUE;
    $name_field->options['alter']['word_boundary'] = FALSE;

    // Tests for simple trimming by string length.
557
    $row->views_test_data_name = $this->randomMachineName(8);
558
    $name_field->options['alter']['max_length'] = 5;
559
    $trimmed_name = Unicode::substr($row->views_test_data_name, 0, 5);
560

561 562 563
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
564 565
    $this->assertSubString($output, $trimmed_name, format_string('Make sure the trimmed output (@trimmed) appears in the rendered output (@output).', ['@trimmed' => $trimmed_name, '@output' => $output]));
    $this->assertNotSubString($output, $row->views_test_data_name, format_string("Make sure the untrimmed value (@untrimmed) shouldn't appear in the rendered output (@output).", ['@untrimmed' => $row->views_test_data_name, '@output' => $output]));
566 567

    $name_field->options['alter']['max_length'] = 9;
568 569 570
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
571
    $this->assertSubString($output, $trimmed_name, format_string('Make sure the untrimmed (@untrimmed) output appears in the rendered output  (@output).', ['@trimmed' => $trimmed_name, '@output' => $output]));
572 573 574 575

    // Take word_boundary into account for the tests.
    $name_field->options['alter']['max_length'] = 5;
    $name_field->options['alter']['word_boundary'] = TRUE;
576 577 578
    $random_text_2 = $this->randomMachineName(2);
    $random_text_4 = $this->randomMachineName(4);
    $random_text_8 = $this->randomMachineName(8);
579
    $tuples = [
580
      // Create one string which doesn't fit at all into the limit.
581
      [
582 583 584
        'value' => $random_text_8,
        'trimmed_value' => '',
        'trimmed' => TRUE
585
      ],
586
      // Create one string with two words which doesn't fit both into the limit.
587
      [
588 589 590
        'value' => $random_text_8 . ' ' . $random_text_8,
        'trimmed_value' => '',
        'trimmed' => TRUE
591
      ],
592 593
      // Create one string which contains of two words, of which only the first
      // fits into the limit.
594
      [
595 596 597
        'value' => $random_text_4 . ' ' . $random_text_8,
        'trimmed_value' => $random_text_4,
        'trimmed' => TRUE
598
      ],
599 600
      // Create one string which contains of two words, of which both fits into
      // the limit.
601
      [
602 603 604
        'value' => $random_text_2 . ' ' . $random_text_2,
        'trimmed_value' => $random_text_2 . ' ' . $random_text_2,
        'trimmed' => FALSE
605 606
      ]
    ];
607

608 609
    foreach ($tuples as $tuple) {
      $row->views_test_data_name = $tuple['value'];
610 611 612
      $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
        return $name_field->advancedRender($row);
      });
613

614
      if ($tuple['trimmed']) {
615
        $this->assertNotSubString($output, $tuple['value'], format_string('The untrimmed value (@untrimmed) should not appear in the trimmed output (@output).', ['@untrimmed' => $tuple['value'], '@output' => $output]));
616
      }
617
      if (!empty($tuple['trimmed_value'])) {
618
        $this->assertSubString($output, $tuple['trimmed_value'], format_string('The trimmed value (@trimmed) should appear in the trimmed output (@output).', ['@trimmed' => $tuple['trimmed_value'], '@output' => $output]));
619 620 621 622
      }
    }

    // Tests for displaying a readmore link when the output got trimmed.
623
    $row->views_test_data_name = $this->randomMachineName(8);
624 625
    $name_field->options['alter']['max_length'] = 5;
    $name_field->options['alter']['more_link'] = TRUE;
626 627
    $name_field->options['alter']['more_link_text'] = $more_text = $this->randomMachineName();
    $name_field->options['alter']['more_link_path'] = $more_path = $this->randomMachineName();
628

629 630 631
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
632
    $this->assertSubString($output, $more_text, 'Make sure a read more text is displayed if the output got trimmed');
633
    $this->assertTrue($this->xpathContent($output, '//a[contains(@href, :path)]', [':path' => $more_path]), 'Make sure the read more link points to the right destination.');
634 635

    $name_field->options['alter']['more_link'] = FALSE;
636 637 638
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
639
    $this->assertNotSubString($output, $more_text, 'Make sure no read more text appears.');
640
    $this->assertFalse($this->xpathContent($output, '//a[contains(@href, :path)]', [':path' => $more_path]), 'Make sure no read more link appears.');
641 642

    // Check for the ellipses.
643
    $row->views_test_data_name = $this->randomMachineName(8);
644
    $name_field->options['alter']['max_length'] = 5;
645 646 647
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
648
    $this->assertSubString($output, '…', 'An ellipsis should appear if the output is trimmed');
649
    $name_field->options['alter']['max_length'] = 10;
650 651 652
    $output = $renderer->executeInRenderContext(new RenderContext(), function () use ($name_field, $row) {
      return $name_field->advancedRender($row);
    });
653
    $this->assertNotSubString($output, '…', 'No ellipsis should appear if the output is not trimmed');
654 655
  }

merlinofchaos's avatar
merlinofchaos committed
656
}