implement update case for SaveEntity
parent
21a93966d7
commit
8d86f09feb
@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Kartierung\Repository\ResolutionStrategy\Execution;
|
||||||
|
|
||||||
|
use Kartierung\Analyze\Result\EntityField;
|
||||||
|
use Kartierung\Analyze\Result\EntityResult;
|
||||||
|
use Kartierung\Repository\InvalidCall;
|
||||||
|
use PDO;
|
||||||
|
|
||||||
|
readonly class UpdateEntity
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private PDO $pdo
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param EntityResult<object> $entityResult
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
* @return object
|
||||||
|
*/
|
||||||
|
public function update(EntityResult $entityResult, array $data): object
|
||||||
|
{
|
||||||
|
$pairs = implode(', ', array_map(
|
||||||
|
static fn(EntityField $field) => "$field->columnName = ?",
|
||||||
|
$entityResult->fieldsWithoutId()
|
||||||
|
));
|
||||||
|
$idWhere = $entityResult->idField->columnName . ' = ?';
|
||||||
|
|
||||||
|
$params = array_map(
|
||||||
|
static fn(EntityField $field) => $data[$field->columnName] ?? null,
|
||||||
|
$entityResult->fieldsWithoutId()
|
||||||
|
);
|
||||||
|
$id = $data[$entityResult->idField->columnName] ?? null;
|
||||||
|
$params[] = $id;
|
||||||
|
// reindex keys for pdo
|
||||||
|
$params = array_values($params);
|
||||||
|
|
||||||
|
$sql = "UPDATE $entityResult->tableName SET $pairs WHERE $idWhere";
|
||||||
|
$prepStmt = $this->pdo->prepare($sql);
|
||||||
|
$success = $prepStmt->execute($params);
|
||||||
|
|
||||||
|
if (!$success) {
|
||||||
|
throw new InvalidCall(
|
||||||
|
"Database reports failed updated statement."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $prepStmt->rowCount();
|
||||||
|
if ($rows !== 1) {
|
||||||
|
throw new InvalidCall(
|
||||||
|
"Database returns $rows affected. Exactly 1 expected."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$entity = (new SelectEntityById($this->pdo))->select($entityResult, $id);
|
||||||
|
if (!$entity) {
|
||||||
|
throw new InvalidCall(
|
||||||
|
"Entity of type $entityResult->classFqcn with id $id can not be selected."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $entity;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue