Inject Virtual Properties for relations

@param Entity $entity
187455
public function injectVirtualProperties($entity)
    {
        $structure = $this->getEntityStructure($entity);
        if (count($structure->relationProperties) > 0) {
            foreach ($structure->relationProperties as $removeProperty) {
                unset($entity->{$removeProperty});
            }
        }
    }
501324
protected function deleteManyToManyReferences(Entity $entity)
    {
        foreach ($this->definition->getService()->getEntities() as $entityName) {
            $data = $this->definition->getService()->getData($entityName);
            foreach ($data->getDefinition()->getFieldNames(true) as $field) {
                if ($data->getDefinition()->getType($field) == 'many') {
                    $otherEntity = $data->getDefinition()->getSubTypeField($field, 'many', 'entity');
                    $otherData   = $this->definition->getService()->getData($otherEntity);
                    if ($entity->getDefinition()->getTable() == $otherData->getDefinition()->getTable()) {
                        $thatField    = $data->getDefinition()->getSubTypeField($field, 'many', 'thatField');
                        $queryBuilder = $this->database->createQueryBuilder();
                        $queryBuilder
                            ->delete('`'.$field.'`')
                            ->where('`'.$thatField.'` = ?')
                            ->setParameter(0, $entity->get('id'))
                            ->execute()
                        ;
                    }
                }
            }
        }
    }
279742
public function associate($entity)
    {
        $this->parent->setEntityAttribute($this->foreignKey, $entity->getEntityAttribute($this->otherKey));
    }
289344
public function save(Entity $entity) {
    $this->_em->persist($entity);
    $this->_em->flush();
    return $this;
  }
286435
public function saveRelations()
    {
        foreach ($this->structure->relationProperties as $virtualProperty) {
            // Check for existing of the relation property
            if (! in_array($virtualProperty, $this->structure->relationProperties) || ! isset($this->structure->relations[$virtualProperty])) {
                throw new RelationException("Relation not defined!"); // @codeCoverageIgnore
            }

            // Get relation and verify
            $relation = $this->structure->relations[$virtualProperty]; /** @var Relation $relation */
            if (! $relation instanceof Relation) {
                throw new RelationException("Relation indexing failed, something is really wrong, please report! Fetch proprty no instance of relation!"); // @codeCoverageIgnore
            }

            // Property existing check
            if (($relation->join instanceof Join && ! isset($this->entity->{$relation->join->column})) ||
                ($relation->join instanceof JoinTable && ! isset($this->entity->{$relation->join->column->entityColumn}))) {
                if ($relation->join->optional) {
                    // Ignore this, the join is optional.
                    continue;
                }

                if ($relation->join instanceof Join) { // @codeCoverageIgnore
                    throw new \Exception("Property with column '".$relation->join->column."' is not set at entity '".get_class($this->entity)."' when trying to solve relationship fetching."); // @codeCoverageIgnore
                } // @codeCoverageIgnore
                if ($relation->join instanceof JoinTable) { // @codeCoverageIgnore
                    throw new \Exception("Property with column '".$relation->join->column->entityColumn."' is not set at entity '".get_class($this->entity)."' when trying to solve relationship fetching."); // @codeCoverageIgnore
                } // @codeCoverageIgnore
            }

            // Is the content changed?
            $value = $this->fetch($virtualProperty, true);
            if ($value === null) {
                // Nothing is changed, lets continue loop
                continue;
            }
            if (! $value instanceof ArrayCollection && ! $value instanceof Entity) {
                throw new RelationException("The value of the relation '".$virtualProperty."' should be an ArrayCollection or Entity!"); // @codeCoverageIgnore
            }

            // Make solver
            $solverName = join('', array_slice(explode("\\", get_class($relation)), -1));
            $class = "\\SweetORM\\Database\\Solver\\" . $solverName;

            $query = new Query($relation->targetEntity, false);

            /** @var Solver $solver */
            $solver = new $class($relation, $this->structure, $query);

            // Lets call the solver to solve this save relation problem
            $solver->solveSave($this->entity, $value);
        }
    }
568720
public function setEntity(Entity $entity)
    {
        /** @var SharedEventManager $events */
        $events = $this->getContainer()->get('sharedEventManager');
        $events->attach(
            get_class($entity),
            Save::BEFORE_SAVE,
            [$this, 'beforeSave']
        );
        $events->attach(
            get_class($entity),
            Select::BEFORE_SELECT,
            [$this, 'beforeSelect']
        );
        $events->attach(
            get_class($entity),
            Select::AFTER_SELECT,
            [$this, 'afterSelect']
        );
        $this->getContainer()->set('sharedEventManager', $events);
        return parent::setEntity($entity);
    }
82419
public function setEntity($entity, $entityId)
    {
        //set the entity
        $method = 'set'.ucfirst($entityId);

        //set the entity
        call_user_func([$this, $method], $entity);
    }
117486
private function buildEntityInjectMethodsForEntity(EntityInterface $entity): void
    {
        $reflection = $entity::getDoctrineStaticMeta()->getReflectionClass();
        $entityFqn  = $this->leadingSlash($reflection->getName());
        if (array_key_exists($entityFqn, $this->entityInjectMethods)) {
            return;
        }
        $this->entityInjectMethods[$entityFqn] = [
            self::TYPE_KEY_INSTANCE => [],
            self::TYPE_KEY_STATIC   => [],
        ];

        $methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
        foreach ($methods as $method) {
            if (!\ts\stringStartsWith($method->getName(), self::INJECT_DEPENDENCY_METHOD_PREFIX)) {
                continue;
            }
            $typeKey = $method->isStatic() ? self::TYPE_KEY_STATIC : self::TYPE_KEY_INSTANCE;

            $this->entityInjectMethods[$entityFqn][$typeKey][$method->getName()] =
                $this->getDependencyForInjectMethod($method);
        }
    }
253508
public function apply(Builder $builder, Entity $entity): void
    {
        $eagerLoads = $builder->getEagerLoads();

        // If there is any eagerload matching the eav key, we will replace it with
        // all the registered properties for the entity. We'll simulate as if the
        // user has manually added all of these withs in purpose when querying.
        if (array_key_exists('eav', $eagerLoads)) {
            $eagerLoads = array_merge($eagerLoads, $entity->getEntityAttributeRelations());

            $builder->setEagerLoads(array_except($eagerLoads, 'eav'));
        }
    }
995680
public function add($entity)
    {
        foreach ($this->restrictions as $preset) {
            if ($preset['op'] == Operator::EQUAL) {
                $property          = Normalise::toVariable($preset['field']);
                $entity->$property = $preset['value'];
            }
        }

        $this->unitOfWork->scheduleForInsertion($entity);
    }
301206
public function entity(Entity $entity, Array $linkRelations = array()) {
    if (!isset($this->meta['links']))
      $this->meta['links'] = array();
      
    foreach ($linkRelations as $linkRelation) {
      $this->meta['links'][] = (object) array(
        'rel'=>$linkRelation->getName(),
        'href'=>$linkRelation->getHref()
      );
    }
    
    return $this;
  }
248453
public function setEntity(Entity $entity)
    {
        $this->each(
            function(Record $record) use ($entity) {
                $record->setEntity($entity);
                $record->setEntityClass(get_class($entity));
            }
        );

        return $this;
    }
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
                );
            }
        }
    }
1192496
protected function setEntityData($entity, $property)
    {
        if (is_array($entity) && count($entity) == 2) {
            TypeChecker::isString($entity[0]);
            TypeChecker::isNumeric($entity[1]);

            $type = $entity[0];
            $id = $entity[1];
        } elseif ($entity[0] instanceof Model) {
            $type = $entity[0]->getMorphClass();
            $id = $entity[0]->getKey();
        } else {
            TypeChecker::isNumeric($entity[0]);

            $type = notifynder_config()->getNotifiedModel();
            $id = $entity[0];
        }

        $this->setNotificationData("{$property}_type", $type);
        $this->setNotificationData("{$property}_id", $id);
    }
610418
public function insert($entity)
    {
        $data     = $this->builder->reduce($entity);
        $entityId = $this->entityRegistry->getEntityId($entity);

        #try
        #{
        $this->connection->insert($this->tableName, $data);

        if (empty($entityId)) {
            $this->entityRegistry->setEntityId($entity, $this->connection->lastInsertId());
        }

        $this->builder->resolve($entity);
        #}
        #catch (\Exception $e)
        #{
        #	throw new OrmException("Entity with id {$entityId} already exists.\n" . $e->getMessage(), 0, $e);
        #}
    }
175943
public function resolve($entity)
    {
        $entityClass = get_class($entity);
        $meta        = $this->getMeta($entityClass);
        $this->resolveRelations($entity, $meta);
    }
1018276
protected function assignRelationships($entity, $attributes)
    {
        $modelAttributes = $this->model->getAttributes($entity);

        // We'll filter through all of the columns, and check
        // to see if there are any defined relationships. If there
        // are, then we'll need to create those records as well.

        foreach ($modelAttributes as $columnName => $value) {
            if ($relationship = $this->findRelation($value)) {
                $entity[$columnName] = $this->fetchRelationId($relationship, $columnName, $attributes);
            }
        }

        return $entity;
    }