leafsphp / router

🏚 router module for leaf PHP
https://leafphp.dev/modules/router/
6 stars 6 forks source link

Optional routes doesn't work #11

Closed milosPavic closed 3 weeks ago

milosPavic commented 1 year ago

Im running leaf mvc app, from public folder with command "leaf serve", im using PHP Version 7.4.24. on Windows 10

For example: Route with 2 optional parameters app()->all('vest/{id}(/\w+)?(/\w+)?', "Api@vest");

IF i put all 3 parameters then works if i add 2 or 1 parameter in URL i get error: trim() expects parameter 1 to be string, bool given

Core.php if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) { return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/'); }

if i change code with this all is working fine if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) { if(isset($match[$index+1][0])){ return trim($matches[$index + 1][0][0],'/'); } }

milosPavic commented 1 year ago

Found error and I fix it in leaf Core.php private static function findRoute ...

        // Extract the matched URL parameters (and only the parameters)
            $params=[];
            foreach ($matches as $match){
                if($match[0][1]>=0){
                    $params[]=trim($match[0][0],'/');
                }
            }
            /*
            $params = array_map(function ($match, $index) use ($matches) {
                // We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
                if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
                    $ret=substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]);
                    if(!is_bool($ret)){
                        return trim($ret, '/');
                    }
                }
                // We have no following parameters: return the whole lot
                return isset($match[0][0]) ? trim($match[0][0], '/') : null;
            }, $matches, array_keys($matches));
            */
milosPavic commented 1 year ago

Commented code makes problem, so when i use foreach loop and extract only parameters that is set in url all starts working fine.

mychidarko commented 3 weeks ago

This has been fixed