Issues (17)

lib/OAuth2HttpClient.php (1 issue)

Labels
Severity
1
<?php
2
/*
3
 * The MIT License
4
 *
5
 * Copyright 2016 BCL Technologies.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 */
25
26
namespace Bcl\EasyPdfCloud;
27
28
use function mb_strlen;
29
use function http_build_query;
30
use function stream_context_create;
31
use function time;
32
33
class OAuth2HttpClient extends HttpClientBase
34
{
35
    private $clientId;
36
    private $clientSecret;
37
    private $tokenManager;
38
    private $urlInfo;
39
40
    public function __construct($clientId, $clientSecret, IOAuth2TokenManager $tokenManager, UrlInfo $urlInfo)
41
    {
42
        $this->clientId = $clientId;
43
        $this->clientSecret = $clientSecret;
44
        $this->tokenManager = $tokenManager;
45
        $this->urlInfo = $urlInfo;
46
    }
47
48
    public function getNewAccessToken()
49
    {
50
        $url = $this->getOAuth2TokenEndPoint();
51
52
        $data = array(
53
            'grant_type' => 'client_credentials',
54
            'client_id' => $this->clientId,
55
            'client_secret' => $this->clientSecret,
56
            'scope' => 'epc.api',
57
        );
58
59
        $postData = http_build_query($data);
60
61
        $httpHeader = 'Content-Type: application/x-www-form-urlencoded' . static::CRLF;
62
        $httpHeader .= 'Accept: application/json; charset=utf-8' . static::CRLF;
63
        $httpHeader .= 'Content-Length: ' . mb_strlen($postData, '8bit') . static::CRLF;
64
65
        $options = array(
66
            'http' => array(
67
                'ignore_errors' => true,
68
                'method' => 'POST',
69
                'header' => $httpHeader,
70
                'content' => $postData,
71
            ),
72
        );
73
74
        $context = stream_context_create($options);
75
76
        $httpResponse = $this->getHttpResponseFromUrl($url, $context);
77
        $http_response_header = $httpResponse['header'];
78
        $contents = $httpResponse['contents'];
79
80
        $headers = $this->mapHttpHeaders($http_response_header);
81
82
        if ($this->handleResponse($headers)) {
83
            $jsonResponse = $this->decodeJsonFromResponse($headers, $contents, true);
84
85
            if (!isset($jsonResponse['access_token'])) {
86
                $statusCode = $this->getStatusCodeFromResponse($headers);
87
88
                throw new EasyPdfCloudApiException(
0 ignored issues
show
The type Bcl\EasyPdfCloud\EasyPdfCloudApiException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
89
                    $statusCode,
90
                    'Response from server does not contain access token'
91
                );
92
            }
93
94
            $accessToken = $jsonResponse['access_token'];
95
96
            if (!isset($jsonResponse['expires_in'])) {
97
                $statusCode = $this->getStatusCodeFromResponse($headers);
98
99
                throw new EasyPdfCloudApiException(
100
                    $statusCode,
101
                    'Response from server does not contain access token expiration'
102
                );
103
            }
104
105
            $expiresIn = $jsonResponse['expires_in'];
106
107
            if ($expiresIn > 120) {
108
                // we'll try to refresh a bit earlier
109
                $expiresIn -= 60;
110
            }
111
112
            $expirationTime = time() + $expiresIn;
113
114
            $tokenInfo = array(
115
                'access_token' => $accessToken,
116
                'expiration_time' => $expirationTime,
117
            );
118
119
            $this->tokenManager->saveTokenInfo($tokenInfo);
120
121
            return $accessToken;
122
        }
123
124
        // This should raise an exception
125
        $this->checkWwwAuthenticateResponseHeader($headers);
126
127
        return null;
128
    }
129
130
    public function getAccessToken()
131
    {
132
        $tokenInfo = $this->tokenManager->loadTokenInfo();
133
        if (null === $tokenInfo) {
134
            return $this->getNewAccessToken();
135
        }
136
137
        if (!isset($tokenInfo['access_token'])) {
138
            return $this->getNewAccessToken();
139
        }
140
141
        $accessToken = $tokenInfo['access_token'];
142
143
        if (!isset($tokenInfo['expiration_time'])) {
144
            return $this->getNewAccessToken();
145
        }
146
147
        $expirationTime = $tokenInfo['expiration_time'];
148
149
        $timeNow = time();
150
        if ($timeNow >= $expirationTime) {
151
            return $this->getNewAccessToken();
152
        }
153
154
        return $accessToken;
155
    }
156
157
    private function getOAuth2TokenEndPoint()
158
    {
159
        return $this->urlInfo->getOAuth2BaseUrl() . '/token';
160
    }
161
}
162