6415252d8942881100915dc4410dede8636183d4
[yaffs-website] / web / modules / contrib / pathauto / src / PathautoState.php
1 <?php
2 namespace Drupal\pathauto;
3
4 use Drupal\Core\TypedData\TypedData;
5
6 /**
7  * A property that stores in keyvalue whether an entity should receive an alias.
8  */
9 class PathautoState extends TypedData {
10
11   /**
12    * An automatic alias should not be created.
13    */
14   const SKIP = 0;
15
16   /**
17    * An automatic alias should be created.
18    */
19   const CREATE = 1;
20
21   /**
22    * Pathauto state.
23    *
24    * @var int
25    */
26   protected $value;
27
28   /**
29    * @var \Drupal\Core\Field\FieldItemInterface
30    */
31   protected $parent;
32
33   /**
34    * {@inheritdoc}
35    */
36   public function getValue() {
37     if ($this->value === NULL) {
38       // If no value has been set or loaded yet, try to load a value if this
39       // entity has already been saved.
40       $this->value = \Drupal::keyValue($this->getCollection())
41         ->get($this->parent->getEntity()->id());
42       // If it was not yet saved or no value was found, then set the flag to
43       // create the alias if there is a matching pattern.
44       if ($this->value === NULL) {
45         $entity = $this->parent->getEntity();
46         $pattern = \Drupal::service('pathauto.generator')->getPatternByEntity($entity);
47         $this->value = !empty($pattern) ? static::CREATE : static::SKIP;
48       }
49     }
50     return $this->value;
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   public function setValue($value, $notify = TRUE) {
57     $this->value = $value;
58     // Notify the parent of any changes.
59     if ($notify && isset($this->parent)) {
60       $this->parent->onChange($this->name);
61     }
62   }
63
64   /**
65    * Returns TRUE if a value was set.
66    */
67   public function hasValue() {
68     return $this->value !== NULL;
69   }
70
71   /**
72    * Persists the state.
73    */
74   public function persist() {
75     \Drupal::keyValue($this->getCollection())->set(
76       $this->parent->getEntity()
77         ->id(), $this->value
78     );
79   }
80
81   /**
82    * Deletes the stored state.
83    */
84   public function purge() {
85     \Drupal::keyValue($this->getCollection())
86       ->delete($this->parent->getEntity()->id());
87   }
88
89   /**
90    * Returns the key value collection that should be used for the given entity.
91    * @return string
92    */
93   protected function getCollection() {
94     return 'pathauto_state.' . $this->parent->getEntity()->getEntityTypeId();
95   }
96
97 }