RpcInterface.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace think\swoole\command;
  3. use Nette\PhpGenerator\ClassType;
  4. use Nette\PhpGenerator\Dumper;
  5. use Nette\PhpGenerator\Helpers;
  6. use Nette\PhpGenerator\PhpFile;
  7. use think\console\Command;
  8. use think\helper\Arr;
  9. use think\swoole\contract\rpc\ParserInterface;
  10. use think\swoole\rpc\client\Gateway;
  11. use think\swoole\rpc\JsonParser;
  12. use function Swoole\Coroutine\run;
  13. class RpcInterface extends Command
  14. {
  15. public function configure()
  16. {
  17. $this->setName('rpc:interface')
  18. ->setDescription('Generate Rpc Service Interfaces');
  19. }
  20. public function handle()
  21. {
  22. run(function () {
  23. $file = new PhpFile;
  24. $file->addComment('This file is auto-generated.');
  25. $file->setStrictTypes();
  26. $services = [];
  27. $clients = $this->app->config->get('swoole.rpc.client', []);
  28. foreach ($clients as $name => $config) {
  29. $parserClass = Arr::get($config, 'parser', JsonParser::class);
  30. /** @var ParserInterface $parser */
  31. $parser = new $parserClass;
  32. $gateway = new Gateway($config, $parser);
  33. $result = $gateway->getServices();
  34. $namespace = $file->addNamespace("rpc\\contract\\${name}");
  35. foreach ($result as $interface => $methods) {
  36. $services[$name][] = $namespace->getName() . "\\{$interface}";
  37. $class = $namespace->addInterface($interface);
  38. foreach ($methods as $methodName => ['parameters' => $parameters, 'returnType' => $returnType, 'comment' => $comment]) {
  39. $method = $class->addMethod($methodName)
  40. ->setVisibility(ClassType::VISIBILITY_PUBLIC)
  41. ->setComment(Helpers::unformatDocComment($comment))
  42. ->setReturnType($returnType);
  43. foreach ($parameters as $parameter) {
  44. if ($parameter['type'] && (class_exists($parameter['type']) || interface_exists($parameter['type']))) {
  45. $namespace->addUse($parameter['type']);
  46. }
  47. $param = $method->addParameter($parameter['name'])
  48. ->setType($parameter['type']);
  49. if (array_key_exists('default', $parameter)) {
  50. $param->setDefaultValue($parameter['default']);
  51. }
  52. if (array_key_exists('nullable', $parameter)) {
  53. $param->setNullable();
  54. }
  55. }
  56. }
  57. }
  58. }
  59. $dumper = new Dumper();
  60. $services = 'return ' . $dumper->dump($services) . ';';
  61. file_put_contents($this->app->getBasePath() . 'rpc.php', $file . $services);
  62. $this->output->writeln('<info>Succeed!</info>');
  63. });
  64. }
  65. }