From c41bc7bef962de33b4b1e7cf03b79e84e01aa88d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Mon, 4 Oct 2021 16:16:34 +0200 Subject: [PATCH] prevent recursion --- .../src/Entity/AsideActivityCategory.php | 27 ++++++++++++++++++- .../src/translations/validators.fr.yaml | 1 + 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/Bundle/ChillAsideActivityBundle/src/translations/validators.fr.yaml diff --git a/src/Bundle/ChillAsideActivityBundle/src/Entity/AsideActivityCategory.php b/src/Bundle/ChillAsideActivityBundle/src/Entity/AsideActivityCategory.php index e405f1556..09087226c 100644 --- a/src/Bundle/ChillAsideActivityBundle/src/Entity/AsideActivityCategory.php +++ b/src/Bundle/ChillAsideActivityBundle/src/Entity/AsideActivityCategory.php @@ -7,6 +7,8 @@ namespace Chill\AsideActivityBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\Validator\Constraints as Assert; +use Symfony\Component\Validator\Context\ExecutionContextInterface; /** * @ORM\Entity @@ -83,11 +85,32 @@ class AsideActivityCategory return $this; } - public function getParent(): ?self + public function getParent(): ?self { return $this->parent; } + /** + * + * @Assert\Callback() + */ + public function preventRecursiveParent(ExecutionContextInterface $context, $payload) + { + if (!$this->hasParent()) { + return; + } + + if ($this->getParent() === $this) { + // replace parent with old parent. This prevent recursive loop + // when displaying form + $this->parent = $this->oldParent; + $context->buildViolation('You must not add twice the same category in the parent tree (previous result returned)') + ->atPath('parent') + ->addViolation() + ; + } + } + public function hasParent(): bool { return $this->parent !== null; @@ -95,6 +118,8 @@ class AsideActivityCategory public function setParent(?self $parent): self { + // cache the old result for changing it during validaiton + $this->oldParent = $this->parent; $this->parent = $parent; return $this; diff --git a/src/Bundle/ChillAsideActivityBundle/src/translations/validators.fr.yaml b/src/Bundle/ChillAsideActivityBundle/src/translations/validators.fr.yaml new file mode 100644 index 000000000..28883568c --- /dev/null +++ b/src/Bundle/ChillAsideActivityBundle/src/translations/validators.fr.yaml @@ -0,0 +1 @@ +You must not add twice the same category in the parent tree (previous result returned): Il est interdit d'indiquer la même entité dans l'arbre des parents. Le résultat précédent a été rétabli