RefreshGrantTrait::refreshSetIntegration()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Limoncello\OAuthServer\GrantTraits;
4
5
/**
6
 * Copyright 2015-2019 [email protected]
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 * http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
use Limoncello\OAuthServer\Contracts\ClientInterface;
22
use Limoncello\OAuthServer\Contracts\Integration\RefreshIntegrationInterface;
23
use Limoncello\OAuthServer\Exceptions\OAuthTokenBodyException;
24
use Psr\Http\Message\ResponseInterface;
25
use function array_diff;
26
use function array_key_exists;
27
use function explode;
28
use function is_string;
29
30
/**
31
 * @package Limoncello\OAuthServer
32
 *
33
 * @link    https://tools.ietf.org/html/rfc6749#section-6
34
 */
35
trait RefreshGrantTrait
36
{
37
    /**
38
     * @var RefreshIntegrationInterface
39 8
     */
40
    private $refreshIntegration;
41 8
42
    /**
43
     * @return RefreshIntegrationInterface
44
     */
45
    protected function refreshGetIntegration(): RefreshIntegrationInterface
46
    {
47
        return $this->refreshIntegration;
48
    }
49 44
50
    /**
51 44
     * @param RefreshIntegrationInterface $refreshIntegration
52
     *
53
     * @return void
54
     */
55
    public function refreshSetIntegration(RefreshIntegrationInterface $refreshIntegration): void
56
    {
57
        $this->refreshIntegration = $refreshIntegration;
58
    }
59 9
60
    /**
61 9
     * @param string[] $parameters
62
     *
63
     * @return string|null
64
     */
65
    protected function refreshGetValue(array $parameters): ?string
66
    {
67
        return $this->refreshReadStringValue($parameters, 'refresh_token');
68
    }
69 5
70
    /**
71 5
     * @param string[] $parameters
72
     *
73 5
     * @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...
74
     */
75
    protected function refreshGetScope(array $parameters): ?array
76
    {
77
        $scope = $this->refreshReadStringValue($parameters, 'scope');
78
79
        return empty($scope) === false ? explode(' ', $scope) : null;
80
    }
81
82
    /**
83
     * @param string[]             $parameters
84
     * @param ClientInterface|null $determinedClient
85
     *
86 9
     * @return ResponseInterface
87
     *
88 9
     * @SuppressWarnings(PHPMD.ElseExpression)
89 1
     * @SuppressWarnings(PHPMD.NPathComplexity)
90
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
91
     */
92 8
    protected function refreshIssueToken(array $parameters, ?ClientInterface $determinedClient): ResponseInterface
93 1
    {
94
        if (($refreshValue = $this->refreshGetValue($parameters)) === null) {
95
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_REQUEST);
96 7
        }
97 7
98 2
        if (($token = $this->refreshGetIntegration()->readTokenByRefreshValue($refreshValue)) === null) {
99 2
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
100
        }
101 5
102
        $clientIdFromToken = $token->getClientIdentifier();
103
        if ($determinedClient === null) {
104
            $isClientFromToken = true;
105
            $determinedClient  = $this->refreshGetIntegration()->readClientByIdentifier($clientIdFromToken);
106 7
        } else {
107 7
            $isClientFromToken = false;
108 7
        }
109
110 1
        // if client didn't provided authentication (but had to) or
111
        // client associated with the token do not match provided client credentials we throw an exception
112
        if (($isClientFromToken === true &&
113 6
                ($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...
114 1
            $determinedClient->getIdentifier() !== $clientIdFromToken
115
        ) {
116
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_CLIENT);
117 5
        }
118 5
119 5
        if ($determinedClient->isRefreshGrantEnabled() === false) {
120
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
121 3
        }
122 1
123
        $isScopeModified = false;
124 2
        $scopeList       = null;
125 2
        if (($requestedScope = $this->refreshGetScope($parameters)) !== null) {
126
            // check requested scope is within the current one
127
            if (empty(array_diff($requestedScope, $token->getScopeIdentifiers())) === false) {
128 4
                throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_SCOPE);
129 4
            }
130 4
            $isScopeModified = true;
131 4
            $scopeList       = $requestedScope;
132 4
        }
133 4
134
        $response = $this->refreshGetIntegration()->refreshCreateAccessTokenResponse(
135
            $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...
136 4
            $token,
137
            $isScopeModified,
138
            $scopeList,
139
            $parameters
140
        );
141
142
        return $response;
143
    }
144
145 9
    /**
146
     * @param array  $parameters
147 9
     * @param string $name
148 9
     *
149
     * @return null|string
150
     */
151
    private function refreshReadStringValue(array $parameters, string $name): ?string
152
    {
153
        return array_key_exists($name, $parameters) === true && is_string($value = $parameters[$name]) === true ?
154
            $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...
155
    }
156
}
157