1: <?php
2:
3: namespace React\Socket;
4:
5: use React\EventLoop\LoopInterface;
6: use React\Dns\Resolver\Resolver;
7: use React\Dns\Resolver\Factory;
8: use React\Promise;
9: use RuntimeException;
10:
11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26: final class Connector implements ConnectorInterface
27: {
28: private $connectors = array();
29:
30: public function __construct(LoopInterface $loop, array $options = array())
31: {
32:
33: $options += array(
34: 'tcp' => true,
35: 'tls' => true,
36: 'unix' => true,
37:
38: 'dns' => true,
39: 'timeout' => true,
40: );
41:
42: if ($options['timeout'] === true) {
43: $options['timeout'] = (float)ini_get("default_socket_timeout");
44: }
45:
46: if ($options['tcp'] instanceof ConnectorInterface) {
47: $tcp = $options['tcp'];
48: } else {
49: $tcp = new TcpConnector(
50: $loop,
51: is_array($options['tcp']) ? $options['tcp'] : array()
52: );
53: }
54:
55: if ($options['dns'] !== false) {
56: if ($options['dns'] instanceof Resolver) {
57: $resolver = $options['dns'];
58: } else {
59: $factory = new Factory();
60: $resolver = $factory->create(
61: $options['dns'] === true ? '8.8.8.8' : $options['dns'],
62: $loop
63: );
64: }
65:
66: $tcp = new DnsConnector($tcp, $resolver);
67: }
68:
69: if ($options['tcp'] !== false) {
70: $options['tcp'] = $tcp;
71:
72: if ($options['timeout'] !== false) {
73: $options['tcp'] = new TimeoutConnector(
74: $options['tcp'],
75: $options['timeout'],
76: $loop
77: );
78: }
79:
80: $this->connectors['tcp'] = $options['tcp'];
81: }
82:
83: if ($options['tls'] !== false) {
84: if (!$options['tls'] instanceof ConnectorInterface) {
85: $options['tls'] = new SecureConnector(
86: $tcp,
87: $loop,
88: is_array($options['tls']) ? $options['tls'] : array()
89: );
90: }
91:
92: if ($options['timeout'] !== false) {
93: $options['tls'] = new TimeoutConnector(
94: $options['tls'],
95: $options['timeout'],
96: $loop
97: );
98: }
99:
100: $this->connectors['tls'] = $options['tls'];
101: }
102:
103: if ($options['unix'] !== false) {
104: if (!$options['unix'] instanceof ConnectorInterface) {
105: $options['unix'] = new UnixConnector($loop);
106: }
107: $this->connectors['unix'] = $options['unix'];
108: }
109: }
110:
111: public function connect($uri)
112: {
113: $scheme = 'tcp';
114: if (strpos($uri, '://') !== false) {
115: $scheme = (string)substr($uri, 0, strpos($uri, '://'));
116: }
117:
118: if (!isset($this->connectors[$scheme])) {
119: return Promise\reject(new RuntimeException(
120: 'No connector available for URI scheme "' . $scheme . '"'
121: ));
122: }
123:
124: return $this->connectors[$scheme]->connect($uri);
125: }
126: }
127:
128: