ampache/ampache

View on GitHub
src/Module/Api/Method/HandshakeMethod.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/HandshakeMethod.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/HandshakeMethod.php - About 30 mins to fix

    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 125 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 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 "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_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.

    Define a constant instead of duplicating this literal "version" 3 times.
    Open

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

    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

                        Api::error('Received Invalid Handshake - Login failed, timestamp is out of range (timestamp: ' . $timestamp . ' 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 "api_format" 5 times.
    Open

                Api::error('Received Invalid Handshake', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'version', $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 "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.

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

            Api::$version = ((int)$version >= 350001) ? Api::$version_numeric : Api::$version;
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    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 read from undeclared class \Ampache\Module\System\Session
    Open

                    if (!Session::read($data['apikey'])) {
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

        public static function handshake(array $input): bool

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

            $username = trim((string) ($input['user'] ?? Session::username($passphrase)));
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

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

                        Session::destroy($data['apikey']);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

                            echo Xml_Data::keyed_array($results);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    Call to method error from undeclared class \Ampache\Module\Api\Api
    Open

                Api::error('Received Invalid Handshake', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'version', $input['api_format']);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

                if ($client instanceof User) {
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    Call to method error from undeclared class \Ampache\Module\Api\Api
    Open

            Api::error('Received Invalid Handshake - Incorrect username or password', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    Call to deprecated function \Ampache\Module\Api\Method\HandshakeMethod::getUserRepository() defined at /code/src/Module/Api/Method/HandshakeMethod.php:194
    Open

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

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

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

        public static function handshake(array $input): bool

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

            Api::$version = ((int)$version >= 350001) ? Api::$version_numeric : Api::$version;
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    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 method error from undeclared class \Ampache\Module\Api\Api
    Open

                        Api::error('Received Invalid Handshake - Login failed, timestamp is out of range', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    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 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 deprecated function \Ampache\Module\Api\Method\HandshakeMethod::getUserRepository() defined at /code/src/Module/Api/Method/HandshakeMethod.php:194
    Open

                $client   = static::getUserRepository()->findByApiKey(trim($passphrase));

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

            $version      = (isset($input['version'])) ? $input['version'] : Api::$version;
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

            if ((int)($version) < Api::$auth_version && $data_version !== 6) {
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

                $client = User::get_from_username($username);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

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

                    $realpwd = static::getUserRepository()->retrievePasswordFromUser($client->getId());
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

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

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

                        Session::extend($data['apikey'], 'api');
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

                    $results = Api::server_details($token);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

    Call to method error from undeclared class \Ampache\Module\Api\Api
    Open

                        Api::error('Received Invalid Handshake - Login failed, timestamp is out of range (timestamp: ' . $timestamp . ' Server: ' . $now_time . ')', ErrorCodeEnum::INVALID_HANDSHAKE, self::ACTION, 'account', $input['api_format']);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

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

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

                        $token = Session::create($data);
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

            if ($client instanceof User) {
    Severity: Critical
    Found in src/Module/Api/Method/HandshakeMethod.php by phan

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

                $user_id = $client->id;

    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/HandshakeMethod.php and 1 other location - About 1 day to fix
    src/Module/Api/Method/Api5/Handshake5Method.php on lines 140..180

    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