|
1 <?php |
|
2 /** |
|
3 * Exception based on HTTP response |
|
4 * |
|
5 * @package Requests\Exceptions |
|
6 */ |
|
7 |
|
8 namespace WpOrg\Requests\Exception; |
|
9 |
|
10 use WpOrg\Requests\Exception; |
|
11 use WpOrg\Requests\Exception\Http\StatusUnknown; |
|
12 |
|
13 /** |
|
14 * Exception based on HTTP response |
|
15 * |
|
16 * @package Requests\Exceptions |
|
17 */ |
|
18 class Http extends Exception { |
|
19 /** |
|
20 * HTTP status code |
|
21 * |
|
22 * @var integer |
|
23 */ |
|
24 protected $code = 0; |
|
25 |
|
26 /** |
|
27 * Reason phrase |
|
28 * |
|
29 * @var string |
|
30 */ |
|
31 protected $reason = 'Unknown'; |
|
32 |
|
33 /** |
|
34 * Create a new exception |
|
35 * |
|
36 * There is no mechanism to pass in the status code, as this is set by the |
|
37 * subclass used. Reason phrases can vary, however. |
|
38 * |
|
39 * @param string|null $reason Reason phrase |
|
40 * @param mixed $data Associated data |
|
41 */ |
|
42 public function __construct($reason = null, $data = null) { |
|
43 if ($reason !== null) { |
|
44 $this->reason = $reason; |
|
45 } |
|
46 |
|
47 $message = sprintf('%d %s', $this->code, $this->reason); |
|
48 parent::__construct($message, 'httpresponse', $data, $this->code); |
|
49 } |
|
50 |
|
51 /** |
|
52 * Get the status message. |
|
53 * |
|
54 * @return string |
|
55 */ |
|
56 public function getReason() { |
|
57 return $this->reason; |
|
58 } |
|
59 |
|
60 /** |
|
61 * Get the correct exception class for a given error code |
|
62 * |
|
63 * @param int|bool $code HTTP status code, or false if unavailable |
|
64 * @return string Exception class name to use |
|
65 */ |
|
66 public static function get_class($code) { |
|
67 if (!$code) { |
|
68 return StatusUnknown::class; |
|
69 } |
|
70 |
|
71 $class = sprintf('\WpOrg\Requests\Exception\Http\Status%d', $code); |
|
72 if (class_exists($class)) { |
|
73 return $class; |
|
74 } |
|
75 |
|
76 return StatusUnknown::class; |
|
77 } |
|
78 } |