Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3925

Symfony 4.4 before create /{slug} check existing routes

$
0
0

I have the entity Page identified by slug. Also I have the action to view a page in the Page controler :

class PageController extends AbstractController
{
   /**
    * @Route("/{slug}", name="fronend_page")
    */
   public function show(Page $page)
   {
       return $this->render("font_end/page/show.html.twig", [
           "page" => $page,
       ]);
   }
}

I am looking for good practice to validate the slug ( check if exist in routes) before save it in the database without use prefixes Example :

route exist : @route ("/blog")

check if blog exist before create slug : /{slug} = /blog

I have created a solution but I am not sure it is the best solution: I Create a custom Validation Constraint

class ContainsCheckSlugValidator extends ConstraintValidator
{

   private $router;

   public function __construct(UrlGeneratorInterface $router)
   {
       $this->router = $router;
   }

   public function validate($value, Constraint $constraint)
   {
       if (!$constraint instanceof ContainsCheckSlug) {
           throw new UnexpectedTypeException($constraint, ContainsCheckSlug::class);
       }

       // custom constraints should ignore null and empty values to allow
       // other constraints (NotBlank, NotNull, etc.) take care of that
       if (null === $value || '' === $value) {
           return;
       }
       $drp = true;
       try {
           $url = $this->router->generate('fronend_page', [
               'slug' => $value,
           ]);
       } catch (RouteNotFoundException $e) {
           $drp = false;
       }
       if ($drp) {
           $this->context->buildViolation($constraint->message)
               ->setParameter('{{ string }}', $value)
               ->addViolation();
       }


   }
}

thanks


Viewing all articles
Browse latest Browse all 3925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>