Skip to content

Commit

Permalink
refac(Validator): ease category name uniqueness
Browse files Browse the repository at this point in the history
see: #14
  • Loading branch information
n3wborn committed Sep 26, 2023
1 parent b6417fe commit 07b85c4
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/Service/Category/CategoryValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,30 @@ public function __construct(
/** @throws BadDataException*/
public function validate(CategoryDTO $dto, bool $isEditRoute = true): void
{
$this
->validateNameNotEmpty($dto->getName())
->validateNameDoesNotExist($dto, $isEditRoute);
$this->validateNameNotEmpty($dto->getName());

$isEditRoute
? $this->validateEditionName($dto)
: $this->validateCreationName($dto);
}

/** @throws BadDataException */
public function validateCreationName(CategoryDTO $dto): self
{
(null !== $this->categoryRepository->findNotArchivedByName($dto->getName()))
&& throw new BadDataException(self::NAME_SHOULD_BE_UNIQUE);

return $this;
}

/** @throws BadDataException */
public function validateNameDoesNotExist(CategoryDTO $dto, bool $onEdit = true): self
public function validateEditionName(CategoryDTO $dto): self
{
($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);
$existingCategory = $this->categoryRepository->findNotArchivedByName($dto->getName());

(null !== $existingCategory)
&& ($existingCategory->getSlug() !== $dto->getSlug())
&& throw new BadDataException(self::NAME_SHOULD_BE_UNIQUE);

return $this;
}
Expand Down

0 comments on commit 07b85c4

Please sign in to comment.