Search code examples
phpzend-framework2constraintszend-route

Zend2 routes constraints like enum


I want to have a enum like constraint on a variable passed to of my project's route

e.g. variable routeVar only can be optin or optout

so lets say I want to have a url like http://subdomain.exampledomain.com/route/ which can get only one of the two following forms

  1. http://subdomain.exampledomain.com/route/optin
  2. http://subdomain.exampledomain.com/route/optout

the route configuration I've put together is as shown bellow and I have tried both [optin|optout] and [optin|optout]+ regexes but no luck

'route-name' => [
    'type' => 'Segment',
    'options' => [
        'route' => '/route/:routeVar',
        'constraints' => [
            'routeVar' => '[optin|optout]',
        ],
        'defaults' => [
            'controller' => someController::class,
            'action' => 'someAction',
        ],
    ],
    'may_terminate' => true,
],

please note: this is a child route and it works fine to address the expected controller and action. I only fail to apply the the limitation I described using the constraint :(


Solution

  • The regex you are looking for is

    (optin|optout)
    

    , the [] syntax is for character groups.

    Actually maybe even

    ^(optin|optout)$
    

    to make sure there are no extra characters in the value.