Fix update segment when the name is the same

[MAILPOET-3343]
This commit is contained in:
Jan Lysý
2020-12-17 10:10:13 +01:00
committed by Veljko V
parent 11036f4255
commit b67c216e31
2 changed files with 21 additions and 5 deletions

View File

@@ -16,18 +16,17 @@ class SegmentSaveController {
} }
public function save(array $data = []): SegmentEntity { public function save(array $data = []): SegmentEntity {
$this->checkSegmenUniqueName($data['name'] ?? '');
$id = isset($data['id']) ? (int)$data['id'] : null; $id = isset($data['id']) ? (int)$data['id'] : null;
$name = $data['name'] ?? ''; $name = $data['name'] ?? '';
$description = $data['description'] ?? ''; $description = $data['description'] ?? '';
$this->checkSegmenUniqueName($name, $id);
return $this->segmentsRepository->createOrUpdate($name, $description, $id); return $this->segmentsRepository->createOrUpdate($name, $description, $id);
} }
private function checkSegmenUniqueName(string $name): void { private function checkSegmenUniqueName(string $name, ?int $id): void {
$segment = $this->segmentsRepository->findOneBy(['name' => $name]); if (!$this->segmentsRepository->isNameUnique($name, $id)) {
if ($segment) {
throw new InvalidArgumentException("Segment with name: '{$name}' already exists."); throw new InvalidArgumentException("Segment with name: '{$name}' already exists.");
} }
} }

View File

@@ -33,6 +33,23 @@ class SegmentsRepository extends Repository {
return $countMap; return $countMap;
} }
public function isNameUnique(string $name, ?int $id): bool {
$qb = $this->doctrineRepository->createQueryBuilder('s')
->select('s')
->where('s.name = :name')
->setParameter('name', $name);
if ($id !== null) {
$qb->andWhere('s.id != :id')
->setParameter('id', $id);
}
$results = $qb->getQuery()
->getResult();
return count($results) === 0;
}
public function createOrUpdate( public function createOrUpdate(
string $name, string $name,
string $description = '', string $description = '',