Completed
Push — master ( 4c10a8...999ca2 )
by thomas
8s
created

Manager::connectNextPeer()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2.0857

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 31
ccs 13
cts 18
cp 0.7221
rs 8.8571
cc 2
eloc 18
nc 2
nop 1
crap 2.0857
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 Connector
13
     */
14
    private $connector;
15
16
    /**
17
     * @var Peer[]
18
     */
19
    private $outPeers = [];
20
21
    /**
22
     * @var Peer[]
23
     */
24
    private $inPeers = [];
25
26
    /**
27
     * @var int
28
     */
29
    private $nOutPeers = 0;
30
31
    /**
32
     * @var int
33
     */
34
    private $nInPeers = 0;
35
36
    /**
37
     * Manager constructor.
38
     * @param Connector $connector
39
     */
40 6
    public function __construct(Connector $connector)
41
    {
42 6
        $this->connector = $connector;
43 6
    }
44
45
    /**
46
     * Store the newly connected peer, and trigger a new connection if they go away.
47
     *
48
     * @param Peer $peer
49
     * @return Peer
50
     */
51 3
    public function registerOutboundPeer(Peer $peer)
52
    {
53 3
        $next = $this->nOutPeers++;
54
        $peer->on('close', function ($peer) use ($next) {
55 3
            $this->emit('disconnect', [$peer]);
56 3
            unset($this->outPeers[$next]);
57 3
        });
58
59 3
        $this->outPeers[$next] = $peer;
60 3
        $this->emit('outbound', [$peer]);
61 3
        return $peer;
62
    }
63
64
    /**
65
     * @param Peer $peer
66
     */
67 3
    public function registerInboundPeer(Peer $peer)
68
    {
69 3
        $next = $this->nInPeers++;
70 3
        $this->inPeers[$next] = $peer;
71
        $peer->on('close', function () use ($next) {
72
            unset($this->inPeers[$next]);
73 3
        });
74 3
        $this->emit('inbound', [$peer]);
75 3
    }
76
77
    /**
78
     * @param Listener $listener
79
     * @return $this
80
     */
81 3
    public function registerListener(Listener $listener)
82
    {
83
        $listener->on('connection', function (Peer $peer) {
84 3
            $this->registerInboundPeer($peer);
85 3
        });
86
87 3
        return $this;
88
    }
89
90
    /**
91
     * @param NetworkAddressInterface $address
92
     * @return \React\Promise\PromiseInterface
93
     * @throws \Exception
94
     */
95 3
    public function connect(NetworkAddressInterface $address)
96
    {
97 3
        return $this->connector->connect($address);
98
    }
99
100
    /**
101
     * @param Locator $locator
102
     * @return \React\Promise\ExtendedPromiseInterface
103
     */
104 3
    public function connectNextPeer(Locator $locator)
105
    {
106 3
        $deferred = new Deferred();
107
108
        // Otherwise, rely on the Locator.
109
        try {
110 3
            $deferred->resolve($locator->popAddress());
111 3
        } catch (\Exception $e) {
112
            $locator->queryDnsSeeds()->then(
113
                function () use ($deferred, $locator) {
114
                    $deferred->resolve($locator->popAddress());
115
                }
116
            );
117
        }
118
119
        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...
120 3
            ->promise()
121 3
            ->then(
122
                function (NetworkAddressInterface $address) {
123 3
                    return $this->connect($address)->then(
124
                        function (Peer $peer) {
125 3
                            $this->registerOutboundPeer($peer);
126 3
                            return $peer;
127
                        }
128 3
                    );
129
                }
130 3
            )
131 3
            ->otherwise(function () use ($locator) {
132
                return $this->connectNextPeer($locator);
133 3
            });
134
    }
135
136
    /**
137
     * Create $n connections to clients available in the PeerLocator
138
     * @param int $n
139
     *
140
     * @param Locator $locator
141
     * @param $n
142
     * @return null|\React\Promise\FulfilledPromise|\React\Promise\Promise|\React\Promise\PromiseInterface|\React\Promise\RejectedPromise|static
143
     */
144 3
    public function connectToPeers(Locator $locator, $n)
145
    {
146 3
        $peers = [];
147 3
        for ($i = 0; $i < $n; $i++) {
148 3
            $peers[$i] = $this->connectNextPeer($locator);
149 3
        }
150
151 3
        return \React\Promise\all($peers);
152
    }
153
}
154