update_browse_from_session accesses the super-global variable $_SESSION. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 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
update_browse_from_session accesses the super-global variable $_SESSION. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 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
set_type accesses the super-global variable $_COOKIE. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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
update_browse_from_session accesses the super-global variable $_SESSION. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 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
update_browse_from_session accesses the super-global variable $_SESSION. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 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
show_objects accesses the super-global variable $_SESSION. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- 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
add_supplemental_object accesses the super-global variable $_SESSION. Open
public function add_supplemental_object(string $class, int $uid): bool
{
$_SESSION['browse']['supplemental'][$this->id][$class] = $uid;
return true;
- 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
set_type accesses the super-global variable $_COOKIE. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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
get_supplemental_objects accesses the super-global variable $_SESSION. Open
public function get_supplemental_objects(): array
{
$objects = $_SESSION['browse']['supplemental'][$this->id] ?? '';
if (!is_array($objects)) {
- 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
set_type accesses the super-global variable $_COOKIE. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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 show_objects
has a Cognitive Complexity of 81 (exceeds 5 allowed). Consider refactoring. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- 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
Browse
has 40 functions (exceeds 20 allowed). Consider refactoring. Open
class Browse extends Query
{
private const BROWSE_TYPES = array(
'album',
'album_disk',
File Browse.php
has 608 lines of code (exceeds 500 allowed). Consider refactoring. Open
<?php
declare(strict_types=0);
/**
The class Browse has an overall complexity of 153 which is very high. The configured complexity threshold is 50. Open
class Browse extends Query
{
private const BROWSE_TYPES = array(
'album',
'album_disk',
- Exclude checks
Method show_objects
has 254 lines of code (exceeds 200 allowed). Consider refactoring. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
Function update_browse_from_session
has a Cognitive Complexity of 16 (exceeds 5 allowed). Consider refactoring. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 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
Function set_type
has a Cognitive Complexity of 15 (exceeds 5 allowed). Consider refactoring. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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 set_api_filter
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
public function set_api_filter($filter, $value): void
{
if (!strlen((string)$value)) {
return;
}
- 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 show_objects() has an NPath complexity of 18163200. The configured NPath complexity threshold is 200. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- 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 show_objects() has 280 lines of code. Current threshold is set to 100. Avoid really long methods. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- Exclude checks
The method set_type() has a Cyclomatic Complexity of 10. The configured cyclomatic complexity threshold is 10. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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 show_objects() has a Cyclomatic Complexity of 70. The configured cyclomatic complexity threshold is 10. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- 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 update_browse_from_session() has a Cyclomatic Complexity of 10. The configured cyclomatic complexity threshold is 10. Open
public function update_browse_from_session(): void
{
if ($this->is_simple() && $this->get_start() == 0) {
$name = 'browse_current_' . $this->get_type();
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 0) {
- 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
Refactor this function to reduce its Cognitive Complexity from 63 to the 15 allowed. Open
public function show_objects($object_ids = array(), $argument = false): void
- 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 switch cases from 31 to at most 30. Open
switch ($type) {
- Read upRead up
- Exclude checks
When switch
statements have large sets of case
clauses, it is usually an attempt to map two sets of data. A real map
structure would be more readable and maintainable, and should be used instead.
Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed. Open
public function set_type($type, $custom_base = ''): void
- 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
Class "Browse" has 40 methods, which is greater than 20 authorized. Split it into smaller classes. Open
class Browse extends Query
- Read upRead up
- Exclude checks
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics.
This function "show_objects" has 279 lines, which is greater than the 150 lines authorized. Split it into smaller functions. Open
public function show_objects($object_ids = array(), $argument = false): void
- Read upRead up
- Exclude checks
A function that grows too large tends to aggregate too many responsibilities.
Such functions inevitably become harder to understand and therefore harder to maintain.
Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks.
Those smaller functions will not only be easier to understand, but also probably easier to test.
Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed. Open
public function update_browse_from_session(): void
- 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
The class Browse has a coupling between objects value of 16. Consider to reduce the number of dependencies under 13. Open
class Browse extends Query
{
private const BROWSE_TYPES = array(
'album',
'album_disk',
- Read upRead up
- Exclude checks
CouplingBetweenObjects
Since: 1.1.0
A class with too many dependencies has negative impacts on several quality aspects of a class. This includes quality criteria like stability, maintainability and understandability
Example
class Foo {
/**
* @var \foo\bar\X
*/
private $x = null;
/**
* @var \foo\bar\Y
*/
private $y = null;
/**
* @var \foo\bar\Z
*/
private $z = null;
public function setFoo(\Foo $foo) {}
public function setBar(\Bar $bar) {}
public function setBaz(\Baz $baz) {}
/**
* @return \SplObjectStorage
* @throws \OutOfRangeException
* @throws \InvalidArgumentException
* @throws \ErrorException
*/
public function process(\Iterator $it) {}
// ...
}
Source https://phpmd.org/rules/design.html#couplingbetweenobjects
The method show_objects uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$argument_param = ($argument)
? '&argument=' . scrub_in((string)$argument)
: '';
}
- 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 set_api_filter uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$this->set_filter('add_gt', strtotime((string)$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 set_use_alpha uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$this->set_filter('regex_not_match', '');
}
- 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 update_browse_from_session uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$total_pages = 0;
}
- 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
Avoid assigning values to variables in if clauses and the like (line '302', column '19'). Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- Read upRead up
- Exclude checks
IfStatementAssignment
Since: 2.7.0
Assignments in if clauses and the like are considered a code smell. Assignments in PHP return the right operand as their result. In many cases, this is an expected behavior, but can lead to many difficult to spot bugs, especially when the right operand could result in zero, null or an empty string and the like.
Example
class Foo
{
public function bar($flag)
{
if ($foo = 'bar') { // possible typo
// ...
}
if ($baz = 0) { // always false
// ...
}
}
}
Source http://phpmd.org/rules/cleancode.html#ifstatementassignment
The method show_objects uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$box_title = $this->get_title(T_('Artist') . $match);
}
- 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 show_objects uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$this->save_objects($object_ids);
}
- 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 set_type uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$default_alpha = (!AmpConfig::get('libitem_browse_alpha')) ? array() : explode(
",",
AmpConfig::get('libitem_browse_alpha')
);
- 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
Avoid assigning values to variables in if clauses and the like (line '300', column '13'). Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- Read upRead up
- Exclude checks
IfStatementAssignment
Since: 2.7.0
Assignments in if clauses and the like are considered a code smell. Assignments in PHP return the right operand as their result. In many cases, this is an expected behavior, but can lead to many difficult to spot bugs, especially when the right operand could result in zero, null or an empty string and the like.
Example
class Foo
{
public function bar($flag)
{
if ($foo = 'bar') { // possible typo
// ...
}
if ($baz = 0) { // always false
// ...
}
}
}
Source http://phpmd.org/rules/cleancode.html#ifstatementassignment
Avoid assigning values to variables in if clauses and the like (line '304', column '19'). Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- Read upRead up
- Exclude checks
IfStatementAssignment
Since: 2.7.0
Assignments in if clauses and the like are considered a code smell. Assignments in PHP return the right operand as their result. In many cases, this is an expected behavior, but can lead to many difficult to spot bugs, especially when the right operand could result in zero, null or an empty string and the like.
Example
class Foo
{
public function bar($flag)
{
if ($foo = 'bar') { // possible typo
// ...
}
if ($baz = 0) { // always false
// ...
}
}
}
Source http://phpmd.org/rules/cleancode.html#ifstatementassignment
The method set_type uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
debug_event(self::class, 'set_type invalid type: ' . $type, 5);
}
- 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 set_api_filter uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$this->set_filter('update_gt', strtotime((string)$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
Add a "case default" clause to this "switch" statement. Open
switch ($filter) {
- 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 "start" 4 times. Open
if (array_key_exists($name, $_SESSION) && array_key_exists('start', $_SESSION[$name]) && $_SESSION[$name]['start'] > 0) {
- 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 "artist" 4 times. Open
'artist',
- 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 "group_disks" 4 times. Open
if (array_key_exists('group_disks', $argument)) {
- 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 "show_videos.inc.php" 5 times. Open
$box_req = Ui::find_template('show_videos.inc.php');
- 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 "title" 6 times. Open
if (array_key_exists('title', $argument)) {
- 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 "browse_" 4 times. Open
$name = 'browse_' . $type . '_pages';
- 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 "grid_view" 4 times. Open
$this->save_cookie_params('grid_view', $grid_view ? 'true' : '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.
Add a "case default" clause to this "switch" statement. Open
switch ($type) {
- 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
Merge this if statement with the enclosing one. Open
if (isset($box_req) && !empty($box_title)) {
- 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 "song_artist" 4 times. Open
if ($type === 'song_artist') {
- 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 "album_artist" 4 times. Open
if ($type === 'album_artist') {
- 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 "alpha_match" 3 times. Open
case 'alpha_match':
- 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 "video" 3 times. Open
'video',
- 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 "false" 3 times. Open
$this->save_cookie_params('pages', $use_pages ? 'true' : '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.
Take the required action to fix the issue indicated by this "FIXME" comment. Open
// FIXME Can be removed if Browse gets instantiated by the factory
- 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
Define a constant instead of duplicating this literal "catalog" 3 times. Open
'catalog',
- 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.
Avoid unused local variables such as '$group_release'. Open
$group_release = false;
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Avoid unused local variables such as '$shoutObjectLoader'. Open
$shoutObjectLoader = $this->getShoutObjectLoader();
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Avoid unused local variables such as '$video_type'. Open
$video_type = 'video';
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Avoid unused local variables such as '$podcastRepository'. Open
$podcastRepository = $this->getPodcastRepository();
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
FIXME found Open
// FIXME Can be removed if Browse gets instantiated by the factory
- Exclude checks
When fetching an array index from a value of type array<int>,</int>
found an array index of type '1',
but expected the index to be of type int
Open
$this->set_filter('add_lt', strtotime((string)$elements['1']));
- Exclude checks
When fetching an array index from a value of type array<int>,</int>
found an array index of type '0',
but expected the index to be of type int
Open
$this->set_filter('update_gt', strtotime((string)$elements['0']));
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_users.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_videos.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_podcast_episodes.inc.php');
- Exclude checks
When fetching an array index from a value of type array<int>,</int>
found an array index of type '0',
but expected the index to be of type int
Open
$this->set_filter('add_gt', strtotime((string)$elements['0']));
- Exclude checks
When fetching an array index from a value of type array<int>,</int>
found an array index of type '1',
but expected the index to be of type int
Open
$this->set_filter('update_lt', strtotime((string)$elements['1']));
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_albums.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_wanted_albums.inc.php');
- Exclude checks
Call to deprecated function \Ampache\Module\System\Core::get_cookie()
defined at /code/src/Module/System/Core.php:93
Open
$this->set_use_pages(Core::get_cookie($name) == 'true');
- Exclude checks
Call to deprecated function \Ampache\Module\System\Core::get_cookie()
defined at /code/src/Module/System/Core.php:93
Open
$this->set_use_alpha(Core::get_cookie($name) == 'true');
- Exclude checks
Call to method show_box_top
from undeclared class \Ampache\Module\Util\Ui
Open
Ui::show_box_top($box_title, $class);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_songs.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_manage_shoutbox.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_videos.inc.php');
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'set_type invalid type: ' . $type, 5);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_catalogs.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_tagcloud_hidden.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_videos.inc.php');
- Exclude checks
Call to method show_box_bottom
from undeclared class \Ampache\Module\Util\Ui
Open
Ui::show_box_bottom();
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_playlist_medias.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_tvshows.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_localplay_playlist.inc.php');
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Tag
Open
Tag::build_cache($object_ids);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_broadcasts.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_album_disks.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_playlists.inc.php');
- Exclude checks
Call to method show_box_bottom
from undeclared class \Ampache\Module\Util\Ui
Open
Ui::show_box_bottom();
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_videos.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_tvshow_seasons.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_searches.inc.php');
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Tag
Open
Tag::build_cache($object_ids);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_podcasts.inc.php');
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'show_objects called. browse {' . $this->id . '} type {' . $type . '}', 5);
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Song
Open
Song::build_cache($object_ids, $limit_threshold);
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Artist
Open
Artist::build_cache($object_ids, true, $limit_threshold);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_artists.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_manage_license.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_tagcloud.inc.php');
- Exclude checks
Argument 3 (expires)
is array{expires:int,path:string,domain:string,secure:bool,samesite:'Strict'}
but \setcookie()
takes int
Open
setcookie('browse_' . $this->get_type() . '_' . $option, $value, $cookie_options);
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Video
Open
Video::build_cache($object_ids);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_democratic_playlist.inc.php');
- Exclude checks
Call to deprecated function \Ampache\Module\System\Core::get_cookie()
defined at /code/src/Module/System/Core.php:93
Open
$this->set_grid_view(Core::get_cookie($name) == 'true');
- Exclude checks
Call to method create_from_id
from undeclared class \Ampache\Repository\Model\Catalog
Open
$catalog = Catalog::create_from_id((int)((string)$filter_value));
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_shared_objects.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_song_previews.inc.php');
- Exclude checks
Call to method build_cache
from undeclared class \Ampache\Repository\Model\Album
Open
Album::build_cache($object_ids);
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_live_streams.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_videos.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_labels.inc.php');
- Exclude checks
Call to method find_template
from undeclared class \Ampache\Module\Util\Ui
Open
$box_req = Ui::find_template('show_pvmsgs.inc.php');
- Exclude checks
This branch's code block is the same as the block for the branch on line 300. Open
} elseif ($filter_value = $this->get_filter('starts_with')) {
$match = ' (' . (string)$filter_value . ')';
} elseif ($filter_value = $this->get_filter('catalog')) {
- Read upRead up
- Exclude checks
Having two cases
in a switch
statement or two branches in an if
chain with the same implementation is at
best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if
chain they should
be combined, or for a switch
, one should fall through to the other.
Noncompliant Code Example
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doSomething(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doOneMoreThing(); // Noncompliant; duplicates then-branch } var b = a ? 12 > 4 : 4; // Noncompliant; always results in the same value
Compliant Solution
switch ($i) { case 1: case 3: doSomething(); break; case 2: doSomethingDifferent(); break; default: doTheRest(); } if (($a >= 0 && $a < 10) || ($a >= 20 && $a < 50)) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else { doTheRest(); } doOneMoreThing(); b = 4;
or
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: doThirdThing(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThirdThing(); } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doTheRest(); } int b = a ? 12 > 4 : 8;
Exceptions
Blocks in an if
chain that contain a single line of code are ignored, as are blocks in a switch
statement that contain a
single line of code with or without a following break
.
Similar blocks of code found in 2 locations. Consider refactoring. Open
case 'update':
// Check for a range, if no range default to gt
if (strpos((string)$value, '/')) {
$elements = explode('/', (string)$value);
$this->set_filter('update_lt', strtotime((string)$elements['1']));
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 115.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 2 locations. Consider refactoring. Open
case 'add':
// Check for a range, if no range default to gt
if (strpos((string)$value, '/')) {
$elements = explode('/', (string)$value);
$this->set_filter('add_lt', strtotime((string)$elements['1']));
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 115.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 3 locations. Consider refactoring. Open
private const BROWSE_TYPES = array(
'album',
'album_disk',
'artist',
'broadcast',
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 101.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
The parameter $use_alpha is not named in camelCase. Open
public function set_use_alpha($use_alpha, $savecookie = true): void
{
if ($savecookie) {
$this->save_cookie_params('alpha', $use_alpha ? 'true' : '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 $use_pages is not named in camelCase. Open
public function set_use_pages($use_pages, $savecookie = true): void
{
if ($savecookie) {
$this->save_cookie_params('pages', $use_pages ? 'true' : '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 $song_artist is not named in camelCase. Open
public function set_song_artist($song_artist): void
{
$this->_state['song_artist'] = $song_artist;
}
- 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 $object_ids is not named in camelCase. Open
public function show_objects($object_ids = array(), $argument = false): void
{
if ($this->is_simple() || !is_array($object_ids) || empty($object_ids)) {
$object_ids = $this->get_saved();
} else {
- 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 $album_artist is not named in camelCase. Open
public function set_album_artist($album_artist): void
{
$this->_state['album_artist'] = $album_artist;
}
- 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 $update_session is not named in camelCase. Open
public function set_update_session($update_session): void
{
$this->_state['update_session'] = $update_session;
}
- 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 $browse_id is not named in camelCase. Open
public function __construct($browse_id = 0, $cached = true)
{
parent::__construct($browse_id, $cached);
if (!$browse_id) {
- 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 $custom_base is not named in camelCase. Open
public function set_type($type, $custom_base = ''): void
{
if (empty($type)) {
return;
}
- 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 $show_header is not named in camelCase. Open
public function set_show_header($show_header): void
{
$this->_state['show_header'] = $show_header;
}
- 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 $grid_view is not named in camelCase. Open
public function set_grid_view($grid_view, $savecookie = true): void
{
if ($savecookie) {
$this->save_cookie_params('grid_view', $grid_view ? 'true' : '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 $use_filters is not named in camelCase. Open
public function set_use_filters($use_filters): void
{
$this->_state['use_filters'] = $use_filters;
}
- 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) {
}
}