Packet   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 20
dl 0
loc 72
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A message() 0 3 1
A received() 0 8 3
A __construct() 0 4 1
A failure() 0 8 3
A cleanup() 0 5 1
1
<?php
2
/**
3
 * Transport packet ops
4
 * User: moyo
5
 * Date: 2018/8/1
6
 * Time: 5:44 PM
7
 */
8
9
namespace Carno\HRPC\Accel\Transport;
10
11
use Carno\Promise\Promise;
12
use Carno\Promise\Promised;
13
use Throwable;
14
15
class Packet
16
{
17
    /**
18
     * @var int
19
     */
20
    private $seq = null;
21
22
    /**
23
     * @var Reconciled
24
     */
25
    private $from = null;
26
27
    /**
28
     * @var Promised
29
     */
30
    private $wait = null;
31
32
    /**
33
     * Packet constructor.
34
     * @param int $seq
35
     * @param Reconciled $from
36
     */
37
    public function __construct(int $seq, Reconciled $from)
38
    {
39
        $this->seq = $seq;
40
        $this->from = $from;
41
    }
42
43
    /**
44
     * @param string $message
45
     * @return bool
46
     */
47
    public function received(string $message) : bool
48
    {
49
        if ($this->wait && $this->wait->pended()) {
50
            $this->wait->resolve($message);
51
            $this->from = null;
52
            return true;
53
        }
54
        return false;
55
    }
56
57
    /**
58
     * @param Throwable $e
59
     * @return bool
60
     */
61
    public function failure(Throwable $e = null) : bool
62
    {
63
        if ($this->wait && $this->wait->pended()) {
64
            $this->wait->reject($e);
65
            $this->from = null;
66
            return true;
67
        }
68
        return false;
69
    }
70
71
    /**
72
     * @return Promised
73
     */
74
    public function message() : Promised
75
    {
76
        return $this->wait ?? $this->wait = Promise::deferred()->sync($this->cleanup());
77
    }
78
79
    /**
80
     * @return Promised
81
     */
82
    private function cleanup() : Promised
83
    {
84
        return Promise::deferred()->catch(function () {
85
            $this->from->free($this->seq);
86
            $this->from = null;
87
        });
88
    }
89
}
90