View source
<?php
namespace Drupal\radioactivity\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
class RadioactivityField extends FieldItemBase {
public static function defaultStorageSettings() {
return array(
'profile' => 0,
'halflife' => 60 * 60 * 12,
'granularity' => 60 * 15,
) + parent::defaultStorageSettings();
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['energy'] = DataDefinition::create('float')
->setLabel(new TranslatableMarkup('Energy level'))
->setRequired(TRUE);
$properties['timestamp'] = DataDefinition::create('integer')
->setLabel(new TranslatableMarkup('Energy timestamp'));
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = array(
'columns' => array(
'energy' => array(
'description' => 'Energy level',
'type' => 'float',
'default' => 0,
),
'timestamp' => array(
'description' => 'Timestamp of last emit',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
),
);
return $schema;
}
public function getConstraints() {
$constraints = parent::getConstraints();
if ($max_length = $this
->getSetting('max_length')) {
$constraint_manager = \Drupal::typedDataManager()
->getValidationConstraintManager();
}
return $constraints;
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$values['energy'] = 1;
$values['timestamp'] = time() / 60 / 60 * 60 * 60;
return $values;
}
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$elements = [];
$elements['profile'] = array(
'#type' => 'select',
'#title' => t('Profile'),
'#default_value' => $this
->getSetting('profile'),
'#required' => TRUE,
'#options' => array(
0 => 'Count',
1 => 'Linear',
2 => 'Decay',
),
'#description' => t('Select the profile to use'),
);
$elements['granularity'] = array(
'#type' => 'textfield',
'#title' => t('Granularity in seconds'),
'#pattern' => '[0-9]*',
'#default_value' => $this
->getSetting('granularity'),
'#description' => t('Granularity defines how long the energy levels are kept before applying any decay.'),
);
$elements['halflife'] = array(
'#type' => 'textfield',
'#title' => t('Half-life'),
'#pattern' => '[0-9]*',
'#default_value' => $this
->getSetting('halflife'),
'#description' => t('Half-life determines the amount of time in which the energy level halves.'),
);
return $elements;
}
public function preSave() {
parent::preSave();
if (!$this->energy) {
$this->energy = 0;
}
$this->timestamp = time();
}
public function isEmpty() {
$value = $this
->get('energy')
->getValue();
return $value === NULL;
}
}