File size: 2,259 Bytes
e4f4821
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<?php

namespace JsonRPC\Request;

/**
 * Class RequestBuilder
 *
 * @package JsonRPC\Request
 * @author  Frederic Guillot
 */
class RequestBuilder
{
    /**
     * Request ID
     *
     * @access private
     * @var mixed
     */
    private $id = null;

    /**
     * Method name
     *
     * @access private
     * @var string
     */
    private $procedure = '';

    /**
     * Method arguments
     *
     * @access private
     * @var array
     */
    private $params = array();

    /**
     * Additional request attributes
     *
     * @access private
     * @var array
     */
    private $reqattrs = array();

    /**
     * Get new object instance
     *
     * @static
     * @access public
     * @return RequestBuilder
     */
    public static function create()
    {
        return new static();
    }

    /**
     * Set id
     *
     * @access public
     * @param  null $id
     * @return RequestBuilder
     */
    public function withId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * Set method
     *
     * @access public
     * @param  string $procedure
     * @return RequestBuilder
     */
    public function withProcedure($procedure)
    {
        $this->procedure = $procedure;
        return $this;
    }

    /**
     * Set parameters
     *
     * @access public
     * @param  array $params
     * @return RequestBuilder
     */
    public function withParams(array $params)
    {
        $this->params = $params;
        return $this;
    }

    /**
     * Set additional request attributes
     *
     * @access public
     * @param  array $reqattrs
     * @return RequestBuilder
     */
    public function withRequestAttributes(array $reqattrs)
    {
        $this->reqattrs = $reqattrs;
        return $this;
    }

    /**
     * Build the payload
     *
     * @access public
     * @return string
     */
    public function build()
    {
        $payload = array_merge_recursive($this->reqattrs, array(
            'jsonrpc' => '2.0',
            'method' => $this->procedure,
            'id' => $this->id ?: mt_rand(),
        ));

        if (! empty($this->params)) {
            $payload['params'] = $this->params;
        }

        return json_encode($payload);
    }
}