BadResponseException::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 7
rs 10
1
<?php
2
3
/**
4
 * @file BadResponseException.php
5
 * @brief This file contains the BadResponseException class.
6
 * @details
7
 * @author Filippo F. Fadda
8
 */
9
10
11
//! The CouchDB's errors namespace
12
namespace Surfer\Exception;
13
14
15
use Surfer\Message\Request;
16
use Surfer\Message\Response;
17
18
19
/**
20
 * @brief Exception thrown when a bad Response is received.
21
 */
22
class BadResponseException extends \RuntimeException {
23
  private $humanReadableError;
24
25
  protected $request;
26
  protected $response;
27
28
  protected $info = [];
29
30
31
  /**
32
   * @brief Creates a BadResponseException class instance.
33
   * @param Request $request An instance of the Request class.
34
   * @param Response $response An instance of the Response class.
35
   */
36
  public function __construct(Request $request, Response $response) {
37
    $this->request = $request;
38
    $this->response = $response;
39
40
    $this->humanReadableError = $response->getSupportedStatusCodes()[$response->getStatusCode()];
41
42
    parent::__construct($this->humanReadableError, $response->getStatusCode());
43
  }
44
45
46
  /**
47
   * @brief Returns the request.
48
   * @retval EoC::Message::Request
49
   */
50
  public final function getRequest() {
51
    return $this->request;
52
  }
53
54
55
  /**
56
   * @brief Returns the response.
57
   * @retval EoC::Message::Response
58
   */
59
  public final function getResponse() {
60
    return $this->response;
61
  }
62
63
64
  /**
65
   * @brief Overrides the magic method to get all the information about the error.
66
   */
67
  public function __toString() {
68
    $error = $this->response->getBodyAsArray();
69
70
    $this->info[] = "[Error Code] ".$error["error"];
71
    $this->info[] = "[Error Reason] ".$error["reason"];
72
73
    $statusCode = (int)$this->response->getStatusCode();
74
75
    // 4xx - Client Error Status Codes
76
    // 5xx - Server Error Status Codes
77
    // 6xx - Unknown Error Status Codes
78
    switch ($statusCode) {
79
      case ($statusCode < 500):
80
        $this->info[] = "[Error Type] Client Error";
81
        break;
82
      case ($statusCode >= 500):
83
        $this->info[] = "[Error Type] Server Error";
84
        break;
85
      default:
86
        $this->info[] = "[Error Type] Unknown Error";
87
        break;
88
    }
89
90
    $this->info[] = "[Error Code] ".$this->response->getStatusCode();
91
    $this->info[] = "[Error Message] ".$this->humanReadableError;
92
    $this->info[] = "[Request]";
93
    $this->info[] = sprintf('%s', $this->request);
94
    $this->info[] = "[Response]";
95
    $this->info[] = sprintf('%s', $this->response);
96
97
    return implode(PHP_EOL, $this->info);
98
  }
99
100
}