base.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 protected mpost;
  8. delete as protected 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. $this->set_scope("get");
  34. }
  35. public function create(...$args) {
  36. $this->set_scope("create");
  37. $ret = $this->method_post(...$args);
  38. $this->json_set_property($this->json_decode($ret));
  39. $this->loaded = true;
  40. return true;
  41. }
  42. public function patch() {
  43. $this->set_scope("patch");
  44. }
  45. public function delete() {
  46. $this->set_scope("delete");
  47. return $this->method_delete();
  48. }
  49. protected function json_decode(string $jenc) {
  50. $obj = json_decode($jenc);
  51. $this->json_error();
  52. return $obj;
  53. }
  54. protected function json_encode(iterable $jdec) {
  55. $jenc = json_encode($jdec);
  56. $this->json_error();
  57. return $jenc;
  58. }
  59. protected function json_error() {
  60. if (($err = json_last_error()) != JSON_ERROR_NONE)
  61. throw new RequestErrorException(json_last_error_msg(), $err);
  62. }
  63. abstract protected function json_set_property($obj);
  64. abstract protected function set_scope(string $method);
  65. public function __destruct() {}
  66. }
  67. ?>