AbstractService.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Stripe\Service;
  3. /**
  4. * Abstract base class for all services.
  5. */
  6. abstract class AbstractService
  7. {
  8. /**
  9. * @var \Stripe\StripeClientInterface
  10. */
  11. protected $client;
  12. /**
  13. * Initializes a new instance of the {@link AbstractService} class.
  14. *
  15. * @param \Stripe\StripeClientInterface $client
  16. */
  17. public function __construct($client)
  18. {
  19. $this->client = $client;
  20. }
  21. /**
  22. * Gets the client used by this service to send requests.
  23. *
  24. * @return \Stripe\StripeClientInterface
  25. */
  26. public function getClient()
  27. {
  28. return $this->client;
  29. }
  30. /**
  31. * Translate null values to empty strings. For service methods,
  32. * we interpret null as a request to unset the field, which
  33. * corresponds to sending an empty string for the field to the
  34. * API.
  35. *
  36. * @param null|array $params
  37. */
  38. private static function formatParams($params)
  39. {
  40. if (null === $params) {
  41. return null;
  42. }
  43. \array_walk_recursive($params, function (&$value, $key) {
  44. if (null === $value) {
  45. $value = '';
  46. }
  47. });
  48. return $params;
  49. }
  50. protected function request($method, $path, $params, $opts)
  51. {
  52. return $this->getClient()->request($method, $path, static::formatParams($params), $opts);
  53. }
  54. protected function requestCollection($method, $path, $params, $opts)
  55. {
  56. return $this->getClient()->requestCollection($method, $path, static::formatParams($params), $opts);
  57. }
  58. protected function buildPath($basePath, ...$ids)
  59. {
  60. foreach ($ids as $id) {
  61. if (null === $id || '' === \trim($id)) {
  62. $msg = 'The resource ID cannot be null or whitespace.';
  63. throw new \Stripe\Exception\InvalidArgumentException($msg);
  64. }
  65. }
  66. return \sprintf($basePath, ...\array_map('\urlencode', $ids));
  67. }
  68. }