2015-08-17 17:00:26 -07:00
< ? php
/**
* @ file
* Builds placeholder replacement tokens for node visitor statistics .
*/
2015-08-27 12:03:05 -07:00
use Drupal\Core\Render\BubbleableMetadata ;
2015-08-17 17:00:26 -07:00
/**
* Implements hook_token_info () .
*/
function statistics_token_info () {
2017-04-13 15:53:35 +01:00
$node [ 'total-count' ] = [
2015-08-17 17:00:26 -07:00
'name' => t ( " Number of views " ),
'description' => t ( " The number of visitors who have read the node. " ),
2017-04-13 15:53:35 +01:00
];
$node [ 'day-count' ] = [
2015-08-17 17:00:26 -07:00
'name' => t ( " Views today " ),
'description' => t ( " The number of visitors who have read the node today. " ),
2017-04-13 15:53:35 +01:00
];
$node [ 'last-view' ] = [
2015-08-17 17:00:26 -07:00
'name' => t ( " Last view " ),
'description' => t ( " The date on which a visitor last read the node. " ),
'type' => 'date' ,
2017-04-13 15:53:35 +01:00
];
2015-08-17 17:00:26 -07:00
2017-04-13 15:53:35 +01:00
return [
'tokens' => [ 'node' => $node ],
];
2015-08-17 17:00:26 -07:00
}
/**
* Implements hook_tokens () .
*/
2015-08-27 12:03:05 -07:00
function statistics_tokens ( $type , $tokens , array $data , array $options , BubbleableMetadata $bubbleable_metadata ) {
2015-08-17 17:00:26 -07:00
$token_service = \Drupal :: token ();
2017-04-13 15:53:35 +01:00
$replacements = [];
2015-08-17 17:00:26 -07:00
if ( $type == 'node' & ! empty ( $data [ 'node' ])) {
$node = $data [ 'node' ];
foreach ( $tokens as $name => $original ) {
if ( $name == 'total-count' ) {
$statistics = statistics_get ( $node -> id ());
$replacements [ $original ] = $statistics [ 'totalcount' ];
}
elseif ( $name == 'day-count' ) {
$statistics = statistics_get ( $node -> id ());
$replacements [ $original ] = $statistics [ 'daycount' ];
}
elseif ( $name == 'last-view' ) {
$statistics = statistics_get ( $node -> id ());
$replacements [ $original ] = format_date ( $statistics [ 'timestamp' ]);
}
}
if ( $created_tokens = $token_service -> findWithPrefix ( $tokens , 'last-view' )) {
$statistics = statistics_get ( $node -> id ());
2017-04-13 15:53:35 +01:00
$replacements += $token_service -> generate ( 'date' , $created_tokens , [ 'date' => $statistics [ 'timestamp' ]], $options , $bubbleable_metadata );
2015-08-17 17:00:26 -07:00
}
}
return $replacements ;
}