ApiBase.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Remote\Api;
  7. use OCP\Http\Client\IClientService;
  8. use OCP\Remote\ICredentials;
  9. use OCP\Remote\IInstance;
  10. class ApiBase {
  11. /** @var IInstance */
  12. private $instance;
  13. /** @var ICredentials */
  14. private $credentials;
  15. /** @var IClientService */
  16. private $clientService;
  17. public function __construct(IInstance $instance, ICredentials $credentials, IClientService $clientService) {
  18. $this->instance = $instance;
  19. $this->credentials = $credentials;
  20. $this->clientService = $clientService;
  21. }
  22. protected function getHttpClient() {
  23. return $this->clientService->newClient();
  24. }
  25. protected function addDefaultHeaders(array $headers) {
  26. return array_merge([
  27. 'OCS-APIREQUEST' => 'true',
  28. 'Accept' => 'application/json'
  29. ], $headers);
  30. }
  31. /**
  32. * @param string $method
  33. * @param string $url
  34. * @param array $body
  35. * @param array $query
  36. * @param array $headers
  37. * @return resource|string
  38. * @throws \InvalidArgumentException
  39. */
  40. protected function request($method, $url, array $body = [], array $query = [], array $headers = []) {
  41. $fullUrl = trim($this->instance->getFullUrl(), '/') . '/' . $url;
  42. $options = [
  43. 'query' => $query,
  44. 'headers' => $this->addDefaultHeaders($headers),
  45. 'auth' => [$this->credentials->getUsername(), $this->credentials->getPassword()]
  46. ];
  47. if ($body) {
  48. $options['body'] = $body;
  49. }
  50. $client = $this->getHttpClient();
  51. switch ($method) {
  52. case 'get':
  53. $response = $client->get($fullUrl, $options);
  54. break;
  55. case 'post':
  56. $response = $client->post($fullUrl, $options);
  57. break;
  58. case 'put':
  59. $response = $client->put($fullUrl, $options);
  60. break;
  61. case 'delete':
  62. $response = $client->delete($fullUrl, $options);
  63. break;
  64. case 'options':
  65. $response = $client->options($fullUrl, $options);
  66. break;
  67. default:
  68. throw new \InvalidArgumentException('Invalid method ' . $method);
  69. }
  70. return $response->getBody();
  71. }
  72. }