skip to Main Content

I need to check if entered value, e.g "specialist", is not in use as an URL in Symfony 6 application.

Simple ANY-method paths are simple:

/** @var RouterInterface $router */
$router->match('/specialist');
// returns array

Non-matching methods are also simple:

/** @var RouterInterface $router */
$router->match('/specialist');
// if route path "/specialist" accepts only POST
// SymfonyComponentRoutingExceptionMethodNotAllowedException is thrown

But I need to check urls that are used as a prefix, e.g if I need to check for string "login" and have urls ‘/login/facebook’ and ‘/login/google’ but no simple ‘/login’. So – how can I check if string is not being used as any url prefix?

Symfony version 6, as said.

EDIT:

How to make this into a Validator, or more specifically, how can I inject Router (or whatever needed) into my validator?

2

Answers


  1. How to make this into a Validator, or more specifically, how can I inject Router (or whatever needed) into my validator?

    If you’re using default services configuration (autowire: true and autoconfigure: true), you can just inject needed dependencies into your validator in the same way as into other services.

    Quick example below:

    use SymfonyComponentRoutingRouterInterface;
    use SymfonyComponentValidatorConstraint;
    use SymfonyComponentValidatorConstraintValidator;
    
    class MyValidator extends ConstraintValidator
    {
        private RouterInterface $router;
    
        public function __construct(RouterInterface $router)
        {
            $this->router = $router;
        }
    
        public function validate($value, Constraint $constraint): void
        {
             // ...
        }
    }
    

    See more in the Constraint Validators with Dependencies documentation paragraph.

    Login or Signup to reply.
  2. I think you want one (or more) catch-all routes, for URLs which don’t already have a controller

    #[Route(path: '/{friendlyURL}', name: '...', methods: ['GET'], requirements: ['friendlyURL' => '[a-zA-Z0-9_-]{2,32}'], priority: -1, options: ['utf8' => true])]
    

    The priority value means it gets checked last

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search