install_check_server_apache accesses the super-global variable $_SERVER. Open
public function install_check_server_apache(): bool
{
return (strpos($_SERVER['SERVER_SOFTWARE'], "Apache/") === 0);
}
- Read upRead up
- Exclude checks
Superglobals
Since: 0.2
Accessing a super-global variable directly is considered a bad practice. These variables should be encapsulated in objects that are provided by a framework, for instance.
Example
class Foo {
public function bar() {
$name = $_POST['foo'];
}
}
Source
Function install_insert_db
has a Cognitive Complexity of 38 (exceeds 5 allowed). Consider refactoring. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
The class InstallationHelper has 13 public methods. Consider refactoring InstallationHelper to keep number of public methods under 10. Open
final class InstallationHelper implements InstallationHelperInterface
{
/**
* splits up a standard SQL dump file into distinct sql queries
* @param string $sql
- Read upRead up
- Exclude checks
TooManyPublicMethods
Since: 0.1
A class with too many public methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way to have more fine grained objects.
By default it ignores methods starting with 'get' or 'set'.
Example
Source https://phpmd.org/rules/codesize.html#toomanypublicmethods
The class InstallationHelper has an overall complexity of 111 which is very high. The configured complexity threshold is 50. Open
final class InstallationHelper implements InstallationHelperInterface
{
/**
* splits up a standard SQL dump file into distinct sql queries
* @param string $sql
- Exclude checks
Function install_check_rewrite_rules
has a Cognitive Complexity of 22 (exceeds 5 allowed). Consider refactoring. Open
public function install_check_rewrite_rules($file, $web_path, $fix = false)
{
if (!is_readable($file)) {
$file .= '.dist';
}
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Function install_create_config
has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring. Open
public function install_create_config($download = false): bool
{
$config_file = __DIR__ . '/../../../config/ampache.cfg.php';
/* Attempt to make DB connection */
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Function split_sql
has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring. Open
private function split_sql($sql): array
{
$sql = trim((string) $sql);
$sql = preg_replace("/\n--[^\n]*\n/", "\n", $sql);
$buffer = array();
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Function generate_config
has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring. Open
public function generate_config(array $current): string
{
// Start building the new config file
$distfile = __DIR__ . '/../../../config/ampache.cfg.php.dist';
$handle = fopen($distfile, 'r');
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Consider simplifying this complex logical expression. Open
if ($in_string && ($sql[$count] == $in_string) && $buffer[1] != "\\") {
$in_string = false;
} elseif (!$in_string && ($sql[$count] == '"' || $sql[$count] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
$in_string = $sql[$count];
}
Method install_insert_db
has 7 arguments (exceeds 4 allowed). Consider refactoring. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
Function install_config_backends
has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring. Open
public function install_config_backends(array $backends)
{
$dbconfig = array(
'subsonic_backend' => '0',
'daap_backend' => '0',
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Avoid too many return
statements within this method. Open
return false;
Avoid too many return
statements within this method. Open
return true;
Avoid too many return
statements within this method. Open
return false;
Avoid too many return
statements within this method. Open
return false;
Avoid too many return
statements within this method. Open
return true;
Avoid too many return
statements within this method. Open
return false;
Avoid too many return
statements within this method. Open
return true;
Avoid too many return
statements within this method. Open
return false;
Function install_rewrite_rules
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
public function install_rewrite_rules($file, $web_path, $download): bool
{
$final = $this->install_check_rewrite_rules($file, $web_path, true);
if (!$download) {
if (!file_put_contents($file, $final)) {
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Function install_create_account
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
public function install_create_account($username, $password, $password2): bool
{
if (!strlen((string) $username) || !strlen((string) $password)) {
AmpError::add('general', T_('No username or password was specified'));
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
The method install_insert_db() has 124 lines of code. Current threshold is set to 100. Avoid really long methods. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Exclude checks
The method install_insert_db() has an NPath complexity of 96768. The configured NPath complexity threshold is 200. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
NPathComplexity
Since: 0.1
The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity.
Example
class Foo {
function bar() {
// lots of complicated code
}
}
Source https://phpmd.org/rules/codesize.html#npathcomplexity
The method install_check_rewrite_rules() has a Cyclomatic Complexity of 11. The configured cyclomatic complexity threshold is 10. Open
public function install_check_rewrite_rules($file, $web_path, $fix = false)
{
if (!is_readable($file)) {
$file .= '.dist';
}
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
The method generate_config() has a Cyclomatic Complexity of 11. The configured cyclomatic complexity threshold is 10. Open
public function generate_config(array $current): string
{
// Start building the new config file
$distfile = __DIR__ . '/../../../config/ampache.cfg.php.dist';
$handle = fopen($distfile, 'r');
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
The method split_sql() has a Cyclomatic Complexity of 14. The configured cyclomatic complexity threshold is 10. Open
private function split_sql($sql): array
{
$sql = trim((string) $sql);
$sql = preg_replace("/\n--[^\n]*\n/", "\n", $sql);
$buffer = array();
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
The method install_insert_db() has a Cyclomatic Complexity of 25. The configured cyclomatic complexity threshold is 10. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
Reduce the number of returns of this function 7, down to the maximum allowed 3. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
- Read upRead up
- Exclude checks
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
Noncompliant Code Example
With the default threshold of 3:
function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; }
Refactor this function to reduce its Cognitive Complexity from 40 to the 15 allowed. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
- Read upRead up
- Exclude checks
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
See
Reduce the number of returns of this function 6, down to the maximum allowed 3. Open
public function install_create_config($download = false): bool
- Read upRead up
- Exclude checks
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
Noncompliant Code Example
With the default threshold of 3:
function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; }
Reduce the number of returns of this function 6, down to the maximum allowed 3. Open
public function install_create_account($username, $password, $password2): bool
- Read upRead up
- Exclude checks
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
Noncompliant Code Example
With the default threshold of 3:
function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; }
Refactor this function to reduce its Cognitive Complexity from 22 to the 15 allowed. Open
public function install_check_rewrite_rules($file, $web_path, $fix = false)
- Read upRead up
- Exclude checks
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
See
Reduce the number of returns of this function 5, down to the maximum allowed 3. Open
public function install_check_status($configfile): bool
- Read upRead up
- Exclude checks
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
Noncompliant Code Example
With the default threshold of 3:
function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; }
The method install_rewrite_rules uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$browser = new Horde_Browser();
$headers = $browser->getDownloadHeaders(basename($file), 'text/plain', false, strlen((string) $final));
foreach ($headers as $headerName => $value) {
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method install_create_config uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
// Given that $final is > 0, we can ignore lazy comparison problems
if (!file_put_contents($config_file, $final)) {
AmpError::add('general', T_('Failed writing config file'));
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method install_create_config uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$browser = new Horde_Browser();
$headers = $browser->getDownloadHeaders('ampache.cfg.php', 'text/plain', false, strlen((string) $final));
foreach ($headers as $headerName => $value) {
header(sprintf('%s: %s', $headerName, $value));
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method install_check_rewrite_rules uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$valid = false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method install_insert_db uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
AmpError::add('general', T_('Database already exists and "overwrite" was not checked'));
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method install_check_status uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
AmpError::add('general', T_('Existing database was detected, unable to continue the installation'));
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
Define a constant instead of duplicating this literal "allowed" 4 times. Open
'transcode_ogg' => 'allowed',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "required" 4 times. Open
'transcode_m4a' => 'required',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Merge this if statement with the enclosing one. Open
if (!Dba::write('CREATE DATABASE `' . $database . '`')) {
- Read upRead up
- Exclude checks
Merging collapsible if
statements increases the code's readability.
Noncompliant Code Example
if (condition1) { if (condition2) { ... } }
Compliant Solution
if (condition1 && condition2) { ... }
Define a constant instead of duplicating this literal "wanted" 4 times. Open
$tables = array("access_list", "album", "artist", "bookmark", "broadcast", "cache_object_count", "cache_object_count_run", "catalog", "catalog_local", "catalog_remote", "channel", "clip", "daap_session", "democratic", "image", "ip_history", "label", "label_asso", "license", "live_stream", "localplay_httpq", "localplay_mpd", "metadata", "metadata_field", "movie", "now_playing", "object_count", "personal_video", "player_control", "playlist", "playlist_data", "podcast", "podcast_episode", "preference", "rating", "recommendation", "recommendation_item", "search", "session", "session_remember", "session_stream", "share", "song", "song_data", "song_preview", "stream_playlist", "tag", "tag_map", "tag_merge", "tmp_browse", "tmp_playlist", "tmp_playlist_data", "tvshow", "tvshow_episode", "tvshow_season", "update_info", "user", "user_activity", "user_catalog", "user_flag", "user_follower", "user_preference", "user_pvmsg", "user_shout", "user_vote", "video", "wanted");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Refactor the code to avoid updating the loop counter "$count" within the loop body. Open
$count = 0;
- Read upRead up
- Exclude checks
A for
loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and
ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.
Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future.
This rule tracks three types of non-invariant stop conditions:
- When the loop counters are updated in the body of the
for
loop - When the stop condition depend upon a method call
- When the stop condition depends on an object property, since such properties could change during the execution of the loop.
Noncompliant Code Example
for ($i = 0; $i < 10; $i++) { echo $i; if(condition) { $i = 20; } }
Compliant Solution
for ($i = 0; $i < 10; $i++) { echo $i; }
See
- MISRA C:2004, 13.6 - Numeric variables being used within a for loop for iteration counting shall not be modified in the body of the loop.
- MISRA C++:2008, 6-5-3 - The loop-counter shall not be modified within condition or statement.
Define a constant instead of duplicating this literal "ffmpeg" 3 times. Open
if ($this->command_exists('ffmpeg')) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "en_US" 4 times. Open
if (AmpConfig::get('lang', 'en_US') != 'en_US') {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "avconv" 3 times. Open
if ($this->command_exists('avconv')) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "general" 19 times. Open
AmpError::add('general', T_('Unable to connect to the database, check your Ampache config'));
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Add a "case default" clause to this "switch" statement. Open
switch ($case) {
- Read upRead up
- Exclude checks
The requirement for a final case default
clause is defensive programming. The clause should either take appropriate action, or contain
a suitable comment as to why no action is taken. Even when the switch
covers all current values of an enum
, a default case
should still be used because there is no guarantee that the enum
won't be extended.
Noncompliant Code Example
switch ($param) { //missing default clause case 0: do_something(); break; case 1: do_something_else(); break; } switch ($param) { default: // default clause should be the last one error(); break; case 0: do_something(); break; case 1: do_something_else(); break; }
Compliant Solution
switch ($param) { case 0: do_something(); break; case 1: do_something_else(); break; default: error(); break; }
See
- MISRA C:2004, 15.0 - The MISRA C switch syntax shall be used.
- MISRA C:2004, 15.3 - The final clause of a switch statement shall be the default clause
- MISRA C++:2008, 6-4-3 - A switch statement shall be a well-formed switch statement.
- MISRA C++:2008, 6-4-6 - The final clause of a switch statement shall be the default-clause
- MISRA C:2012, 16.1 - All switch statements shall be well-formed
- MISRA C:2012, 16.4 - Every switch statement shall have a default label
- MISRA C:2012, 16.5 - A default label shall appear as either the first or the last switch label of a switch statement
- MITRE, CWE-478 - Missing Default Case in Switch Statement
- CERT, MSC01-C. - Strive for logical completeness
- CERT, MSC01-CPP. - Strive for logical completeness
Define a constant instead of duplicating this literal "live_stream" 4 times. Open
$tables = array("access_list", "album", "artist", "bookmark", "broadcast", "cache_object_count", "cache_object_count_run", "catalog", "catalog_local", "catalog_remote", "channel", "clip", "daap_session", "democratic", "image", "ip_history", "label", "label_asso", "license", "live_stream", "localplay_httpq", "localplay_mpd", "metadata", "metadata_field", "movie", "now_playing", "object_count", "personal_video", "player_control", "playlist", "playlist_data", "podcast", "podcast_episode", "preference", "rating", "recommendation", "recommendation_item", "search", "session", "session_remember", "session_stream", "share", "song", "song_data", "song_preview", "stream_playlist", "tag", "tag_map", "tag_merge", "tmp_browse", "tmp_playlist", "tmp_playlist_data", "tvshow", "tvshow_episode", "tvshow_season", "update_info", "user", "user_activity", "user_catalog", "user_flag", "user_follower", "user_preference", "user_pvmsg", "user_shout", "user_vote", "video", "wanted");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Merge this if statement with the enclosing one. Open
if (!Dba::write($pieces[$count])) {
- Read upRead up
- Exclude checks
Merging collapsible if
statements increases the code's readability.
Noncompliant Code Example
if (condition1) { if (condition2) { ... } }
Compliant Solution
if (condition1 && condition2) { ... }
Define a constant instead of duplicating this literal "false" 14 times. Open
'licensing' => 'false',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "share" 5 times. Open
$tables = array("access_list", "album", "artist", "bookmark", "broadcast", "cache_object_count", "cache_object_count_run", "catalog", "catalog_local", "catalog_remote", "channel", "clip", "daap_session", "democratic", "image", "ip_history", "label", "label_asso", "license", "live_stream", "localplay_httpq", "localplay_mpd", "metadata", "metadata_field", "movie", "now_playing", "object_count", "personal_video", "player_control", "playlist", "playlist_data", "podcast", "podcast_episode", "preference", "rating", "recommendation", "recommendation_item", "search", "session", "session_remember", "session_stream", "share", "song", "song_data", "song_preview", "stream_playlist", "tag", "tag_map", "tag_merge", "tmp_browse", "tmp_playlist", "tmp_playlist_data", "tvshow", "tvshow_episode", "tvshow_season", "update_info", "user", "user_activity", "user_catalog", "user_flag", "user_follower", "user_preference", "user_pvmsg", "user_shout", "user_vote", "video", "wanted");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Add a "case default" clause to this "switch" statement. Open
switch ($backend) {
- Read upRead up
- Exclude checks
The requirement for a final case default
clause is defensive programming. The clause should either take appropriate action, or contain
a suitable comment as to why no action is taken. Even when the switch
covers all current values of an enum
, a default case
should still be used because there is no guarantee that the enum
won't be extended.
Noncompliant Code Example
switch ($param) { //missing default clause case 0: do_something(); break; case 1: do_something_else(); break; } switch ($param) { default: // default clause should be the last one error(); break; case 0: do_something(); break; case 1: do_something_else(); break; }
Compliant Solution
switch ($param) { case 0: do_something(); break; case 1: do_something_else(); break; default: error(); break; }
See
- MISRA C:2004, 15.0 - The MISRA C switch syntax shall be used.
- MISRA C:2004, 15.3 - The final clause of a switch statement shall be the default clause
- MISRA C++:2008, 6-4-3 - A switch statement shall be a well-formed switch statement.
- MISRA C++:2008, 6-4-6 - The final clause of a switch statement shall be the default-clause
- MISRA C:2012, 16.1 - All switch statements shall be well-formed
- MISRA C:2012, 16.4 - Every switch statement shall have a default label
- MISRA C:2012, 16.5 - A default label shall appear as either the first or the last switch label of a switch statement
- MITRE, CWE-478 - Missing Default Case in Switch Statement
- CERT, MSC01-C. - Strive for logical completeness
- CERT, MSC01-CPP. - Strive for logical completeness
Define a constant instead of duplicating this literal "download" 3 times. Open
'download' => '1',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Take the required action to fix the issue indicated by this "FIXME" comment. Open
// FIXME: 31? I hate magic.
- Read upRead up
- Exclude checks
FIXME
tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.
Sometimes the developer will not have the time or will simply forget to get back to that tag.
This rule is meant to track those tags and to ensure that they do not go unnoticed.
Noncompliant Code Example
function divide($numerator, $denominator) { return $numerator / $denominator; // FIXME denominator value might be 0 }
See
- MITRE, CWE-546 - Suspicious Comment
FIXME found Open
// FIXME: 31? I hate magic.
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
AmpError::add('general', sprintf(T_('Unable to create the database: %s'), Dba::error()));
- Exclude checks
Call to method disconnect
from undeclared class \Ampache\Module\System\Dba
Open
Dba::disconnect();
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
Dba::error()
- Exclude checks
Call to method create
from undeclared class \Ampache\Repository\Model\User
Open
$user_id = User::create($username, 'Administrator', '', '', $password, 100);
- Exclude checks
Call to method read
from undeclared class \Ampache\Module\System\Dba
Open
$db_exists = Dba::read('SHOW TABLES');
- Exclude checks
Call to method escape
from undeclared class \Ampache\Module\System\Dba
Open
$sql_user = "CREATE USER '" . Dba::escape($db_user) . "'";
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
$errors[] = array(Dba::error(), $pieces[$count]);
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
Dba::write($sql, array(AmpConfig::get('lang', 'en_US')));
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
AmpError::add('general', sprintf(T_('Administrative user creation failed: %s'), Dba::error()));
- Exclude checks
Call to method num_rows
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::num_rows($db_results)) {
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
Dba::write('DROP DATABASE `' . $database . '`');
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::write('CREATE DATABASE `' . $database . '`')) {
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
Dba::write($sql);
- Exclude checks
Call to method check_database
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::check_database()) {
- Exclude checks
Call to method fix_preferences
from undeclared class \Ampache\Repository\Model\User
Open
User::fix_preferences('-1');
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::write($sql_grant)) {
- Exclude checks
Call to method dbh
from undeclared class \Ampache\Module\System\Dba
Open
Dba::dbh();
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
AmpError::add('general', sprintf(T_('Database select failed: %s'), Dba::error()));
- Exclude checks
Call to method escape
from undeclared class \Ampache\Module\System\Dba
Open
$sql_grant = "GRANT ALL PRIVILEGES ON `" . Dba::escape($database) . "`.* TO '" . Dba::escape($db_user) . "'";
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::write($pieces[$count])) {
- Exclude checks
Argument 3 (expires)
is array{expires:int,path:'/',samesite:'Strict'}
but \setcookie()
takes int
Open
setcookie('browse_album_grid_view', 'false', $cookie_options);
- Exclude checks
Argument 3 (expires)
is array{expires:int,path:'/',samesite:'Strict'}
but \setcookie()
takes int
Open
setcookie('browse_artist_grid_view', 'false', $cookie_options);
- Exclude checks
Invalid offset 1
of array type array{}
Open
if ($in_string && ($sql[$count] == $in_string) && $buffer[1] != "\\") {
- Exclude checks
Argument 4 (cLength)
is int
but \Ampache\Module\Util\Horde_Browser::getDownloadHeaders()
takes string
defined at /code/src/Module/Util/Horde_Browser.php:739
Open
$headers = $browser->getDownloadHeaders(basename($file), 'text/plain', false, strlen((string) $final));
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
Dba::write($sql, array(AmpConfig::get('lang', 'en_US')));
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
AmpError::add('general', sprintf(T_('Unable to connect to the database: %s'), Dba::error()));
- Exclude checks
Call to method read
from undeclared class \Ampache\Module\System\Dba
Open
$db_results = Dba::read($sql);
- Exclude checks
Call to method check_database
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::check_database()) {
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::write($sql_user)) {
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
Dba::error()
- Exclude checks
Call to method check_database
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::check_database()) {
- Exclude checks
Argument 3 (expires)
is array{expires:int,path:'/',samesite:'Strict'}
but \setcookie()
takes int
Open
setcookie('sidebar_state', 'collapsed', $cookie_options);
- Exclude checks
Call to method escape
from undeclared class \Ampache\Module\System\Dba
Open
$sql_user .= " IDENTIFIED BY '" . Dba::escape($db_pass) . "'";
- Exclude checks
Argument 4 (cLength)
is int
but \Ampache\Module\Util\Horde_Browser::getDownloadHeaders()
takes string
defined at /code/src/Module/Util/Horde_Browser.php:739
Open
$headers = $browser->getDownloadHeaders('ampache.cfg.php', 'text/plain', false, strlen((string) $final));
- Exclude checks
Call to method check_database_inserted
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::check_database_inserted()) {
- Exclude checks
Call to method check_database
from undeclared class \Ampache\Module\System\Dba
Open
if (!Dba::check_database()) {
- Exclude checks
Call to method write
from undeclared class \Ampache\Module\System\Dba
Open
Dba::write($sql);
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\System\Dba
Open
AmpError::add('general', sprintf(T_('Connection to the database failed: %s'), Dba::error()));
- Exclude checks
The parameter $web_path is not named in camelCase. Open
public function install_rewrite_rules($file, $web_path, $download): bool
{
$final = $this->install_check_rewrite_rules($file, $web_path, true);
if (!$download) {
if (!file_put_contents($file, $final)) {
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $create_db is not named in camelCase. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $create_tables is not named in camelCase. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $db_pass is not named in camelCase. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $current_file_path is not named in camelCase. Open
public function write_config(string $current_file_path): bool
{
if (!is_writeable($current_file_path)) {
return false;
}
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $db_user is not named in camelCase. Open
public function install_insert_db($db_user = null, $db_pass = null, $create_db = true, $overwrite = false, $create_tables = true, $charset = 'utf8mb4', $collation = 'utf8mb4_unicode_ci'): bool
{
$database = (string) AmpConfig::get('database_name');
// Make sure that the database name is valid
preg_match('/([^\d\w\_\-])/', $database, $matches);
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
The parameter $web_path is not named in camelCase. Open
public function install_check_rewrite_rules($file, $web_path, $fix = false)
{
if (!is_readable($file)) {
$file .= '.dist';
}
- Read upRead up
- Exclude checks
CamelCaseParameterName
Since: 0.2
It is considered best practice to use the camelCase notation to name parameters.
Example
class ClassName {
public function doSomething($user_name) {
}
}
Source
Expected 0 spaces after opening bracket; newline found Open
if (
- Exclude checks