Passed
Push — dev ( f5cf87...4396b8 )
by Marwan
14:15
created

ServerEndpoint   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 120
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 50
c 1
b 0
f 0
dl 0
loc 120
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A callback() 0 3 1
A onRequest() 0 33 2
A respond() 0 42 3
A serve() 0 3 1
1
<?php
2
/**
3
 * @author Marwan Al-Soltany <[email protected]>
4
 * @copyright Marwan Al-Soltany 2020
5
 * For the full copyright and license information, please view
6
 * the LICENSE file that was distributed with this source code.
7
 */
8
9
namespace MAKS\AmqpAgent\RPC;
10
11
use PhpAmqpLib\Message\AMQPMessage;
12
use MAKS\AmqpAgent\Helper\ClassProxy;
13
use MAKS\AmqpAgent\RPC\AbstractEndpoint;
14
use MAKS\AmqpAgent\RPC\ServerEndpointInterface;
15
use MAKS\AmqpAgent\Exception\RPCEndpointException;
16
17
/**
18
 * A class specialized in responding. Implementing only the methods needed for a server.
19
 *
20
 * Example:
21
 * ```
22
 * $serverEndpoint = new ServerEndpoint();
23
 * $serverEndpoint->on('some.event', function () { ... });
24
 * $serverEndpoint->connect();
25
 * $serverEndpoint->respond('Namespace\SomeClass::someMethod', 'queue.name');
26
 * $serverEndpoint->disconnect();
27
 * ```
28
 *
29
 * @since 2.0.0
30
 * @api
31
 */
32
class ServerEndpoint extends AbstractEndpoint implements ServerEndpointInterface
33
{
34
    /**
35
     * The callback to use when processing the requests.
36
     * @var array
37
     */
38
    protected $callback;
39
40
41
    /**
42
     * Listens on requests coming via the passed queue and processes them with the passed callback.
43
     * @param callable|null $callback [optional] The callback to process the request. This callback will be passed an `AMQPMessage` and must return a string.
44
     * @param string|null $queueName [optional] The name of the queue to listen on.
45
     * @return string The last processed request.
46
     * @throws RPCEndpointException If the server is not connected yet or if the passed callback didn't return a string.
47
     */
48
    public function respond(?callable $callback = null, ?string $queueName = null): string
49
    {
50
        $this->callback = $callback ?? [$this, 'callback'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $callback ?? array($this, 'callback') can also be of type callable. However, the property $callback is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
51
        $this->queueName = $queueName ?? $this->queueName;
0 ignored issues
show
Documentation Bug introduced by
It seems like $queueName ?? $this->queueName can also be of type string. However, the property $queueName is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
52
53
        if ($this->isConnected()) {
54
            $this->requestQueue = $this->queueName;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->queueName can also be of type array. However, the property $requestQueue is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
55
56
            $this->channel->queue_declare(
57
                $this->requestQueue,
0 ignored issues
show
Bug introduced by
It seems like $this->requestQueue can also be of type array; however, parameter $queue of PhpAmqpLib\Channel\AMQPChannel::queue_declare() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

57
                /** @scrutinizer ignore-type */ $this->requestQueue,
Loading history...
58
                false,
59
                false,
60
                false,
61
                false
62
            );
63
64
            $this->channel->basic_qos(
65
                null,
66
                1,
67
                null
68
            );
69
70
            $this->channel->basic_consume(
71
                $this->requestQueue,
0 ignored issues
show
Bug introduced by
It seems like $this->requestQueue can also be of type array; however, parameter $queue of PhpAmqpLib\Channel\AMQPChannel::basic_consume() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

71
                /** @scrutinizer ignore-type */ $this->requestQueue,
Loading history...
72
                null,
73
                false,
74
                false,
75
                false,
76
                false,
77
                function ($message) {
78
                    ClassProxy::call($this, 'onRequest', $message);
79
                }
80
            );
81
82
            while ($this->channel->is_consuming()) {
83
                $this->channel->wait();
84
            }
85
86
            return $this->request;
87
        }
88
89
        throw new RPCEndpointException('Server is not connected yet!');
90
    }
91
92
    /**
93
     * Listens on requests coming via the passed queue and processes them with the passed callback.
94
     * Alias for `self::respond()`.
95
     * @param callable|null $callback [optional] The callback to process the request. This callback will be passed an `AMQPMessage` and must return a string.
96
     * @param string|null $queueName [optional] The queue to listen on.
97
     * @return string The last processed request.
98
     * @throws RPCEndpointException If the server is not connected yet or if the passed callback didn't return a string.
99
     */
100
    public function serve(?callable $callback = null, ?string $queueName = null): string
101
    {
102
        return $this->respond($callback, $queueName);
103
    }
104
105
    /**
106
     * Replies to the client.
107
     * @param AMQPMessage $request
108
     * @return void
109
     */
110
    protected function onRequest(AMQPMessage $request): void
111
    {
112
        $this->trigger('request.on.get', [$request]);
113
114
        $this->request = $request->body;
115
        $this->response = call_user_func($this->callback, $request);
116
        $this->responseQueue = $request->get('reply_to');
0 ignored issues
show
Documentation Bug introduced by
It seems like $request->get('reply_to') can also be of type PhpAmqpLib\Channel\AMQPChannel. However, the property $responseQueue is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
117
        $this->correlationId = $request->get('correlation_id');
0 ignored issues
show
Documentation Bug introduced by
It seems like $request->get('correlation_id') can also be of type PhpAmqpLib\Channel\AMQPChannel. However, the property $correlationId is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
118
119
        if (!is_string($this->response)) {
120
            throw new RPCEndpointException(
121
                sprintf(
122
                    'The passed processing callback must return a string, instead it returned (data-type: %s)!',
123
                    gettype($this->response)
124
                )
125
            );
126
        }
127
128
        $message = new AMQPMessage($this->response);
129
        $message->set('correlation_id', $this->correlationId);
130
        $message->set('timestamp', time());
131
132
        $this->trigger('response.before.send', [$message]);
133
134
        $request->getChannel()->basic_publish(
135
            $message,
136
            null,
137
            $this->responseQueue
0 ignored issues
show
Bug introduced by
It seems like $this->responseQueue can also be of type PhpAmqpLib\Channel\AMQPChannel; however, parameter $routing_key of PhpAmqpLib\Channel\AMQPChannel::basic_publish() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

137
            /** @scrutinizer ignore-type */ $this->responseQueue
Loading history...
138
        );
139
140
        $request->ack();
141
142
        $this->trigger('response.after.send', [$message]);
143
    }
144
145
    /**
146
     * Returns the final request body. This method will be ignored if a callback in `self::respond()` is specified.
147
     * @return string
148
     */
149
    protected function callback(AMQPMessage $message): string
150
    {
151
        return $message->body;
152
    }
153
}
154