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