MapItem.php 2.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php

namespace Drupal\Core\Field\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;

/**
 * Defines the 'map' entity field type.
 *
 * @FieldType(
 *   id = "map",
 *   label = @Translation("Map"),
 *   description = @Translation("An entity field for storing a serialized array of values."),
15 16
 *   no_ui = TRUE,
 *   list_class = "\Drupal\Core\Field\MapFieldItemList",
17 18 19 20 21 22 23 24 25
 * )
 */
class MapItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // The properties are dynamic and can not be defined statically.
26
    return [];
27 28 29 30 31 32
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
33 34 35
    return [
      'columns' => [
        'value' => [
36 37 38
          'type' => 'blob',
          'size' => 'big',
          'serialize' => TRUE,
39 40 41
        ],
      ],
    ];
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  }

  /**
   * {@inheritdoc}
   */
  public function toArray() {
    // The default implementation of toArray() only returns known properties.
    // For a map, return everything as the properties are not pre-defined.
    return $this->getValue();
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($values, $notify = TRUE) {
57
    $this->values = [];
58 59 60 61 62 63 64 65 66
    if (!isset($values)) {
      return;
    }

    if (!is_array($values)) {
      if ($values instanceof MapItem) {
        $values = $values->getValue();
      }
      else {
67
        $values = unserialize($values, ['allowed_classes' => FALSE]);
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
      }
    }

    $this->values = $values;

    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function __get($name) {
    if (!isset($this->values[$name])) {
84
      $this->values[$name] = [];
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }

    return $this->values[$name];
  }

  /**
   * {@inheritdoc}
   */
  public function __set($name, $value) {
    if (isset($value)) {
      $this->values[$name] = $value;
    }
    else {
      unset($this->values[$name]);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    // A map item has no main property.
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return empty($this->values);
  }

}