PathItem.php 2.45 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\path\Plugin\Field\FieldType\PathItem.
6 7
 */

8
namespace Drupal\path\Plugin\Field\FieldType;
9

10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Field\FieldItemBase;
12
use Drupal\Core\TypedData\DataDefinition;
13 14

/**
15
 * Defines the 'path' entity field type.
16
 *
17 18 19
 * @FieldType(
 *   id = "path",
 *   label = @Translation("Path"),
20
 *   description = @Translation("An entity field containing a path alias and related data."),
21
 *   configurable = FALSE
22
 * )
23 24 25 26 27 28 29 30 31 32 33 34 35
 */
class PathItem extends FieldItemBase {

  /**
   * Definitions of the contained properties.
   *
   * @see PathItem::getPropertyDefinitions()
   *
   * @var array
   */
  static $propertyDefinitions;

  /**
36
   * {@inheritdoc}
37 38 39
   */
  public function getPropertyDefinitions() {
    if (!isset(static::$propertyDefinitions)) {
40 41 42 43 44
      static::$propertyDefinitions['alias'] = DataDefinition::create('string')
        ->setLabel(t('Path alias'));

      static::$propertyDefinitions['pid'] = DataDefinition::create('string')
        ->setLabel(t('Path id'));
45 46 47 48
    }
    return static::$propertyDefinitions;
  }

49 50 51 52 53 54 55
  /**
   * {@inheritdoc}
   */
  public static function schema(FieldDefinitionInterface $field_definition) {
    return array();
  }

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    $this->alias = trim($this->alias);
  }

  /**
   * {@inheritdoc}
   */
  public function insert() {
    if ($this->alias) {
      $entity = $this->getEntity();

      // Ensure fields for programmatic executions.
      $langcode = $entity->language()->id;

      if ($path = \Drupal::service('path.crud')->save($entity->getSystemPath(), $this->alias, $langcode)) {
        $this->pid = $path['pid'];
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function update() {
    // Delete old alias if user erased it.
    if ($this->pid && !$this->alias) {
      \Drupal::service('path.crud')->delete(array('pid' => $this->pid));
    }
    // Only save a non-empty alias.
    elseif ($this->alias) {
      $entity = $this->getEntity();

      // Ensure fields for programmatic executions.
      $langcode = $entity->language()->id;

      \Drupal::service('path.crud')->save($entity->getSystemPath(), $this->alias, $langcode, $this->pid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    // Delete all aliases associated with this entity.
    $entity = $this->getEntity();
    \Drupal::service('path.crud')->delete(array('source' => $entity->getSystemPath()));
  }

107
}