public function persist(IEntity $entity)
{
$this->initializeData();
$data = $this->entityToArray($entity);
$data = $this->getStorageReflection()->convertEntityToStorage($data);
if ($entity->isPersisted()) {
$id = $entity->getPersistedId();
$primaryValue = implode(',', (array) $id);
} else {
$this->lock();
try {
$storedData = $this->readEntityData();
if (!$entity->hasValue('id')) {
$id = $storedData ? max(array_keys($storedData)) + 1 : 1;
$storagePrimaryKey = $this->storageReflection->getStoragePrimaryKey();
$data[$storagePrimaryKey[0]] = $id;
} else {
$id = $entity->getValue('id');
}
$primaryValue = implode(',', (array) $id);
if (isset($storedData[$primaryValue])) {
throw new InvalidStateException("Unique constraint violation: entity with '{$primaryValue}' primary value already exists.");
}
$storedData[$primaryValue] = null;
$this->saveEntityData($storedData);
} finally {
$this->unlock();
}
}
$this->data[$primaryValue] = $entity;
$this->dataToStore[$primaryValue] = $data;
return $id;
}