ProxyFactory.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\RpcClient;
  12. use Hyperf\RpcClient\Proxy\Ast;
  13. use Hyperf\RpcClient\Proxy\CodeLoader;
  14. use Hyperf\Utils\Coroutine\Locker;
  15. use Hyperf\Utils\Filesystem\Filesystem;
  16. use Hyperf\Utils\Traits\Container;
  17. class ProxyFactory
  18. {
  19. use Container;
  20. /**
  21. * @var Ast
  22. */
  23. protected $ast;
  24. /**
  25. * @var \Hyperf\RpcClient\Proxy\CodeLoader
  26. */
  27. protected $codeLoader;
  28. /**
  29. * @var Filesystem
  30. */
  31. protected $filesystem;
  32. public function __construct()
  33. {
  34. $this->ast = new Ast();
  35. $this->codeLoader = new CodeLoader();
  36. $this->filesystem = new Filesystem();
  37. }
  38. public function createProxy($serviceClass): string
  39. {
  40. if (self::has($serviceClass)) {
  41. return (string) self::get($serviceClass);
  42. }
  43. $dir = BASE_PATH . '/runtime/container/proxy/';
  44. if (! file_exists($dir)) {
  45. mkdir($dir, 0755, true);
  46. }
  47. $proxyFileName = str_replace('\\', '_', $serviceClass);
  48. $proxyClassName = $serviceClass . '_' . md5($this->codeLoader->getCodeByClassName($serviceClass));
  49. $path = $dir . $proxyFileName . '.rpc-client.proxy.php';
  50. $key = md5($path);
  51. // If the proxy file does not exist, then try to acquire the coroutine lock.
  52. if ($this->isModified($serviceClass, $path) && Locker::lock($key)) {
  53. $targetPath = $path . '.' . uniqid();
  54. $code = $this->ast->proxy($serviceClass, $proxyClassName);
  55. file_put_contents($targetPath, $code);
  56. rename($targetPath, $path);
  57. Locker::unlock($key);
  58. }
  59. include_once $path;
  60. self::set($serviceClass, $proxyClassName);
  61. return $proxyClassName;
  62. }
  63. protected function isModified(string $interface, string $path): bool
  64. {
  65. if (! $this->filesystem->exists($path)) {
  66. return true;
  67. }
  68. $time = $this->filesystem->lastModified(
  69. $this->codeLoader->getPathByClassName($interface)
  70. );
  71. return $time >= $this->filesystem->lastModified($path);
  72. }
  73. }