Save and optionally flush an entity

@param $entity
@param bool $flush
@return $this
199911
public function save($entity, $flush = true)
    {
        $this->getEntityManager()->persist($entity);

        if ($flush) {
            $this->getEntityManager()->flush($entity);
        }
        return $this;
    }
1006525
public function delete($object, $flush = true)
    {
        try {
            $entityManager = $this->getEntityManager($object);
            $this->preDelete($object);
            $entityManager->remove($object);
            if ($flush) {
                $entityManager->flush();
            }
            $this->postDelete($object);
        } catch (\PDOException $e) {
            throw new ModelManagerException('', 0, $e);
        }
    }
937877
public function insert(Entity $entity = null, Repository $repository = null)
    {
        $entity = $this->getEntityIfEmpty($entity);
        $repository = $entity->getRepositoryIfEmpty($repository);

        $this->trigger(['saving', 'inserting']);

        $insert = $repository->insert($this, $entity);

        $this->trigger(['inserted', 'saved']);

        $this->setOriginalFromData();

        return $insert;
    }
599094
public function insert($entity)
    {
        $persistor = new CsvPersistor(
            $this->gateway,
            $this->table,
            $this->entityRegistry->getEntityBuilder(),
            $this->entityRegistry
        );
        $persistor->insert($entity);
    }
183437
public function deleteAndFlush($entity, $entityManager = null)
    {
        $entityManager = $this->getEntityManager($entityManager);

        $entityManager->remove($entity);
        $entityManager->flush($entity);
    }
376935
public static function save($entity): ResultInterface
    {
        $className = \get_class($entity);
        list($table, , , $fields) = self::getFields($entity, 1);
        $instance = self::getInstance($className);

        $fields = $fields ?? [];
        $query  = Query::table($table)->selectInstance($instance);
        // Set Primary Id to Entity
        $query->addDecorator(function ($primaryId) use ($entity, $className) {
            list(, , $idColumn) = self::getTable($className);
            // When Primary Id is auto increment
            $getter = 'get' . StringHelper::camel($idColumn, false);
            $setter = 'set' . StringHelper::camel($idColumn, false);
            if (method_exists($entity, $getter) && method_exists($entity, $setter)) {
                if ($entity->$getter() === null) {
                    $entity->$setter($primaryId);
                } else {
                    $primaryId = $entity->$getter();
                }
            }
            return $primaryId;
        });
        return $query->insert($fields);
    }
546413
public function saveEntity($entity, $flush = true)
    {
        $this->preSaveEntity($entity);

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

        if ($flush) {
            $this->getEntityManager()->flush($entity);
        }

        // Get updated fields, and include changes so that we have everything.
        $fields  = $entity->getUpdatedFields();
        $changes = [];
        if (method_exists($entity, 'getChanges')) {
            $changes = $entity->getChanges();

            // remove the fields that are part of changes as they were already saved via a setter
            $fields = array_diff_key($fields, $changes);
        }

        // Get Extended Fields to separate from standard Update statement.
        $extendedFields = [];
        $fieldList      = $this->getCustomFieldList('lead');
        foreach ($fields as $alias => $value) {
            if (in_array($fieldList[0][$alias]['object'], ['extendedField', 'extendedFieldSecure'])) {
                // Depends on object added by alteration in organizeFieldsByGroup.
                $extendedFields[$alias]['object'] = $fieldList[0][$alias]['object'];
                $extendedFields[$alias]['id']     = $fieldList[0][$alias]['id'];
                $extendedFields[$alias]['type']   = $fieldList[0][$alias]['type'];
                $extendedFields[$alias]['alias']  = $alias;
                $extendedFields[$alias]['value']  = $value;
                unset($fields[$alias]);
            }
        }

        $this->prepareDbalFieldsForSave($fields);

        // Save standard/core fields (same as core).
        if (!empty($fields)) {
            $table = $this->getEntityManager()->getClassMetadata($this->getClassName())->getTableName();
            $this->getEntityManager()->getConnection()->update($table, $fields, ['id' => $entity->getId()]);
        }

        // Now to update extended fields if there were any to be updated.
        if (!empty($extendedFields)) {
            $insertUpdates = $deletions = [];
            $leadId        = $entity->getId();
            /** @var \Doctrine\DBAL\Connection $connection */
            $connection = $this->getEntityManager()->getConnection();
            foreach ($extendedFields as $extendedField) {
                if (
                    !isset($changes['fields'])
                    || !isset($changes['fields'][$extendedField['alias']])
                ) {
                    // No change to this extended field detected.
                    continue;
                }
                $schema  = $this->leadFieldModel->getSchemaDefinition($extendedField['alias'], $extendedField['type']);
                $columns = [
                    'value' => $extendedField['value'],
                ];
                // Corrects boolean field values, nothing more at this point.
                $this->prepareDbalFieldsForSave($columns);
                $secure    = 'extendedFieldSecure' === $extendedField['object'] ? '_secure' : '';
                $tableName = MAUTIC_TABLE_PREFIX.'lead_fields_leads_'.$schema['type'].$secure.'_xref';

                if (
                    null !== $changes['fields'][$extendedField['alias']][0]
                    && null === $changes['fields'][$extendedField['alias']][1]
                ) {
                    // Removed an existing value.
                    $connection->delete(
                        $tableName,
                        [
                            'lead_id'       => $leadId,
                            'lead_field_id' => $extendedField['id'],
                        ]
                    );
                } else {
                    // Mark for insert/update.
                    if (!isset($insertUpdates[$tableName])) {
                        $insertUpdates[$tableName] = [];
                    }
                    if (!isset($insertUpdates[$tableName][$extendedField['id']])) {
                        $insertUpdates[$tableName][$extendedField['id']] = $columns['value'];
                    }
                }
            }
            // Handle inserts/updates in bulk by table.
            if ($insertUpdates) {
                foreach ($insertUpdates as $tableName => $leadField) {
                    $rows = $params = [];
                    foreach ($leadField as $leadFieldId => $value) {
                        $key          = $tableName.$leadFieldId;
                        $rows[]       = $leadId.', '.$leadFieldId.', :'.$key;
                        $params[$key] = $value;
                    }
                    $sql  = 'INSERT INTO '.$tableName.' (`lead_id`, `lead_field_id`, `value`) '.
                        'VALUES ('.implode('),(', $rows).') '.
                        'ON DUPLICATE KEY UPDATE `value`=VALUES(`value`);';
                    $stmt = $connection->prepare($sql);
                    $stmt->execute($params);
                }
            }
        }

        $this->postSaveEntity($entity);
    }
1312585
public function pushData(EntityInterface $entity)
    {
        if ($this->isMany()) {
            $this->data[] = $entity;
            return $this;
        }
        $this->data = $entity;
        return $this;
    }
1168103
private function save(RedirectRouteInterface $entity)
    {
        $this->manager->save($entity);

        if (0 === count($this->sources) % $this->batchSize) {
            $this->entityManager->flush();
        }
    }
254451
public function flush($entity)
    {
        /**
         * @var ObjectManager $objectManager
         */
        $objectManager = $this
            ->get('elcodi.provider.manager')
            ->getManagerByEntityNamespace(get_class($entity));

        $objectManager->persist($entity);
        $objectManager->flush($entity);

        return $this;
    }
891495
public function save($entity)
    {
        $query = new Query($entity, false);
        $structure = $this->getEntityStructure($entity);

        if ($entity->_saved) {
            // Update
            $result = $query->update()->set($this->getEntityDataArray($entity))->where(array($structure->primaryColumn->name => $entity->_id))->apply();

            // Update relations
            RelationManager::with($entity)->saveRelations();

            return $result;
        } else {
            // Insert
            $id = $query->insert()->into($structure->tableName)->values($this->getEntityDataArray($entity))->apply();

            if ($id === false) {
                return false; // @codeCoverageIgnore
            }

            // Update relations
            RelationManager::with($entity)->saveRelations();

            // Save ID and state
            $entity->{$structure->primaryColumn->propertyName} = $id;
            $entity->_id = $id;
            $entity->_saved = true;

            return true;
        }
    }
717988
public function saveItem($entity)
    {
        $this->em->persist($entity);
        $this->em->flush();
        return $entity;
    }
493067
public void put(Entity entity) {
    int bytesHere = EntityTranslator.convertToPb(entity).getSerializedSize();

    // Do this before the add so that we guarantee that size is never > sizeLimit
    if (putsBytes + bytesHere >= params.getBytesLimit()) {
      flushPuts();
    }

    putsBytes += bytesHere;
    puts.add(entity);

    if (puts.size() >= params.getCountLimit()) {
      flushPuts();
    }
  }
658482
protected function saveEntity($entity)
    {
        try {
            $this->entityManager->persist($entity);
            $this->entityManager->flush($entity);
            return $entity;
        } catch (OptimisticLockException $e) {
            throw new DatabaseException($e->getMessage());
        }
    }
740967
final public function remove(BaseEntityInterface $entity, $flush = false): self
    {
        $this->_em->remove($entity);

        if (true === $flush) {
            $this->_em->flush();
        }

        return $this;
    }
416031
public function moveBefore($entity)
    {
        /* @var \Eloquent $this */
        $this->getConnection()->beginTransaction();

        if ($this->position > $entity->position) {
            $this->getConnection()->table($this->getTable())->where('position', '>=', $entity->position)->where(
                'position',
                '<',
                $this->position
            )->increment('position');
            $this->position = $entity->position;

            $entity->position = $entity->position + 1;
        } else {
            if ($this->position < $entity->position) {
                $this->getConnection()->table($this->getTable())->where('position', '<', $entity->position)->where(
                    'position',
                    '>',
                    $this->position
                )->decrement('position');
                $this->position = $entity->position - 1;
            }
        }

        $this->{ $this->getSaveMethod() }();

        $this->getConnection()->commit();
    }
831544
public function save(SaveEntityInterface $entity)
    {
        $entity = $this->persist($entity);
        $this->flush();

        return $entity;
    }