RequestOptions.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Stripe\Util;
  3. use Stripe\Error;
  4. class RequestOptions
  5. {
  6. /**
  7. * @var array A list of headers that should be persisted across requests.
  8. */
  9. public static $HEADERS_TO_PERSIST = [
  10. 'Stripe-Account',
  11. 'Stripe-Version',
  12. ];
  13. public $headers;
  14. public $apiKey;
  15. public function __construct($key = null, $headers = [])
  16. {
  17. $this->apiKey = $key;
  18. $this->headers = $headers;
  19. }
  20. /**
  21. * Unpacks an options array and merges it into the existing RequestOptions
  22. * object.
  23. * @param array|string|null $options a key => value array
  24. *
  25. * @return RequestOptions
  26. */
  27. public function merge($options)
  28. {
  29. $other_options = self::parse($options);
  30. if ($other_options->apiKey === null) {
  31. $other_options->apiKey = $this->apiKey;
  32. }
  33. $other_options->headers = array_merge($this->headers, $other_options->headers);
  34. return $other_options;
  35. }
  36. /**
  37. * Discards all headers that we don't want to persist across requests.
  38. */
  39. public function discardNonPersistentHeaders()
  40. {
  41. foreach ($this->headers as $k => $v) {
  42. if (!in_array($k, self::$HEADERS_TO_PERSIST)) {
  43. unset($this->headers[$k]);
  44. }
  45. }
  46. }
  47. /**
  48. * Unpacks an options array into an RequestOptions object
  49. * @param array|string|null $options a key => value array
  50. *
  51. * @return RequestOptions
  52. */
  53. public static function parse($options)
  54. {
  55. if ($options instanceof self) {
  56. return $options;
  57. }
  58. if (is_null($options)) {
  59. return new RequestOptions(null, []);
  60. }
  61. if (is_string($options)) {
  62. return new RequestOptions($options, []);
  63. }
  64. if (is_array($options)) {
  65. $headers = [];
  66. $key = null;
  67. if (array_key_exists('api_key', $options)) {
  68. $key = $options['api_key'];
  69. }
  70. if (array_key_exists('idempotency_key', $options)) {
  71. $headers['Idempotency-Key'] = $options['idempotency_key'];
  72. }
  73. if (array_key_exists('stripe_account', $options)) {
  74. $headers['Stripe-Account'] = $options['stripe_account'];
  75. }
  76. if (array_key_exists('stripe_version', $options)) {
  77. $headers['Stripe-Version'] = $options['stripe_version'];
  78. }
  79. return new RequestOptions($key, $headers);
  80. }
  81. $message = 'The second argument to Stripe API method calls is an '
  82. . 'optional per-request apiKey, which must be a string, or '
  83. . 'per-request options, which must be an array. (HINT: you can set '
  84. . 'a global apiKey by "Stripe::setApiKey(<apiKey>)")';
  85. throw new Error\Api($message);
  86. }
  87. }