Orgs.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Gogs\API\Request {
  3. /**
  4. * Orgs is a collection of organizations.
  5. *
  6. * @author Joachim M. Giaever (joachim[]giaever.org)
  7. * @version 0.1
  8. */
  9. final class Orgs extends Collection {
  10. protected $owner;
  11. public function __construct(string $api_url, string $api_token, User $owner) {
  12. $this->owner = $owner;
  13. parent::__construct($api_url, $api_token);
  14. }
  15. protected function set_scope(string $method) {
  16. switch ($method) {
  17. case "get":
  18. $this->scope = ($this->owner == null || $this->owner->authenticated() ? "/user" : "/users/" . $this->owner->uusername) . "/orgs";
  19. return true;
  20. }
  21. }
  22. public function create(...$args) {
  23. $org = new Org($this->url, $this->token, null, $this->owner);
  24. if (count($args) > 0)
  25. $org->create(...$args);
  26. return $org;
  27. }
  28. /**
  29. * Get an organization by indentifier.
  30. *
  31. * Method will first look through organizations
  32. * already loaded. If not found it will return a
  33. * new object.
  34. *
  35. * Method does not ensure the organization in loaded
  36. * from Gogs so the user should call `->load()` on
  37. * returned element.
  38. *
  39. * @param string $s
  40. * @return Org
  41. */
  42. public function get(string $s) {
  43. if (($org = $this->by_key($s)))
  44. return $org;
  45. return new Org($this->url, $this->token, $s, $this->owner);
  46. }
  47. /**
  48. * Search for an organization.
  49. *
  50. * Params can be an array of
  51. * ```php
  52. * $orgs->search(array(
  53. * "name" => "name", // alt. "q". required
  54. * "limit" => 10, // not required, default: 10
  55. * ));
  56. * ```
  57. * By now, this method can be intensive, as it will load
  58. * every organization and then do a match on each entry.
  59. *
  60. * @param array $params
  61. * @return CollectionResult
  62. */
  63. public function search(array $params = array()) {
  64. if (!isset($params["name"]) && !isset($params["q"]))
  65. throw new Exception\SearchParamException("Missing param <name>|<q>");
  66. $q = isset($params["name"]) ? $params["name"] : $params["q"];
  67. $l = isset($params["limit"]) ? $params["limit"] : 10;
  68. $this->load();
  69. $orgs = new CollectionResult();
  70. foreach ($this->all() as $key => $org) {
  71. if ($org->search($q))
  72. $orgs->set($org);
  73. if ($orgs->len() == $l)
  74. break;
  75. }
  76. return $orgs;
  77. }
  78. protected function json_set_property($obj) {
  79. foreach($obj as $val) {
  80. $org = new Org($this->url, $this->token, null, $this->owner);
  81. $org->json_set_property($val);
  82. $this->add($org, $val->username);
  83. }
  84. }
  85. }
  86. }