Completed
Push — develop ( 5a49ee...0049e3 )
by Neomerx
03:37
created

RefreshGrantTrait::refreshIssueToken()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 52
c 0
b 0
f 0
ccs 30
cts 30
cp 1
rs 5.9999
cc 11
eloc 31
nc 12
nop 2
crap 11

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Limoncello\OAuthServer\GrantTraits;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use Limoncello\OAuthServer\Contracts\ClientInterface;
20
use Limoncello\OAuthServer\Contracts\Integration\RefreshIntegrationInterface;
21
use Limoncello\OAuthServer\Exceptions\OAuthTokenBodyException;
22
use Psr\Http\Message\ResponseInterface;
23
24
/**
25
 * @package Limoncello\OAuthServer
26
 *
27
 * @link    https://tools.ietf.org/html/rfc6749#section-6
28
 */
29
trait RefreshGrantTrait
30
{
31
    /**
32
     * @var RefreshIntegrationInterface
33
     */
34
    private $refreshIntegration;
35
36
    /**
37
     * @return RefreshIntegrationInterface
38
     */
39 8
    protected function refreshGetIntegration(): RefreshIntegrationInterface
40
    {
41 8
        return $this->refreshIntegration;
42
    }
43
44
    /**
45
     * @param RefreshIntegrationInterface $refreshIntegration
46
     *
47
     * @return void
48
     */
49 44
    public function refreshSetIntegration(RefreshIntegrationInterface $refreshIntegration): void
50
    {
51 44
        $this->refreshIntegration = $refreshIntegration;
52
    }
53
54
    /**
55
     * @param string[] $parameters
56
     *
57
     * @return string|null
58
     */
59 9
    protected function refreshGetValue(array $parameters): ?string
60
    {
61 9
        return $this->refreshReadStringValue($parameters, 'refresh_token');
62
    }
63
64
    /**
65
     * @param string[] $parameters
66
     *
67
     * @return string[]|null
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
68
     */
69 5
    protected function refreshGetScope(array $parameters): ?array
70
    {
71 5
        $scope = $this->refreshReadStringValue($parameters, 'scope');
72
73 5
        return empty($scope) === false ? explode(' ', $scope) : null;
74
    }
75
76
    /**
77
     * @param string[]             $parameters
78
     * @param ClientInterface|null $determinedClient
79
     *
80
     * @return ResponseInterface
81
     */
82 9
    protected function refreshIssueToken(array $parameters, ?ClientInterface $determinedClient): ResponseInterface
83
    {
84 9
        if (($refreshValue = $this->refreshGetValue($parameters)) === null) {
85 1
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_REQUEST);
86
        }
87
88 8
        if (($token = $this->refreshGetIntegration()->readTokenByRefreshValue($refreshValue)) === null) {
89 1
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
90
        }
91
92 7
        $clientIdFromToken = $token->getClientIdentifier();
93 7
        if ($determinedClient === null) {
94 2
            $isClientFromToken = true;
95 2
            $determinedClient  = $this->refreshGetIntegration()->readClientByIdentifier($clientIdFromToken);
96
        } else {
97 5
            $isClientFromToken = false;
98
        }
99
100
        // if client didn't provided authentication (but had to) or
101
        // client associated with the token do not match provided client credentials we throw an exception
102 7
        if (($isClientFromToken === true &&
103 7
                ($determinedClient->isConfidential() === true || $determinedClient->hasCredentials() === true)) ||
0 ignored issues
show
Bug introduced by
It seems like $determinedClient is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
104 7
            $determinedClient->getIdentifier() !== $clientIdFromToken
105
        ) {
106 1
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_CLIENT);
107
        }
108
109 6
        if ($determinedClient->isRefreshGrantEnabled() === false) {
110 1
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
111
        }
112
113 5
        $isScopeModified = false;
114 5
        $scopeList       = null;
115 5
        if (($requestedScope = $this->refreshGetScope($parameters)) !== null) {
116
            // check requested scope is within the current one
117 3
            if (empty(array_diff($requestedScope, $token->getScopeIdentifiers())) === false) {
118 1
                throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_SCOPE);
119
            }
120 2
            $isScopeModified = true;
121 2
            $scopeList       = $requestedScope;
122
        }
123
124 4
        $response = $this->refreshGetIntegration()->refreshCreateAccessTokenResponse(
125 4
            $determinedClient,
0 ignored issues
show
Bug introduced by
It seems like $determinedClient can be null; however, refreshCreateAccessTokenResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
126 4
            $token,
127 4
            $isScopeModified,
128 4
            $scopeList,
129 4
            $parameters
130
        );
131
132 4
        return $response;
133
    }
134
135
    /**
136
     * @param array  $parameters
137
     * @param string $name
138
     *
139
     * @return null|string
140
     */
141 9
    private function refreshReadStringValue(array $parameters, string $name): ?string
142
    {
143 9
        return array_key_exists($name, $parameters) === true && is_string($value = $parameters[$name]) === true ?
144 9
            $value : null;
0 ignored issues
show
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
145
    }
146
}
147