Save.
@param  Oppa\ActiveRecord\Entity $entity
@return ?int On insert: last insert id.
@return int  On update: affected rows.
@throws Oppa\Exception\InvalidValueException
327373
public final function save(Entity $entity): ?int
    {
        $data = $entity->toArray();
        if (empty($data)) {
            throw new InvalidValueException('There is no data enough on entity for save action!');
        }

        // use only owned fields
        $data = array_intersect_key($data, array_flip(self::$tableInfo['@fields']));

        $return = null;

        // insert action
        if (!$entity->hasPrimaryValue()) {
            $return = $this->db->getLink()->getAgent()->insert($this->table, $data);
            // set primary value
            $entity->setPrimaryValue($return);
        } else {
            // update action
            $return = $this->db->getLink()->getAgent()->update($this->table, $data,
                "{$this->tablePrimary} = ?", [$entity->getPrimaryValue()]);
        }

        if (method_exists($this, 'onSave')) {
            $this->onSave($return);
        }

        return $return;
    }
649483
protected function storeEntity($entity)
    {
        $this->checkEntityType($entity);

        $store = new Store($this->aggregate($entity), $this->newQueryBuilder());

        return $store->execute();
    }
310461
public function saveEntity(EntityInterface $entity)
    {
        $check = $this->storage->fetchEntityById($entity->getIdentifier());

        if ($check) {
            return $this->storage->updateEntity($entity);
        } else {
            return $this->storage->insertEntity($entity);
        }
    }
123954
protected function updateEntity(Entity $entity)
    {
        $action = \Schema::hasTable($entity->getTable()) ? 'update' : 'create';

        $this->migrations[$action][$entity->getTable()]['cols'] = $this->buildTable($entity);

        if($action == 'create' && $entity->timestamps) $this->migrations[$action][$entity->getTable()]['cols'][] = '$table->timestamps();';
    }
39840
public function setEntity($entity)
    {
        $this->debugLog(sprintf('ENTITY: %s', $entity));

        $expectedEntity = $this->makeSQLSafe($this->getParams()['DBPREFIX'] . $entity);

        $this->debugLog(sprintf('SET ENTITY: %s', $expectedEntity));

        // Concatinate the entity with the sqldbprefix value only if not already done.
        if ($expectedEntity !== $this->entity) {
            $this->entity = $expectedEntity;
        }

        return $this;
    }
509091
public function create(Entity $entity)
    {
        if (!$entity->getValidator()->validate()) {
            throw new Exception\ValidatorException($entity->getValidator());
        }

        $values = $entity->getData();

        $reflection = $entity::getReflection();

        // Prevent to force empty primary property
        if ($reflection->hasPrimary()) {

            $primaryName = $reflection->getPrimaryProperty()->getName();

            if (empty($values[$primaryName])) {
                unset($values[$primaryName]);
            }
        }

        try {
            $primaryValue = $this->query()->insert($values)->run($this->connection);
        } catch (Exception\QueryException $e) {
            throw new Exception\RepositoryException($e->getMessage());
        }

        $this->_saveAssociated($primaryValue, $entity);

        return $primaryValue;
    }
985453
protected function insertIntoDatabase(Entity $entity)
    {
        $primaryKey = $this->mapper->getPrimaryKey($this->getTable());
        $values = $entity->getModifiedRowData();
        $this->connection->query(
            'INSERT INTO %n %v',
            $this->getTable(),
            $values
        );
        return isset($values[$primaryKey]) ? $values[$primaryKey] : $this->connection->getInsertId();
    }
721458
public function insert($entity)
    {
        $persistor = new DoctrinePersistor(
            $this->connection,
            $this->table,
            $this->entityRegistry->getEntityBuilder(),
            $this->entityRegistry
        );
        $persistor->insert($entity);
    }
112109
public function update(Entity $entity)
    {
        if (!$this->events->shouldExecute($entity, 'before', 'update')) {
            return false;
        }
        $result = $this->doUpdate($entity);
        $this->events->shouldExecute($entity, 'after', 'update');
        return $result;
    }
943935
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        if (!$this->config('status')) {
            return true;
        }

        // as we don't know entity's ID on beforeSave, we must delay values storage;
        // all this occurs inside a transaction so we are safe
        if (!empty($this->_cache['createValues'])) {
            foreach ($this->_cache['createValues'] as $valueEntity) {
                $valueEntity->set('entity_id', $this->_toolbox->getEntityId($entity));
                $valueEntity->unsetProperty('id');
                TableRegistry::get('Eav.EavValues')->save($valueEntity);
            }
            $this->_cache['createValues'] = [];
        }

        foreach ($this->_attributesForEntity($entity) as $attr) {
            $field = $this->_prepareMockField($entity, $attr);
            $field->afterSave();
        }

        if ($this->config('cacheMap')) {
            $this->updateEavCache($entity);
        }

        return true;
    }
1034094
public function save(&$entity, $depth = 1) {
		if (is_null($entity))
			return null;
		
		//connect to database
		$this->mapper->connect();
		
		//begin transaction
		$this->mapper->beginTransaction();
		
		if ($depth == 0) { //don't store associated data
			//get primary key value
			$pk = $this->getPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey());
			
			if (is_null($pk)) { //new instance
				//check for duplicated values
				$checks = $this->entityProfile->getDuplicateChecks();
				
				if (!empty($checks)) {
					$ignore = true;
					
					foreach ($checks as $attr) {
						//get unique field value
						$attribute = $this->entityProfile->getProperty($attr);
						$value = $this->getPropertyValue($this->entityProfile, $entity, $attr);
						
						//get duplicate value id
						$query = $this->mapper->newQuery();
						$pk = $query->from($this->entityProfile->getEntityTable())
						->select(new Column($this->entityProfile->getPrimaryKey(true)))
						->where(Column::__callstatic($attribute->getColumn())->eq($value))
						->fetch('i');
						
						if (!is_null($pk)) {
							$ignore = $attribute->getCheckDuplicate() == 'ignore';
							break;
						}
					}
					
					if (!is_null($pk)) { //duplicated value found
						$this->setPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey(), $pk);
						//ignore or update
						return $ignore ? $pk : $this->save($entity, $depth);
					}
				}
				
				//build insert query
				$query = $this->mapper->newQuery();
				$query->insertInto($this->entityProfile->getEntityTable())
				->columns(array_keys($this->insertColumns))
				->valuesArray($this->castToArray($entity))
				->exec();
				$pk = $this->mapper->getLastId();
				
				//update primary key property
				$this->setPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey(), $pk);
				$this->mapper->commit();
				return $pk;
			}
			
			//build update query
			$query = $this->mapper->newQuery();
			$query->update($this->entityProfile->getEntityTable())
			->setValue($this->castToArray($entity))
			->where(Column::__callstatic($this->entityProfile->getPrimaryKey(true))->eq($pk))
			->exec();
			$this->mapper->commit();
			return $pk;
		}
		
		$foreignKeys = [];
		
		//store parent instances
		if ($this->entityProfile->hasForeignKeys()) {
			$foreignKeys = $this->entityProfile->getForeignKeys();
			
			foreach ($foreignKeys as $attr => $assoc) {
				$assoc = $this->entityProfile->getAssociation($assoc);
				
				if ($assoc->isReadOnly())
					continue;
				
				$related = $this->getAssociationValue($this->entityProfile, $entity, $assoc);
				if (is_null($related))
					$this->setPropertyValue($this->entityProfile, $entity, $attr, null);
				else {
					$id = $assoc->save($this->mapper, $entity, $related, $depth - 1);
					if (!is_null($id))
						$this->setPropertyValue($this->entityProfile, $entity, $attr, $id);
				}
			}
		}
		
		//get primary key value
		$pk = $this->getPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey());
		
		//new instance
		if (is_null($pk)) {
			//check for duplicated values
			$checks = $this->entityProfile->getDuplicateChecks();
			
			if (!empty($checks)) {
				$ignore = true;
					
				foreach ($checks as $attr) {
					//get unique field value
					$attribute = $this->entityProfile->getProperty($attr);
					$value = $this->getPropertyValue($this->entityProfile, $entity, $attr);
			
					//obtain duplicate value id
					$query = $this->mapper->newQuery();
					$pk = $query->from($this->entityProfile->getEntityTable())
					->select(new Column($this->entityProfile->getPrimaryKey(true)))
					->where(Column::__callstatic($attribute->getColumn())->eq($value))
					->fetch('i');
					
					if (!is_null($pk)) {
						$ignore = $attribute->getCheckDuplicate() == 'ignore';
						break;
					}
				}
					
				if (!is_null($pk)) {
					//persist or ignore
					$this->setPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey(), $pk);
					return $ignore ? $pk : $this->save($entity, $depth);
				}
			}
			
			//build insert query
			$query = $this->mapper->newQuery();
			$query->insertInto($this->entityProfile->getEntityTable())
			->columns(array_keys($this->insertColumns))
			->valuesArray($this->castToArray($entity))
			->exec();
			$pk = $this->mapper->getLastId();
			
			//update primary key property
			$this->setPropertyValue($this->entityProfile, $entity, $this->entityProfile->getPrimaryKey(), $pk);
		}
		else {
			//update value
			$query = $this->mapper->newQuery();
			$query->update($this->entityProfile->getEntityTable())
			->setValue($this->castToArray($entity))
			->where(Column::__callstatic($this->entityProfile->getPrimaryKey(true))->eq($pk))
			->exec();
		}
		
		//persist related data
		foreach ($this->entityProfile->getAssociations() as $attr => $assoc) {
			if (in_array($attr, $foreignKeys)) //already persisted
				continue;
			
			if ($assoc->isReadOnly())
				continue;
			
			//get associated data
			$value = $this->getAssociationValue($this->entityProfile, $entity, $assoc);
			if (!is_null($value))
				$assoc->save($this->mapper, $entity, $value, $depth - 1);
		}
		
		$this->mapper->commit();
		return $pk;
	}
106128
public function beforeSave(Event $event, Entity $entity): void
    {
        $this->__originalSortValue = $entity->getOriginal($this->getConfig('sortField'));
    }
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);
    }
427746
public function save($entity)
    {
        $this
            ->objectManager
            ->persist($entity);

        $this
            ->objectManager
            ->flush($entity);
    }
248453
public function setEntity(Entity $entity)
    {
        $this->each(
            function(Record $record) use ($entity) {
                $record->setEntity($entity);
                $record->setEntityClass(get_class($entity));
            }
        );

        return $this;
    }
426945
public function isSatisfiedBy(Entity $entity)
    {
        if (property_exists($entity, 'active')) {
            return (bool)$entity->active;
        }

        throw new InvalidArgumentException("Property 'active' does not exist in class " . get_class($entity));
    }
1287990
public function save(EntityInterface $entity)
    {
        $entity = $this->beforeSave($entity);

        $this->getEntityManager()->persist($entity);
        $this->getEntityManager()->flush($entity);

        $this->afterSave($entity);
    }