I played around with it some more. After debugging, I still couldn't figure it out. I tried to add a default value to the code
parameter and that seemed to do the trick. Why on Earth that works and how it makes sense, I have no idea. To me it shouldn't matter if I have a default value specified or not if I have provided a value in the URL for the parameter in the URL. Nevertheless, apparently it does matter - or at least in this case it did.
Here is the working code. I also updated the regular expression for the code parameter.
'profile' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/profile',
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'profile',
),
),
'may_terminate' => true,
'child_routes' => array(
'view' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/:code[/:username]',
'constraints' => array(
'code' => '\d+',
'username' => '[a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'viewProfile',
'code' => 0,
),
),
),
),
),