TextItemBase.php in Drupal 10
File
core/modules/text/src/Plugin/Field/FieldType/TextItemBase.php
View source
<?php
namespace Drupal\text\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\TypedData\DataDefinition;
abstract class TextItemBase extends FieldItemBase {
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(t('Text'))
->setRequired(TRUE);
$properties['format'] = DataDefinition::create('filter_format')
->setLabel(t('Text format'));
$properties['processed'] = DataDefinition::create('string')
->setLabel(t('Processed text'))
->setDescription(t('The text with the text format applied.'))
->setComputed(TRUE)
->setClass('\\Drupal\\text\\TextProcessed')
->setSetting('text source', 'value')
->setInternal(FALSE);
return $properties;
}
public function applyDefaultValue($notify = TRUE) {
$this
->setValue([
'format' => NULL,
], $notify);
return $this;
}
public function isEmpty() {
$value = $this
->get('value')
->getValue();
return $value === NULL || $value === '';
}
public function onChange($property_name, $notify = TRUE) {
foreach ($this->definition
->getPropertyDefinitions() as $property => $definition) {
if ($definition
->getClass() == '\\Drupal\\text\\TextProcessed') {
if ($property_name == 'format' || $definition
->getSetting('text source') == $property_name) {
$this
->writePropertyValue($property, NULL);
}
}
}
parent::onChange($property_name, $notify);
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$random = new Random();
$settings = $field_definition
->getSettings();
if (empty($settings['max_length'])) {
$value = $random
->paragraphs();
}
else {
$max = ceil($settings['max_length'] / 3);
$value = substr($random
->sentences(mt_rand(1, $max), FALSE), 0, $settings['max_length']);
}
$values = [
'value' => $value,
'summary' => $value,
'format' => filter_fallback_format(),
];
return $values;
}
}