Completed
Pull Request — master (#79)
by ARCANEDEV
07:58
created

Response::toJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\NoCaptcha\Utilities;
2
3
use Arcanedev\NoCaptcha\Contracts\Utilities\Response as ResponseContract;
4
5
/**
6
 * Class     Response
7
 *
8
 * @package  Arcanedev\NoCaptcha\Utilities
9
 * @author   ARCANEDEV <[email protected]>
10
 */
11
class Response implements ResponseContract
12
{
13
    /* -----------------------------------------------------------------
14
     |  Constants
15
     | -----------------------------------------------------------------
16
     */
17
18
    /**
19
     * Invalid JSON received
20
     */
21
    const E_INVALID_JSON = 'invalid-json';
22
23
    /**
24
     * Could not connect to service
25
     */
26
    const E_CONNECTION_FAILED = 'connection-failed';
27
28
    /**
29
     * Did not receive a 200 from the service
30
     */
31
    const E_BAD_RESPONSE = 'bad-response';
32
33
    /**
34
     * Not a success, but no error codes received!
35
     */
36
    const E_UNKNOWN_ERROR = 'unknown-error';
37
38
    /**
39
     * ReCAPTCHA response not provided
40
     */
41
    const E_MISSING_INPUT_RESPONSE = 'missing-input-response';
42
43
    /**
44
     * Expected hostname did not match
45
     */
46
    const E_HOSTNAME_MISMATCH = 'hostname-mismatch';
47
48
    /**
49
     * Expected APK package name did not match
50
     */
51
    const E_APK_PACKAGE_NAME_MISMATCH = 'apk_package_name-mismatch';
52
53
    /**
54
     * Expected action did not match
55
     */
56
    const E_ACTION_MISMATCH = 'action-mismatch';
57
58
    /**
59
     * Score threshold not met
60
     */
61
    const E_SCORE_THRESHOLD_NOT_MET = 'score-threshold-not-met';
62
63
    /**
64
     * Challenge timeout
65
     */
66
    const E_CHALLENGE_TIMEOUT = 'challenge-timeout';
67
68
    /* -----------------------------------------------------------------
69
     |  Properties
70
     | -----------------------------------------------------------------
71
     */
72
73
    /**
74
     * Success or failure.
75
     *
76
     * @var boolean
77
     */
78
    private $success = false;
79
80
    /**
81
     * Error code strings.
82
     *
83
     * @var array
84
     */
85
    private $errorCodes = [];
86
87
    /**
88
     * The hostname of the site where the reCAPTCHA was solved.
89
     * @var string
90
     */
91
    private $hostname;
92
93
    /**
94
     * Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
95
     *
96
     * @var string
97
     */
98
    private $challengeTs;
99
100
    /**
101
     * APK package name
102
     *
103
     * @var string
104
     */
105
    private $apkPackageName;
106
107
    /**
108
     * Score assigned to the request
109
     *
110
     * @var float|null
111
     */
112
    private $score;
113
114
    /**
115
     * Action as specified by the page
116
     *
117
     * @var string
118
     */
119
    private $action;
120
121
    /* -----------------------------------------------------------------
122
     |  Constructor
123
     | -----------------------------------------------------------------
124
     */
125
126
    /**
127
     * Response constructor.
128
     *
129
     * @param  bool         $success
130
     * @param  array        $errorCodes
131
     * @param  string|null  $hostname
132
     * @param  string|null  $challengeTs
133
     * @param  string|null  $apkPackageName
134
     * @param  float|null   $score
135
     * @param  string|null  $action
136
     */
137 45
    public function __construct($success, array $errorCodes = [], $hostname = null, $challengeTs = null, $apkPackageName = null, $score = null, $action = null)
138
    {
139 45
        $this->success        = $success;
140 45
        $this->errorCodes     = $errorCodes;
141 45
        $this->hostname       = $hostname;
142 45
        $this->challengeTs    = $challengeTs;
143 45
        $this->apkPackageName = $apkPackageName;
144 45
        $this->score          = $score;
145 45
        $this->action         = $action;
146 45
    }
147
148
    /* -----------------------------------------------------------------
149
     |  Getters
150
     | -----------------------------------------------------------------
151
     */
152
153
    /**
154
     * Get error codes.
155
     *
156
     * @return array
157
     */
158 12
    public function getErrorCodes()
159
    {
160 12
        return $this->errorCodes;
161
    }
162
163
    /**
164
     * Get hostname.
165
     *
166
     * @return string
167
     */
168 12
    public function getHostname()
169
    {
170 12
        return $this->hostname;
171
    }
172
173
    /**
174
     * Get challenge timestamp
175
     *
176
     * @return string
177
     */
178 9
    public function getChallengeTs()
179
    {
180 9
        return $this->challengeTs;
181
    }
182
183
    /**
184
     * Get APK package name
185
     *
186
     * @return string
187
     */
188 9
    public function getApkPackageName()
189
    {
190 9
        return $this->apkPackageName;
191
    }
192
193
    /**
194
     * Get score
195
     *
196
     * @return float
197
     */
198 12
    public function getScore()
199
    {
200 12
        return $this->score;
201
    }
202
203
    /**
204
     * Get action
205
     *
206
     * @return string
207
     */
208 12
    public function getAction()
209
    {
210 12
        return $this->action;
211
    }
212
213
    /* -----------------------------------------------------------------
214
     |  Main Methods
215
     | -----------------------------------------------------------------
216
     */
217
218
    /**
219
     * Build the response from the expected JSON returned by the service.
220
     *
221
     * @param  string  $json
222
     *
223
     * @return \Arcanedev\NoCaptcha\Utilities\Response
224
     */
225 9
    public static function fromJson($json)
226
    {
227 9
        $responseData = json_decode($json, true);
228
229 9
        if ( ! $responseData)
230 3
            return new static(false, [Response::E_INVALID_JSON]);
231
232 6
        return static::fromArray($responseData);
233
    }
234
235
    /**
236
     * Build the response from an array.
237
     *
238
     * @param  array  $array
239
     *
240
     * @return \Arcanedev\NoCaptcha\Utilities\Response
241
     */
242 30
    public static function fromArray(array $array)
243
    {
244 30
        $hostname       = $array['hostname'] ?? null;
245 30
        $challengeTs    = $array['challenge_ts'] ?? null;
246 30
        $apkPackageName = $array['apk_package_name'] ?? null;
247 30
        $score          = isset($array['score']) ? floatval($array['score']) : null;
248 30
        $action         = $array['action'] ?? null;
249
250 30
        if (isset($array['success']) && $array['success'] == true)
251 24
            return new static(true, [], $hostname, $challengeTs, $apkPackageName, $score, $action);
252
253 6
        if ( ! (isset($array['error-codes']) && is_array($array['error-codes'])))
254 6
            $array['error-codes'] = [Response::E_UNKNOWN_ERROR];
255
256 6
        return new static(false, $array['error-codes'], $hostname, $challengeTs, $apkPackageName, $score, $action);
257
    }
258
259
    /**
260
     * Convert the response object to array.
261
     *
262
     * @return array
263
     */
264 9
    public function toArray()
265
    {
266
        return [
267 9
            'success'          => $this->isSuccess(),
268 9
            'hostname'         => $this->getHostname(),
269 9
            'challenge_ts'     => $this->getChallengeTs(),
270 9
            'apk_package_name' => $this->getApkPackageName(),
271 9
            'score'            => $this->getScore(),
272 9
            'action'           => $this->getAction(),
273 9
            'error-codes'      => $this->getErrorCodes(),
274
        ];
275
    }
276
277
    /**
278
     * Convert the object to its JSON representation.
279
     *
280
     * @param  int  $options
281
     *
282
     * @return string
283
     */
284 3
    public function toJson($options = 0)
285
    {
286 3
        return json_encode($this->jsonSerialize(), $options);
287
    }
288
289
    /**
290
     * Convert the response object to array.
291
     *
292
     * @return array
293
     */
294 3
    public function jsonSerialize()
295
    {
296 3
        return $this->toArray();
297
    }
298
299
    /* -----------------------------------------------------------------
300
     |  Check Methods
301
     | -----------------------------------------------------------------
302
     */
303
304
    /**
305
     * Check if the response is successful.
306
     *
307
     * @return bool
308
     */
309 36
    public function isSuccess()
310
    {
311 36
        return $this->success === true;
312
    }
313
314
    /**
315
     * Check the score.
316
     *
317
     * @param  float  $score
318
     *
319
     * @return bool
320
     */
321 3
    public function isScore($score)
322
    {
323 3
        return $this->getScore() >= floatval($score);
324
    }
325
326
    /**
327
     * Check the hostname.
328
     *
329
     * @param  string  $hostname
330
     *
331
     * @return bool
332
     */
333 3
    public function isHostname($hostname)
334
    {
335 3
        return $this->getHostname() === $hostname;
336
    }
337
338
    /**
339
     * Check the action name.
340
     *
341
     * @param  string  $action
342
     *
343
     * @return bool
344
     */
345 3
    public function isAction($action)
346
    {
347 3
        return $this->getAction() === $action;
348
    }
349
}
350