| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\Framework\Foundation; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use WP_Error; |
| 7 |
|
| 8 |
/** |
| 9 |
* Exception Class. |
| 10 |
*/ |
| 11 |
class WPException extends Exception { |
| 12 |
|
| 13 |
/** |
| 14 |
* Http code |
| 15 |
* @var integer |
| 16 |
*/ |
| 17 |
protected $code = 400; |
| 18 |
|
| 19 |
/** |
| 20 |
* Exception message. |
| 21 |
* @var string |
| 22 |
*/ |
| 23 |
protected $message = ''; |
| 24 |
|
| 25 |
/** |
| 26 |
* Error messages |
| 27 |
* @var array |
| 28 |
*/ |
| 29 |
protected $errorData = []; |
| 30 |
|
| 31 |
/** |
| 32 |
* WPError object |
| 33 |
* @var \WP_Error |
| 34 |
*/ |
| 35 |
protected $wpError = null; |
| 36 |
|
| 37 |
/** |
| 38 |
* Construct the WPException instance |
| 39 |
* @param WP_Error $wpError |
| 40 |
*/ |
| 41 |
public function __construct(WP_Error $wpError) |
| 42 |
{ |
| 43 |
$this->wpError = $wpError; |
| 44 |
$this->errorData = $wpError->get_error_data(); |
| 45 |
$this->message = $wpError->get_error_message(); |
| 46 |
|
| 47 |
if (is_array($this->errorData) && isset($this->errorData['status'])) { |
| 48 |
$this->code = $this->errorData['status']; |
| 49 |
} |
| 50 |
|
| 51 |
parent::__construct($this->message, $this->code); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Get the error messages |
| 56 |
* @return array |
| 57 |
*/ |
| 58 |
public function errors() |
| 59 |
{ |
| 60 |
return $this->toArray(); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Retrive the full formatted error messages. |
| 65 |
* @return [type] [description] |
| 66 |
*/ |
| 67 |
protected function toArray() |
| 68 |
{ |
| 69 |
$errors = []; |
| 70 |
|
| 71 |
foreach ((array) $this->wpError->errors as $code => $messages) { |
| 72 |
foreach ((array) $messages as $message) { |
| 73 |
$errors[] = [ |
| 74 |
'code' => $code, |
| 75 |
'message' => $message, |
| 76 |
'data' => $this->wpError->get_error_data($code), |
| 77 |
]; |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
return $errors; |
| 82 |
} |
| 83 |
} |
| 84 |
|