Declaring the return parameter with NULLable type as an option.
null_return.php
/**
* Retrieves the name of a role based on its ID.
*
* @param string $role_id
* The ID of the role to retrieve.
*
* @return string|null
* The name of the role if it exists, or NULL if the role is not found.
*/
public function getRoleName(string $role_id): ?string {
// Example roles array.
$roles = [
'admin' => 'Administrator',
'editor' => 'Content Editor',
'viewer' => 'Viewer',
];
// Use the null coalescing operator to return the role name or null.
return $roles[$role_id] ?? NULL;
}
Issue:
Handling a situation where a function might return an error since it returns NULL.
Solution:
Utilizes the "?" in the definition of the return type.
// web/modules/contrib/eca/src/Entity/Eca.php (simplified excerpt)
protected function isValidationDisabled(): bool {
return $this->request()->query->get('eca_validation', '') === 'off';
}
public function getPluginCollections(): array {
if ($this->isValidationDisabled()) {
return [];
}
// Otherwise every referenced event/condition/action plugin is
// instantiated here, throwing PluginNotFoundException if one
// of them no longer exists.
...
}
hint.txt
# Delete URL — load this directly, don't click through from a listing page
/admin/config/workflow/eca/{eca_id}/delete?eca_validation=off