PathItem.php in Drupal 10
File
core/modules/path/src/Plugin/Field/FieldType/PathItem.php
View source
<?php
namespace Drupal\path\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
class PathItem extends FieldItemBase {
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['alias'] = DataDefinition::create('string')
->setLabel(t('Path alias'));
$properties['pid'] = DataDefinition::create('integer')
->setLabel(t('Path id'));
$properties['langcode'] = DataDefinition::create('string')
->setLabel(t('Language Code'));
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [];
}
public function isEmpty() {
return ($this->alias === NULL || $this->alias === '') && ($this->pid === NULL || $this->pid === '') && ($this->langcode === NULL || $this->langcode === '');
}
public function preSave() {
if ($this->alias !== NULL) {
$this->alias = trim($this->alias);
}
}
public function postSave($update) {
$path_alias_storage = \Drupal::entityTypeManager()
->getStorage('path_alias');
$entity = $this
->getEntity();
$alias_langcode = $this->langcode && $this->pid ? $this->langcode : $this
->getLangcode();
if ($this->alias) {
if (!$update || !$this->pid) {
$path_alias = $path_alias_storage
->create([
'path' => '/' . $entity
->toUrl()
->getInternalPath(),
'alias' => $this->alias,
'langcode' => $alias_langcode,
]);
$path_alias
->save();
$this->pid = $path_alias
->id();
}
elseif ($this->pid) {
$path_alias = $path_alias_storage
->load($this->pid);
if ($this->alias != $path_alias
->getAlias()) {
$path_alias
->setAlias($this->alias);
$path_alias
->save();
}
}
}
elseif ($this->pid && !$this->alias) {
$path_alias = $path_alias_storage
->load($this->pid);
if ($entity
->isDefaultRevision()) {
$path_alias_storage
->delete([
$path_alias,
]);
}
else {
$path_alias_storage
->deleteRevision($path_alias
->getRevisionID());
}
}
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$random = new Random();
$values['alias'] = '/' . str_replace(' ', '-', strtolower($random
->sentences(3)));
return $values;
}
public static function mainPropertyName() {
return 'alias';
}
}
Classes
Name |
Description |
PathItem |
Defines the 'path' entity field type. |