class TrackerController in Drupal 8
Same name and namespace in other branches
- 9 core/modules/tracker/src/Controller/TrackerController.php \Drupal\tracker\Controller\TrackerController
- 10 core/modules/tracker/src/Controller/TrackerController.php \Drupal\tracker\Controller\TrackerController
Controller for tracker pages.
Hierarchy
- class \Drupal\Core\Controller\ControllerBase implements ContainerInjectionInterface uses LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\tracker\Controller\TrackerController
Expanded class hierarchy of TrackerController
1 file declares its use of TrackerController
- tracker.pages.inc in core/
modules/ tracker/ tracker.pages.inc - User page callbacks for tracker.module.
File
- core/
modules/ tracker/ src/ Controller/ TrackerController.php, line 20
Namespace
Drupal\tracker\ControllerView source
class TrackerController extends ControllerBase {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* The database replica connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $databaseReplica;
/**
* The comment statistics.
*
* @var \Drupal\comment\CommentStatisticsInterface
*/
protected $commentStatistics;
/**
* The date formatter.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The node storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* Constructs a TrackerController object.
*
* @param \Drupal\Core\Database\Connection $database
* The database connection.
* @param \Drupal\Core\Database\Connection $databaseReplica
* The database replica connection.
* @param \Drupal\comment\CommentStatisticsInterface $commentStatistics
* The comment statistics.
* @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
* The date formatter.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity type manager.
*/
public function __construct(Connection $database, Connection $databaseReplica, CommentStatisticsInterface $commentStatistics, DateFormatterInterface $dateFormatter, EntityTypeManagerInterface $entityTypeManager) {
$this->database = $database;
$this->databaseReplica = $databaseReplica;
$this->commentStatistics = $commentStatistics;
$this->dateFormatter = $dateFormatter;
$this->entityTypeManager = $entityTypeManager;
$this->nodeStorage = $entityTypeManager
->getStorage('node');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('database'), $container
->get('database.replica'), $container
->get('comment.statistics'), $container
->get('date.formatter'), $container
->get('entity_type.manager'));
}
/**
* Title callback for the tracker.user_tab route.
*
* @param \Drupal\user\UserInterface $user
* The user.
*
* @return string
* The title.
*/
public function getTitle(UserInterface $user) {
return $user
->getDisplayName();
}
/**
* Checks access for the users recent content tracker page.
*
* @param \Drupal\user\UserInterface $user
* The user being viewed.
* @param \Drupal\Core\Session\AccountInterface $account
* The account viewing the page.
*
* @return \Drupal\Core\Access\AccessResult
* The access result.
*/
public function checkAccess(UserInterface $user, AccountInterface $account) {
return AccessResult::allowedIf($account
->isAuthenticated() && $user
->id() == $account
->id())
->cachePerUser();
}
/**
* Builds content for the tracker controllers.
*
* @param \Drupal\user\UserInterface|null $user
* (optional) The user account.
*
* @return array
* The render array.
*/
public function buildContent(UserInterface $user = NULL) {
if ($user) {
$query = $this->database
->select('tracker_user', 't')
->extend(PagerSelectExtender::class)
->addMetaData('base_table', 'tracker_user')
->condition('t.uid', $user
->id());
}
else {
$query = $this->databaseReplica
->select('tracker_node', 't')
->extend(PagerSelectExtender::class)
->addMetaData('base_table', 'tracker_node');
}
// This array acts as a placeholder for the data selected later
// while keeping the correct order.
$tracker_data = $query
->addTag('node_access')
->fields('t', [
'nid',
'changed',
])
->condition('t.published', 1)
->orderBy('t.changed', 'DESC')
->limit(25)
->execute()
->fetchAllAssoc('nid');
$cacheable_metadata = new CacheableMetadata();
$rows = [];
if (!empty($tracker_data)) {
// Load nodes into an array with the same order as $tracker_data.
/** @var \Drupal\node\NodeInterface[] $nodes */
$nodes = $this->nodeStorage
->loadMultiple(array_keys($tracker_data));
// Enrich the node data.
$result = $this->commentStatistics
->read($nodes, 'node', FALSE);
foreach ($result as $statistics) {
// The node ID may not be unique; there can be multiple comment fields.
// Make comment_count the total of all comments.
$nid = $statistics->entity_id;
if (empty($nodes[$nid]->comment_count) || !is_numeric($tracker_data[$nid]->comment_count)) {
$tracker_data[$nid]->comment_count = $statistics->comment_count;
}
else {
$tracker_data[$nid]->comment_count += $statistics->comment_count;
}
// Make the last comment timestamp reflect the latest comment.
if (!isset($tracker_data[$nid]->last_comment_timestamp)) {
$tracker_data[$nid]->last_comment_timestamp = $statistics->last_comment_timestamp;
}
else {
$tracker_data[$nid]->last_comment_timestamp = max($tracker_data[$nid]->last_comment_timestamp, $statistics->last_comment_timestamp);
}
}
// Display the data.
foreach ($nodes as $node) {
// Set the last activity time from tracker data. This also takes into
// account comment activity, so getChangedTime() is not used.
$last_activity = $tracker_data[$node
->id()]->changed;
$owner = $node
->getOwner();
$row = [
'type' => node_get_type_label($node),
'title' => [
'data' => [
'#type' => 'link',
'#url' => $node
->toUrl(),
'#title' => $node
->getTitle(),
],
'data-history-node-id' => $node
->id(),
'data-history-node-timestamp' => $node
->getChangedTime(),
],
'author' => [
'data' => [
'#theme' => 'username',
'#account' => $owner,
],
],
'comments' => [
'class' => [
'comments',
],
'data' => $tracker_data[$node
->id()]->comment_count ?? 0,
'data-history-node-last-comment-timestamp' => $tracker_data[$node
->id()]->last_comment_timestamp ?? 0,
],
'last updated' => [
'data' => t('@time ago', [
'@time' => $this->dateFormatter
->formatTimeDiffSince($last_activity),
]),
],
];
$rows[] = $row;
// Add node and node owner to cache tags.
$cacheable_metadata
->addCacheTags($node
->getCacheTags());
if ($owner) {
$cacheable_metadata
->addCacheTags($owner
->getCacheTags());
}
}
}
// Add the list cache tag for nodes.
$cacheable_metadata
->addCacheTags($this->nodeStorage
->getEntityType()
->getListCacheTags());
$page['tracker'] = [
'#rows' => $rows,
'#header' => [
$this
->t('Type'),
$this
->t('Title'),
$this
->t('Author'),
$this
->t('Comments'),
$this
->t('Last updated'),
],
'#type' => 'table',
'#empty' => $this
->t('No content available.'),
];
$page['pager'] = [
'#type' => 'pager',
'#weight' => 10,
];
$page['#sorted'] = TRUE;
$cacheable_metadata
->addCacheContexts([
'user.node_grants:view',
]);
// Display the reading history if that module is enabled.
if ($this
->moduleHandler()
->moduleExists('history')) {
// Reading history is tracked for authenticated users only.
if ($this
->currentUser()
->isAuthenticated()) {
$page['#attached']['library'][] = 'tracker/history';
}
$cacheable_metadata
->addCacheContexts([
'user.roles:authenticated',
]);
}
$cacheable_metadata
->applyTo($page);
return $page;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ControllerBase:: |
protected | property | The configuration factory. | |
ControllerBase:: |
protected | property | The current user service. | 1 |
ControllerBase:: |
protected | property | The entity form builder. | |
ControllerBase:: |
protected | property | The entity manager. | |
ControllerBase:: |
protected | property | The entity type manager. | |
ControllerBase:: |
protected | property | The form builder. | 2 |
ControllerBase:: |
protected | property | The key-value storage. | 1 |
ControllerBase:: |
protected | property | The language manager. | 1 |
ControllerBase:: |
protected | property | The module handler. | 2 |
ControllerBase:: |
protected | property | The state service. | |
ControllerBase:: |
protected | function | Returns the requested cache bin. | |
ControllerBase:: |
protected | function | Retrieves a configuration object. | |
ControllerBase:: |
private | function | Returns the service container. | |
ControllerBase:: |
protected | function | Returns the current user. | 1 |
ControllerBase:: |
protected | function | Retrieves the entity form builder. | |
ControllerBase:: |
protected | function | Retrieves the entity manager service. | |
ControllerBase:: |
protected | function | Retrieves the entity type manager. | |
ControllerBase:: |
protected | function | Returns the form builder service. | 2 |
ControllerBase:: |
protected | function | Returns a key/value storage collection. | 1 |
ControllerBase:: |
protected | function | Returns the language manager service. | 1 |
ControllerBase:: |
protected | function | Returns the module handler. | 2 |
ControllerBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
ControllerBase:: |
protected | function | Returns the state storage service. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
TrackerController:: |
protected | property | The comment statistics. | |
TrackerController:: |
protected | property | The database connection. | |
TrackerController:: |
protected | property | The database replica connection. | |
TrackerController:: |
protected | property | The date formatter. | |
TrackerController:: |
protected | property | The node storage. | |
TrackerController:: |
public | function | Builds content for the tracker controllers. | |
TrackerController:: |
public | function | Checks access for the users recent content tracker page. | |
TrackerController:: |
public static | function |
Instantiates a new instance of this class. Overrides ControllerBase:: |
|
TrackerController:: |
public | function | Title callback for the tracker.user_tab route. | |
TrackerController:: |
public | function | Constructs a TrackerController object. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |