ampache/ampache

View on GitHub
src/Module/Api/Method/Api5/Handshake5Method.php

Summary

Maintainability
D
2 days
Test Coverage

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'];
Severity: Minor
Found in src/Module/Api/Method/Api5/Handshake5Method.php - About 6 hrs to fix

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;
Severity: Major
Found in src/Module/Api/Method/Api5/Handshake5Method.php - About 30 mins to fix

    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'];

    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'];

    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'];

    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

    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

    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);
            }

    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'];
                    }

    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']);

    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']);

    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']);

    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'));

    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'])) {

    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'])) {

    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'])) {

    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;

    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);

    Call to method destroy from undeclared class \Ampache\Module\System\Session
    Open

                        Session::destroy($data['apikey']);

    Call to method getId from undeclared class \Ampache\Repository\Model\User
    Open

                    $realpwd = static::getUserRepository()->retrievePasswordFromUser($client->getId());

    Reference to static property version from undeclared class \Ampache\Module\Api\Api5
    Open

            Api5::$version = ((int)$version >= 350001) ? Api5::$version_numeric : Api5::$version;

    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']);

    @throws type of handshake has undeclared type \Psr\Container\ContainerExceptionInterface
    Open

        public static function handshake(array $input): bool

    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);

    Call to method username from undeclared class \Ampache\Module\System\Session
    Open

            $username = trim((string) ($input['user'] ?? Session::username($passphrase)));

    Call to method get_from_username from undeclared class \Ampache\Repository\Model\User
    Open

                $client = User::get_from_username($username);

    Reference to instance property id from undeclared class \Ampache\Repository\Model\User
    Open

                $user_id = $client->id;

    @throws type of handshake has undeclared type \Psr\Container\NotFoundExceptionInterface
    Open

        public static function handshake(array $input): bool

    Reference to instance property apikey from undeclared class \Ampache\Repository\Model\User
    Open

                    $data['apikey']   = (string)$client->apikey;

    Reference to static property auth_version from undeclared class \Ampache\Module\Api\Api5
    Open

            if ((int)($version) < Api5::$auth_version && $data_version !== 5) {

    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);

    Checking instanceof against undeclared class \Ampache\Repository\Model\User
    Open

                if ($client instanceof User) {

    Reference to instance property username from undeclared class \Ampache\Repository\Model\User
    Open

                    $data['username'] = (string)$client->username;

    Call to method extend from undeclared class \Ampache\Module\System\Session
    Open

                        Session::extend($data['apikey'], 'api');

    Call to method read from undeclared class \Ampache\Module\System\Session
    Open

                    if (!Session::read($data['apikey'])) {

    Checking instanceof against undeclared class \Ampache\Repository\Model\User
    Open

            if ($client instanceof User) {

    Reference to static property version_numeric from undeclared class \Ampache\Module\Api\Api5
    Open

            Api5::$version = ((int)$version >= 350001) ? Api5::$version_numeric : Api5::$version;

    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());

    Reference to static property version from undeclared class \Ampache\Module\Api\Api5
    Open

            $version       = (isset($input['version'])) ? $input['version'] : Api5::$version;

    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));

    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']);

    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']);

    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);

    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);

    Call to deprecated function \debug_event() defined at /code/src/Config/functions.php:651
    Open

                    debug_event(self::class, 'Login Success, passphrase matched', 1);

    Call to method server_details from undeclared class \Ampache\Module\Api\Api5
    Open

                    $results = Api5::server_details($token);

    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);

    Call to method keyed_array from undeclared class \Ampache\Module\Api\Xml5_Data
    Open

                            echo Xml5_Data::keyed_array($results);

    Call to method create from undeclared class \Ampache\Module\System\Session
    Open

                        $token = Session::create($data);

    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';
    Severity: Major
    Found in src/Module/Api/Method/Api5/Handshake5Method.php and 1 other location - About 1 day to fix
    src/Module/Api/Method/HandshakeMethod.php on lines 142..182

    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

    Further Reading

    Expected 0 spaces after opening bracket; newline found
    Open

            if (

    Expected 0 spaces after opening bracket; newline found
    Open

                    if (

    There are no issues that match your filters.

    Category
    Status