GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#22)
by Cees-Jan
07:20
created

Factory::parentFromClass()   C

Complexity

Conditions 11
Paths 2

Size

Total Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 20.7823

Importance

Changes 0
Metric Value
dl 0
loc 70
ccs 21
cts 37
cp 0.5676
rs 6.5077
c 0
b 0
f 0
cc 11
nc 2
nop 3
crap 20.7823

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace WyriHaximus\React\ChildProcess\Messenger;
4
5
use React\ChildProcess\Process;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, WyriHaximus\React\ChildProcess\Messenger\Process.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use React\EventLoop\LoopInterface;
7
use React\Promise;
8
use React\Socket\ConnectionInterface;
9
use React\Socket\Connector;
10
use React\Socket\Server;
11
use WyriHaximus\FileDescriptors\Factory as FileDescriptorsFactory;
12
use WyriHaximus\FileDescriptors\ListerInterface;
13
use WyriHaximus\React\ChildProcess\Messenger\Messages\Factory as MessengesFactory;
14
use WyriHaximus\React\ChildProcess\Messenger\Messages\Payload;
15
16
final class Factory
17
{
18
    const INTERVAL = 0.1;
19
    const TIMEOUT = 13;
20
    const TERMINATE_TIMEOUT = 1;
21
    const PROCESS_REGISTER = 'wyrihaximus.react.child-process.messenger.child.register';
22
23
    public static function parent(
24
        Process $process,
25
        LoopInterface $loop,
26
        array $options = []
27
    ) {
28
        return new Promise\Promise(function ($resolve, $reject) use ($process, $loop, $options) {
29
            $server = new Server('127.0.0.1:0', $loop);
30
            $argvString = \escapeshellarg(ArgvEncoder::encode([
31
                'address' => $server->getAddress(),
32
            ]));
33
34
            $process = new Process($process->getCommand() . ' ' . $argvString);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $process, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
35
36
            self::startParent($process, $server, $loop, $options)->done($resolve, $reject);
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 done() 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...
37
        });
38
    }
39
40
    /**
41
     * @param  string                              $class
42
     * @param  LoopInterface                       $loop
43
     * @param  array                               $options
44
     * @return Promise\PromiseInterface<Messenger>
0 ignored issues
show
Documentation introduced by
The doc-type Promise\PromiseInterface<Messenger> could not be parsed: Expected "|" or "end of type", but got "<" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
45 2
     */
46
    public static function parentFromClass(
47
        $class,
48
        LoopInterface $loop,
49
        array $options = []
50 2
    ) {
51 1
        if (!\is_subclass_of($class, 'WyriHaximus\React\ChildProcess\Messenger\ChildInterface')) {
52
            throw new \Exception('Given class doesn\'t implement ChildInterface');
53
        }
54
55 1
        return new Promise\Promise(function ($resolve, $reject) use ($class, $loop, $options) {
56 1
            $server = new Server('127.0.0.1:0', $loop);
57 1
            $options['address'] = $server->getAddress();
58
            $options['random'] = \bin2hex(\random_bytes(512));
59 1
60 1
            $template = '%s';
61
            if (isset($options['cmdTemplate'])) {
62
                $template = $options['cmdTemplate'];
63
                unset($options['cmdTemplate']);
64
            }
65 1
66 1
            $fds = [];
67 1
            if (\DIRECTORY_SEPARATOR !== '\\') {
68 1
                if (isset($options['fileDescriptorLister']) && $options['fileDescriptorLister'] instanceof ListerInterface) {
69 1
                    /** @var ListerInterface $fileDescriptorLister */
70 1
                    $fileDescriptorLister = $options['fileDescriptorLister'];
71 1
                    unset($options['fileDescriptorLister']);
72 1
                }
73
74
                if (!isset($fileDescriptorLister)) {
75
                    /** @var ListerInterface $fileDescriptorLister */
76
                    $fileDescriptorLister = FileDescriptorsFactory::create();
77 1
                }
78 1
79
                if (\method_exists($fileDescriptorLister, 'list')) {
80 1
                    $fds = $fileDescriptorLister->list();
0 ignored issues
show
Bug introduced by
The method list() does not seem to exist on object<WyriHaximus\FileD...iptors\ListerInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
81 1
                } else {
82 1
                    $fds = $fileDescriptorLister->listFileDescriptors();
83 1
                }
84
                foreach ($fds as $id) {
85
                    $fds[(int)$id] = ['file', '/dev/null', 'r'];
86
                }
87
            }
88
89
            $phpBinary = \escapeshellarg(PHP_BINARY . (PHP_SAPI === 'phpdbg' ? ' -qrr --' : ''));
90
            $childProcessPath = \escapeshellarg(__DIR__ . DIRECTORY_SEPARATOR . 'child-process.php');
91
            $argvString = \escapeshellarg(ArgvEncoder::encode($options));
92
            $command = $phpBinary . ' ' . $childProcessPath;
93
94
            $process = new Process(
95
                \sprintf(
96
                    $template,
97
                    $command . ' ' . $argvString
98
                ),
99
                null,
100
                null,
101
                $fds
102
            );
103
104
            $connectTimeout = isset($options['connect-timeout']) ? $options['connect-timeout'] : 5;
105
            \WyriHaximus\React\futurePromise($loop)->then(function () use ($process, $server, $loop, $options, $connectTimeout) {
106
                return Promise\Timer\timeout(self::startParent($process, $server, $loop, $options), $connectTimeout, $loop);
107
            })->then(function (Messenger $messenger) use ($class) {
108
                return $messenger->rpc(MessengesFactory::rpc(Factory::PROCESS_REGISTER, [
109
                    'className' => $class,
110
                ]))->then(function ($p) use ($messenger) {
0 ignored issues
show
Unused Code introduced by
The parameter $p is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
111
                    return Promise\resolve($messenger);
112
                });
113
            })->done($resolve, $reject);
114
        });
115
    }
116
117
    /**
118
     * @param  LoopInterface                       $loop
119
     * @param  array                               $options
120
     * @param  callable                            $termiteCallable
121
     * @return Promise\PromiseInterface<Messenger>
0 ignored issues
show
Documentation introduced by
The doc-type Promise\PromiseInterface<Messenger> could not be parsed: Expected "|" or "end of type", but got "<" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
122
     */
123
    public static function child(LoopInterface $loop, array $options = [], callable $termiteCallable = null)
124
    {
125
        $connectTimeout = isset($options['connect-timeout']) ? $options['connect-timeout'] : 5;
126
127
        return (new Connector($loop, ['timeout' => $connectTimeout]))->connect($options['address'])->then(function (ConnectionInterface $connection) use ($options, $loop, $connectTimeout) {
128
            return new Promise\Promise(function ($resolve, $reject) use ($connection, $options, $loop, $connectTimeout) {
129
                Promise\Timer\timeout(Promise\Stream\first($connection), $connectTimeout, $loop)->then(function ($chunk) use ($resolve, $connection, $options) {
130
                    list($confirmation) = \explode(PHP_EOL, $chunk);
131
                    if ($confirmation === 'syn') {
132
                        $connection->write('ack' . PHP_EOL);
133
                        $resolve(new Messenger($connection, $options));
134
                    }
135
                }, $reject);
136 1
                $connection->write(\hash_hmac('sha512', $options['address'], $options['random']) . PHP_EOL);
137
            });
138
        })->then(function (Messenger $messenger) use ($loop, $termiteCallable) {
139
            if ($termiteCallable === null) {
140
                $termiteCallable = function () use ($loop) {
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $termiteCallable, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
141
                    $loop->addTimer(
142
                        self::TERMINATE_TIMEOUT,
143 1
                        [
144 1
                            $loop,
145
                            'stop',
146
                        ]
147 1
                    );
148 1
                };
149 1
            }
150 1
151
            $messenger->registerRpc(
152 1
                Messenger::TERMINATE_RPC,
153
                function (Payload $payload, Messenger $messenger) use ($termiteCallable) {
154
                    $messenger->emit('terminate', [
155 1
                        $messenger,
156 1
                    ]);
157 1
                    $termiteCallable($payload, $messenger);
158
159 1
                    return Promise\resolve([]);
160 1
                }
161
            );
162
163
            return $messenger;
164 1
        });
165
    }
166 1
167
    private static function startParent(
168 1
        Process $process,
169 1
        Server $server,
170 1
        LoopInterface $loop,
171
        array $options
172 1
    ) {
173 1
        return (new Promise\Promise(function ($resolve, $reject) use ($process, $server, $loop, $options) {
174 1
            $server->on(
175
                'connection',
176
                function (ConnectionInterface $connection) use ($server, $resolve, $reject, $options, $loop) {
177
                    Promise\Stream\first($connection)->then(function ($chunk) use ($options, $connection, $resolve) {
178
                        list($confirmation) = \explode(PHP_EOL, $chunk);
179 1
                        if ($confirmation === \hash_hmac('sha512', $options['address'], $options['random'])) {
180
                            $connection->write('syn' . PHP_EOL);
181 1
182 1
                            return Promise\Stream\first($connection);
183
                        }
184
                    })->then(function ($chunk) use ($options, $connection) {
185
                        list($confirmation) = \explode(PHP_EOL, $chunk);
186
                        if ($confirmation === 'ack') {
187
                            return Promise\resolve(new Messenger($connection, $options));
188
                        }
189
190
                        return Promise\reject(new \RuntimeException('Handshake failed'));
191
                    })->always(function () use ($server) {
192
                        $server->close();
193
                    })->done($resolve, $reject);
194
                }
195
            );
196
            $server->on('error', function ($et) use ($reject) {
197
                $reject($et);
198
            });
199
200
            $process->start($loop);
201
        }, function () use ($server, $process) {
202
            $server->close();
203
            $process->terminate();
204
        }))->then(function (Messenger $messenger) use ($loop, $process) {
205
            $loop->addPeriodicTimer(self::INTERVAL, function ($timer) use ($messenger, $loop, $process) {
206
                if (!$process->isRunning()) {
207
                    $loop->cancelTimer($timer);
208
209
                    $exitCode = $process->getExitCode();
210
                    if ($exitCode === 0) {
211
                        return;
212
                    }
213
214
                    $messenger->crashed($exitCode);
215
                }
216
            });
217
218
            return $messenger;
219
        });
220
    }
221
}
222