Search code examples
symfonyfosrestbundle

symfony + fosrest: how to validate route param


I have several actions with same route param, for example

/**
 * @Rest\Get("/api/ip/{ip}", name="app_ip_get")
 */
public function ipGetAction(DocumentManager $documentManager, $ip)

How i can to create one ip validator and use it everywhere ? Сan this be done only with forms?


Solution

  • If I were you I would create a Value Object called IpAddress:

    final class IpAddress
    {
        private $value;
    
        public function __construct($value)
        {
            if (inet_pton($value) === false) {
                throw new \LogicException('Invalid IPv4/6 address');
            }
    
            $this->value = (string)$value;
        }
    
        public function getAddress(): string
        {
            return $this->value;
        }
    
        public function __toString(): string
        {
            return $this->getAddress();
        }
    }
    

    and create custom param converter which would load this value object based on the request:

    /**
     * @Rest\Get("/api/ip/{ip}", name="app_ip_get")
     */
    public function ipGetAction(DocumentManager $documentManager, IpAddress $ip)
    

    In the param converter simply catch the exception when creating the address and if one is catched, rethrow the BadRequestHttpException which will get handled by the framework. Embrace proper OOP and stop this primitive obsession maddness :)