Test Failed
Push — development ( 07d7f1...a41c7d )
by Philippe
02:16
created

HubicService::getAccounts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/*
3
 * This program is free software: you can redistribute it and/or modify
4
 * it under the terms of the GNU General Public License as published by
5
 * the Free Software Foundation, either version 3 of the License, or
6
 * (at your option) any later version.
7
 *
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 * GNU General Public License for more details.
12
 *
13
 * You should have received a copy of the GNU General Public License
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
 */
16
17
namespace Filoucrackeur\Hubic\Service;
18
19
use Filoucrackeur\Hubic\Domain\Model\Account;
20
use Filoucrackeur\Hubic\Domain\Repository\AccountRepository;
21
use GuzzleHttp\RequestOptions;
22
use Psr\Http\Message\ResponseInterface;
23
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
24
use TYPO3\CMS\Core\Http\RequestFactory;
25
use TYPO3\CMS\Core\SingletonInterface;
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
28
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
29
30
class HubicService implements SingletonInterface
31
{
32
    const AUTHORIZATION_ENDPOINT = 'https://api.hubic.com/oauth/auth/';
33
34
    const TOKEN_ENDPOINT = 'https://api.hubic.com/oauth/token/';
35
36
    const DOMAIN_API = 'https://api.hubic.com/';
37
38
    const VERSION_API = '1.0';
39
40
    /**
41
     * @var RequestFactory
42
     */
43
    protected $requestFactory;
44
45
    /**
46
     * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
47
     */
48
    protected $persistenceManager;
49
50
    /**
51
     * @var \Filoucrackeur\Hubic\Domain\Repository\AccountRepository
52
     */
53
    protected $accountRepository;
54
55
    /**
56
     * @var \Filoucrackeur\Hubic\Domain\Model\Account
57
     */
58
    protected $account;
59
60
    /**
61
     * @param Account $account
62
     *
63
     * @return bool
64
     * @throws \RuntimeException
65
     */
66
    public function accessToken(Account $account)
67
    {
68
        $credentials = base64_encode($account->getClientId() . ':' . $account->getClientSecret());
69
        $additionalOptions = [
70
            'headers' => [
71
                'Content-Type' => 'application/x-www-form-urlencoded',
72
                'Authorization' => 'Basic ' . $credentials,
73
            ],
74
            RequestOptions::FORM_PARAMS => [
75
                'code' => GeneralUtility::_GET('code'),
76
                'redirect_uri' => $this->getHost() . '/',
77
                'grant_type' => 'authorization_code',
78
            ],
79
            RequestOptions::VERSION => '1.1',
80
        ];
81
82
        $response = $this->requestFactory->request(self::TOKEN_ENDPOINT, 'POST', $additionalOptions);
83
84
        if (200 === $response->getStatusCode()) {
85
            $content = json_decode($response->getBody()->getContents());
86
            $account->setAccessToken($content->access_token);
87
            $account->setRefreshToken($content->refresh_token);
88
            $expireIn = new \DateTime('+ ' . $content->expires_in . ' seconds');
89
            $account->setExpirationDate($expireIn);
90
            $this->persistenceManager->update($account);
91
            $this->persistenceManager->persistAll();
92
        }
93
94
        return true;
95
    }
96
97
    /**
98
     * @return string
99
     */
100
    public function getHost(): string
101
    {
102
        return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
103
    }
104
105
    /**
106
     * @param Account $account
107
     */
108
    public function redirectUrlRequestToken(Account $account)
109
    {
110
        $arguments = [
111
            'client_id' => $account->getClientId(),
112
            'redirect_uri' => $this->getRedirectUri($account),
113
            'scope' => $account->getScope(),
114
            'response_type' => 'code',
115
            'state' => time(),
116
        ];
117
118
        $uri = self::AUTHORIZATION_ENDPOINT . '?' . urldecode(http_build_query($arguments));
119
        header('Location: ' . $uri);
120
        die();
121
    }
122
123
    /**
124
     * @param Account $account
125
     *
126
     * @return string
127
     */
128
    private function getRedirectUri(Account $account): string
129
    {
130
        $formProtection = FormProtectionFactory::get();
131
        $formToken = $formProtection->generateToken('AuthorizationRequest');
132
133
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
134
135
        return urlencode($this->getHost() . $uriBuilder
136
                ->setCreateAbsoluteUri(true)
137
                ->setArguments([
138
                    'tx_hubic_tools_hubichubic' => [
139
                        'action' => 'callback',
140
                        'controller' => 'Backend\Account',
141
                        'account' => $account->getUid(),
142
                    ],
143
                    'formToken' => $formToken
144
                ])->buildBackendUri());
145
    }
146
147
    public function getAccount()
148
    {
149
        return $this->fetch('/account');
150
    }
151
152
    /**
153
     * @param Account $account
154
     */
155
    public function setAccount(Account $account)
156
    {
157
        $this->account = $account;
158
    }
159
160
    /**
161
     * @param string $path
162
     * @param string $method
163
     *
164
     * @return \Psr\Http\Message\ResponseInterface|string
165
     */
166
    public function fetch(string $path, $method = 'GET')
167
    {
168
        $additionalOptions = [
169
            'headers' => [
170
                'Content-Type' => 'application/x-www-form-urlencoded',
171
                'Authorization' => 'Bearer ' . $this->account->getAccessToken(),
172
            ],
173
            RequestOptions::VERSION => '1.1',
174
        ];
175
176
        try {
177
            $response = $this->requestFactory->request(self::DOMAIN_API . self::VERSION_API . $path, $method,
178
                $additionalOptions);
179
180
            if (200 === $response->getStatusCode()) {
181
                return json_decode($response->getBody()->getContents());
182
            }
183
        } catch (\Exception $e) {
184
            \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($method);
185
            \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($response);
186
        }
187
        return null;
188
    }
189
190
    /**
191
     * @param Account $account
192
     * @return bool
193
     */
194
    public function refreshToken(Account $account): bool
195
    {
196
197
        $credentials = base64_encode($account->getClientId() . ':' . $account->getClientSecret());
198
        $additionalOptions = [
199
            'headers' => [
200
                'Content-Type' => 'application/x-www-form-urlencoded',
201
                'Authorization' => 'Basic ' . $credentials,
202
            ],
203
            RequestOptions::FORM_PARAMS => [
204
                'refresh_token' => $account->getRefreshToken(),
205
                'grant_type' => 'refresh_token',
206
            ],
207
            RequestOptions::VERSION => '1.1',
208
        ];
209
210
        $response = $this->requestFactory->request(self::TOKEN_ENDPOINT, 'POST', $additionalOptions);
211
212
        if (200 === $response->getStatusCode()) {
213
            $content = json_decode($response->getBody()->getContents());
214
            $account->setAccessToken($content->access_token);
215
            $this->persistenceManager->update($account);
216
            $this->persistenceManager->persistAll();
217
        }
218
219
        return true;
220
    }
221
222
    /**
223
     * @param Account $account
224
     */
225
    public function delete(Account $account): void
226
    {
227
        $this->persistenceManager->remove($account);
228
        $this->persistenceManager->persistAll();
229
    }
230
231
    /**
232
     * @param Account $account
233
     */
234
    public function unlink(Account $account): void
235
    {
236
        $account->setAccessToken('');
237
        $account->setRefreshToken('');
238
        $this->persistenceManager->update($account);
239
        $this->persistenceManager->persistAll();
240
    }
241
242
    /**
243
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
244
     */
245
    public function getAccounts()
246
    {
247
        return $this->accountRepository->findAll();
248
    }
249
250
    /**
251
     * Get hubiC account Quota.
252
     *
253
     * @see https://api.hubic.com/console/
254
     *
255
     * @return ResponseInterface
256
     */
257
    public function getAccountQuota()
258
    {
259
        return $this->fetch('/account/usage');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->fetch('/account/usage'); of type Psr\Http\Message\ResponseInterface|string adds the type string to the return on line 259 which is incompatible with the return type documented by Filoucrackeur\Hubic\Serv...ervice::getAccountQuota of type Psr\Http\Message\ResponseInterface.
Loading history...
260
    }
261
262
    /**
263
     * Get hubiC agreements.
264
     *
265
     * @see https://api.hubic.com/console/
266
     *
267
     * @return ResponseInterface
268
     */
269
    public function getAgreement()
270
    {
271
        return $this->fetch('/agreement');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->fetch('/agreement'); of type Psr\Http\Message\ResponseInterface|string adds the type string to the return on line 271 which is incompatible with the return type documented by Filoucrackeur\Hubic\Serv...icService::getAgreement of type Psr\Http\Message\ResponseInterface.
Loading history...
272
    }
273
274
    /**
275
     * Get hubiC getAllLinks.
276
     *
277
     * @see https://api.hubic.com/console/
278
     *
279
     * @return ResponseInterface
280
     */
281
    public function getAllLinks()
282
    {
283
        return $this->fetch('/account/getAllLinks');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->fetch('/account/getAllLinks'); of type Psr\Http\Message\ResponseInterface|string adds the type string to the return on line 283 which is incompatible with the return type documented by Filoucrackeur\Hubic\Serv...bicService::getAllLinks of type Psr\Http\Message\ResponseInterface.
Loading history...
284
    }
285
286
    /**
287
     * Delete hubiC link.
288
     *
289
     * @see https://api.hubic.com/console/
290
     *
291
     * @param string $uri
292
     * @return ResponseInterface
293
     */
294
    public function deleteLink(string $uri)
0 ignored issues
show
Unused Code introduced by
The parameter $uri is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
295
    {
296
        return $this->fetch('/account/link', 'DELETE');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->fetch('/account/link', 'DELETE'); of type Psr\Http\Message\ResponseInterface|string adds the type string to the return on line 296 which is incompatible with the return type documented by Filoucrackeur\Hubic\Serv...ubicService::deleteLink of type Psr\Http\Message\ResponseInterface.
Loading history...
297
    }
298
299
    /**
300
     * @param RequestFactory $requestFactory
301
     */
302
    public function injectRequestFactory(RequestFactory $requestFactory): void
303
    {
304
        $this->requestFactory = $requestFactory;
305
    }
306
307
    /**
308
     * @param PersistenceManager $persistenceManager
309
     */
310
    public function injectPersistenceManager(PersistenceManager $persistenceManager): void
311
    {
312
        $this->persistenceManager = $persistenceManager;
313
    }
314
315
    /**
316
     * @param AccountRepository $accountRepository
317
     */
318
    public function injectAccountRepository(AccountRepository $accountRepository)
319
    {
320
        $this->accountRepository = $accountRepository;
321
    }
322
}
323