Completed
Pull Request — master (#15)
by Mischa
04:46
created

OAuthPasswordAuthentication::refreshAccessToken()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 33
Code Lines 22

Duplication

Lines 3
Ratio 9.09 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 3
loc 33
rs 8.439
cc 6
eloc 22
nc 4
nop 0
1
<?php
2
3
/**
4
 * This file is part of the PHP SDK library for the Superdesk Content API.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú.
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace Superdesk\ContentApiSdk\API\Authentication;
16
17
use Superdesk\ContentApiSdk\API\Request\RequestInterface;
18
use Superdesk\ContentApiSdk\Exception\AuthenticationException;
19
use Superdesk\ContentApiSdk\Exception\ClientException;
20
21
class OAuthPasswordAuthentication extends AbstractAuthentication
22
{
23
    const AUTHENTICATION_GRANT_TYPE = 'password';
24
25
    /**
26
     * Username for OAuth password authentication.
27
     *
28
     * @var string
29
     */
30
    protected $username;
31
32
    /**
33
     * Password for OAuth password authentication.
34
     *
35
     * @var string
36
     */
37
    protected $password;
38
39
    /**
40
     * Gets the value of username.
41
     *
42
     * @return string
43
     */
44
    public function getUsername()
45
    {
46
        return $this->username;
47
    }
48
49
    /**
50
     * Sets the value of username.
51
     *
52
     * @param string $username Value to set
53
     *
54
     * @return self
55
     */
56
    public function setUsername($username)
57
    {
58
        $this->username = $username;
59
60
        return $this;
61
    }
62
63
    /**
64
     * Gets the value of password.
65
     *
66
     * @return string
67
     */
68
    public function getPassword()
69
    {
70
        return $this->password;
71
    }
72
73
    /**
74
     * Sets the value of password.
75
     *
76
     * @param string $password Value to set
77
     *
78
     * @return self
79
     */
80
    public function setPassword($password)
81
    {
82
        $this->password = $password;
83
84
        return $this;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function refreshAccessToken()
91
    {
92
        try {
93
            $response = $this->client->makeCall(
94
                $this->getAuthenticationUrl(),
95
                array(),
96
                array(),
97
                'POST',
98
                array(
0 ignored issues
show
Documentation introduced by
array('client_id' => $th...> $this->refresh_token) is of type array<string,?,{"client_...","refresh_token":"?"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
99
                    'client_id' => $this->getClientId(),
100
                    'grant_type' => self::REFRESH_GRANT_TYPE,
101
                    'username' => $this->getUsername(),
102
                    'refresh_token' => $this->refresh_token
0 ignored issues
show
Bug introduced by
The property refresh_token does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
103
                )
104
            );
105
        } catch (ClientException $e) {
106
            throw new AuthenticationException('Could not refresh access token.', $e->getCode(), $e);
107
        }
108
109
        $responseObj = json_decode($response);
110 View Code Duplication
        if (is_null($jsonObj) || json_last_error() !== JSON_ERROR_NONE) {
0 ignored issues
show
Bug introduced by
The variable $jsonObj does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
            throw new AuthenticationException('Authentication response body is not (valid) json.', json_last_error());
112
        }
113
114
        if ($responseObj->access_token && $responseObj->refresh_token) {
115
            $this->access_token = $responseObj->access_token;
0 ignored issues
show
Bug introduced by
The property access_token does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
116
            $this->refresh_token = $responseObj->refresh_token;
117
118
            return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type declared by the interface Superdesk\ContentApiSdk\...ace::refreshAccessToken of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
119
        }
120
121
        throw new AuthenticationException('The server returned an unexpected response body.');
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public function getAuthenticationTokens()
128
    {
129
        try {
130
            $response = $this->client->makeCall(
131
                $this->getAuthenticationUrl(),
132
                array(),
133
                array(),
134
                'POST',
135
                array(
0 ignored issues
show
Documentation introduced by
array('client_id' => $th...> $this->getPassword()) is of type array<string,string,{"cl...","password":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
136
                    'client_id' => $this->getClientId(),
137
                    'grant_type' => self::AUTHENTICATION_GRANT_TYPE,
138
                    'username' => $this->getUsername(),
139
                    'password' => $this->getPassword()
140
                )
141
            );
142
        } catch (ClientException $e) {
143
            throw new AuthenticationException('Could not request access token.', $e->getCode(), $e);
144
        }
145
146
        $responseObj = json_decode($response['body']);
147 View Code Duplication
        if (is_null($responseObj) || json_last_error() !== JSON_ERROR_NONE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            throw new AuthenticationException('Authentication response body is not (valid) json.', json_last_error());
149
        }
150
151
        if (property_exists($responseObj, 'access_token') && property_exists($responseObj, 'refresh_token')) {
152
            $this->accessToken = $responseObj->access_token;
153
            $this->refreshToken = $responseObj->refresh_token;
154
155
            return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type declared by the interface Superdesk\ContentApiSdk\...getAuthenticationTokens of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
156
        }
157
158
        throw new AuthenticationException('The server returned an unexpected response body.');
159
    }
160
}
161