AbstractServiceFactory.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Stripe\Service;
  3. /**
  4. * Abstract base class for all service factories used to expose service
  5. * instances through {@link \Stripe\StripeClient}.
  6. *
  7. * Service factories serve two purposes:
  8. *
  9. * 1. Expose properties for all services through the `__get()` magic method.
  10. * 2. Lazily initialize each service instance the first time the property for
  11. * a given service is used.
  12. */
  13. abstract class AbstractServiceFactory
  14. {
  15. /** @var \Stripe\StripeClientInterface */
  16. private $client;
  17. /** @var array<string, AbstractService|AbstractServiceFactory> */
  18. private $services;
  19. /**
  20. * @param \Stripe\StripeClientInterface $client
  21. */
  22. public function __construct($client)
  23. {
  24. $this->client = $client;
  25. $this->services = [];
  26. }
  27. /**
  28. * @param string $name
  29. *
  30. * @return null|string
  31. */
  32. abstract protected function getServiceClass($name);
  33. /**
  34. * @param string $name
  35. *
  36. * @return null|AbstractService|AbstractServiceFactory
  37. */
  38. public function __get($name)
  39. {
  40. $serviceClass = $this->getServiceClass($name);
  41. if (null !== $serviceClass) {
  42. if (!\array_key_exists($name, $this->services)) {
  43. $this->services[$name] = new $serviceClass($this->client);
  44. }
  45. return $this->services[$name];
  46. }
  47. \trigger_error('Undefined property: ' . static::class . '::$' . $name);
  48. return null;
  49. }
  50. }