Completed
Push — master ( 2c2879...0e2a64 )
by Cees-Jan
09:24
created

Pool::paginateCall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 2
1
<?php declare(strict_types=1);
2
3
namespace WyriHaximus\React\Cake\Orm;
4
5
use Cake\Core\Configure;
6
use React\EventLoop\LoopInterface;
7
use React\EventLoop\Timer\TimerInterface;
8
use React\Promise\Deferred;
9
use React\Promise\PromiseInterface;
10
use WyriHaximus\React\ChildProcess\Messenger\Messages\Factory;
11
use WyriHaximus\React\ChildProcess\Pool\Factory\Flexible;
12
use WyriHaximus\React\ChildProcess\Pool\Options;
13
use WyriHaximus\React\ChildProcess\Pool\PoolInfoInterface;
14
use WyriHaximus\React\ChildProcess\Pool\PoolInterface;
15
use WyriHaximus\React\ChildProcess\Pool\PoolUtilizerInterface;
16
17
/**
18
 * Class Pool.
19
 * @package WyriHaximus\React\Cake\Orm
20
 */
21
class Pool implements PoolUtilizerInterface
22
{
23
    /**
24
     * @var LoopInterface
25
     */
26
    protected $loop;
27
28
    /**
29
     * @var PoolInfoInterface
30
     */
31
    protected $pool;
32
33
    /**
34
     * @var Pool
35
     */
36
    protected static $instance = null;
37
38
    /**
39
     * @var bool
40
     */
41
    protected static $reset = false;
42
43
    /**
44
     * @param LoopInterface $loop
45
     * @param array         $config
46
     */
47
    protected function __construct(LoopInterface $loop, array $config = [])
48 4
    {
49
        $this->loop = $loop;
50 4
51
        Flexible::createFromClass(
52 4
            WorkerChild::class,
53 4
            $this->loop,
54 4
            $this->applyConfig($config)
55
        )->then(function (PoolInterface $pool) {
56 4
            $this->pool = $pool;
57 4
        });
58
    }
59 4
60 4
    /**
61 4
     * @param  LoopInterface|null $loop
62
     * @param  array              $config
63
     * @throws \Exception
64
     * @return Pool
65
     */
66
    public static function getInstance(LoopInterface $loop = null, array $config = [])
67 4
    {
68
        if (null === self::$instance || self::$reset) {
69 4
            if (null === $loop) {
70 4
                throw new \Exception('Missing event loop');
71
            }
72
            self::$instance = new static($loop, $config);
73 4
            self::$reset = false;
74 4
        }
75
76
        return self::$instance;
77 4
    }
78
79
    public static function reset()
80
    {
81
        self::$reset = true;
82
    }
83
84
    /**
85
     * @param $className
86 4
     * @param $tableName
87
     * @param $function
88 4
     * @param  array            $arguments
89 4
     * @return PromiseInterface
90
     */
91
    public function call($className, $tableName, $function, array $arguments)
92 4
    {
93 4
        if ($this->pool instanceof PoolInterface) {
94
            return $this->poolCall($className, $tableName, $function, $arguments);
95
        }
96 4
97
        return $this->waitForPoolCall($className, $tableName, $function, $arguments);
0 ignored issues
show
Unused Code introduced by
The call to Pool::waitForPoolCall() has too many arguments starting with $arguments.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
98
    }
99 25
100
    public function paginate($tableName, $params, $settings)
101 25
    {
102 25
        if ($this->pool instanceof PoolInterface) {
103
            return $this->paginateCall($tableName, $params, $settings);
104
        }
105
106
        return $this->waitForPaginateCall($tableName, $params, $settings);
107
    }
108
109
    private function paginateCall($tableName, $params, $settings)
110
    {
111
        return $this->pool->rpc(Factory::rpc('paginate', [
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface WyriHaximus\React\ChildP...\Pool\PoolInfoInterface as the method rpc() does only exist in the following implementations of said interface: WyriHaximus\React\ChildProcess\Pool\Pool\Dummy, WyriHaximus\React\ChildProcess\Pool\Pool\Fixed, WyriHaximus\React\ChildProcess\Pool\Pool\Flexible.

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...
112
            'table' => $tableName,
113
            'params' => $params,
114
            'settings' => $settings,
115
        ]));
116
    }
117
118 View Code Duplication
    protected function waitForPaginateCall($tableName, $params, $settings)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
    {
120
        $deferred = new Deferred();
121
122
        $this->loop->addPeriodicTimer(
123
            0.1,
124
            function (TimerInterface $timer) use ($deferred, $tableName, $params, $settings) {
125
                if ($this->pool instanceof PoolInterface) {
126
                    $timer->cancel();
127
                    $deferred->resolve($this->paginateCall($tableName, $params, $settings));
128
                }
129
            }
130
        );
131
132
        return $deferred->promise();
133
    }
134
135
    /**
136
     * @inheritDoc
137
     */
138
    public function info()
139
    {
140
        if ($this->pool instanceof PoolInterface) {
141
            return $this->pool->info();
142
        }
143
144
        return [];
145
    }
146
147
    /**
148
     * @return LoopInterface
149
     */
150
    public function getLoop()
151
    {
152
        return $this->loop;
153
    }
154
155
    /**
156
     * @return PoolInfoInterface
157
     */
158
    public function getPool()
159
    {
160
        return $this->pool;
161
    }
162
163
    /**
164
     * @param  array $config
165
     * @return array
166
     */
167
    protected function applyConfig(array $config)
168
    {
169
        if (!isset($config['processOptions'])) {
170
            $config['processOptions'] = Configure::read('WyriHaximus.React.Cake.Orm.Line');
171
        }
172
173
        if (!isset($config[Options::TTL])) {
174
            $config[Options::TTL] = Configure::read('WyriHaximus.React.Cake.Orm.TTL');
175
        }
176
177 1
        return $config;
178
    }
179 1
180
    /**
181
     * @param $className
182
     * @param $tableName
183
     * @param $function
184
     * @param  array            $arguments
185 1
     * @return PromiseInterface
186
     */
187 1
    protected function poolCall($className, $tableName, $function, array $arguments)
188
    {
189
        return $this->pool->rpc(Factory::rpc('table.call', [
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface WyriHaximus\React\ChildP...\Pool\PoolInfoInterface as the method rpc() does only exist in the following implementations of said interface: WyriHaximus\React\ChildProcess\Pool\Pool\Dummy, WyriHaximus\React\ChildProcess\Pool\Pool\Fixed, WyriHaximus\React\ChildProcess\Pool\Pool\Flexible.

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...
190
            'className' => $className,
191
            'function' => $function,
192
            'table' => $tableName,
193
            'arguments' => serialize($arguments),
194
        ]))->then(function ($result) {
195
            return \React\Promise\resolve($result['result']);
196
        });
197
    }
198
199
    /**
200
     * @param $tableName
201
     * @param $function
202
     * @param  array            $arguments
203
     * @return PromiseInterface
204
     */
205 View Code Duplication
    protected function waitForPoolCall($tableName, $function, array $arguments)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
    {
207
        $deferred = new Deferred();
208
209
        $this->loop->addPeriodicTimer(
210
            0.1,
211
            function (TimerInterface $timer) use ($deferred, $tableName, $function, $arguments) {
212
                if ($this->pool instanceof PoolInterface) {
213
                    $timer->cancel();
214
                    $deferred->resolve($this->call($tableName, $function, $arguments));
0 ignored issues
show
Bug introduced by
The call to call() misses a required argument $arguments.

This check looks for function calls that miss required arguments.

Loading history...
215
                }
216
            }
217
        );
218
219
        return $deferred->promise();
220
    }
221
}
222