PathAlias.php in Drupal 8
File
core/modules/path_alias/src/Entity/PathAlias.php
View source
<?php
namespace Drupal\path_alias\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\path_alias\PathAliasInterface;
class PathAlias extends ContentEntityBase implements PathAliasInterface {
use EntityPublishedTrait;
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields['path'] = BaseFieldDefinition::create('string')
->setLabel(new TranslatableMarkup('System path'))
->setDescription(new TranslatableMarkup('The path that this alias belongs to.'))
->setRequired(TRUE)
->setRevisionable(TRUE)
->addPropertyConstraints('value', [
'Regex' => [
'pattern' => '/^\\//i',
'message' => new TranslatableMarkup('The source path has to start with a slash.'),
],
])
->addPropertyConstraints('value', [
'ValidPath' => [],
]);
$fields['alias'] = BaseFieldDefinition::create('string')
->setLabel(new TranslatableMarkup('URL alias'))
->setDescription(new TranslatableMarkup('An alias used with this path.'))
->setRequired(TRUE)
->setRevisionable(TRUE)
->addPropertyConstraints('value', [
'Regex' => [
'pattern' => '/^\\//i',
'message' => new TranslatableMarkup('The alias path has to start with a slash.'),
],
]);
$fields['langcode']
->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED);
$fields += static::publishedBaseFieldDefinitions($entity_type);
$fields['status']
->setTranslatable(FALSE);
return $fields;
}
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
$alias = rtrim(trim($this
->getAlias()), "\\/");
$this
->setAlias($alias);
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
$alias_manager = \Drupal::service('path_alias.manager');
$alias_manager
->cacheClear($this
->getPath());
if ($update) {
$alias_manager
->cacheClear($this->original
->getPath());
}
}
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
$alias_manager = \Drupal::service('path_alias.manager');
foreach ($entities as $entity) {
$alias_manager
->cacheClear($entity
->getPath());
}
}
public function getPath() {
return $this
->get('path')->value;
}
public function setPath($path) {
$this
->set('path', $path);
return $this;
}
public function getAlias() {
return $this
->get('alias')->value;
}
public function setAlias($alias) {
$this
->set('alias', $alias);
return $this;
}
public function label() {
return $this
->getAlias();
}
public function getCacheTagsToInvalidate() {
return [
'route_match',
];
}
}