1

I have a PHP-Lumen project and when I execute sonar scanner in my project I get this error.

'String literals should not be duplicated'

Is it something that I should fix or just ignore?

$errorArray['code'] = config('errormessages.invalidJson.error_code');

$errorArray['message'] = config('errormessages.invalidJson.error_message')

In the above code snippet, SonarQube says that the 'code' and 'messages' are duplicated across my the code and expects me to define a constant instead of using these index directly. But these are just indexes of $errorArray, why should I have a constant defined?

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • In this case it's most likely a false positive and can be ignored. You will find you get a lot of false flags in SonarCube when working with a php framework. – Jeemusu Jun 05 '19 at 08:02
  • So this is the only place in your application where you have used $errorArray['code']? – Jeroen Heier Jun 05 '19 at 17:53
  • No. I have used this in so many places wherever errors are handled. – Ashwin Vikraman Jun 07 '19 at 07:44
  • The rationale is for obtaining code that is easier to change. For instance, if you decide to change the `'message'` index to `'warning'`, you will have to change it throughout the code (every place you put `'message'`). If you define a constant `MESSAGE` that is equal to `'message'` and you use *that* throughout your code, you only have to change where it's defined if it changes. This is a basic software coding principle, known as [avoiding magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). – Fuhrmanator Feb 21 '20 at 14:03
  • Nope. When using literals as index keys, they behave like identifiers. It makes no sense to declare MESSAGE = 'message' and later change that because it will make really confusing read somewhere x[MESSAGE] and meaning x['warning']. – Carlos Mora Jul 06 '21 at 11:46

0 Answers0