{@inheritdoc}

@throws \Drupal\Core\Entity\EntityStorageException
774401
public function createContent() {
    // Create node.
    $node = Node::create([
      'type' => 'page',
      'title' => 'Products',
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
      'uid' => 1,
      'status' => 1,
      'promote' => 0,
      'field_fields' => [],
      'path' => [
        'alias' => '/products',
      ],
    ]);
    $node->save();

    // Create menu link.
    $menuLink = MenuLinkContent::create([
      'title' => 'Products',
      'link' => [
        'uri' => "internal:/node/{$node->id()}",
      ],
      'menu_name' => 'main',
      'weight' => 30,
      'expanded' => TRUE,
    ]);
    $menuLink->save();
  }
477811
public function addStorage(Search $entity)
    {
        if ($entity->getStorage() instanceof Storage) {
            $this->add(function (QueryBuilder $query) use ($entity) {
                $query
                    ->andWhere('i.storage = :storage')
                    ->setParameter('storage', $entity->getStorage()->getId());
            });
        }

        return $this;
    }
277037
private function querySingleValue($sql, $parameters = [])
    {
        try {
            $statement = $this->pdo->prepare($sql);
            $statement->execute($parameters);

            $value = $statement->fetchColumn();

            $statement->closeCursor();
            if ($value === false) {
                throw new StorageException("The query returned no result.");
            }
            return $value;
        } catch (\PDOException $e) {
            throw new StorageException("The query failed.", 0, $e);
        }
    }
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);
        }
    }
579679
public function index()
    {
        $entities = $this->Dblists->find('all');

        $this->set(compact('entities'));
        $this->set('_serialize', ['entities']);
    }
1050649
public function setStorage($storageName)
    {
        Assertion::keyExists($this->availableStorages, $storageName, "Storage '{$storageName}' not available.");
        $this->enabledStorage = $storageName;

        return $this;
    }
922966
function store( $fieldFilters = null )
    {
        $db = eZDB::instance();

        $db->begin();
        parent::store( $fieldFilters );
        $this->updateAndStoreModified();
        $db->commit();
    }
463979
public function toStorageFieldDefinition(FieldDefinition $fieldDef, StorageFieldDefinition $storageDef)
    {
        $fieldSettings = $fieldDef->fieldTypeConstraints->fieldSettings;
        $validators = $fieldDef->fieldTypeConstraints->validators;
        $doc = new DOMDocument('1.0', 'utf-8');
        $root = $doc->createElement('related-objects');
        $doc->appendChild($root);

        $constraints = $doc->createElement('constraints');
        if (!empty($fieldSettings['selectionContentTypes'])) {
            foreach ($fieldSettings['selectionContentTypes'] as $typeIdentifier) {
                $allowedClass = $doc->createElement('allowed-class');
                $allowedClass->setAttribute('contentclass-identifier', $typeIdentifier);
                $constraints->appendChild($allowedClass);
                unset($allowedClass);
            }
        }
        $root->appendChild($constraints);

        $type = $doc->createElement('type');
        $type->setAttribute('value', 2); //Deprecated advance object relation list type, set since 4.x does
        $root->appendChild($type);

        $objectClass = $doc->createElement('object_class');
        $objectClass->setAttribute('value', ''); //Deprecated advance object relation class type, set since 4.x does
        $root->appendChild($objectClass);

        $selectionType = $doc->createElement('selection_type');
        if (isset($fieldSettings['selectionMethod'])) {
            $selectionType->setAttribute('value', (int)$fieldSettings['selectionMethod']);
        } else {
            $selectionType->setAttribute('value', 0);
        }
        $root->appendChild($selectionType);

        $defaultLocation = $doc->createElement('contentobject-placement');
        if (!empty($fieldSettings['selectionDefaultLocation'])) {
            $defaultLocation->setAttribute('node-id', (int)$fieldSettings['selectionDefaultLocation']);
        }
        $root->appendChild($defaultLocation);

        $selectionLimit = $doc->createElement('selection_limit');
        if (isset($validators['RelationListValueValidator']['selectionLimit'])) {
            $selectionLimit->setAttribute('value', (int)$validators['RelationListValueValidator']['selectionLimit']);
        } else {
            $selectionLimit->setAttribute('value', 0);
        }
        $root->appendChild($selectionLimit);

        $doc->appendChild($root);
        $storageDef->dataText5 = $doc->saveXML();
    }
146704
public function saveContent(Content $content, $comment = null)
    {
        $contenttype = $content->contenttype;
        $fieldvalues = $content->values;

        if (empty($contenttype)) {
            $this->app['logger.system']->error('Contenttype is required for ' . __FUNCTION__, ['event' => 'exception']);
            throw new StorageException('Contenttype is required for ' . __FUNCTION__);
        }

        // Test to see if this is a new record, or an update
        if (empty($fieldvalues['id'])) {
            $create = true;
        } else {
            $create = false;
        }

        // We need to verify if the slug is unique. If not, we update it.
        $getId = $create ? null : $fieldvalues['id'];
        $fieldvalues['slug'] = $this->getUri($fieldvalues['slug'], $getId, $contenttype['slug'], false, false);

        // Update the content object
        $content->setValues($fieldvalues);

        // Dispatch pre-save event
        if (! $this->inDispatcher && $this->app['dispatcher']->hasListeners(StorageEvents::PRE_SAVE)) {
            $event = new StorageEvent($content, ['contenttype' => $contenttype, 'create' => $create]);
            $this->app['dispatcher']->dispatch(StorageEvents::PRE_SAVE, $event);
        }

        // Decide whether to insert a new record, or update an existing one.
        if ($create) {
            $this->insertContent($content, $comment);
        } else {
            $this->updateContent($content, $comment);
        }

        // Update taxonomy and record relationships
        $this->updateTaxonomy($contenttype, $content->values['id'], $content->taxonomy);
        $this->updateRelation($contenttype, $content->values['id'], $content->relation);

        // Dispatch post-save event
        if (!$this->inDispatcher && $this->app['dispatcher']->hasListeners(StorageEvents::POST_SAVE)) {
            // Block loops
            $this->inDispatcher = true;

            $event = new StorageEvent($content, ['contenttype' => $contenttype, 'create' => $create]);
            $this->app['dispatcher']->dispatch(StorageEvents::POST_SAVE, $event);

            // Re-enable the dispatcher
            $this->inDispatcher = false;
        }

        return $content->values['id'];
    }
559269
public function persist($entity)
    {
        if ($this->evm->hasListeners(Events::prePersist)) {
            $this->evm->dispatchEvent(Events::prePersist, new Event\LifecycleEventArgs($entity, $this->sm));
        }

        $oid = spl_object_hash($entity);
        $this->scheduledForPersist[$oid] = $entity;

        if ($this->evm->hasListeners(Events::postPersist)) {
            $this->evm->dispatchEvent(Events::postPersist, new Event\LifecycleEventArgs($entity, $this->sm));
        }
    }
706343
public function delete(EntityDefinition $definition, array $ids, WriteContext $writeContext): DeleteResult
    {
        $this->validateWriteInput($ids);

        $commandQueue = new WriteCommandQueue();

        $fields = $definition->getPrimaryKeys();

        $resolved = [];
        foreach ($ids as $raw) {
            $mapped = [];

            /** @var Field $field */
            foreach ($fields as $field) {
                if (!($field instanceof StorageAware)) {
                    continue;
                }

                if (array_key_exists($field->getPropertyName(), $raw)) {
                    $mapped[$field->getStorageName()] = $raw[$field->getPropertyName()];
                    continue;
                }

                if ($field instanceof ReferenceVersionField) {
                    $mapped[$field->getStorageName()] = $writeContext->getContext()->getVersionId();
                    continue;
                }

                if ($field instanceof VersionField) {
                    $mapped[$field->getStorageName()] = $writeContext->getContext()->getVersionId();
                    continue;
                }

                $fieldKeys = $fields
                    ->filter(function (Field $field) {
                        return !$field instanceof VersionField && !$field instanceof ReferenceVersionField;
                    })
                    ->map(function (Field $field) {
                        return $field->getPropertyName();
                    });

                throw new IncompletePrimaryKeyException($fieldKeys);
            }

            $resolved[] = $mapped;
        }

        if (!$definition instanceof MappingEntityDefinition) {
            $restrictions = $this->foreignKeyResolver->getAffectedDeleteRestrictions($definition, $resolved, $writeContext->getContext());

            if (!empty($restrictions)) {
                $restrictions = array_map(function ($restriction) {
                    return new RestrictDeleteViolation($restriction['pk'], $restriction['restrictions']);
                }, $restrictions);

                throw new RestrictDeleteViolationException($definition, $restrictions, $this->registry);
            }
        }

        $cascades = [];
        if (!$definition instanceof MappingEntityDefinition) {
            $cascadeDeletes = $this->foreignKeyResolver->getAffectedDeletes($definition, $resolved, $writeContext->getContext());

            $cascadeDeletes = array_column($cascadeDeletes, 'restrictions');
            foreach ($cascadeDeletes as $cascadeDelete) {
                $cascades = array_merge_recursive($cascades, $cascadeDelete);
            }

            foreach ($cascades as $affectedDefinitionClass => &$cascade) {
                $affectedDefinition = $this->registry->get($affectedDefinitionClass);

                $cascade = array_map(function ($key) use ($affectedDefinition) {
                    $payload = $key;

                    if (!\is_array($key)) {
                        $payload = ['id' => $key];
                    }

                    return new EntityWriteResult($key, $payload, $affectedDefinition, null);
                }, $cascade);
            }
        }

        $skipped = [];
        foreach ($resolved as $mapped) {
            $mappedBytes = array_map(function ($id) {
                return Uuid::fromHexToBytes($id);
            }, $mapped);

            $existence = $this->gateway->getExistence($definition, $mappedBytes, [], $commandQueue);

            if (!$existence->exists()) {
                $skipped[$definition->getClass()][] = new EntityWriteResult($mapped, $mapped, $definition, $existence);
                continue;
            }

            $commandQueue->add(
                $definition,
                new DeleteCommand(
                    $definition,
                    $mappedBytes,
                    $existence
                )
            );
        }

        $writeContext->setLanguages($this->languageLoader->loadLanguages());
        $identifiers = $this->getWriteResults($commandQueue);
        $this->gateway->execute($commandQueue->getCommandsInOrder(), $writeContext);

        return new DeleteResult(
            array_merge_recursive($identifiers, $cascades),
            $skipped
        );
    }
948113
public function solveSave(Entity &$entity, &$value) // TODO: Refactor Query builder to be able to use it more often.
    {
        // We need to sync our collection with the jointable inbetween us.
        // We can have some deleted ones in our collection, but we are not sure.
        /** @var JoinTable $joinTable */
        $joinTable = $this->relation->join; // Table to sync it to.

        // First we need to verify if we got an ArrayCollection here
        if (! $value instanceof ArrayCollection) {
            throw new RelationException("Value given in your '".$this->structure->name."' entity relation (many to many) should always be an ArrayCollection instance!");
        }

        // Prepare to get id's from our entities!
        $currentId = $entity->_id;
        $insertIds = array();

        $ourColumn = $joinTable->column->name;
        $targetColumn = $joinTable->targetColumn->name;

        // Check if we only have an empty collection, then only delete from the joinTable
        if ($value->count() === 0) {
            // Only clear table contents (with join params)
            $delete = EntityManager::query($entity, false)
                ->delete($joinTable->name)
                ->where($ourColumn, $currentId)
                ->apply();

            if ($delete === false) {
                throw new RelationException("We can not solve the Many to Many relation save! Please verify your 
                structure in PHP classes and the database for the join table. Delete problems (all delete)!");
            }

            return true; // Make sure we stop here, no inserts needed
        }

        // Parse all items in the collection, prepare the jointable inserts.
        foreach ($value as $item) {
            if (is_int($item)) {
                // The user already gave us an ID only! Add it anyway
                $insertIds[] = $item;
                continue;
            }

            if (! $item instanceof Entity) {
                throw new RelationException("Values given in your '".$this->structure->name."' entity relation 
                (many to many) should always be an ArrayCollection with inside ID's or Entities!");
            }

            if ($item->_id === null) {
                throw new RelationException("Entities given inside of your ArrayCollection for relations 
                (entity: '".$this->structure->name."') should always be saved or fetched, 
                current entity not saved/fetched!");
            }

            $insertIds[] = $item->_id;
        }

        // We have enough information, we need to sync the db with our ids.
        // Delete all current entries with our current id in it.
        $delete = EntityManager::query($entity, false)
            ->delete($joinTable->name)
            ->where($ourColumn, $currentId)
            ->apply(); // This could be a bit better with syncing, instead of just replacing everything (TODO).
        if ($delete === false) {
            throw new RelationException("We can not solve the Many to Many relation save! 
            Please verify your structure in PHP classes and the database for the join table. Delete problems!");
        }

        $sql = "INSERT INTO $joinTable->name (`{$ourColumn}`, `{$targetColumn}`) VALUES ";
        $idx = 0;
        $max = count($insertIds);
        foreach ($insertIds as $rowNum => $rowId) {
            $sql .= " (:ourid, :target_$rowNum)";
            if (($idx+1) < $max) {
                $sql .= ", ";
            }
            $idx++;
        }
        $statement = EntityManager::query($entity, false)->prepare($sql);
        $statement->bindValue(":ourid", $currentId);
        foreach ($insertIds as $num => $rowId) {
            $statement->bindValue(":target_$num", $rowId);
        }

        $insert = $statement->execute();

        if ($insert === false) {
            throw new RelationException("We can not solve the Many to Many relation save! Please verify your structure in PHP classes and the database for the join table. Insert problems! " . implode(' - ', $statement->errorInfo()));
        }

        return true;
    }
69660
function store( $fieldFilters = null )
    {
        // Unset the cache
        global $eZContentObjectContentObjectCache;
        unset( $eZContentObjectContentObjectCache[$this->ContentObjectID] );
        global $eZContentObjectDataMapCache;
        unset( $eZContentObjectDataMapCache[$this->ContentObjectID] );

        $classAttribute = $this->contentClassAttribute();

        $dataType = $classAttribute->dataType();
        if ( $dataType )
        {
            $this->setAttribute( 'data_type_string', $classAttribute->attribute( 'data_type_string' ) );
            $this->updateSortKey( false );

            $db = eZDB::instance();
            $db->begin();

            // store the content data for this attribute
            $dataType->storeObjectAttribute( $this );

            parent::store( $fieldFilters );
            $dataType->postStore( $this );
            $db->commit();
        }
    }
1165659
public function initializeObject()
    {
        if (!is_writable($this->path)) {
            Files::createDirectoryRecursively($this->path);
        }
        if (!is_dir($this->path) && !is_link($this->path)) {
            throw new StorageException('The directory "' . $this->path . '" which was configured as a resource storage does not exist.', 1361533189);
        }
        if (!is_writable($this->path)) {
            throw new StorageException('The directory "' . $this->path . '" which was configured as a resource storage is not writable.', 1361533190);
        }
    }
427536
function store( $publish = false )
    {
        if ( $publish )
        {
            $originalVersion = $this->attribute( 'version' );
            $this->setAttribute( 'version', eZPDFExport::VERSION_VALID );
        }
        $user = eZUser::currentUser();
        $this->setAttribute( 'modified', time() );
        $this->setAttribute( 'modifier_id', $user->attribute( 'contentobject_id' ) );

        $db = eZDB::instance();
        $db->begin();
        parent::store();
        if ( $publish )
        {
            $this->setAttribute( 'version', eZPDFExport::VERSION_DRAFT );
            $this->remove();
            $this->setAttribute( 'version', $originalVersion );
        }
        $db->commit();
    }
1221386
public function load($entities, $depth = 1)
    {
        if (!\is_array($entities) && !$entities instanceof \Traversable) {
            throw new \InvalidArgumentException(self::E_MSG);
        }

        $entitiesByValueClassByIds = $this->sortEntitiesByValueClass($entities);
        foreach ($entitiesByValueClassByIds as $valueClass => $entitiesById) {
            $this->loadEntityValues($valueClass, $entitiesById);
        }

        $this->loadRelatedEntities($entities, $depth);
    }
1128085
public function saveAll(array $entities): void
    {
        if ([] === $entities) {
            return;
        }
        foreach ($entities as $entity) {
            if (false === $entity instanceof EntityInterface) {
                throw new \InvalidArgumentException(
                    'Found invalid $entity was not an EntityInterface, was ' . \get_class($entity)
                );
            }
            $this->entityManager->persist($entity);
        }
        $this->entityManager->flush();
    }