1 | <?php |
||
2 | |||
3 | namespace Ridvanbaluyos\Pwned; |
||
4 | |||
5 | use \GuzzleHttp\Client as Client; |
||
6 | /** |
||
7 | * Have I Been Pwned? API v2 only. |
||
8 | * https://haveibeenpwned.com/About |
||
9 | * |
||
10 | * @package Pwned |
||
11 | * @author Ridvan Baluyos <[email protected]> |
||
12 | * @link https://github.com/ridvanbaluyos/haveibeenpwned |
||
13 | * @license MIT |
||
14 | */ |
||
15 | class Pwned |
||
16 | { |
||
17 | protected $endpoint; |
||
18 | protected $client; |
||
19 | |||
20 | /** |
||
21 | * Pwned constructor. |
||
22 | */ |
||
23 | public function __construct() |
||
24 | { |
||
25 | $this->client = new Client(); |
||
26 | $this->endpoint = 'https://haveibeenpwned.com/api/v2/'; |
||
27 | } |
||
28 | |||
29 | /** |
||
30 | * Set the filters. |
||
31 | * |
||
32 | * @param array $filters |
||
33 | * @return string |
||
34 | */ |
||
35 | protected function setFilters(string $url, array $filters): string |
||
36 | { |
||
37 | // Append query filters if available. |
||
38 | if (!empty($filters)) { |
||
39 | $query = http_build_query($filters); |
||
40 | $url .= '?' . $query; |
||
41 | } |
||
42 | |||
43 | return $url; |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * Guzzle GET request. |
||
48 | * |
||
49 | * @param string $url |
||
50 | * @return array |
||
51 | */ |
||
52 | protected function requestGet(string $url): array |
||
53 | { |
||
54 | try { |
||
55 | $result = $this->client->request('GET', $url); |
||
56 | $jsonResponse = $this->getJsonResponse($result); |
||
57 | |||
58 | return $jsonResponse; |
||
59 | } catch(\GuzzleHttp\Exception\ClientException $e) { |
||
60 | return [ |
||
61 | 'code' => $e->getCode(), |
||
62 | 'message' => $e->getMessage() |
||
63 | ]; |
||
64 | } |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * This function converts a guzzle response into a JSON response. |
||
69 | * |
||
70 | * @param \GuzzleHttp\Psr7\Response $response |
||
71 | * @return array |
||
72 | */ |
||
73 | private function getJsonResponse(\GuzzleHttp\Psr7\Response $response): array |
||
74 | { |
||
75 | switch ($response->getStatusCode()) { |
||
76 | case 200: |
||
77 | $response = (string) $response->getBody(); |
||
78 | |||
79 | if (empty($response) || !isset($response) || $response == '') { |
||
80 | $response = '{}'; |
||
81 | } |
||
82 | break; |
||
83 | case 404: |
||
84 | $response = []; |
||
85 | break; |
||
86 | default: |
||
87 | $response = []; |
||
88 | break; |
||
89 | } |
||
90 | |||
91 | return json_decode($response, true); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
92 | } |
||
93 | } |