Completed
Push — devel ( 7508db...540322 )
by Philippe
03:02
created

TokenController::actionIndex()   C

Complexity

Conditions 10
Paths 18

Size

Total Lines 59
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 10.1685

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 59
ccs 37
cts 42
cp 0.881
rs 6.5919
cc 10
eloc 41
nc 18
nop 0
crap 10.1685

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
2
/**
3
 * DefaultController.php
4
 *
5
 * PHP version 5.6+
6
 *
7
 * @author pgaultier
8
 * @copyright 2010-2016 Ibitux
9
 * @license http://www.ibitux.com/license license
10
 * @version XXX
11
 * @link http://www.ibitux.com
12
 * @package sweelix\oauth2\server\controllers
13
 */
14
15
namespace sweelix\oauth2\server\controllers;
16
17
use OAuth2\Request as OAuth2Request;
18
use OAuth2\Response as OAuth2Response;
19
use sweelix\oauth2\server\Module;
20
use yii\rest\Controller;
21
use yii\web\Response;
22
use Yii;
23
24
/**
25
 * Oauth2 main controller
26
 *
27
 * @author pgaultier
28
 * @copyright 2010-2016 Ibitux
29
 * @license http://www.ibitux.com/license license
30
 * @version XXX
31
 * @link http://www.ibitux.com
32
 * @package sweelix\oauth2\server\controllers
33
 * @since XXX
34
 */
35
class TokenController extends Controller
36
{
37
38
    /**
39
     * @inheritdoc
40
     */
41 8
    public function behaviors()
42
    {
43 8
        $behaviors = parent::behaviors();
44 8
        unset($behaviors['authenticator']);
45 8
        unset($behaviors['rateLimiter']);
46 8
        return $behaviors;
47
    }
48
49
    /**
50
     * Send back an oauth token
51
     * @return Response
52
     * @since XXX
53
     */
54 8
    public function actionIndex()
55
    {
56 8
        $oauthServer = Yii::createObject('OAuth2\Server');
57
        /* @var \Oauth2\Server $oauthServer */
58 8
        $grantType = Yii::$app->request->getBodyParam('grant_type');
59 8
        $grantIsValid = false;
60
        switch ($grantType) {
61
            // Client Credentials
62 8
            case 'client_credentials':
63 3
                if (Module::getInstance()->allowClientCredentials === true) {
64 3
                    $grantIsValid = true;
65 2
                    $oauthGrantType = Yii::createObject('OAuth2\GrantType\ClientCredentials');
66
                    /* @var \OAuth2\GrantType\ClientCredentials $oauthGrantType */
67 2
                    $oauthServer->addGrantType($oauthGrantType);
68 2
                }
69 3
                break;
70
            // Resource Owner Password Credentials
71 5
            case 'password':
72 4
                if (Module::getInstance()->allowPassword === true) {
73 4
                    $grantIsValid = true;
74 4
                    $oauthGrantType = Yii::createObject('OAuth2\GrantType\UserCredentials');
75
                    /* @var \OAuth2\GrantType\UserCredentials $oauthGrantType */
76 4
                    $oauthServer->addGrantType($oauthGrantType);
77 4
                }
78 4
                break;
79
            // Refresh Token
80 2
            case 'refresh_token':
81 1
                $grantIsValid = true;
82 1
                $oauthGrantType = Yii::createObject('OAuth2\GrantType\RefreshToken');
83
                /* @var \OAuth2\GrantType\RefreshToken $oauthGrantType */
84 1
                $oauthServer->addGrantType($oauthGrantType);
85 1
                break;
86 1
            case 'authorization_code':
87 1
                if (Module::getInstance()->allowAuthorizationCode === true) {
88 1
                    $grantIsValid = true;
89 1
                    $oauthGrantType = Yii::createObject('OAuth2\GrantType\AuthorizationCode');
90
                    /* @var \OAuth2\GrantType\AuthorizationCode $oauthGrantType */
91 1
                    $oauthServer->addGrantType($oauthGrantType);
92 1
                }
93 1
                break;
94
            case 'urn:ietf:params:oauth:grant-type:jwt-bearer':
95
                $grantIsValid = true;
96
                $oauthGrantType = Yii::createObject('OAuth2\GrantType\RefreshToken');
97
                /* @var \OAuth2\GrantType\JwtBearer $oauthGrantType */
98
                $oauthServer->addGrantType($oauthGrantType);
99
                break;
100
        }
101
102 8
        if ($grantIsValid === true) {
103 7
            $response = $oauthServer->handleTokenRequest(OAuth2Request::createFromGlobals());
104 7
            $response = $this->convertResponse($response);
0 ignored issues
show
Compatibility introduced by
$response of type object<OAuth2\ResponseInterface> is not a sub-type of object<OAuth2\Response>. It seems like you assume a concrete implementation of the interface OAuth2\ResponseInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
105 7
        } else {
106
            $response = [
0 ignored issues
show
Bug Compatibility introduced by
The expression array('error' => 'invali...alid for the client.'); of type array<string,string> adds the type array<string,string> to the return on line 111 which is incompatible with the return type documented by sweelix\oauth2\server\co...Controller::actionIndex of type yii\web\Response.
Loading history...
107 2
                'error' => 'invalid_grant',
108
                'error_description' => $grantType.' doesn\'t exist or is invalid for the client.'
109 2
            ];
110
        }
111 8
        return $response;
112
    }
113
114
    /**
115
     * convert OAuth2 response to Yii2 response
116
     * @param OAuth2Response $oauthResponse
117
     * @return \yii\web\Response
118
     * @since XXX
119
     */
120 7
    protected function convertResponse(OAuth2Response $oauthResponse)
121
    {
122
        //TODO: check if we should use acceptable contentType
123
        /*
1 ignored issue
show
Unused Code Comprehensibility introduced by
48% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
124
        $acceptableContentTypes = Yii::$app->request->getAcceptableContentTypes();
125
        foreach ($acceptableContentTypes as $acceptableContentType => $q) {
126
            $rawContentType = $acceptableContentType;
127
            if (($pos = strpos($rawContentType, ';')) !== false) {
128
                // e.g. application/json; charset=UTF-8
129
                $contentType = substr($rawContentType, 0, $pos);
130
            } else {
131
                $contentType = $rawContentType;
132
            }
133
            break;
134
        }
135
        */
136 7
        $contentType = 'application/json';
137 7
        $response = Yii::$app->response;
138 7
        $response->statusCode = $oauthResponse->getStatusCode();
139 7
        $response->statusText = $oauthResponse->getStatusText();
140 7
        if ($contentType === 'application/json') {
141 7
            $response->content = $oauthResponse->getResponseBody();
142 7
        } else {
143
            $response->content = $oauthResponse->getResponseBody('xml');
144
        }
145
146 7
        $headers = $oauthResponse->getHttpHeaders();
147 7
        foreach($headers as $name => $value)
148
        {
149 7
            $response->headers->set($name, $value);
150 7
        }
151 7
        return $response;
152
    }
153
}
154