SmmService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace App\Services;
  3. use App\Services\Contracts\SmmPlatformInterface;
  4. use InvalidArgumentException;
  5. class SmmService
  6. {
  7. protected SmmPlatformInterface $platform;
  8. public function __construct(string $platform)
  9. {
  10. $this->platform = $this->resolvePlatform($platform);
  11. }
  12. protected function resolvePlatform(string $platform): SmmPlatformInterface
  13. {
  14. $className = $this->getPlatformClassName($platform);
  15. if (!class_exists($className)) {
  16. throw new InvalidArgumentException("Platform [{$platform}] not supported");
  17. }
  18. $instance = new $className();
  19. if (!$instance instanceof SmmPlatformInterface) {
  20. throw new \RuntimeException("Platform [{$platform}] must implement SmmPlatformInterface");
  21. }
  22. return $instance;
  23. }
  24. protected function getPlatformClassName(string $platform): string {
  25. $platform = ucfirst(strtolower($platform));
  26. return "App\\Services\\Smm\\{$platform}Service";
  27. }
  28. // 代理调用平台方法
  29. public function __call(string $method, array $arguments) {
  30. if (method_exists($this->platform, $method)) {
  31. return $this->platform->{$method}(...$arguments);
  32. }
  33. throw new \BadMethodCallException("Method [{$method}] not found on platform");
  34. }
  35. }