DnsResolver::resolve()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.1308

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 4
nop 1
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
crap 6.1308
rs 8.7624
c 0
b 0
f 0
1
<?php
2
/**
3
 * Nucleus - XMPP Library for PHP
4
 *
5
 * Copyright (C) 2016, Some rights reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Xmpp\Utils;
17
18
use Traversable;
19
20
class DnsResolver implements \IteratorAggregate
21
{
22
    private $_results;
23
    private $_port;
24
    private $_pool;
25
26 1
    public function __construct(array $pool, int $port)
27
    {
28 1
        $this->_pool = $pool;
29 1
        $this->_port = $port;
30 1
    }
31
32
    /**
33
     * Retrieve an external iterator
34
     *
35
     * @link  http://php.net/manual/en/iteratoraggregate.getiterator.php
36
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
37
     *        <b>Traversable</b>
38
     * @since 5.0.0
39
     */
40 1
    public function getIterator()
41
    {
42 1
        $this->resolve();
43
44 1
        return new \ArrayIterator($this->_results);
45
    }
46
47 1
    public function resolve(bool $force = false) : bool
48
    {
49 1
        if (!$force && is_array($this->_results)) {
50
            return true;
51
        }
52
53 1
        $this->_results = [];
54 1
        foreach ($this->_pool as $address => $type) {
55 1
            if (!($result = dns_get_record($address, $type))) {
56
                continue;
57
            }
58
59 1
            $this->_results = array_merge($this->_results, array_map(function ($record) use($type) {
60 1
                return $type === DNS_SRV
61 1
                    ? [$record['target'], $record['port']]
62 1
                    : [$record['ip'], $this->_port];
63 1
            }, $result));
64
        }
65
66 1
        return true;
67
    }
68
}
69