Browse Source

Improve casting of integer routing parameters

Allow negative numbers to be cast to integers for typed routing
parameters.
Mark Story 3 years ago
parent
commit
50efa360d9

+ 1 - 1
src/Controller/ControllerFactory.php

@@ -268,7 +268,7 @@ class ControllerFactory implements ControllerFactoryInterface, RequestHandlerInt
             case 'float':
                 return is_numeric($argument) ? (float)$argument : null;
             case 'int':
-                return ctype_digit($argument) ? (int)$argument : null;
+                return ctype_digit($argument) || filter_var($argument, FILTER_VALIDATE_INT) ? (int)$argument : null;
             case 'bool':
                 return $argument === '0' ? false : ($argument === '1' ? true : null);
             case 'array':

+ 15 - 5
tests/TestCase/Controller/ControllerFactoryTest.php

@@ -740,8 +740,6 @@ class ControllerFactoryTest extends TestCase
 
         $result = $this->factory->invoke($controller);
         $data = json_decode((string)$result->getBody(), true);
-
-        $this->assertNotNull($data);
         $this->assertSame(['one' => 1.0, 'two' => 2, 'three' => false, 'four' => ['8', '9']], $data);
 
         $request = new ServerRequest([
@@ -757,9 +755,22 @@ class ControllerFactoryTest extends TestCase
 
         $result = $this->factory->invoke($controller);
         $data = json_decode((string)$result->getBody(), true);
-
-        $this->assertNotNull($data);
         $this->assertSame(['one' => 1.0, 'two' => 2, 'three' => false, 'four' => []], $data);
+
+        $request = new ServerRequest([
+            'url' => 'test_plugin_three/dependencies/requiredTyped',
+            'params' => [
+                'plugin' => null,
+                'controller' => 'Dependencies',
+                'action' => 'requiredTyped',
+                'pass' => ['1.0', '-1', '0', ''],
+            ],
+        ]);
+        $controller = $this->factory->create($request);
+
+        $result = $this->factory->invoke($controller);
+        $data = json_decode((string)$result->getBody(), true);
+        $this->assertSame(['one' => 1.0, 'two' => -1, 'three' => false, 'four' => []], $data);
     }
 
     /**
@@ -781,7 +792,6 @@ class ControllerFactoryTest extends TestCase
         $result = $this->factory->invoke($controller);
         $data = json_decode((string)$result->getBody(), true);
 
-        $this->assertNotNull($data);
         $this->assertSame(['one' => 1.0, 'two' => 2, 'three' => true], $data);
     }