function google_analytics_counter_cron in Google Analytics Counter 8.3
Same name and namespace in other branches
- 7.3 google_analytics_counter.module \google_analytics_counter_cron()
- 7.2 google_analytics_counter.module \google_analytics_counter_cron()
Implements hook_cron().
File
- ./
google_analytics_counter.module, line 26 - Basic functions for this module.
Code
function google_analytics_counter_cron() {
$config = \Drupal::config('google_analytics_counter.settings');
$database = \Drupal::database();
$state = \Drupal::state();
// $interval must be a value in seconds.
$interval = 60 * $config
->get('general_settings.cron_interval');
// Set the total number of published nodes.
$query = $database
->select('node_field_data', 'nfd');
$query
->fields('nfd', [
'nid',
]);
$query
->condition('status', NodeInterface::PUBLISHED);
$total_nodes = $query
->countQuery()
->execute()
->fetchField();
$state
->set('google_analytics_counter.total_nodes', $total_nodes);
// On some systems, cron could be every minute. Throttle updating with the
// cron_interval on the settings form.
// To avoid this interval, set cron_interval to 0.
if (!\Drupal::time()
->getRequestTime() >= \Drupal::state()
->get('system.cron_last') + $interval) {
return FALSE;
}
// Proceed no further if not authenticated.
/* @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterAuthManagerInterface $auth_manager */
$auth_manager = \Drupal::service('google_analytics_counter.auth_manager');
if (!$auth_manager
->isAuthenticated()) {
\Drupal::logger('google_analytics_counter')
->alert('Google Analytics Counter is not authenticated.');
return FALSE;
}
// Returns the google_analytics_counter_worker queue.
$queue = \Drupal::queue('google_analytics_counter_worker');
/* @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface $app_manager */
$app_manager = \Drupal::service('google_analytics_counter.app_manager');
try {
// Fetch the total results from Google first.
$app_manager
->reportData();
$total_results = $state
->get('google_analytics_counter.total_paths');
// Create queue fetch items from the total results divided into chunks.
for ($index = 0; $index < $total_results / $config
->get('general_settings.chunk_to_fetch'); $index++) {
// Add a queue item to fetch for all chunks.
$queue
->createItem([
'type' => 'fetch',
'index' => $index,
]);
}
// Select all the published nodes and create queue count items.
$query = $database
->select('node_field_data', 'nfd');
$query
->fields('nfd', [
'nid',
'type',
'vid',
]);
$query
->condition('status', NodeInterface::PUBLISHED);
$query
->addTag('google_analytics_counter');
$result = $query
->execute();
while ($record = $result
->fetchAssoc()) {
$queue
->createItem([
'type' => 'count',
'nid' => $record['nid'],
'bundle' => $record['type'],
'vid' => $record['vid'],
]);
}
} catch (RuntimeException $e) {
\Drupal::logger('google_analytics_counter')
->alert('Cron experienced a problem: ' . $e
->getMessage());
}
}