Completed
Push — master ( f9183d...fce916 )
by thomas
55:20 queued 47:07
created

Manager::connectNextPeer()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 2
Metric Value
c 3
b 1
f 2
dl 0
loc 31
ccs 18
cts 18
cp 1
rs 8.8571
cc 2
eloc 18
nc 2
nop 1
crap 2
1
<?php
2
3
namespace BitWasp\Bitcoin\Networking\Peer;
4
5
use BitWasp\Bitcoin\Networking\Structure\NetworkAddressInterface;
6
use Evenement\EventEmitter;
7
use React\Promise\Deferred;
8
9
class Manager extends EventEmitter
10
{
11
    /**
12
     * @var Factory
13
     */
14
    private $peerFactory;
15
16
    /**
17
     * @var bool|false
18
     */
19
    private $requestRelay;
20
21
    /**
22
     * @var Peer[]
23
     */
24
    private $outPeers = [];
25
26
    /**
27
     * @var Peer[]
28
     */
29
    private $inPeers = [];
30
31
    /**
32
     * @var int
33
     */
34
    private $nOutPeers = 0;
35
36
    /**
37
     * @var int
38
     */
39
    private $nInPeers = 0;
40
41
    /**
42
     * @param Factory $factory
43
     * @param bool|false $requestRelay
44
     */
45 12
    public function __construct(Factory $factory, $requestRelay = false)
46
    {
47 12
        $this->peerFactory = $factory;
48 12
        $this->requestRelay = $requestRelay;
49 12
    }
50
51
    /**
52
     * Store the newly connected peer, and trigger a new connection if they go away.
53
     *
54
     * @param Peer $peer
55
     * @return Peer
56
     */
57 5
    public function registerOutboundPeer(Peer $peer)
58
    {
59 5
        $next = $this->nOutPeers++;
60
        $peer->on('close', function ($peer) use ($next) {
61 3
            $this->emit('disconnect', [$peer]);
62 3
            unset($this->outPeers[$next]);
63 5
        });
64
65 5
        $this->outPeers[$next] = $peer;
66 5
        $this->emit('outbound', [$peer]);
67 5
        return $peer;
68
    }
69
70
    /**
71
     * @param Peer $peer
72
     */
73 3
    public function registerInboundPeer(Peer $peer)
74
    {
75 3
        $next = $this->nInPeers++;
76 3
        $this->inPeers[$next] = $peer;
77
        $peer->on('close', function () use ($next) {
78
            unset($this->inPeers[$next]);
79 3
        });
80 3
        $this->emit('inbound', [$peer]);
81 3
    }
82
83
    /**
84
     * @param Listener $listener
85
     * @return $this
86
     */
87 3
    public function registerListener(Listener $listener)
88
    {
89
        $listener->on('connection', function (Peer $peer) {
90 3
            $this->registerInboundPeer($peer);
91 3
        });
92
93 3
        return $this;
94
    }
95
96
    /**
97
     * @param Recorder $recorder
98
     */
99
    public function registerRecorder(Recorder $recorder)
100
    {
101
        $this->on('outbound', function (Peer $peer) use ($recorder) {
102
            $recorder->save($peer->getRemoteAddr());
103
        });
104
    }
105
106
    /**
107
     * @param PacketHandler $packetHandler
108
     */
109
    public function registerHandler(PacketHandler $packetHandler)
110
    {
111
        $attach = function ($connectionType) use ($packetHandler) {
112
            return function (Peer $peer) use ($connectionType, $packetHandler) {
113
                $packetHandler->emit($connectionType, [$peer]);
114
            };
115
        };
116
117
        $this->on('inbound', $attach('inbound'));
118
        $this->on('outbound', $attach('outbound'));
119
    }
120
121
    /**
122
     * @param NetworkAddressInterface $address
123
     * @return \React\Promise\Promise|\React\Promise\PromiseInterface
124
     * @throws \Exception
125
     */
126 5
    public function connect(NetworkAddressInterface $address)
127
    {
128 5
        $peer = $this->peerFactory->getPeer();
129 5
        if ($this->requestRelay) {
130 3
            $peer->requestRelay();
131 3
        }
132
133 5
        $deferred = new Deferred();
134
        $peer
135 5
            ->connect($this->peerFactory->getConnector(), $address)
136 5
            ->then(
137
                function ($peer) use ($deferred) {
138 5
                    $deferred->resolve($peer);
139 5
                },
140
                function () use ($deferred) {
141 1
                    $deferred->reject();
142 1
                }
143 5
            );
144
145 5
        return $deferred->promise();
146
    }
147
148
    /**
149
     * @param Locator $locator
150
     * @return \React\Promise\ExtendedPromiseInterface|\React\Promise\Promise|static
151
     */
152 5
    public function connectNextPeer(Locator $locator)
153
    {
154 5
        $deferred = new Deferred();
155
156
        // Otherwise, rely on the Locator.
157
        try {
158 5
            $deferred->resolve($locator->popAddress());
159 5
        } catch (\Exception $e) {
160 1
            $locator->queryDnsSeeds()->then(
161
                function () use ($deferred, $locator) {
162 1
                    $deferred->resolve($locator->popAddress());
163 1
                }
164 1
            );
165
        }
166
167
        return $deferred
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface React\Promise\PromiseInterface as the method otherwise() does only exist in the following implementations of said interface: React\Promise\FulfilledPromise, React\Promise\LazyPromise, React\Promise\Promise, React\Promise\RejectedPromise.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
168 5
            ->promise()
169 5
            ->then(
170
                function (NetworkAddressInterface $address) {
171 5
                    return $this->connect($address)->then(
172
                        function (Peer $peer) {
173 5
                            $this->registerOutboundPeer($peer);
174 5
                            return $peer;
175
                        }
176 5
                    );
177
                }
178 5
            )
179 5
            ->otherwise(function () use ($locator) {
180 1
                return $this->connectNextPeer($locator);
181 5
            });
182
    }
183
184
    /**
185
     * Create $n connections to clients available in the PeerLocator
186
     * @param int $n
187
     *
188
     * @param Locator $locator
189
     * @param $n
190
     * @return null|\React\Promise\FulfilledPromise|\React\Promise\Promise|\React\Promise\PromiseInterface|\React\Promise\RejectedPromise|static
191
     */
192 2
    public function connectToPeers(Locator $locator, $n)
193
    {
194 2
        $peers = [];
195 2
        for ($i = 0; $i < $n; $i++) {
196 2
            $peers[$i] = $this->connectNextPeer($locator);
197 2
        }
198
199 2
        return \React\Promise\all($peers);
200
    }
201
}
202