Completed
Push — master ( bf714f...ee79de )
by thomas
07:40
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 6
    public function registerOutboundPeer(Peer $peer)
58
    {
59 6
        $next = $this->nOutPeers++;
60
        $peer->on('close', function ($peer) use ($next) {
61 3
            $this->emit('disconnect', [$peer]);
62 3
            unset($this->outPeers[$next]);
63 6
        });
64
65 6
        $this->outPeers[$next] = $peer;
66 6
        $this->emit('outbound', [$peer]);
67 6
        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 PacketHandler $packetHandler
98
     */
99
    public function registerHandler(PacketHandler $packetHandler)
100
    {
101
        $attach = function ($connectionType) use ($packetHandler) {
102
            return function (Peer $peer) use ($connectionType, $packetHandler) {
103
                $packetHandler->emit($connectionType, [$peer]);
104
            };
105
        };
106
107
        $this->on('inbound', $attach('inbound'));
108
        $this->on('outbound', $attach('outbound'));
109
    }
110
111
    /**
112
     * @param NetworkAddressInterface $address
113
     * @return \React\Promise\Promise|\React\Promise\PromiseInterface
114
     * @throws \Exception
115
     */
116 6
    public function connect(NetworkAddressInterface $address)
117
    {
118 6
        $peer = $this->peerFactory->getPeer();
119 6
        if ($this->requestRelay) {
120 3
            $peer->requestRelay();
121 3
        }
122
123 6
        $deferred = new Deferred();
124
        $peer
125 6
            ->connect($this->peerFactory->getConnector(), $address)
126 6
            ->then(
127
                function ($peer) use ($deferred) {
128 6
                    $deferred->resolve($peer);
129 6
                },
130
                function () use ($deferred) {
131 2
                    $deferred->reject();
132 2
                }
133 6
            );
134
135 6
        return $deferred->promise();
136
    }
137
138
    /**
139
     * @param Locator $locator
140
     * @return \React\Promise\ExtendedPromiseInterface|\React\Promise\Promise|static
141
     */
142 6
    public function connectNextPeer(Locator $locator)
143
    {
144 6
        $deferred = new Deferred();
145
146
        // Otherwise, rely on the Locator.
147
        try {
148 6
            $deferred->resolve($locator->popAddress());
149 6
        } catch (\Exception $e) {
150 1
            $locator->queryDnsSeeds()->then(
151
                function () use ($deferred, $locator) {
152 1
                    $deferred->resolve($locator->popAddress());
153 1
                }
154 1
            );
155
        }
156
157
        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...
158 6
            ->promise()
159 6
            ->then(
160
                function (NetworkAddressInterface $address) {
161 6
                    return $this->connect($address)->then(
162
                        function (Peer $peer) {
163 6
                            $this->registerOutboundPeer($peer);
164 6
                            return $peer;
165
                        }
166 6
                    );
167
                }
168 6
            )
169 6
            ->otherwise(function () use ($locator) {
170 2
                return $this->connectNextPeer($locator);
171 6
            });
172
    }
173
174
    /**
175
     * Create $n connections to clients available in the PeerLocator
176
     * @param int $n
177
     *
178
     * @param Locator $locator
179
     * @param $n
180
     * @return null|\React\Promise\FulfilledPromise|\React\Promise\Promise|\React\Promise\PromiseInterface|\React\Promise\RejectedPromise|static
181
     */
182 3
    public function connectToPeers(Locator $locator, $n)
183
    {
184 3
        $peers = [];
185 3
        for ($i = 0; $i < $n; $i++) {
186 3
            $peers[$i] = $this->connectNextPeer($locator);
187 3
        }
188
189 3
        return \React\Promise\all($peers);
190
    }
191
}
192