base.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php namespace Client\Request;
  2. abstract class Base implements RequestInterface {
  3. protected $loaded = false;
  4. protected $scope;
  5. use \Lib\Curl {
  6. get as private mget;
  7. post as private mpost;
  8. delete as private mdelete;
  9. }
  10. public function __construct(string $api_url, string $api_token) {
  11. $this->url = $api_url;
  12. $this->token = $api_token;
  13. }
  14. public function load(bool $force = false) {
  15. $this->set_scope("get");
  16. if ($this->loaded && !$force)
  17. return $this;
  18. $jenc = $this->mget($this->scope);
  19. $this->json_set_property($this->json_decode($jenc));
  20. $this->loaded = true;
  21. return $this;
  22. }
  23. protected function method_get(array $params = array()) {
  24. return $this->mget($this->scope, $params);
  25. }
  26. protected function method_post(array $params = array()) {
  27. return $this->mpost($this->scope, $params);
  28. }
  29. protected function method_delete() {
  30. return $this->mdelete($this->scope);
  31. }
  32. public function get(string $s) {
  33. if (!$this->set_scope("get"))
  34. throw new NotImplementedException("::get:: Not implemented for class");
  35. }
  36. public function create(...$args) {
  37. if ($this->loaded)
  38. throw new Exception("::create:: Cant create on an git-initialized object. Create new object.");
  39. if (!$this->set_scope("create"))
  40. throw new NotImplementedException("::create:: Not implemented for class");
  41. $ret = $this->method_post(...$args);
  42. $this->json_set_property($this->json_decode($ret));
  43. return true;
  44. }
  45. public function patch() {
  46. if (!$this->loaded)
  47. throw new InvalidMethodRequest("::patch:: Cant patch an git-uninitialized object. Load it first.");
  48. if (!$this->set_scope("patch"))
  49. throw new NotImplementedException("::patch:: Not implemented for class");
  50. }
  51. public function delete() {
  52. if (!$this->set_scope("delete"))
  53. throw new NotImplementedException("::delete:: Not implemented for class");
  54. return $this->method_delete();
  55. }
  56. protected function json_decode(string $jenc) {
  57. $obj = json_decode($jenc);
  58. $this->json_error();
  59. return $obj;
  60. }
  61. protected function json_encode(iterable $jdec) {
  62. $jenc = json_encode($jdec);
  63. $this->json_error();
  64. return $jenc;
  65. }
  66. protected function json_error() {
  67. if (($err = json_last_error()) != JSON_ERROR_NONE)
  68. throw new RequestErrorException(json_last_error_msg(), $err);
  69. }
  70. abstract protected function json_set_property($obj);
  71. abstract protected function set_scope(string $method);
  72. public function __destruct() {}
  73. }
  74. ?>