Generates a unique hash for the given entity.

Used by revision system to detect if an entity has changed or not.

@param \Cake\Datasource\EntityInterface $entity The entity for which calculate its hash
@return string MD5 hash for this particular entity
432885
protected function _calculateHash($entity)
    {
        $hash = [];
        foreach ($entity->visibleProperties() as $property) {
            if (strpos($property, 'created') === false &&
                strpos($property, 'created_by') === false &&
                strpos($property, 'modified') === false &&
                strpos($property, 'modified_by') === false
            ) {
                if ($property == '_fields') {
                    foreach ($entity->get('_fields') as $field) {
                        if ($field instanceof \Field\Model\Entity\Field) {
                            $hash[] = is_object($field->value) || is_array($field->value) ? md5(serialize($field->value)) : md5($field->value);
                        }
                    }
                } else {
                    $hash[] = $entity->get($property);
                }
            }
        }

        return md5(serialize($hash));
    }
282366
protected function getEditSuccessMessage(EntityInterface $entity)
    {
        $singleName = $this->getEntityNameSingular();
        $message = "The {$singleName} '%s' was successfully updated.";
        return sprintf($this->translate($message), $entity);
    }
195469
private function getEncryptionMode($entity)
    {
        $className = ClassUtils::getClass($entity);
        $classMetadata = $this->metadataFactory->getMetadataFor($className);

        return $classMetadata->encryptionMode;
    }
217210
protected function generateEntityReferenceLinks(EntityInterface $entity) {
    // Use the node to add link headers for each entity reference.
    $entity_type = $entity->getEntityType()->id();
    $bundle = $entity->bundle();

    // Get all fields for the entity.
    $fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);

    // Strip out everything but entity references that are not base fields.
    $entity_reference_fields = array_filter($fields, function ($field) {
      return $field->getFieldStorageDefinition()->isBaseField() == FALSE && $field->getType() == "entity_reference";
    });

    // Collect links for referenced entities.
    $links = [];
    foreach ($entity_reference_fields as $field_name => $field_definition) {
      foreach ($entity->get($field_name)->referencedEntities() as $referencedEntity) {
        // Headers are subject to an access check.
        if ($referencedEntity->access('view')) {

          // Taxonomy terms are written out as
          // <url>; rel="tag"; title="Tag Name"
          // where url is defined in field_same_as.
          // If field_same_as doesn't exist or is empty,
          // it becomes the taxonomy term's local uri.
          if ($referencedEntity->getEntityTypeId() == 'taxonomy_term') {
            $rel = "tag";
            $entity_url = $referencedEntity->url('canonical', ['absolute' => TRUE]);
            if ($referencedEntity->hasField('field_external_uri')) {
              $external_uri = $referencedEntity->get('field_external_uri')->getValue();
              if (!empty($external_uri) && isset($external_uri[0]['uri'])) {
                $entity_url = $external_uri[0]['uri'];
              }
            }
            $title = $referencedEntity->label();
          }
          else {
            // If it's not a taxonomy term, referenced entity link
            // headers take the form
            // <url>; rel="related"; title="Field Label"
            // and the url is the local uri.
            $rel = "related";
            $entity_url = $referencedEntity->url('canonical', ['absolute' => TRUE]);
            $title = $field_definition->label();
          }
          $links[] = "<$entity_url>; rel=\"$rel\"; title=\"$title\"";
        }
      }
    }

    return $links;
  }
292537
protected function formatKeyCondition(EntityInterface $entity)
    {
        $attributes = array(
            $entity::getHashKeyAttribute() => $entity->getHashKey(),
        );

        $rangeKeyAttribute = $entity::getRangeKeyAttribute();
        if ($rangeKeyAttribute !== false) {
            $attributes[$rangeKeyAttribute] = $entity->getRangeKey();
        }

        return $this->formatAttributes(get_class($entity), $attributes);
    }
152810
protected function entityToString($entity)
    {
        return method_exists($entity, '__toString') ? (string) $entity : get_class($entity) . '@' . spl_object_hash($entity);
    }
878442
public function encryptEntity(EntityInterface $entity): EntityInterface
    {
        if (!$this->isEncryptable($entity)) {
            return $entity;
        }

        $fields = $this->getFields();
        $encryptionKey = $this->getConfig('encryptionKey');
        $base64 = $this->getConfig('base64');
        $table = $this->getTable();

        $patch = [];
        foreach ($fields as $name => $field) {
            if (!$table->hasField($name)) {
                continue;
            }
            $value = $entity->get($name);
            if ($value === null || is_resource($value)) {
                continue;
            }
            $encrypted = Security::encrypt($value, $encryptionKey);
            if ($base64 === true) {
                $encrypted = base64_encode($encrypted);
            }
            $patch[$name] = $encrypted;
        }

        if (!empty($patch)) {
            $accessible = array_fill_keys(array_keys($patch), true);
            $entity = $table->patchEntity($entity, $patch, [
                'accessibleFields' => $accessible,
            ]);
        }

        return $entity;
    }
476273
private static function decrypt_entity( FS_Entity $entity ) {
            $clone = clone $entity;
            $props = get_object_vars( $entity );

            foreach ( $props as $key => $val ) {
                $clone->{$key} = self::_decrypt( $val );
            }

            return $clone;
        }
632851
public function delete(EntityInterface $entity)
    {
        $this->entity = $entity;
        $primaryKey = $this->getDescriptor()->getPrimaryKey()->getName();
        $table = $this->getDescriptor()->getTableName();
        $sql = Sql::createSql($this->getAdapter());

        $this->triggerBeforeDelete($entity);

        $this->setUpdateCriteria(
            $sql->delete($table),
            $primaryKey,
            $table
        )->execute();

        $this->triggerAfterDelete($entity);
        $this->removeEntity($entity);
        return $this;
    }
360936
protected function generateGetUnknownFieldSetMethod(Entity $entity)
    {
        $methodName = 'unknownFieldSet';
        $descriptor = $entity->getDescriptor();
        $fieldName  = $this->getUniqueFieldName($descriptor, $methodName);
        $method     = MethodGenerator::fromArray([
            'name'       => $methodName,
            'body'       => 'return $this->' . $fieldName . ';',
            'docblock'   => [
                'shortDescription' => "{@inheritdoc}"
            ]
        ]);

        return $method;
    }
1246023
public function remove(EntityInterface $entity)
    {
        $reflection = $this->getEntityClassReflection();
        
        if ($reflection->isInstance($entity)) {
            
            // trigger event for entity and dispatcher on before remove
            $this->dispatchEvent(ORMEvents::beforeRemove, new EntityLifecycleEvent($this, $entity));
            
            // needed variables
            $metadata = $this->getEntityMetadata();
            $remover = $this->createRemover();
            $identifier = $this->getEntityIdentifier();
            $connection = $this->getConnection();
            $propertyIdentifier = $metadata->getName($identifier, Metadata::CAMILIZED);
            
            // refinement of the request
            $remover->addConditions($identifier, $entity->getByProperty($propertyIdentifier));
            $remover->setLimit(1)->setOffset(0);
            
            // open transaction and try to execute sql
            $connection->transaction(function () use ($connection, $remover) {
                $connection->execute($remover->toSQL());
            });
            
            // reset identifier for removed entity
            $entity->setByProperty($propertyIdentifier, null);
            
            // trigger event for entity and dispatcher on after remove and all actions
            $this->dispatchEvent(ORMEvents::afterRemove, new EntityLifecycleEvent($this, $entity));
            
            return $this;
        }
        
        throw new NotSupportedException(sprintf('Unable to remove entity! Actual entity "%s" expected entity "%s"',
            get_class($entity), $this->getEntityName()));
    }
1309042
protected function getCurrent(EntityInterface $entity) {
		$conditions = $this->buildConditions($entity);

		return $this->_table->find()
			->where($conditions)
			->first();
	}
575679
protected function _attributesForEntity(EntityInterface $entity)
    {
        $bundle = $this->_resolveBundle($entity);
        $attrs = $this->_toolbox->attributes($bundle);
        $attrByIds = []; // attrs indexed by id
        $attrByNames = []; // attrs indexed by name

        foreach ($attrs as $name => $attr) {
            $attrByNames[$name] = $attr;
            $attrByIds[$attr->get('id')] = $attr;
            $attr->set(':value', null);
        }

        if (!empty($attrByIds)) {
            $instances = $this->Attributes->Instance
                ->find()
                ->where(['eav_attribute_id IN' => array_keys($attrByIds)])
                ->all();
            foreach ($instances as $instance) {
                if (!empty($attrByIds[$instance->get('eav_attribute_id')])) {
                    $attr = $attrByIds[$instance->get('eav_attribute_id')];
                    if (!$attr->has('instance')) {
                        $attr->set('instance', $instance);
                    }
                }
            }
        }

        $values = $this->_fetchValues($entity, array_keys($attrByNames));
        foreach ($values as $value) {
            if (!empty($attrByNames[$value->get('eav_attribute')->get('name')])) {
                $attrByNames[$value->get('eav_attribute')->get('name')]->set(':value', $value);
            }
        }

        return $this->_toolbox->attributes($bundle);
    }
258058
public function slug(EntityInterface $entity, array $options = []) {
		$overwrite = isset($options['overwrite']) ? $options['overwrite'] : $this->_config['overwrite'];
		if (!$overwrite && $entity->get($this->_config['overwriteField'])) {
			$overwrite = true;
		}
		if ($overwrite || $entity->isNew() || !$entity->get($this->_config['field'])) {
			$slug = [];
			foreach ((array)$this->_config['label'] as $v) {
				$v = $entity->get($v);
				if ($v !== null && $v !== '') {
					$slug[] = $v;
				}
			}
			$slug = implode($slug, $this->_config['separator']);
			$slug = $this->generateSlug($slug, $entity);
			$entity->set($this->_config['field'], $slug);
		}
	}
1137905
public function generateBody(Entity $entity)
    {
        $lines      = [];
        $addLine    = false;
        $descriptor = $entity->getDescriptor();
        $fields     = $descriptor->getFieldList() ?: [];
        $defaults   = $this->generateDefaultValues($entity);

        foreach ($fields as $field) {
            if ($field->getLabel() !== Label::LABEL_REQUIRED()) {
                continue;
            }

            if ($field->hasDefaultValue()) {
                continue;
            }

            $item  = $this->generateRequiredFieldException($entity, $field);
            $lines = array_merge($lines, $item, [null]);
        }

        $lines[] = '$message = new self();';
        $lines[] = '$values  = array_merge([';
        $lines   = array_merge($lines, $this->addIndentation($defaults, 1));
        $lines[] = '], $values);';
        $lines[] = null;

        foreach ($fields as $field) {
            if ($field->getLabel() === Label::LABEL_REPEATED()) {
                continue;
            }

            $item  = $this->generateSetValue($entity, $field);
            $lines = array_merge($lines, $item);

            $addLine = true;
        }

        if ($addLine) {
            $lines[] = null;
        }

        foreach ($fields as $field) {
            if ($field->getLabel() !== Label::LABEL_REPEATED()) {
                continue;
            }

            $item  = $this->generateAddValue($entity, $field);
            $lines = array_merge($lines, $item, [null]);
        }

        $lines[] = 'return $message;';

        return $lines;
    }
684593
public function getTimes(IdentifierInterface $entity)
    {
        $handle = $this->getTimerHandle($entity);
        $past = $this->localStorage->get($handle, []);

        return $past;
    }
975938
protected function _getTableAlias(EntityInterface $entity)
    {
        $alias = $entity->source();
        if (mb_strpos($alias, '.') !== false) {
            $parts = explode('.', $alias);
            $alias = array_pop($parts);
        }

        return strtolower($alias);
    }