improvements-2.x-dev/src/Plugin/Field/FieldType/RequestInfoItem.php
src/Plugin/Field/FieldType/RequestInfoItem.php
<?php
namespace Drupal\improvements\Plugin\Field\FieldType;
use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
/**
* @TODO Add tests
*/
#[FieldType(
id: 'request_info',
label: new TranslatableMarkup('Request info'),
description: new TranslatableMarkup('Field for storing request data - ip, host, useragent, referrer.'),
default_widget: '',
default_formatter: '',
)]
class RequestInfoItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition): array {
return [
'columns' => [
'ip' => [
'type' => 'varchar',
'length' => 15,
'description' => 'User IP',
],
'host' => [
'type' => 'varchar',
'length' => 255,
'description' => 'User host',
],
'useragent' => [
'type' => 'varchar',
'length' => 255,
'description' => 'User browser agent',
],
'referer' => [
'type' => 'varchar',
'length' => 1000,
'description' => 'Request referer',
],
],
];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array {
$properties = [];
$properties['ip'] = DataDefinition::create('string')
->setLabel(t('User IP'));
$properties['host'] = DataDefinition::create('string')
->setLabel(t('User host'));
$properties['useragent'] = DataDefinition::create('string')
->setLabel(t('User browser agent'));
$properties['referer'] = DataDefinition::create('string')
->setLabel(t('Request referer'));
return $properties;
}
/**
* {@inheritdoc}
*/
public static function mainPropertyName(): string {
return 'ip';
}
/**
* {@inheritdoc}
*/
public function isEmpty(): bool {
return empty($this->ip);
}
/**
* {@inheritdoc}
*/
public function applyDefaultValue($notify = TRUE): self {
$user_ip = \Drupal::request()->getClientIp();
$this->setValue([
'ip' => $user_ip,
'host' => NULL, // Moved long operation to preSave() method, because applyDefaultValue() executed on EntityInterface::create()
'useragent' => substr(\Drupal::request()->server->get('HTTP_USER_AGENT') ?? '', 0, 255),
'referer' => substr(\Drupal::request()->server->get('HTTP_REFERER') ?? '', 0, 1000),
], $notify);
return $this;
}
/**
* {@inheritdoc}
*/
public function preSave(): void {
if ($this->ip) {
$this->set('host', @gethostbyaddr($this->ip));
}
parent::preSave();
}
}
