RequestOptions.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Pingpp\Util;
  3. use Pingpp\Error;
  4. class RequestOptions
  5. {
  6. public $headers;
  7. public $apiKey;
  8. public function __construct($key = null, $headers = array())
  9. {
  10. $this->apiKey = $key;
  11. $this->headers = $headers;
  12. }
  13. /**
  14. * Unpacks an options array and merges it into the existing RequestOptions
  15. * object.
  16. * @param array|string|null $options a key => value array
  17. *
  18. * @return RequestOptions
  19. */
  20. public function merge($options)
  21. {
  22. $other_options = self::parse($options);
  23. if ($other_options->apiKey === null) {
  24. $other_options->apiKey = $this->apiKey;
  25. }
  26. $other_options->headers = array_merge($this->headers, $other_options->headers);
  27. return $other_options;
  28. }
  29. /**
  30. * Unpacks an options array into an RequestOptions object
  31. * @param array|string|null $options a key => value array
  32. *
  33. * @return RequestOptions
  34. */
  35. public static function parse($options)
  36. {
  37. if ($options instanceof self) {
  38. return $options;
  39. }
  40. if (is_null($options)) {
  41. return new RequestOptions(null, array());
  42. }
  43. if (is_string($options)) {
  44. return new RequestOptions($options, array());
  45. }
  46. if (is_array($options)) {
  47. $headers = array();
  48. $key = null;
  49. if (array_key_exists('api_key', $options)) {
  50. $key = $options['api_key'];
  51. }
  52. if (array_key_exists('pingpp_version', $options)) {
  53. $headers['Pingpp-Version'] = $options['pingpp_version'];
  54. }
  55. return new RequestOptions($key, $headers);
  56. }
  57. $message = 'The second argument to Pingpp API method calls is an '
  58. . 'optional per-request apiKey, which must be a string, or '
  59. . 'per-request options, which must be an array. (HINT: you can set '
  60. . 'a global apiKey by "Pingpp::setApiKey(<apiKey>)")';
  61. throw new Error\Api($message);
  62. }
  63. }