diff --git a/src/Service/Category/CategoryPersister.php b/src/Service/Category/CategoryPersister.php index cd0afc5..b3d0e3b 100644 --- a/src/Service/Category/CategoryPersister.php +++ b/src/Service/Category/CategoryPersister.php @@ -26,7 +26,7 @@ public function processRequest(Category $category, CategoryDTO $dto, Request $re { try { $this->helper->validateRequestResource($request, $category); - $this->validator->validate($dto); + $this->validator->validate($dto, $this->helper->isEditRoute($request)); $this->persist($category, $dto); $response = ApiResponse::createAndFormat( diff --git a/src/Service/Category/CategoryValidator.php b/src/Service/Category/CategoryValidator.php index 316ebc8..f7cee66 100644 --- a/src/Service/Category/CategoryValidator.php +++ b/src/Service/Category/CategoryValidator.php @@ -20,19 +20,24 @@ public function __construct( } /** @throws BadDataException*/ - public function validate(CategoryDTO $dto): void + public function validate(CategoryDTO $dto, bool $isEditRoute = true): void { $this ->validateNameNotEmpty($dto->getName()) - ->validateNameIsUnique($dto->getName()) - ; + ->validateNameDoesNotExist($dto, $isEditRoute); } - /** @throws BadDataException*/ - private function validateNameIsUnique(string $name): self + /** @throws BadDataException */ + public function validateNameDoesNotExist(CategoryDTO $dto, bool $onEdit = true): self { - $this->categoryRepository->findBy(['name' => $name, 'archivedAt' => null]) - && throw new BadDataException(self::NAME_SHOULD_BE_UNIQUE); + ($CategoryByName = $this->categoryRepository->findOneBy(['name' => $dto->getName(), 'archivedAt' => null])) instanceof Category + && ( + ( + $onEdit + && ($CategoryBySlug = $this->categoryRepository->findOneBySlug($dto->getSlug())) instanceof Category + && $CategoryByName->getId() !== $CategoryBySlug->getId() + ) || !$onEdit + ) && throw new BadDataException(self::NAME_SHOULD_BE_UNIQUE); return $this; }