View source
<?php
namespace Drupal\Tests\statistics\Functional;
use Drupal\Component\Render\FormattableMarkup;
class StatisticsTokenReplaceTest extends StatisticsTestBase {
protected $defaultTheme = 'stark';
public function testStatisticsTokenReplacement() {
$language_interface = \Drupal::languageManager()
->getCurrentLanguage();
$user = $this
->drupalCreateUser([
'create page content',
]);
$this
->drupalLogin($user);
$node = $this
->drupalCreateNode([
'type' => 'page',
'uid' => $user
->id(),
]);
$date_formatter = $this->container
->get('date.formatter');
$request_time = \Drupal::time()
->getRequestTime();
$tests = [];
$tests['[node:total-count]'] = 0;
$tests['[node:day-count]'] = 0;
$tests['[node:last-view]'] = t('never');
$tests['[node:last-view:short]'] = $date_formatter
->format($request_time, 'short');
foreach ($tests as $input => $expected) {
$output = \Drupal::token()
->replace($input, [
'node' => $node,
], [
'langcode' => $language_interface
->getId(),
]);
$this
->assertEquals($expected, $output, new FormattableMarkup('Statistics token %token replaced.', [
'%token' => $input,
]));
}
$this
->drupalGet('node/' . $node
->id());
$nid = $node
->id();
$post = http_build_query([
'nid' => $nid,
]);
$headers = [
'Content-Type' => 'application/x-www-form-urlencoded',
];
global $base_url;
$stats_path = $base_url . '/' . $this
->getModulePath('statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client
->post($stats_path, [
'headers' => $headers,
'body' => $post,
]);
$statistics = \Drupal::service('statistics.storage.node')
->fetchView($node
->id());
$tests = [];
$tests['[node:total-count]'] = 1;
$tests['[node:day-count]'] = 1;
$tests['[node:last-view]'] = $date_formatter
->format($statistics
->getTimestamp());
$tests['[node:last-view:short]'] = $date_formatter
->format($statistics
->getTimestamp(), 'short');
$this
->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = \Drupal::token()
->replace($input, [
'node' => $node,
], [
'langcode' => $language_interface
->getId(),
]);
$this
->assertEquals($expected, $output, new FormattableMarkup('Statistics token %token replaced.', [
'%token' => $input,
]));
}
}
}