Base.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. namespace Gogs\API\Request {
  3. /**
  4. * Base class for request types.
  5. *
  6. * Each request shall inherit this class to ensure
  7. * it will have the correct methods required by interface,
  8. * and get the cURL functionality.
  9. *
  10. * @deprecated since 0.1, to be removed in 3.0
  11. * @author Joachim M. Giaever (joachim[]giaever.org)
  12. * @abstact
  13. */
  14. abstract class Base implements RequestInterface {
  15. private $tag;
  16. protected $loaded = false;
  17. protected $scope;
  18. use \Gogs\Lib\Curl\Client {
  19. get as private mget;
  20. post as private mpost;
  21. delete as private mdelete;
  22. }
  23. /**
  24. * @param string $api_url The URL to the API.
  25. * @param string $api_token A token for an authorized user
  26. */
  27. public function __construct(string $api_url, string $api_token) {
  28. $this->url = $api_url;
  29. $this->token = $api_token;
  30. $this->tag = strtolower(basename(str_replace("\\", "/", get_class($this))));
  31. }
  32. /**
  33. * Load an object.
  34. *
  35. * If `$force = true` the object will be fetched
  36. * from the Gogs API again.
  37. *
  38. * @deprecated since 2.0 to be removed in 3.0
  39. * @return object
  40. */
  41. final public function load(bool $force = false) {
  42. $this->set_scope("get");
  43. if ($this->loaded && !$force)
  44. return $this;
  45. $jenc = $this->mget($this->scope);
  46. $this->json_set_property($this->json_decode($jenc));
  47. /*
  48. * JSON set property should also do this, but
  49. * to ensure its done, we'll also do it here
  50. */
  51. $this->loaded = true;
  52. return $this;
  53. }
  54. /**
  55. * Perform a GET-request against the Gogs API.
  56. *
  57. * Ensure the correct scope i set first, with
  58. * ```php
  59. * $this->set_scope("*valid scope*"); // e.g create
  60. * ```
  61. *
  62. * @param array $params The parameters
  63. * @return string
  64. */
  65. final protected function method_get(array $params = array()) {
  66. return $this->mget($this->scope, $params);
  67. }
  68. /**
  69. * Perform a POST-request against the Gogs API.
  70. *
  71. * Ensure the correct scope i set first, with
  72. * ```php
  73. * $this->set_scope("*valid scope*"); // e.g create
  74. * ```
  75. *
  76. * @param array $params The parameters
  77. * @return string
  78. */
  79. final protected function method_post(array $params = array()) {
  80. return $this->mpost($this->scope, $params);
  81. }
  82. /**
  83. * Perform a DELETE-request against the Gogs API.
  84. *
  85. * Ensure the correct scope i set first, with
  86. * ```php
  87. * $this->set_scope("*valid scope*"); // e.g delete
  88. * ```
  89. *
  90. * @return string
  91. */
  92. final protected function method_delete() {
  93. return $this->mdelete($this->scope);
  94. }
  95. /**
  96. * Get object references by identifier.
  97. *
  98. * @param string $s Identifier to look up.
  99. * @return null
  100. */
  101. public function get(string $s) {
  102. if (!$this->set_scope("get"))
  103. throw new Exception\NotImplementedException("::get:: Not implemented for class '" . get_class($this) . "'");
  104. return null;
  105. }
  106. /**
  107. * Create object inherited by class.
  108. *
  109. * Child class must add a scope for 'create' and ensure child is not *loaded*,
  110. * otherwise will `create` throw an exception.
  111. *
  112. * @param string $args yeah, well
  113. * @return true
  114. * @throws Exception\InvalidMethodRequestException
  115. * @throws Exception\NotImplementedException
  116. */
  117. public function create(...$args) {
  118. if ($this->loaded)
  119. throw new Exception\InvalidMethodRequestException("::create:: Cant create on an git-initialized object. Create new object.");
  120. if (!$this->set_scope("create"))
  121. throw new Exception\NotImplementedException("::create:: Not implemented for class '" . get_class($this) . "'");
  122. $ret = $this->method_post(...$args);
  123. $this->json_set_property($this->json_decode($ret));
  124. return true;
  125. }
  126. /**
  127. * Patch (update) object
  128. *
  129. * @throws Exception\InvalidMethodRequestException
  130. * @throws Exception\NotImplementedException
  131. */
  132. public function patch() {
  133. if (!$this->loaded)
  134. throw new Exception\InvalidMethodRequestException("::patch:: Cant patch an git-uninitialized object. Load it first.");
  135. if (!$this->set_scope("patch"))
  136. throw new Exception\NotImplementedException("::patch:: Not implemented for class '" . get_class($this) . "'");
  137. }
  138. /**
  139. * Delete object.
  140. *
  141. * @throws Exception\NotImplementedException
  142. */
  143. public function delete() {
  144. if (!$this->set_scope("delete"))
  145. throw new Exception\NotImplementedException("::delete:: Not implemented for class '" . get_class($this) . "'");
  146. return $this->method_delete();
  147. }
  148. /**
  149. * Decode JSON-string.
  150. *
  151. * Will ensure that there weren't any errors by calling `$this->json_error`.
  152. *
  153. * @param string $jenc Encoded JSON string
  154. * @return object
  155. */
  156. final protected function json_decode(string $jenc) {
  157. $obj = json_decode($jenc);
  158. $this->json_error();
  159. return $obj;
  160. }
  161. /**
  162. * Encode JSON-object/array.
  163. *
  164. * Will ensure that there weren't any errors by calling `$this->json_error`.
  165. *
  166. * @param iterable $jdec JSON-data
  167. * @return string
  168. */
  169. final protected function json_encode(iterable $jdec) {
  170. $jenc = json_encode($jdec);
  171. $this->json_error();
  172. return $jenc;
  173. }
  174. /**
  175. * Check for errors on encoding/decoding.
  176. *
  177. * @throws Exception\RequestErrorException
  178. */
  179. final protected function json_error() {
  180. if (($err = json_last_error()) != JSON_ERROR_NONE)
  181. throw new Exception\RequestErrorException(json_last_error_msg(), $err);
  182. }
  183. /**
  184. * Get basename of a class (remove namespace).
  185. *
  186. * @param string $class The FQN
  187. * @return string
  188. */
  189. private function basename_class(string $class) {
  190. return strtolower(basename(str_replace("\\", "/", $class)));
  191. }
  192. /**
  193. * Return basename of parent class.
  194. *
  195. * @return string
  196. */
  197. private function get_parent() {
  198. $parent = get_parent_class($this);
  199. if ($parent != __CLASS__)
  200. return $this->basename_class($parent);
  201. return null;
  202. }
  203. /**
  204. * Get property key by name.
  205. *
  206. * Classes sets property from json directly, but they are
  207. * named within the class by `classname_propertyname`. This
  208. * method returns the key name.
  209. *
  210. * @param string $name Name of the key
  211. * @param bool $parent Get key in parent
  212. * @return string
  213. */
  214. final private function key(string $name, bool $parent = false) {
  215. $tag = sprintf("%s_", $this->tag);
  216. if (strpos($name, $tag) === 0) {
  217. if ($parent && !empty($ptag = $this->get_parent()))
  218. return sprintf("%s_%s", $ptag, substr($name, strlen($tag)));
  219. return $name . "?";
  220. }
  221. if ($parent && !empty($ptag = $this->get_parent()))
  222. return sprintf("%s_%s", $ptag, $name);
  223. return $tag . $name;
  224. }
  225. /**
  226. * Checks if the property (key) exists within self
  227. * or parent class.
  228. *
  229. * Returns the actual key if it does. A class key (aka property)
  230. * start with the tag `classname_` followed by property name,
  231. * reflecting the JSON-object, and can be reached by
  232. *
  233. * * `$class->parameter`,
  234. * * `$class->classname_parameter` or alternatively (for classes that inherits another class).
  235. * * `$class->parentclassname_parameter`.
  236. *
  237. * If a class override a parent class with the same parameter,
  238. * the class's own parameter will be favoured.
  239. *
  240. * As this is public properties this wont be an security issue;
  241. *
  242. * @param $name Name of the key.
  243. * @return string|false False on failure
  244. */
  245. final protected function property_exists($name) {
  246. if (property_exists($this, $key = $this->key($name)))
  247. return $key;
  248. if (property_exists($this, $key = $this->key($name, true)))
  249. return $key;
  250. return false;
  251. }
  252. /**
  253. * Get property by name.
  254. *
  255. * Checks both self and parent for the property.
  256. *
  257. * Returns the value if property exists, otherwise an `E_USER_NOTICE`
  258. * is triggered.
  259. *
  260. * @param string $name
  261. * @return mixed|null Null when unknown
  262. */
  263. final public function __get(string $name) {
  264. $key = $this->property_exists($name);
  265. if ($key)
  266. return $this->{$key};
  267. $trace = debug_backtrace();
  268. trigger_error(
  269. sprintf(
  270. "Undefined property '%s' {%s} in '%s' on line %s. Neither does its parent '%s'",
  271. $name,
  272. $this->key($name),
  273. $trace[0]["file"],
  274. $trace[0]["line"],
  275. $this->basename_class(get_parent_class($this))
  276. ),
  277. E_USER_NOTICE
  278. );
  279. return null;
  280. }
  281. /**
  282. * Set property by name.
  283. *
  284. * Checks both self and parent for the property.
  285. *
  286. * Returns the value if property exists, otherwise an `E_USER_NOTICE`
  287. * is triggered.
  288. *
  289. * @param string $name Property name
  290. * @param mixed $value Property value
  291. * @return mixed|null Null when unknown
  292. */
  293. final public function __set(string $name, $value) {
  294. $key = $this->property_exists($name);
  295. if ($key)
  296. return $this->{$key} = $value;
  297. $trace = debug_backtrace();
  298. trigger_error(
  299. sprintf(
  300. "Undefined property '%s' {%s} in '%s' on line %s. Neither does its parent '%s'",
  301. $name,
  302. $this->key($name),
  303. $trace[0]["file"],
  304. $trace[0]["line"],
  305. $this->basename_class(get_parent_class($this))
  306. ),
  307. E_USER_NOTICE
  308. );
  309. return null;
  310. }
  311. /**
  312. * Checks if property is set.
  313. *
  314. * Checks both self and parent for property.
  315. *
  316. * Triggers E_USER_NOTICE if property is unknown.
  317. *
  318. * @param string $name Property name
  319. * @return bool
  320. */
  321. final public function __isset(string $name) {
  322. $key = $this->property_exists($name);
  323. if ($key)
  324. return isset($this->{$key});
  325. $trace = debug_backtrace();
  326. trigger_error(
  327. sprintf(
  328. "Undefined property '%s' {%s} in '%s' on line %s. Neither does its parent '%s'",
  329. $name,
  330. $this->key($name),
  331. $trace[0]["file"],
  332. $trace[0]["line"],
  333. $this->basename_class(get_parent_class($this))
  334. ),
  335. E_USER_NOTICE
  336. );
  337. return false;
  338. }
  339. /**
  340. * Set properties for the current object.
  341. *
  342. * Each child class must implement this to set its data. Will
  343. * be called by methods such as `load` and from collection
  344. * classes.
  345. *
  346. * Will return true/false for singel objects but an array on collections.
  347. * The array will contain the newly inserted elements. This to prevent
  348. * additional iterations.
  349. *
  350. * This method should also set loaded to true or false, depending
  351. * on success or failure.
  352. *
  353. * @see Collection
  354. * @param mixed $obj
  355. * @return true|array
  356. */
  357. abstract protected function json_set_property($obj);
  358. /**
  359. * Set the scope for the request methods accepted by the child.
  360. *
  361. * This can be
  362. * * `get`,
  363. * * `search`,
  364. * * `delete` etc.
  365. *
  366. * Must return true if scope exists of false otherwise. Methods
  367. * the calls this will throw an exception if not true is returned.
  368. *
  369. * @param string $method Method type, e.g "get"
  370. * @return bool
  371. */
  372. abstract protected function set_scope(string $method);
  373. }
  374. }
  375. ?>