Function handshake
has a Cognitive Complexity of 40 (exceeds 5 allowed). Consider refactoring. Open
public static function handshake(array $input): bool
{
$now_time = time();
$timestamp = (int)preg_replace('/[^0-9]/', '', $input['timestamp'] ?? $now_time);
$passphrase = $input['auth'];
- 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;
The method handshake() has 124 lines of code. Current threshold is set to 100. Avoid really long methods. Open
public static function handshake(array $input): bool
{
$now_time = time();
$timestamp = (int)preg_replace('/[^0-9]/', '', $input['timestamp'] ?? $now_time);
$passphrase = $input['auth'];
- Exclude checks
The method handshake() has an NPath complexity of 81312. The configured NPath complexity threshold is 200. Open
public static function handshake(array $input): bool
{
$now_time = time();
$timestamp = (int)preg_replace('/[^0-9]/', '', $input['timestamp'] ?? $now_time);
$passphrase = $input['auth'];
- 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 handshake() has a Cyclomatic Complexity of 22. The configured cyclomatic complexity threshold is 10. Open
public static function handshake(array $input): bool
{
$now_time = time();
$timestamp = (int)preg_replace('/[^0-9]/', '', $input['timestamp'] ?? $now_time);
$passphrase = $input['auth'];
- 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 5, down to the maximum allowed 3. Open
public static function handshake(array $input): 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 43 to the 15 allowed. Open
public static function handshake(array $input): 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
The method handshake uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$client = User::get_from_username($username);
}
- 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 handshake uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
Session::extend($data['apikey'], 'api');
$token = $data['apikey'];
}
- 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 "api_format" 4 times. Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Login failed, timestamp is out of range') . ' (timestamp: ' . $timestamp . ' ' . T_('Server') . ': ' . $now_time . ')', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- 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 "Received Invalid Handshake" 3 times. Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Login failed, timestamp is out of range') . ' (timestamp: ' . $timestamp . ' ' . T_('Server') . ': ' . $now_time . ')', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- 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 "account" 3 times. Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Login failed, timestamp is out of range') . ' (timestamp: ' . $timestamp . ' ' . T_('Server') . ': ' . $now_time . ')', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- 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 "Login failed, timestamp is out of range" 3 times. Open
AmpError::add('api', T_('Login failed, timestamp is out of range'));
- 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 "geo_name" 3 times. Open
if (isset($input['geo_name'])) {
- 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 "geo_longitude" 3 times. Open
if (isset($input['geo_longitude'])) {
- 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 "geo_latitude" 3 times. Open
if (isset($input['geo_latitude'])) {
- 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 "apikey" 5 times. Open
$data['apikey'] = (string)$client->apikey;
- 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.
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'Login Failed: Version too old', 1);
- Exclude checks
Call to method destroy
from undeclared class \Ampache\Module\System\Session
Open
Session::destroy($data['apikey']);
- Exclude checks
Call to method getId
from undeclared class \Ampache\Repository\Model\User
Open
$realpwd = static::getUserRepository()->retrievePasswordFromUser($client->getId());
- Exclude checks
Reference to static property version
from undeclared class \Ampache\Module\Api\Api5
Open
Api5::$version = ((int)$version >= 350001) ? Api5::$version_numeric : Api5::$version;
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\Api\Api5
Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Incorrect username or password'), ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- Exclude checks
@throws type of handshake
has undeclared type \Psr\Container\ContainerExceptionInterface
Open
public static function handshake(array $input): bool
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'Login Failed, unable to match passphrase', 1);
- Exclude checks
Call to method username
from undeclared class \Ampache\Module\System\Session
Open
$username = trim((string) ($input['user'] ?? Session::username($passphrase)));
- Exclude checks
Call to method get_from_username
from undeclared class \Ampache\Repository\Model\User
Open
$client = User::get_from_username($username);
- Exclude checks
Reference to instance property id
from undeclared class \Ampache\Repository\Model\User
Open
$user_id = $client->id;
- Exclude checks
@throws type of handshake
has undeclared type \Psr\Container\NotFoundExceptionInterface
Open
public static function handshake(array $input): bool
- Exclude checks
Reference to instance property apikey
from undeclared class \Ampache\Repository\Model\User
Open
$data['apikey'] = (string)$client->apikey;
- Exclude checks
Reference to static property auth_version
from undeclared class \Ampache\Module\Api\Api5
Open
if ((int)($version) < Api5::$auth_version && $data_version !== 5) {
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'Login Failed: timestamp out of range ' . $timestamp . '/' . $now_time, 1);
- Exclude checks
Checking instanceof against undeclared class \Ampache\Repository\Model\User
Open
if ($client instanceof User) {
- Exclude checks
Reference to instance property username
from undeclared class \Ampache\Repository\Model\User
Open
$data['username'] = (string)$client->username;
- Exclude checks
Call to method extend
from undeclared class \Ampache\Module\System\Session
Open
Session::extend($data['apikey'], 'api');
- Exclude checks
Call to method read
from undeclared class \Ampache\Module\System\Session
Open
if (!Session::read($data['apikey'])) {
- Exclude checks
Checking instanceof against undeclared class \Ampache\Repository\Model\User
Open
if ($client instanceof User) {
- Exclude checks
Reference to static property version_numeric
from undeclared class \Ampache\Module\Api\Api5
Open
Api5::$version = ((int)$version >= 350001) ? Api5::$version_numeric : Api5::$version;
- Exclude checks
Call to deprecated function \Ampache\Module\Api\Method\Api5\Handshake5Method::getUserRepository()
defined at /code/src/Module/Api/Method/Api5/Handshake5Method.php:192
Open
$realpwd = static::getUserRepository()->retrievePasswordFromUser($client->getId());
- Exclude checks
Reference to static property version
from undeclared class \Ampache\Module\Api\Api5
Open
$version = (isset($input['version'])) ? $input['version'] : Api5::$version;
- Exclude checks
Call to deprecated function \Ampache\Module\Api\Method\Api5\Handshake5Method::getUserRepository()
defined at /code/src/Module/Api/Method/Api5/Handshake5Method.php:192
Open
$client = static::getUserRepository()->findByApiKey(trim($passphrase));
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\Api\Api5
Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Login failed, timestamp is out of range'), ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- Exclude checks
Call to method error
from undeclared class \Ampache\Module\Api\Api5
Open
Api5::error(T_('Received Invalid Handshake') . ' - ' . T_('Login failed, timestamp is out of range') . ' (timestamp: ' . $timestamp . ' ' . T_('Server') . ': ' . $now_time . ')', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, "Login$data_version Attempt, IP: $user_ip Time: $timestamp User: " . ($client->username ?? '') . " ($user_id)", 1);
- Exclude checks
Reference to instance property username
from undeclared class \Ampache\Repository\Model\User
Open
debug_event(self::class, "Login$data_version Attempt, IP: $user_ip Time: $timestamp User: " . ($client->username ?? '') . " ($user_id)", 1);
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'Login Success, passphrase matched', 1);
- Exclude checks
Call to method server_details
from undeclared class \Ampache\Module\Api\Api5
Open
$results = Api5::server_details($token);
- Exclude checks
Call to deprecated function \debug_event()
defined at /code/src/Config/functions.php:651
Open
debug_event(self::class, 'Unable to find user with userid of ' . $user_id, 1);
- Exclude checks
Call to method keyed_array
from undeclared class \Ampache\Module\Api\Xml5_Data
Open
echo Xml5_Data::keyed_array($results);
- Exclude checks
Call to method create
from undeclared class \Ampache\Module\System\Session
Open
$token = Session::create($data);
- Exclude checks
Identical blocks of code found in 2 locations. Consider refactoring. Open
if ($client instanceof User) {
// Create the session
$data = array();
$data['username'] = (string)$client->username;
$data['type'] = 'api';
- 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 340.
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
Expected 0 spaces after opening bracket; newline found Open
if (
- Exclude checks
Expected 0 spaces after opening bracket; newline found Open
if (
- Exclude checks