Skip to content

Commit 41e5596

Browse files
committed
[dns] Factory to load config from /etc/resolv.conf
1 parent 2d98323 commit 41e5596

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Config/Config.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace React\Dns\Config;
4+
5+
class Config
6+
{
7+
public $nameservers = array();
8+
}

Config/FilesystemFactory.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace React\Dns\Config;
4+
5+
use React\EventLoop\LoopInterface;
6+
use React\Stream\Stream;
7+
8+
class FilesystemFactory
9+
{
10+
private $loop;
11+
12+
public function __construct(LoopInterface $loop)
13+
{
14+
$this->loop = $loop;
15+
}
16+
17+
public function create($filename, $callback)
18+
{
19+
$that = $this;
20+
21+
$this->loadEtcResolvConf($filename, function ($contents) use ($that, $callback) {
22+
return $that->parseEtcResolvConf($contents, $callback);
23+
});
24+
}
25+
26+
public function parseEtcResolvConf($contents, $callback)
27+
{
28+
$nameservers = array();
29+
30+
$contents = preg_replace('/^#/', '', $contents);
31+
$lines = preg_split('/\r?\n/is', $contents);
32+
foreach ($lines as $line) {
33+
if (preg_match('/^nameserver (.+)/', $line, $match)) {
34+
$nameservers[] = $match[1];
35+
}
36+
}
37+
38+
$config = new Config();
39+
$config->nameservers = $nameservers;
40+
41+
$callback($config);
42+
}
43+
44+
public function loadEtcResolvConf($filename, $callback)
45+
{
46+
if (!file_exists($filename)) {
47+
throw new \InvalidArgumentException("The filename for /etc/resolv.conf given does not exist: $filename");
48+
}
49+
50+
$fd = fopen($filename, 'r');
51+
stream_set_blocking($fd, 0);
52+
53+
$contents = '';
54+
55+
$stream = new Stream($fd, $this->loop);
56+
$stream->on('data', function ($data) use (&$contents) {
57+
$contents .= $data;
58+
});
59+
$stream->on('end', function () use (&$contents, $callback) {
60+
call_user_func($callback, $contents);
61+
});
62+
}
63+
}

0 commit comments

Comments
 (0)