UnixConnector.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace React\Socket;
  3. use React\EventLoop\Loop;
  4. use React\EventLoop\LoopInterface;
  5. use React\Promise;
  6. use InvalidArgumentException;
  7. use RuntimeException;
  8. /**
  9. * Unix domain socket connector
  10. *
  11. * Unix domain sockets use atomic operations, so we can as well emulate
  12. * async behavior.
  13. */
  14. final class UnixConnector implements ConnectorInterface
  15. {
  16. private $loop;
  17. /**
  18. * @param ?LoopInterface $loop
  19. */
  20. public function __construct($loop = null)
  21. {
  22. if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
  23. throw new \InvalidArgumentException('Argument #1 ($loop) expected null|React\EventLoop\LoopInterface');
  24. }
  25. $this->loop = $loop ?: Loop::get();
  26. }
  27. public function connect($path)
  28. {
  29. if (\strpos($path, '://') === false) {
  30. $path = 'unix://' . $path;
  31. } elseif (\substr($path, 0, 7) !== 'unix://') {
  32. return Promise\reject(new \InvalidArgumentException(
  33. 'Given URI "' . $path . '" is invalid (EINVAL)',
  34. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  35. ));
  36. }
  37. $resource = @\stream_socket_client($path, $errno, $errstr, 1.0);
  38. if (!$resource) {
  39. return Promise\reject(new \RuntimeException(
  40. 'Unable to connect to unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno),
  41. $errno
  42. ));
  43. }
  44. $connection = new Connection($resource, $this->loop);
  45. $connection->unix = true;
  46. return Promise\resolve($connection);
  47. }
  48. }