Score:0

Avoid TypeError when route with type hinted parameter in controller is called with wrong parameter type

cn flag

We defined a route under which a visitor of the website can find some information about how to get data related to the currently shown entity:

aw_api.open_data.info:
  path: '/open-data/info/{entity_type}/{entity_id}/{related_entity_type}'
  defaults:
    _controller: 'Drupal\aw_api\Controller\OpenDataInfoController::build'
    _title_callback: 'Drupal\aw_api\Controller\OpenDataInfoController::title'
    related_entity_type: ''
  requirements:
    _custom_access: 'Drupal\aw_api\Controller\OpenDataInfoController::access'

The method definition of the access check method looks as following:

public function access(AccountInterface $account, string $entity_type, int $entity_id, string $related_entity_type = '')

We now see log entries from time to time as the following:

TypeError: Drupal\aw_api\Controller\OpenDataInfoController::access(): Argument #3 ($entity_id) must be of type int, string given in Drupal\aw_api\Controller\OpenDataInfoController->access() (line 76 of modules\custom\aw_api\src\Controller\OpenDataInfoController.php).

It is the case when the path /open-data/info/core/scripts/transliteration_data.php.txt was called what seems to be done by scraper or any kind of software.

I know wonder how we can avoid this error? The page is only a WSOD what is not the problem as such a page should never be reached but we would like to avoid this error message in the logs.

By now I think the only solution seems to be to remove the type hinting from the method definition?!

cn flag
It could be related to a [bug like this](https://www.drupal.org/project/drupal/issues/3224376). To deal with this, I use int/string as the typehint and then immediately cast to int in my code.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.