work_time-1.0.x-dev/src/Plugin/Field/FieldFormatter/WorkTimeFormatter.php
src/Plugin/Field/FieldFormatter/WorkTimeFormatter.php
<?php
namespace Drupal\work_time\Plugin\Field\FieldFormatter;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldConfigInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'Work Time' formatter.
*
* @FieldFormatter(
* id = "worktime",
* label = @Translation("Work Time"),
* field_types = {
* "daterange"
* }
* )
*/
class WorkTimeFormatter extends FormatterBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity field manager service.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The database connection service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructs a Work time Formatter instance.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Session\AccountInterface|null $current_user
* The current user.
* @param \Drupal\Core\Database\Connection $database
* The database service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccountInterface $current_user, Connection $database) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->entityTypeManager = $entity_type_manager;
$this->entityFieldManager = $entity_field_manager;
$this->currentUser = $current_user;
$this->database = $database;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('entity_type.manager'),
$container->get('entity_field.manager'),
$container->get('current_user'),
$container->get('database'),
);
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'field_reference' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$options = [];
$storage = $form_state->getStorage();
if (!empty($storage) && !empty($storage['view'])) {
$entity_type = $this->fieldDefinition->getTargetEntityTypeId();
$viewDisplay = $storage['view']->get('display');
$types = $viewDisplay["default"]["display_options"]["filters"]["type"]["value"];
foreach ($types as $bundle) {
foreach ($this->entityFieldManager->getFieldDefinitions($entity_type, $bundle) as $field_name => $field_definition) {
if (!empty($field_definition->getTargetBundle())) {
if ($field_definition->getType() == 'entity_reference') {
$options[$field_name] = $field_definition->getLabel();
}
}
}
}
}
else {
$options = $this->getConfigurableFields('entity_reference');
}
$elements['field_reference'] = [
'#title' => $this->t('Field reference'),
'#type' => 'select',
'#options' => $options,
"#empty_option" => $this->t('- Select -'),
'#default_value' => $this->getSetting('field_reference'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
$fields = $this->getConfigurableFields('entity_reference');
if (!empty($this->getSetting('field_reference'))) {
$summary[] = $this->t('Field reference: @field', ['@field' => $fields[$this->getSetting('field_reference')] ?? '']);
}
return $summary;
}
/**
* Get list of fields.
*
* {@inheritdoc}
*/
protected function getConfigurableFields($type = FALSE) {
$entity_type = $this->fieldDefinition->getTargetEntityTypeId();
$bundle = $this->fieldDefinition->getTargetBundle();
$fieldDefinitions = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
$fields = [];
foreach ($fieldDefinitions as $field_name => $field) {
if (($field instanceof FieldConfigInterface) && $field->getType() == $type) {
$fields[$field_name] = $field->getLabel();
}
}
return $fields;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$reference_field = $this->getSetting('field_reference') ?? '';
$entity = $items->getEntity();
$reference_id = !empty($reference_field) ? $entity->{$reference_field}->target_id : '';
$reference_type = '';
if (!empty($reference_id)) {
$referenceItem = $entity->{$reference_field}->first();
if (!empty($reference_definition = $referenceItem->getFieldDefinition())) {
$reference_type = $reference_definition->getTargetEntityTypeId();
}
}
$beginning = $this->getTimeStartPlaying($entity);
$totalTime = $this->getTimeTotal($entity);
return [
[
'#theme' => 'work_time_formatter',
'#entity_id' => $entity->id(),
'#entity_type' => $this->fieldDefinition->getTargetEntityTypeId(),
'#entity_field' => $this->fieldDefinition->getName(),
'#reference_id' => $reference_id,
'#reference_field' => $reference_field,
'#reference_type' => $reference_type,
'#beginning' => $beginning,
'#time' => $totalTime,
'#items' => $items->getValue(),
'#attached' => [
'library' => ['work_time/work_time'],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getTimeStartPlaying($entity) {
$workTimeStorage = $this->entityTypeManager->getStorage('work_time');
$query = $workTimeStorage->getQuery()
->condition('uid', $this->currentUser->id())
->condition('entity_id', $entity->id())
->condition('stopped', NULL, 'IS NULL');
$workTimes = $query->execute();
$start = 0;
if (!empty($workTimes)) {
$workTimeId = current($workTimes);
$workTime = $workTimeStorage->load($workTimeId);
return $workTime->get('created')->value;
}
return $start;
}
/**
* {@inheritdoc}
*/
public function getTimeTotal($entity) {
$query = $this->database->select('work_time', 'w')
->condition('uid', $this->currentUser->id())
->condition('entity_id', $entity->id())
->condition('stopped', NULL, 'IS NOT NULL');
$query->addExpression('sum(w.time_total)', 'total');
$total = $query->execute()->fetchAllKeyed(0, 0);
return current($total);
}
}
