66use Amp \ForbidSerialization ;
77use Amp \Process \Process ;
88use function Amp \ByteStream \buffer ;
9+ use function Amp \ByteStream \splitLines ;
910
1011final class WindowsDnsConfigLoader implements DnsConfigLoader
1112{
@@ -19,15 +20,20 @@ public function __construct(
1920
2021 public function loadConfig (): DnsConfig
2122 {
22- $ wmic = Process::start (['wmic ' , 'NICCONFIG ' , 'GET ' , 'DNSServerSearchOrder ' ]);
23-
24- if ($ wmic ->join () !== 0 ) {
25- throw new DnsConfigException ("Could not fetch DNS servers from WMI: " . buffer ($ wmic ->getStderr ()));
23+ $ powershell = Process::start ([
24+ 'powershell ' ,
25+ '-Command ' ,
26+ 'Get-WmiObject -Class Win32_NetworkAdapterConfiguration |
27+ Select-Object -ExpandProperty DNSServerSearchOrder ' ,
28+ ]);
29+
30+ if ($ powershell ->join () !== 0 ) {
31+ throw new DnsConfigException ("Could not fetch DNS servers from WMI: " . buffer ($ powershell ->getStderr ()));
2632 }
2733
28- $ ips = self :: parseWmicOutput ( buffer ( $ wmic ->getStdout ()));
34+ $ output = \iterator_to_array ( splitLines ( $ powershell ->getStdout ()));
2935
30- $ nameservers = \array_reduce ($ ips , static function (array $ nameservers , string $ address ): array {
36+ $ nameservers = \array_reduce ($ output , static function (array $ nameservers , string $ address ): array {
3137 $ ip = \inet_pton ($ address );
3238
3339 if (isset ($ ip [15 ])) { // IPv6
@@ -43,28 +49,4 @@ public function loadConfig(): DnsConfig
4349
4450 return new DnsConfig ($ nameservers , $ hosts );
4551 }
46-
47- private static function parseWmicOutput (string $ output ): array
48- {
49- // Massage WMIC output into JSON format.
50- $ json = \preg_replace (
51- [
52- // Convert header line into opening bracket.
53- '[^\V*\v+] ' ,
54- // Convert closing braces into commas.
55- '[}] ' ,
56- // Remove final comma.
57- '[,(?=[^,]*+$)] ' ,
58- // Removing opening braces.
59- '[{] ' ,
60- ],
61- [
62- '[ ' ,
63- ', ' ,
64- ],
65- $ output ,
66- );
67-
68- return \json_decode ("$ json] " , true , flags: \JSON_THROW_ON_ERROR );
69- }
7052}
0 commit comments