UnixConnector.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. public function __construct(LoopInterface $loop = null)
  18. {
  19. $this->loop = $loop ?: Loop::get();
  20. }
  21. public function connect($path)
  22. {
  23. if (\strpos($path, '://') === false) {
  24. $path = 'unix://' . $path;
  25. } elseif (\substr($path, 0, 7) !== 'unix://') {
  26. return Promise\reject(new \InvalidArgumentException(
  27. 'Given URI "' . $path . '" is invalid (EINVAL)',
  28. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22
  29. ));
  30. }
  31. $resource = @\stream_socket_client($path, $errno, $errstr, 1.0);
  32. if (!$resource) {
  33. return Promise\reject(new \RuntimeException(
  34. 'Unable to connect to unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno),
  35. $errno
  36. ));
  37. }
  38. $connection = new Connection($resource, $this->loop);
  39. $connection->unix = true;
  40. return Promise\resolve($connection);
  41. }
  42. }