setEntityTypeId($entity->getEntityTypeId()) ->setBundles([$entity->bundle()]); $instance = new static($definition); $instance->setValue($entity); return $instance; } /** * {@inheritdoc} */ public function getValue() { return $this->entity; } /** * {@inheritdoc} */ public function setValue($entity, $notify = TRUE) { $this->entity = $entity; // Notify the parent of any changes. if ($notify && isset($this->parent)) { $this->parent->onChange($this->name); } } /** * {@inheritdoc} */ public function get($property_name) { if (!isset($this->entity)) { throw new MissingDataException("Unable to get property $property_name as no entity has been provided."); } if (!$this->entity instanceof FieldableEntityInterface) { // @todo: Add support for config entities in // https://www.drupal.org/node/1818574. throw new \InvalidArgumentException("Unable to get unknown property $property_name."); } // This will throw an exception for unknown fields. return $this->entity->get($property_name); } /** * {@inheritdoc} */ public function set($property_name, $value, $notify = TRUE) { if (!isset($this->entity)) { throw new MissingDataException("Unable to set property $property_name as no entity has been provided."); } if (!$this->entity instanceof FieldableEntityInterface) { // @todo: Add support for config entities in // https://www.drupal.org/node/1818574. throw new \InvalidArgumentException("Unable to set unknown property $property_name."); } // This will throw an exception for unknown fields. $this->entity->set($property_name, $value, $notify); return $this; } /** * {@inheritdoc} */ public function getProperties($include_computed = FALSE) { if (!isset($this->entity)) { throw new MissingDataException('Unable to get properties as no entity has been provided.'); } if (!$this->entity instanceof FieldableEntityInterface) { // @todo: Add support for config entities in // https://www.drupal.org/node/1818574. return []; } return $this->entity->getFields($include_computed); } /** * {@inheritdoc} */ public function toArray() { if (!isset($this->entity)) { throw new MissingDataException('Unable to get property values as no entity has been provided.'); } return $this->entity->toArray(); } /** * {@inheritdoc} */ public function isEmpty() { return !isset($this->entity); } /** * {@inheritdoc} */ public function onChange($property_name) { if (isset($this->entity) && $this->entity instanceof FieldableEntityInterface) { // Let the entity know of any changes. $this->entity->onChange($property_name); } } /** * {@inheritdoc} */ public function getString() { return isset($this->entity) ? $this->entity->label() : ''; } /** * {@inheritdoc} */ public function applyDefaultValue($notify = TRUE) { // Apply the default value of all properties. foreach ($this->getProperties() as $property) { $property->applyDefaultValue(FALSE); } return $this; } /** * {@inheritdoc} */ public function getIterator() { return isset($this->entity) ? $this->entity->getIterator() : new \ArrayIterator([]); } }