DotEnvStorage::setAuthorization()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
nc 1
nop 3
dl 0
loc 8
ccs 0
cts 7
cp 0
crap 2
rs 9.4285
c 1
b 0
f 0
1
<?php
2
3
namespace Baguette\Mastodon\Config;
4
5
use Baguette\Mastodon;
6
use Baguette\Mastodon\Service\Authorization;
7
use Baguette\Mastodon\Service\Scope;
8
use Respect\Validation\Validator as v;
9
10
/**
11
 * Mastodon config storage using PHP dotenv
12
 *
13
 * NOTICE: This class is designed for simple development use.
14
 * You should not use this for production environments or for batch processing.
15
 *
16
 * @see https://github.com/vlucas/phpdotenv
17
 * @author    USAMI Kenta <[email protected]>
18
 * @copyright 2017 Baguette HQ
19
 * @license   https://www.gnu.org/licenses/gpl-3.0.html GPL-3.0
20
 */
21
class DotEnvStorage extends \Dotenv\Loader implements Storage
22
{
23
    use \Teto\Object\ReadOnly;
24
25
    /** @var string|resource */
26
    private $file_path;
27
28
    /** @var array */
29
    private $key_names = [
30
        'app_name'      => 'APP_NAME',
31
        'client_id'     => 'CLIENT_ID',
32
        'client_secret' => 'CLIENT_SECRET',
33
        'username'      => 'USERNAME',
34
        'password'      => 'PASSWORD',
35
        'access_token'  => 'ACCESS_TOKEN',
36
        'scope'         => 'SCOPE',
37
        'created_at'    => 'CREATED_AT',
38
    ];
39
40
    /** @var bool */
41
    private $read_only = true;
42
43
    /** @var array */
44
    private $save_values = [];
45
46
    /**
47
     * @param string $file_path
48
     * @param array  $options
49
     * @throws \Dotenv\Exception\InvalidPathException
50
     */
51 13
    public function __construct($file_path, $options = [])
52
    {
53 13
        $this->file_path = $file_path;
54
55 13
        if (isset($options['key_names'])) {
56
            $this->key_names = $options['key_names'] + $this->key_names;
57
        }
58
59 13
        if (isset($options['read_only'])) {
60 8
            v::boolType()->assert($options['read_only']);
61 8
            $this->read_only = $options['read_only'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $options['read_only'] of type array is incompatible with the declared type boolean of property $read_only.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
62
        }
63
64
        // ignore parent class constructor
65 13
        if (false) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
66
            parent::__construct($file_path);
67
        }
68 13
    }
69
70
    /**
71
     * @return array
72
     */
73 5
    public function getAppName()
74
    {
75 5
        $appname_key = $this->key_names['app_name'];
76
77 5
        $values = $this->getValues();
78
79
        return [
80 5
            'app_name' => isset($values[$appname_key]) ? $values[$appname_key] : null,
81
        ];
82
    }
83
84
    /**
85
     * @param  string $app_name
86
     * @return void
87
     */
88 7
    public function setAppName($app_name)
89
    {
90 7
        v::stringType()->not(v::contains("\n"))->assert($app_name);
91 7
        $this->save_values['app_name'] = $app_name;
92 7
    }
93
94
    /**
95
     * @return array
96
     */
97
    public function getAuthorization()
98
    {
99
        $token_key = $this->key_names['access_token'];
100
        $scope_key = $this->key_names['scope'];
101
        $cat_key   = $this->key_names['created_at'];
102
103
        $values = $this->getValues();
104
105
        return [
106
            'access_token' => isset($values[$token_key]) ? $values[$token_key] : null,
107
            'scope'        => isset($values[$scope_key]) ? $values[$scope_key] : null,
108
            'created_at'   => isset($values[$cat_key])   ? $values[$cat_key]   : null,
109
        ];
110
    }
111
112
    /**
113
     * @param  string                $access_token
114
     * @param  string|string[]|Scope $scope
115
     * @param  int                   $created_at
116
     * @return void
117
     */
118
    public function setAuthorization($access_token, $scope = null, $created_at = null)
119
    {
120
        v::stringType()->not(v::contains("\n"))->assert($access_token);
121
        v::intType()->min(0)->assert($created_at);
122
        $this->save_values['access_token'] = $access_token;
123
        $this->save_values['scope'] = (string)Mastodon\scope($scope);
124
        $this->save_values['created_at'] = $created_at;
125
    }
126
127
    /**
128
     * @param  Authorization $authorization
129
     * @return void
130
     */
131
    public function setAuthorizationFromObject(Authorization $authorization)
132
    {
133
        $this->setAuthorization(
134
            $authorization->access_token,
135
            $authorization->scope,
136
            $authorization->created_at ? $authorization->created_at->getTimestamp() : time()
137
        );
138
    }
139
140
    /**
141
     * @Return array
142
     */
143 5 View Code Duplication
    public function getClientIdAndSecret()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
144
    {
145 5
        $id_key  = $this->key_names['client_id'];
146 5
        $sec_key = $this->key_names['client_secret'];
147
148 5
        $values = $this->getValues();
149
150
        return [
151 5
            'client_id'     => isset($values[$id_key])  ? $values[$id_key]  : null,
152 5
            'client_secret' => isset($values[$sec_key]) ? $values[$sec_key] : null,
153
        ];
154
    }
155
156
    /**
157
     * @param  string $client_id
158
     * @param  string $client_secret
159
     */
160 3 View Code Duplication
    public function setClientIdAndSecret($client_id, $client_secret)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
161
    {
162 3
        v::stringType()->not(v::contains("\n"))->assert($client_id);
163 3
        v::stringType()->not(v::contains("\n"))->assert($client_secret);
164 3
        $this->save_values['client_id']     = $client_id;
165 3
        $this->save_values['client_secret'] = $client_secret;
166 3
    }
167
168
    /**
169
     * @return array
170
     */
171 5 View Code Duplication
    public function getUsernameAndPassword()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
172
    {
173 5
        $user_key = $this->key_names['username'];
174 5
        $pass_key = $this->key_names['password'];
175 5
        $values = $this->getValues();
176
177
        return [
178 5
            'username' => isset($values[$user_key]) ? $values[$user_key] : null,
179 5
            'password' => isset($values[$pass_key]) ? $values[$pass_key] : null,
180
        ];
181
    }
182
183
    /**
184
     * @param  string $username
185
     * @param  string $password
186
     */
187 1 View Code Duplication
    public function setUsernameAndPassword($username, $password)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
188
    {
189 1
        v::stringType()->not(v::contains("\n"))->assert($username);
190 1
        v::stringType()->not(v::contains("\n"))->assert($password);
191 1
        $this->save_values['username']     = $username;
192 1
        $this->save_values['password'] = $password;
193 1
    }
194
195
    /**
196
     * Returns all stored key-value pairs
197
     *
198
     * @return array
199
     */
200 5
    public function getValues()
201
    {
202 5
        $values = [];
203
204 5
        foreach ($this->getLines() as $line) {
205 4
            if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
206 3
                list($key, $val) = $this->normaliseEnvironmentVariable($line, '');
207 4
                $values[$key] = $val;
208
            }
209
        }
210
211 5
        return $values;
212
    }
213
214
    /**
215
     * @param  resource $fp
216
     * @return string[]
217
     */
218 13
    public function getLines($fp = null)
219
    {
220 13
        $fp = ($fp === null) ? $this->file_path : $fp;
221
222 13
        if (is_string($fp)) {
223 2
            return $this->readLinesFromFile($fp);
224
        }
225
226 11
        rewind($fp);
227
228 11
        return preg_split("/\r?\n/", stream_get_contents($fp));
229
    }
230
231
    /**
232
     * @return void
233
     */
234 8
    public function save()
235
    {
236 8
        if ($this->read_only) {
237
            throw new \RuntimeException('This config store is read only.');
238
        }
239
240 8
        $tbl = array_flip($this->key_names);
241
242 8
        $opend_file = false;
243 8
        if (is_string($this->file_path)) {
244
            $fp = fopen($this->file_path, 'rwb');
245
            $opend_file = true;
246
        } else {
247 8
            $fp = $this->file_path;
248 8
            rewind($fp);
249
        }
250
251 8
        $lines = $this->getLines($fp);
252 8
        $orig_lines = $lines;
253
254 8
        if ($opend_file) {
255
            fclose($fp);
256
        }
257
258 8
        foreach ($lines as $i => $line) {
259 8
            if ($this->isComment($line) || !$this->looksLikeSetter($line)) {
260 8
                continue;
261
            }
262
263 3
            list($key, $val) = $this->normaliseEnvironmentVariable($line, '');
0 ignored issues
show
Unused Code introduced by
The assignment to $val is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
264
265 3
            if (isset($tbl[$key]) && isset($this->save_values[$tbl[$key]])) {
266 3
                $saveval = $this->save_values[$tbl[$key]];
267 3
                $lines[$i] = sprintf('%s=%s', $key, $this->quoteValue($saveval));
268 3
                unset($this->save_values[$tbl[$key]]);
269
            }
270
        }
271
272 8
        foreach ($this->save_values as $key => $saveval) {
273 4
            $lines[] = sprintf('%s=%s', $this->key_names[$key], $this->quoteValue($saveval));
274
        }
275
276
        // noop
277 8
        if ($orig_lines === $lines) {
278 1
            return;
279
        }
280
281 7
        if ($opend_file) {
282
            file_put_contents($this->file_path, implode("\n", $lines) . "\n");
283
        } else {
284 7
            rewind($fp);
285 7
            fwrite($fp, implode("\n", $lines) . "\n");
286
        }
287 7
    }
288
289
    /**
290
     * @param string $value
291
     */
292 7
    public static function quoteValue($value)
293
    {
294 7
        return sprintf('"%s"', strtr($value, [
295 7
            '"'  => '\\"',
296
        ]));
297
    }
298
}
299