Skip to content

Commit

Permalink
feat(Category): improve unique name validation
Browse files Browse the repository at this point in the history
  • Loading branch information
n3wborn committed Sep 22, 2023
1 parent acc8d91 commit 91330c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/Service/Category/CategoryPersister.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
19 changes: 12 additions & 7 deletions src/Service/Category/CategoryValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 91330c9

Please sign in to comment.