You are here

function radioactivity_process_decay in Radioactivity 8.2

Apply decay to entities.

1 call to radioactivity_process_decay()
radioactivity_cron in ./radioactivity.module
Implements hook_cron().

File

./radioactivity.module, line 47
Contains radioactivity.module..

Code

function radioactivity_process_decay() {
  $field_type_plugin_manager = \Drupal::service('plugin.manager.field.field_type');
  $entity_manager = \Drupal::service('entity.manager');
  if (!($field_storage_configs = $entity_manager
    ->getStorage('field_storage_config')
    ->loadByProperties(array(
    'type' => 'radioactivity',
  )))) {
    return;
  }
  $time_now = time();
  foreach ($field_storage_configs as $field_storage) {

    // Only act when field has data.
    if ($field_storage
      ->hasData()) {
      $radioactivity_profile = $field_storage
        ->getSetting('profile');

      // Simple view counter.
      if ($radioactivity_profile == 0) {
        continue;
      }
      $halflife = $field_storage
        ->getSetting('halflife', 60 * 60 * 12);
      $granularity = $field_storage
        ->getSetting('granularity', 60 * 60);
      $field_name = $field_storage
        ->get('field_name');
      $entity_type_id = $field_storage
        ->getTargetEntityTypeId();
      $query = \Drupal::entityQuery($entity_type_id)
        ->condition($field_name . '.timestamp', time() - 5, ' < ')
        ->condition($field_name . '.energy', 0, ' > ');
      $nids = $query
        ->execute();
      $entities = \Drupal::service('entity_type.manager')
        ->getStorage($entity_type_id)
        ->loadMultiple($nids);

      // Loop through entities:
      foreach ($entities as $entity) {
        $timestamp = $entity->{$field_name}->timestamp;
        $energy = $entity->{$field_name}->energy;
        switch ($radioactivity_profile) {
          case 1:
            break;
          case 2:
            $energy = $energy * pow(2, ($timestamp - $time_now) / $halflife);
            break;
        }
        $entity->{$field_name}
          ->setValue([
          'energy' => $energy,
          'timestamp' => $time_now,
        ]);
        $entity
          ->save();
      }
    }
  }
}