Skip to content

Instantly share code, notes, and snippets.

@chadmandoo
Created February 3, 2017 01:36
Show Gist options
  • Save chadmandoo/854bf8fae132c3029d5e59268507ad22 to your computer and use it in GitHub Desktop.
Save chadmandoo/854bf8fae132c3029d5e59268507ad22 to your computer and use it in GitHub Desktop.
<?php
/**
* Class EntityDecorator.
*/
class EntityDecorator {
protected $entity;
protected $wrapper;
/**
* EntityDecorator constructor.
*
* @param mixed $entity
* Entity object or array to load entity.
* @param string $type
* String of type of entity if entity sent does not contain that data.
*/
public function __construct($entity, $type = '') {
if (is_array($entity)) {
$entity = entity_load_single($entity['type'], $entity['id']);
}
$this->entity = $entity;
if ($type) {
$this->entity->entity_type = $type;
}
$this->wrapper = entity_metadata_wrapper($this->entity->entity_type, $this->entity);
}
/**
* Set the entity arguments.
*
* @param string $propertyName
* Property name.
* @param string $arguments
* Property argument.
*/
public function set($propertyName, $arguments) {
$this->wrapper->$propertyName->set($arguments);
}
/**
* Get a property name off the wrapper.
*
* @param string $propertyName
* Name of field or property.
*
* @return \Core\Entity\EntityDecorator|mixed
* Return value.
*/
public function get($propertyName) {
$property = $this->wrapper->$propertyName->value();
if (is_object($property)) {
$property = new EntityDecorator($property);
}
return $property;
}
/**
* Get identifier.
*
* @return mixed
* Return identifier.
*/
public function getId() {
return $this->wrapper->getIdentifier();
}
/**
* Get entity object.
*
* @return object
* Returns entity object.
*/
public function getEntity() {
return $this->entity;
}
/**
* Set entity object.
*
* @param object $entity
* Set the entity object.
*/
public function setEntity($entity) {
$this->entity = $entity;
}
/**
* Get the metadata wrapper.
*
* @return \EntityMetadataWrapper
* Return metadata wrapper.
*/
public function getWrapper() {
return $this->wrapper;
}
/**
* Get entity path.
*
* @param bool $edit
* If true returns edit path.
*
* @return string
* Returns path string.
*/
public function getPath($edit = FALSE) {
$path = entity_uri($this->entity->entity_type, $this->entity);
if ($edit) {
$path['path'] .= '/edit';
}
return $path['path'];
}
/**
* Save entity.
*/
public function save() {
$this->wrapper->save();
}
/**
* Delete wrapper.
*/
public function delete() {
$this->wrapper->delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment