John Davidson

How to define a php constant with parameter to prevent a sonar alert

0 comments
Message:


I am using laravel 8 and sonarcloud.


I have some controllers with some "code smells" about duplication code. This code , for example, is duplicated 3 times in the same controller :


return redirect('/organizations/' . $organization->id . '/classified-ads')

Sonar cloud suggests to define a constant. So I would like to do something like that :


CONST REDIRECT = 'a string with a parameter'

and then :


return redirect(self::REDIRECT)

But how to write this constant, as it contains the parameter $organization->id ?



My Answer:
functions that use constants defined in a separate file. To prevent a Sonar alert for using a constant with a parameter, you can define the constant with a function that returns the value based on the parameter. Here's an example:

1. Create a separate file to define your constants, for example, `Constants.php`:

php

function getConstantValue($param) {
switch ($param) {
case 'CONSTANT_1':
return 'value_1';
case 'CONSTANT_2':
return 'value_2';
// Add more cases as needed
default:
return null;
}
}


2. In your controller or wherever you need to use the constant, call the `getConstantValue` function with the parameter:

php
$value = getConstantValue('CONSTANT_1');


This way, you can define your constants with parameters without triggering a Sonar alert. Sonar will not flag the use of a function to retrieve the constant value.

Rate this post

3 of 5 based on 6091 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us