Response.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * ApiClient
  4. *
  5. * PHP version 5
  6. *
  7. * @category Services
  8. * @package Authy
  9. * @author David Cuadrado <[email protected]>
  10. * @license http://creativecommons.org/licenses/MIT/ MIT
  11. * @link http://authy.github.com/pear
  12. */
  13. /**
  14. * Friendly class to parse response from the authy API
  15. *
  16. * @category Services
  17. * @package Authy
  18. * @author David Cuadrado <[email protected]>
  19. * @license http://creativecommons.org/licenses/MIT/ MIT
  20. * @link http://authy.github.com/pear
  21. */
  22. class Authy_Response
  23. {
  24. protected $raw_response;
  25. protected $body;
  26. protected $errors;
  27. /**
  28. * Constructor.
  29. *
  30. * @param array $raw_response Raw server response
  31. */
  32. public function __construct($raw_response)
  33. {
  34. $this->raw_response = $raw_response;
  35. $this->body = $raw_response['body'];
  36. $this->errors = new stdClass();
  37. // Handle errors
  38. if (isset($this->body->errors)) {
  39. $this->errors = $this->body->errors; // when response is {errors: {}}
  40. unset($this->body->errors);
  41. } else if ($raw_response['status'] == 400) {
  42. $this->errors = $this->body; // body here is a stdClass
  43. $this->body = new stdClass();
  44. } else if (!$this->ok() && gettype($this->body) == 'string') {
  45. // the response was an error so put the body as an error
  46. $this->errors = (object) array("error" => $this->body);
  47. $this->body = new stdClass();
  48. }
  49. }
  50. /**
  51. * Check if the response was ok
  52. *
  53. * @return boolean return true if the response code is 200
  54. */
  55. public function ok()
  56. {
  57. return $this->raw_response['status'] == 200;
  58. }
  59. /**
  60. * Returns the id of the response if present
  61. *
  62. * @return integer id of the response
  63. */
  64. public function id()
  65. {
  66. return isset($this->body->id) ? $this->body->id : null;
  67. }
  68. /**
  69. * Get the request errors
  70. *
  71. * @return stdClass object containing the request errors
  72. */
  73. public function errors()
  74. {
  75. return $this->errors;
  76. }
  77. }