Passed
Push — master ( b9401f...4e5288 )
by Gaetano
06:45
created

Response::setCharsetEncoder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace PhpXmlRpc;
4
5
use PhpXmlRpc\Helper\Charset;
6
7
/**
8
 * This class provides the representation of the response of an XML-RPC server.
9
 * Server-side, a server method handler will construct a Response and pass it as its return value.
10
 * An identical Response object will be returned by the result of an invocation of the send() method of the Client class.
11
 *
12
 * @property array $hdrs deprecated, use $httpResponse['headers']
13
 * @property array _cookies deprecated, use $httpResponse['cookies']
14
 * @property string $raw_data deprecated, use $httpResponse['raw_data']
15
 */
16
class Response
17
{
18
    protected static $charsetEncoder;
19
20
    /// @todo: do these need to be public?
21
    /** @internal */
22
    public $val = 0;
23
    /** @internal */
24
    public $valtyp;
25
    /** @internal */
26
    public $errno = 0;
27
    /** @internal */
28
    public $errstr = '';
29
    public $payload;
30
    public $content_type = 'text/xml';
31
    protected $httpResponse = array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null);
32
33
    public function getCharsetEncoder()
34
    {
35
        if (self::$charsetEncoder === null) {
36
            self::$charsetEncoder = Charset::instance();
37
        }
38
        return self::$charsetEncoder;
39
    }
40
41
    public function setCharsetEncoder($charsetEncoder)
42
    {
43
        self::$charsetEncoder = $charsetEncoder;
44
    }
45
46
    /**
47
     * @param Value|string|mixed $val either a Value object, a php value or the xml serialization of an xmlrpc value (a string)
48
     * @param integer $fCode set it to anything but 0 to create an error response. In that case, $val is discarded
49
     * @param string $fString the error string, in case of an error response
50
     * @param string $valType The type of $val passed in. Either 'xmlrpcvals', 'phpvals' or 'xml'. Leave empty to let
51
     *                        the code guess the correct type.
52
     * @param array|null $httpResponse
53
     *
54
     * @todo add check that $val / $fCode / $fString is of correct type???
55
     *       NB: as of now we do not do it, since it might be either an xmlrpc value or a plain php val, or a complete
56
     *       xml chunk, depending on usage of Client::send() inside which creator is called...
57
     */
58 651
    public function __construct($val, $fCode = 0, $fString = '', $valType = '', $httpResponse = null)
59
    {
60 651
        if ($fCode != 0) {
61
            // error response
62 168
            $this->errno = $fCode;
63 168
            $this->errstr = $fString;
64
        } else {
65
            // successful response
66 619
            $this->val = $val;
67 619
            if ($valType == '') {
68
                // user did not declare type of response value: try to guess it
69 511
                if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
70 511
                    $this->valtyp = 'xmlrpcvals';
71
                } elseif (is_string($this->val)) {
72
                    $this->valtyp = 'xml';
73
                } else {
74 25
                    $this->valtyp = 'phpvals';
75
                }
76
            } else {
77
                // user declares type of resp value: believe him
78 618
                $this->valtyp = $valType;
79
            }
80
        }
81
82 651
        if (is_array($httpResponse)) {
83 646
            $this->httpResponse = array_merge(array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null), $httpResponse);
84
        }
85 651
    }
86
87
    /**
88
     * Returns the error code of the response.
89
     *
90
     * @return integer the error code of this response (0 for not-error responses)
91
     */
92 637
    public function faultCode()
93
    {
94 637
        return $this->errno;
95
    }
96
97
    /**
98
     * Returns the error code of the response.
99
     *
100
     * @return string the error string of this response ('' for not-error responses)
101
     */
102 508
    public function faultString()
103
    {
104 508
        return $this->errstr;
105
    }
106
107
    /**
108
     * Returns the value received by the server. If the Response's faultCode is non-zero then the value returned by this
109
     * method should not be used (it may not even be an object).
110
     *
111
     * @return Value|string|mixed the Value object returned by the server. Might be an xml string or plain php value
112
     *                            depending on the convention adopted when creating the Response
113
     */
114 616
    public function value()
115
    {
116 616
        return $this->val;
117
    }
118
119
    /**
120
     * Returns an array with the cookies received from the server.
121
     * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 => $val2, ...)
122
     * with attributes being e.g. 'expires', 'path', domain'.
123
     * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past) are still present in the array.
124
     * It is up to the user-defined code to decide how to use the received cookies, and whether they have to be sent back
125
     * with the next request to the server (using Client::setCookie) or not.
126
     *
127
     * @return array[] array of cookies received from the server
128
     */
129 20
    public function cookies()
130
    {
131 20
        return $this->httpResponse['cookies'];
132
    }
133
134
    /**
135
     * @return array array with keys 'headers', 'cookies', 'raw_data' and 'status_code'
136
     */
137
    public function httpResponse()
138
    {
139
        return $this->httpResponse;
140
    }
141
142
    /**
143
     * Returns xml representation of the response. XML prologue not included.
144
     *
145
     * @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed
146
     *
147
     * @return string the xml representation of the response
148
     *
149
     * @throws \Exception
150
     */
151 513
    public function serialize($charsetEncoding = '')
152
    {
153 513
        if ($charsetEncoding != '') {
154 52
            $this->content_type = 'text/xml; charset=' . $charsetEncoding;
155
        } else {
156 461
            $this->content_type = 'text/xml';
157
        }
158 513
        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
159 2
            $result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
160
        } else {
161 512
            $result = "<methodResponse>\n";
162
        }
163 513
        if ($this->errno) {
164
            // Let non-ASCII response messages be tolerated by clients by xml-encoding non ascii chars
165
            $result .= "<fault>\n" .
166 81
                "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
167 81
                "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
168 81
                Charset::instance()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</string></value>\n</member>\n" .
169 81
                "</struct>\n</value>\n</fault>";
170
        } else {
171 509
            if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) {
0 ignored issues
show
introduced by
The condition is_object($this->val) is always false.
Loading history...
172
                if (is_string($this->val) && $this->valtyp == 'xml') {
0 ignored issues
show
introduced by
The condition is_string($this->val) is always false.
Loading history...
173
                    $result .= "<params>\n<param>\n" .
174
                        $this->val .
175
                        "</param>\n</params>";
176
                } else {
177
                    /// @todo try to build something serializable using the Encoder...
178
                    throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values');
179
                }
180
            } else {
181
                $result .= "<params>\n<param>\n" .
182 509
                    $this->val->serialize($charsetEncoding) .
183 509
                    "</param>\n</params>";
184
            }
185
        }
186 513
        $result .= "\n</methodResponse>";
187 513
        $this->payload = $result;
188
189 513
        return $result;
190
    }
191
192
    // BC layer
193
194 2
    public function __get($name)
195
    {
196
        //trigger_error('getting property Response::' . $name . ' is deprecated', E_USER_DEPRECATED);
197
198 2
        switch($name) {
199 2
            case 'hdrs':
200
                return $this->httpResponse['headers'];
201 2
            case '_cookies':
202
                return $this->httpResponse['cookies'];
203 2
            case 'raw_data':
204 2
                return $this->httpResponse['raw_data'];
205
            default:
206
                $trace = debug_backtrace();
207
                trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
208
                return null;
209
        }
210
    }
211
212 509
    public function __set($name, $value)
213
    {
214
        //trigger_error('setting property Response::' . $name . ' is deprecated', E_USER_DEPRECATED);
215
216 509
        switch($name) {
217 509
            case 'hdrs':
218
                $this->httpResponse['headers'] = $value;
219
                break;
220 509
            case '_cookies':
221
                $this->httpResponse['cookies'] = $value;
222
                break;
223 509
            case 'raw_data':
224 509
                $this->httpResponse['raw_data'] = $value;
225 509
                break;
226
            default:
227
                $trace = debug_backtrace();
228
                trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
229
        }
230 509
    }
231
232
    public function __isset($name)
233
    {
234
        switch($name) {
235
            case 'hdrs':
236
                return isset($this->httpResponse['headers']);
237
            case '_cookies':
238
                return isset($this->httpResponse['cookies']);
239
            case 'raw_data':
240
                return isset($this->httpResponse['raw_data']);
241
            default:
242
                return false;
243
        }
244
    }
245
246
    public function __unset($name)
247
    {
248
        switch($name) {
249
            case 'hdrs':
250
                unset($this->httpResponse['headers']);
251
                break;
252
            case '_cookies':
253
                unset($this->httpResponse['cookies']);
254
                break;
255
            case 'raw_data':
256
                unset($this->httpResponse['raw_data']);
257
                break;
258
            default:
259
                $trace = debug_backtrace();
260
                trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
261
        }
262
    }
263
}
264