Passed
Push — master ( cf05b0...ebef44 )
by Gaetano
06:06
created

Response   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 270
Duplicated Lines 0 %

Test Coverage

Coverage 53.92%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 127
c 4
b 1
f 0
dl 0
loc 270
rs 8.96
ccs 55
cts 102
cp 0.5392
wmc 43

12 Methods

Rating   Name   Duplication   Size   Complexity  
A cookies() 0 3 1
A faultString() 0 3 1
A httpResponse() 0 3 1
A value() 0 3 1
B __construct() 0 30 11
A faultCode() 0 3 1
A __set() 0 19 4
A __unset() 0 19 4
A xml_header() 0 6 2
B serialize() 0 40 9
A __get() 0 18 4
A __isset() 0 14 4

How to fix   Complexity   

Complex Class

Complex classes like Response often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Response, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpXmlRpc;
4
5
use PhpXmlRpc\Exception\StateErrorException;
6
use PhpXmlRpc\Traits\CharsetEncoderAware;
7
use PhpXmlRpc\Traits\DeprecationLogger;
8
use PhpXmlRpc\Traits\PayloadBearer;
9
10
/**
11
 * This class provides the representation of the response of an XML-RPC server.
12
 * Server-side, a server method handler will construct a Response and pass it as its return value.
13
 * An identical Response object will be returned by the result of an invocation of the send() method of the Client class.
14
 *
15
 * @property array $hdrs deprecated, use $httpResponse['headers']
16
 * @property array _cookies deprecated, use $httpResponse['cookies']
17
 * @property string $raw_data deprecated, use $httpResponse['raw_data']
18
 */
19
class Response
20
{
21
    use CharsetEncoderAware;
22
    use DeprecationLogger;
23
    use PayloadBearer;
24
25
    /// @todo: do these need to be public?
26
    /** @internal */
27
    public $val = 0;
28
    /** @internal */
29
    public $valtyp;
30
    /** @internal */
31
    public $errno = 0;
32
    /** @internal */
33
    public $errstr = '';
34
35
    protected $httpResponse = array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null);
36
37
    /**
38
     * @param Value|string|mixed $val either a Value object, a php value or the xml serialization of an xml-rpc value (a string).
39
     *                                Note that using anything other than a Value object wll have an impact on serialization.
40
     * @param integer $fCode set it to anything but 0 to create an error response. In that case, $val is discarded
41
     * @param string $fString the error string, in case of an error response
42
     * @param string $valType The type of $val passed in. Either 'xmlrpcvals', 'phpvals' or 'xml'. Leave empty to let
43
     *                        the code guess the correct type by looking at $val - in which case strings are assumed
44
     *                        to be serialized xml
45
     * @param array|null $httpResponse this should be set when the response is being built out of data received from
46
     *                                 http (i.e. not when programmatically building a Response server-side). Array
47
     *                                 keys should include, if known: headers, cookies, raw_data, status_code
48
     *
49
     * @todo add check that $val / $fCode / $fString is of correct type? We could at least log a warning for fishy cases...
50
     *       NB: as of now we do not do it, since it might be either an xml-rpc value or a plain php val, or a complete
51
     *       xml chunk, depending on usage of Client::send() inside which the constructor is called.
52
     */
53
    public function __construct($val, $fCode = 0, $fString = '', $valType = '', $httpResponse = null)
54
    {
55
        if ($fCode != 0) {
56
            // error response
57
            $this->errno = $fCode;
58 716
            $this->errstr = $fString;
59
        } else {
60 716
            // successful response
61
            $this->val = $val;
62 184
            if ($valType == '') {
63 184
                // user did not declare type of response value: try to guess it
64
                if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
65
                    $this->valtyp = 'xmlrpcvals';
66 682
                } elseif (is_string($this->val)) {
67 682
                    $this->valtyp = 'xml';
68
                } else {
69 564
                    $this->valtyp = 'phpvals';
70 564
                }
71
            } else {
72
                $this->valtyp = $valType;
73
                // user declares the type of resp value: we "almost" trust it... but log errors just in case
74 27
                if (($this->valtyp == 'xmlrpcvals' && (!is_a($this->val, 'PhpXmlRpc\Value'))) ||
75
                    ($this->valtyp == 'xml' && (!is_string($this->val)))) {
76
                    $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': value passed in does not match type ' . $valType);
77
                }
78 681
            }
79
        }
80
81
        if (is_array($httpResponse)) {
82 716
            $this->httpResponse = array_merge(array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null), $httpResponse);
83 711
        }
84
    }
85 716
86
    /**
87
     * Returns the error code of the response.
88
     *
89
     * @return integer the error code of this response (0 for not-error responses)
90
     */
91
    public function faultCode()
92 702
    {
93
        return $this->errno;
94 702
    }
95
96
    /**
97
     * Returns the error code of the response.
98
     *
99
     * @return string the error string of this response ('' for not-error responses)
100
     */
101
    public function faultString()
102 560
    {
103
        return $this->errstr;
104 560
    }
105
106
    /**
107
     * Returns the value received by the server. If the Response's faultCode is non-zero then the value returned by this
108
     * method should not be used (it may not even be an object).
109
     *
110
     * @return Value|string|mixed the Value object returned by the server. Might be an xml string or plain php value
111
     *                            depending on the convention adopted when creating the Response
112
     */
113
    public function value()
114 679
    {
115
        return $this->val;
116 679
    }
117
118
    /**
119
     * Returns an array with the cookies received from the server.
120
     * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 => $val2, ...)
121
     * with attributes being e.g. 'expires', 'path', domain'.
122
     * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past) are still present in the array.
123
     * It is up to the user-defined code to decide how to use the received cookies, and whether they have to be sent back
124
     * with the next request to the server (using $client->setCookie) or not.
125
     * The values are filled in at constructor time, and might not be set for specific debug values used.
126
     *
127
     * @return array[] array of cookies received from the server
128
     */
129 22
    public function cookies()
130
    {
131 22
        return $this->httpResponse['cookies'];
132
    }
133
134
    /**
135
     * Returns an array with info about the http response received from the server.
136
     * The values are filled in at constructor time, and might not be set for specific debug values used.
137 46
     *
138
     * @return array array with keys 'headers', 'cookies', 'raw_data' and 'status_code'.
139 46
     */
140
    public function httpResponse()
141
    {
142
        return $this->httpResponse;
143
    }
144
145
    /**
146
     * Returns xml representation of the response, XML prologue _not_ included. Sets `payload` and `content_type` properties
147
     *
148
     * @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed
149
     * @return string the xml representation of the response
150
     * @throws StateErrorException if the response was built out of a value of an unsupported type
151 565
     */
152
    public function serialize($charsetEncoding = '')
153 565
    {
154 52
        if ($charsetEncoding != '') {
155
            $this->content_type = 'text/xml; charset=' . $charsetEncoding;
156 513
        } else {
157
            $this->content_type = 'text/xml';
158 565
        }
159 2
160
        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
161 564
            $result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
162
        } else {
163 565
            $result = "<methodResponse>\n";
164
        }
165
        if ($this->errno) {
166 89
            // Let non-ASCII response messages be tolerated by clients by xml-encoding non ascii chars
167 89
            $result .= "<fault>\n" .
168 89
                "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
169 89
                "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
170
                $this->getCharsetEncoder()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) .
171 561
                "</string></value>\n</member>\n</struct>\n</value>\n</fault>";
172
        } else {
173
            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...
174
                $result .= "<params>\n<param>\n" . $this->val->serialize($charsetEncoding) . "</param>\n</params>";
175
            } else 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...
176
                $result .= "<params>\n<param>\n" .
177
                    $this->val .
178
                    "</param>\n</params>";
179
            } else if ($this->valtyp == 'phpvals') {
180
                    $encoder = new Encoder();
181
                    $val = $encoder->encode($this->val);
182 561
                    $result .= "<params>\n<param>\n" . $val->serialize($charsetEncoding) . "</param>\n</params>";
183 561
            } else {
184
                throw new StateErrorException('cannot serialize xmlrpc response objects whose content is native php values');
185
            }
186 565
        }
187 565
        $result .= "\n</methodResponse>";
188
189 565
        $this->payload = $result;
190
191
        return $result;
192
    }
193
194 2
    /**
195
     * @param string $charsetEncoding
196
     * @return string
197
     */
198 2
    public function xml_header($charsetEncoding = '')
199 2
    {
200
        if ($charsetEncoding != '') {
201 2
            return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
202
        } else {
203 2
            return "<?xml version=\"1.0\"?" . ">\n";
204 2
        }
205
    }
206
207
    // *** BC layer ***
208
209
    // we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
210
    public function &__get($name)
211
    {
212 561
        switch ($name) {
213
            case 'hdrs':
214
                $this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
215
                return $this->httpResponse['headers'];
216 561
            case '_cookies':
217 561
                $this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
218
                return $this->httpResponse['cookies'];
219
            case 'raw_data':
220 561
                $this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
221
                return $this->httpResponse['raw_data'];
222
            default:
223 561
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
224 561
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
225 561
                trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
226
                $result = null;
227
                return $result;
228
        }
229
    }
230 561
231
    public function __set($name, $value)
232
    {
233
        switch ($name) {
234
            case 'hdrs':
235
                $this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
236
                $this->httpResponse['headers'] = $value;
237
                break;
238
            case '_cookies':
239
                $this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
240
                $this->httpResponse['cookies'] = $value;
241
                break;
242
            case 'raw_data':
243
                $this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
244
                $this->httpResponse['raw_data'] = $value;
245
                break;
246
            default:
247
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
248
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
249
                trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
250
        }
251
    }
252
253
    public function __isset($name)
254
    {
255
        switch ($name) {
256
            case 'hdrs':
257
                $this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
258
                return isset($this->httpResponse['headers']);
259
            case '_cookies':
260
                $this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
261
                return isset($this->httpResponse['cookies']);
262
            case 'raw_data':
263
                $this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
264
                return isset($this->httpResponse['raw_data']);
265
            default:
266
                return false;
267
        }
268
    }
269
270
    public function __unset($name)
271
    {
272
        switch ($name) {
273
            case 'hdrs':
274
                $this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
275
                unset($this->httpResponse['headers']);
276
                break;
277
            case '_cookies':
278
                $this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
279
                unset($this->httpResponse['cookies']);
280
                break;
281
            case 'raw_data':
282
                $this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
283
                unset($this->httpResponse['raw_data']);
284
                break;
285
            default:
286
                /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
287
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
288
                trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
289
        }
290
    }
291
}
292