3 namespace Drupal\statistics;
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\State\StateInterface;
7 use Symfony\Component\HttpFoundation\RequestStack;
10 * Provides the default database storage backend for statistics.
12 class NodeStatisticsDatabaseStorage implements StatisticsStorageInterface {
15 * The database connection used.
17 * @var \Drupal\Core\Database\Connection
19 protected $connection;
24 * @var \Drupal\Core\State\StateInterface
31 * @var \Symfony\Component\HttpFoundation\RequestStack
33 protected $requestStack;
36 * Constructs the statistics storage.
38 * @param \Drupal\Core\Database\Connection $connection
39 * The database connection for the node view storage.
40 * @param \Drupal\Core\State\StateInterface $state
43 public function __construct(Connection $connection, StateInterface $state, RequestStack $request_stack) {
44 $this->connection = $connection;
45 $this->state = $state;
46 $this->requestStack = $request_stack;
52 public function recordView($id) {
53 return (bool) $this->connection
54 ->merge('node_counter')
59 'timestamp' => $this->getRequestTime(),
61 ->expression('daycount', 'daycount + 1')
62 ->expression('totalcount', 'totalcount + 1')
69 public function fetchViews($ids) {
70 $views = $this->connection
71 ->select('node_counter', 'nc')
72 ->fields('nc', ['totalcount', 'daycount', 'timestamp'])
73 ->condition('nid', $ids, 'IN')
76 foreach ($views as $id => $view) {
77 $views[$id] = new StatisticsViewsResult($view->totalcount, $view->daycount, $view->timestamp);
85 public function fetchView($id) {
86 $views = $this->fetchViews([$id]);
93 public function fetchAll($order = 'totalcount', $limit = 5) {
94 assert(in_array($order, ['totalcount', 'daycount', 'timestamp']), "Invalid order argument.");
96 return $this->connection
97 ->select('node_counter', 'nc')
98 ->fields('nc', ['nid'])
99 ->orderBy($order, 'DESC')
108 public function deleteViews($id) {
109 return (bool) $this->connection
110 ->delete('node_counter')
111 ->condition('nid', $id)
118 public function resetDayCount() {
119 $statistics_timestamp = $this->state->get('statistics.day_timestamp') ?: 0;
120 if (($this->getRequestTime() - $statistics_timestamp) >= 86400) {
121 $this->state->set('statistics.day_timestamp', $this->getRequestTime());
122 $this->connection->update('node_counter')
123 ->fields(['daycount' => 0])
131 public function maxTotalCount() {
132 $query = $this->connection->select('node_counter', 'nc');
133 $query->addExpression('MAX(totalcount)');
134 $max_total_count = (int)$query->execute()->fetchField();
135 return $max_total_count;
139 * Get current request time.
142 * Unix timestamp for current server request time.
144 protected function getRequestTime() {
145 return $this->requestStack->getCurrentRequest()->server->get('REQUEST_TIME');