Version 1
[yaffs-website] / web / core / modules / path / src / Plugin / Field / FieldType / PathItem.php
1 <?php
2
3 namespace Drupal\path\Plugin\Field\FieldType;
4
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\Core\Field\FieldItemBase;
9 use Drupal\Core\TypedData\DataDefinition;
10
11 /**
12  * Defines the 'path' entity field type.
13  *
14  * @FieldType(
15  *   id = "path",
16  *   label = @Translation("Path"),
17  *   description = @Translation("An entity field containing a path alias and related data."),
18  *   no_ui = TRUE,
19  *   default_widget = "path",
20  *   list_class = "\Drupal\path\Plugin\Field\FieldType\PathFieldItemList"
21  * )
22  */
23 class PathItem extends FieldItemBase {
24
25   /**
26    * {@inheritdoc}
27    */
28   public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
29     $properties['alias'] = DataDefinition::create('string')
30       ->setLabel(t('Path alias'));
31     $properties['pid'] = DataDefinition::create('integer')
32       ->setLabel(t('Path id'));
33     return $properties;
34   }
35
36   /**
37    * {@inheritdoc}
38    */
39   public static function schema(FieldStorageDefinitionInterface $field_definition) {
40     return [];
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public function preSave() {
47     $this->alias = trim($this->alias);
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function postSave($update) {
54     if (!$update) {
55       if ($this->alias) {
56         $entity = $this->getEntity();
57         if ($path = \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $this->getLangcode())) {
58           $this->pid = $path['pid'];
59         }
60       }
61     }
62     else {
63       // Delete old alias if user erased it.
64       if ($this->pid && !$this->alias) {
65         \Drupal::service('path.alias_storage')->delete(['pid' => $this->pid]);
66       }
67       // Only save a non-empty alias.
68       elseif ($this->alias) {
69         $entity = $this->getEntity();
70         \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $this->getLangcode(), $this->pid);
71       }
72     }
73   }
74
75   /**
76    * {@inheritdoc}
77    */
78   public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
79     $random = new Random();
80     $values['alias'] = str_replace(' ', '-', strtolower($random->sentences(3)));
81     return $values;
82   }
83
84   /**
85    * {@inheritdoc}
86    */
87   public static function mainPropertyName() {
88     return 'alias';
89   }
90
91 }