Lazy loading of relations callback method

@param \Slick\Orm\Entity $entity
@return Entity|RecordList
174779
public function load(Entity $entity)
    {
        $data = $entity->getRawData();
        if (!is_array($data) || !isset($data[$this->getForeignKey()])) {
            return null;
        }
        /** @var Select $sql */
        $sql = call_user_func_array(
            [$this->getRelatedEntity(), 'find'],
            []
        );
        $pmk = Entity\Manager::getInstance()->get($this->getRelatedEntity())
            ->getEntity()->getPrimaryKey();
        $table = Entity\Manager::getInstance()->get($this->getRelatedEntity())
            ->getEntity()->getTableName();
        $sql-> where(
            [
                "{$table}.{$pmk} = :id" => [
                    ':id' => $data[$this->getForeignKey()]
                ]
            ]
        );
        return $sql->first();
    }
969229
public function solveFetch(Entity &$entity)
    {
        // We need to find all target entities with the ID defined in the current entity source column
        $column = $this->relation->join->column;

        $value = $entity->{$column};
        $where = array($this->relation->join->targetColumn => $value);

        $query = EntityManager::find($this->relation->targetEntity);
        return $query->where($where)->all();
    }
1143708
public function hasMany($entity, string $related, string $foreignKey = null, string $localKey = null): HasMany
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $localKey = $localKey ?: $this->getKeyName();

        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addManyRelation($relation);
        $this->addForeignRelation($relation);

        return new HasMany($relatedMapper, $entity, $foreignKey, $localKey);
    }
830684
public function getEntityProperties($entity)
    {
        $metadata = $this->em->getClassMetadata(get_class($entity));
        return array_merge($metadata->getFieldNames(), $metadata->getAssociationNames());
    }
219687
public function getMentionsFromRelatedEntity($entity) {
    if ($entity->getEntityTypeId() === 'comment') {
      if ($entity->getParentComment()) {
        $entity = $entity->getParentComment();
      }
    }
    // Mention entity can't be loaded at time of new post or comment creation.
    $mentions = \Drupal::entityTypeManager()
      ->getStorage('mentions')
      ->loadByProperties([
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
      ]);
    return $mentions;
  }
922390
private function createObject(Entity $entity, array $record, array $relations, $readOnly)
    {
        $fields = $entity->getFieldNames();

        $object = $entity->create(array_intersect_key($record, $fields), true);
        $entity->setReadOnly($object, $readOnly);

        foreach ($relations as $relation) {
            $relation->set($object, $relation->getEmptyValue());
        }

        return $object;
    }
923167
protected function generateExtensionMethods(Entity $entity)
    {
        $methods    = [];
        $descriptor = $entity->getDescriptor();
        $extensions = $descriptor->getExtensionList() ?: [];

        foreach ($extensions as $field) {
            $methods[] = $this->generateExtensionMethod($entity, $field);
        }

        return $methods;
    }
957402
public function toArray(Entity $entity, $depth=0) {
		$res = [];

		foreach($entity->getDefinition()->properties() as $name=>$property) {
			if($entity->getDefinition()->property($name) instanceof Property\EntityProperty) {
				if($depth < 1)
					continue;
				if($entity->getDefinition()->property($name)->get('many')) {
					foreach($entity->get($name, null, false) as $subentity)
						$res[$name][] = $subentity->toArray($depth-1);
				}
				else {
					if($subentity = $entity->get($name, null, false))
						$res[$name] = $subentity->toArray($depth-1);
					else
						$res[$name] = null;
				}
			}
			elseif($property->get('many')) {
				$res[$name] = [];
				foreach($entity->get($name) as $k=>$v)
					$res[$name][$k] = $this->propertyToArray($v, $property);
			}
			else
				$res[$name] = $this->propertyToArray($entity->get($name), $property);
		}

		return $res;
	}
1076569
public function mapEntity(Entity $entity) {
		$entity['_loc'] = $this->_table->getUrl($entity);
		$entity['_lastmod'] = $entity->{$this->_config['lastmod']};
		$entity['_changefreq'] = $this->_config['changefreq'];
		$entity['_priority'] = $this->_config['priority'];

		return $entity;
	}
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;
    }
1143165
public function handle(Entity $entity): void
    {
        $this->trash = $entity->getEntityAttributeValueTrash();

        // Wrap the whole process inside database transaction
        $connection = $entity->getConnection();
        $connection->beginTransaction();

        try {
            foreach ($entity->getEntityAttributes() as $attribute) {
                if ($entity->relationLoaded($relation = $attribute->getAttribute('slug'))) {
                    $relationValue = $entity->getRelationValue($relation);

                    if ($relationValue instanceof ValueCollection) {
                        foreach ($relationValue as $value) {
                            // Set attribute value's entity_id since it's always null,
                            // because when RelationBuilder::build is called very early
                            $value->setAttribute('entity_id', $entity->getKey());
                            $this->saveOrTrashValue($value);
                        }
                    } elseif (! is_null($relationValue)) {
                        // Set attribute value's entity_id since it's always null,
                        // because when RelationBuilder::build is called very early
                        $relationValue->setAttribute('entity_id', $entity->getKey());
                        $this->saveOrTrashValue($relationValue);
                    }
                }
            }

            if ($this->trash->count()) {
                // Fetch the first item's class to know the model used for deletion
                $class = get_class($this->trash->first());

                // Let's batch delete all the values based on their ids
                $class::whereIn('id', $this->trash->pluck('id'))->delete();

                // Now, empty the trash
                $this->trash = collect([]);
            }
        } catch (Exception $e) {
            // Rollback transaction on failure
            $connection->rollBack();

            throw $e;
        }

        // Commit transaction on success
        $connection->commit();
    }
532443
protected function update(Entity $entity) {
		$this->updateActiveRow($entity);
		$this->referencesUpdate($entity, $entity->getLoadedReferences());
	}
237644
public function many($property, $entity = null)
    {
        $builder = new Many();
        $builder->property($property);

        if($entity){
            $builder->entity($entity);
        }

        return $builder;
    }
245777
public function call_related(\Asgard\Entity\Entity $entity, $relation) {
		return $this->getDataMapper()->related($entity, $relation);
	}
410011
public function getPositionFieldByEntity($entity)
	{
		if (is_object($entity)) {
			$entity = \Doctrine\Common\Util\ClassUtils::getClass($entity);
		}

		if (isset($this->positionField['entities'][$entity])) {
			return $this->positionField['entities'][$entity];
		} else {
			return $this->positionField['default'];
		}
	}
740144
protected function persistHasManyChanges(Entity $entity)
    {
        $primaryKey = $this->mapper->getPrimaryKey($this->getTable());
        $idField = $this->mapper->getEntityField($this->getTable(), $primaryKey);
        $driver = $this->connection->getDriver();

        foreach ($entity->getHasManyRowDifferences() as $key => $difference) {
            list($columnReferencingSourceTable, $relationshipTable, $columnReferencingTargetTable) = explode(':', $key);
            $multiInsert = [];
            foreach ($difference as $value => $count) {
                if ($count > 0) {
                    for ($i = 0; $i < $count; $i++) {
                        $multiInsert[] = [
                            $columnReferencingSourceTable => $entity->$idField,
                            $columnReferencingTargetTable => $value,
                        ];
                    }
                } else {
                    if ($driver instanceof \Dibi\Drivers\PostgreDriver) {
                        $this->connection->query(
                            'DELETE FROM %n WHERE [ctid] IN (SELECT [ctid] FROM %n WHERE %n = ? AND %n = ? LIMIT %i)',
                            $relationshipTable,
                            $relationshipTable,
                            $columnReferencingSourceTable,
                            $entity->$idField,
                            $columnReferencingTargetTable,
                            $value,
                            -$count
                        );
                    } elseif ($driver instanceof \Dibi\Drivers\Sqlite3Driver) {
                        $this->connection->query(
                            'DELETE FROM %n WHERE [rowid] IN (SELECT [rowid] FROM %n WHERE %n = ? AND %n = ? LIMIT %i)',
                            $relationshipTable,
                            $relationshipTable,
                            $columnReferencingSourceTable,
                            $entity->$idField,
                            $columnReferencingTargetTable,
                            $value,
                            -$count
                        );
                    } else {
                        $this->connection->query(
                            'DELETE FROM %n WHERE %n = ? AND %n = ? %lmt',
                            $relationshipTable,
                            $columnReferencingSourceTable,
                            $entity->$idField,
                            $columnReferencingTargetTable,
                            $value,
                            -$count
                        );
                    }
                }
            }
            if (!empty($multiInsert)) {
                $this->connection->query(
                    'INSERT INTO %n %ex',
                    $relationshipTable,
                    $multiInsert
                );
            }
        }
    }
1112607
protected function getRelationClosure(Entity $entity, Attribute $attribute)
    {
        $method = $attribute->is_collection ? 'hasMany' : 'hasOne';

        // This will return a closure fully binded to the current entity instance,
        // which will help us to simulate any relation as if it was made in the
        // original entity class definition using a function statement.
        return Closure::bind(function () use ($entity, $attribute, $method) {
            $relation = $entity->$method($attribute->getAttribute('type'), 'entity_id', 'id');

            // Since an attribute could be attached to multiple entities, then values could have
            // same entity ID, but for different entity types, so we need to add type where
            // clause to fetch only values related to the given entity ID + entity type.
            $relation->where('entity_type', get_class($entity));

            // We add a where clause in order to fetch only the elements that are
            // related to the given attribute. If no condition is set, it will
            // fetch all the value rows related to the current entity.
            return $relation->where($attribute->getForeignKey(), $attribute->getKey());
        }, $entity, get_class($entity));
    }