Primitive Types in Controllers and Closure Routes

0
31
laravel-route-type-hints-featured.png


Something I’ve not considered is type-hinting primitive types in Laravel controllers. PHP only has four scalar primitive types: bool, int, float, and string—regarding routes, string and int are the most likely types you’d want. However, I usually don’t type-hint scalar primitive types in my controllers.

I recently saw an issue crop up with type-hinting controller actions caused by a TypeError, so I’d like to demonstrate a few examples where you can safely use type-hinted controllers with the int type.

Consider the following route action and think about what type the $orderId will be when called:

1Route::get('/order/{order_id}', function ($orderId) {

2 return [

3 'type' => gettype($orderId),

4 'value' => $orderId,

5 ];

6});

The $orderId will be a string when this closure is called. If you write a quick test, this is what you’ll see passing:

1/**

2 * A basic test example.

3 *

4 * @return void

5 */

6public function test_example()

7{

8 $response = $this->get('/order/123');

9 

10 $response->assertJson([

11 'type' => 'string',

12 'value' => '123',

13 ]);

14}

Now, let’s say that you expect the order id always to be an integer, so you want to type-hint the parameter:

1Route::get('/order/{order_id}', function (int $orderId) {

2 return [

3 'type' => gettype($orderId),

4 'value' => $orderId,

5 ];

6});

If you go back to your test, it will now fail with the following output:

1--- Expected

2+++ Actual

3@@ @@

4 array (

5- 'type' => 'string',

6- 'value' => '123',

7+ 'type' => 'integer',

8+ 'value' => 123,

9 )

Although we technically pass a string of 123 to the route function, PHP handles this by default via type coercion. In other words, PHP tries to convert our value from a string to an integer when calling the route function.

Though technically this approach will work and guarantee a type of integer, we still have another issue you may have spotted: what if the user passes something that cannot convert from a string to an integer?

If we update our test to the following, we will get a TypeError:

1public function test_example()

2{

3 $this->withoutExceptionHandling();

4 

5 $response = $this->get('/order/ABC-123');

6 

7 $response->assertJson([

8 'type' => 'integer',

9 'value' => 123,

10 ]);

11}

Running the test will give you the following error:

1TypeError: IlluminateRoutingRouteFileRegistrar::{closure}():

2Argument #1 ($orderId) must be of type int, string given, called in .../vendor/laravel/framework/src/Illuminate/Routing/Route.php on line 238

If we want to type-hint an integer in a route, we should ensure our route has a regular expression constraint:

1Route::get('/order/{order_id}', function (int $orderId) {

2 return [

3 'type' => gettype($orderId),

4 'value' => $orderId,

5 ];

6})->where('order_id', '[0-9]+');

After adding the route parameter constraint, only numeric values will match the route, thus ensuring type coercion works as expected. The following test will be more accurate to ensure you cannot match the order route with a non-numeric router parameter:

1public function test_example()

2{

3 $response = $this->get('/order/ABC-123');

4 

5 $response->assertNotFound();

6}

Now you can assume that your closure route’s type safely coerces to an integer if you want to use type-hinting. Though the use-case is limited, I think learning about this nuance could help people trying to type-hint router parameters.

How is This Affected By Strict Types?

I’d like to point out that declare(strict_types=1); has no effect since the calling code is within the Laravel framework which does not use the strict_types declaration, thus type coercion will occur:

  1. Laravel’s Controller::callAction() for controllers
  2. Laravel’s Route::runCallable() for closure-based routes

In PHP’s type declarations documentation, Strict typing has the following note about how strict types work:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function defined in a file with strict typing, the caller’s preference (coercive typing) will be respected, and the value will be coerced.

Alternative Approaches

If you have scalar routing parameters in controllers and closures, you can omit scalar types and do type-casting within your controller method:

1Route::get(

2 '/order/{order_id}',

3 function ($orderId, SomeService $someService) {

4 // Cast for a method that strictly type-hints an integer

5 $result = $someService->someMethod((int) $orderId);

6 // ...

7 }

8);

Most of the time, you’ll use route model binding for route parameters matching numeric IDs; however, consider this approach when you have a numeric route parameter that you want to type-hint with a primitive scalar type int.



Source link

Leave a reply

Please enter your comment!
Please enter your name here