Completed
Push — master ( 820f99...3ba560 )
by Gaetano
07:24
created

Wrapper::xmlrpc2PhpType()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 15.6406

Importance

Changes 0
Metric Value
cc 13
nc 13
nop 1
dl 0
loc 25
ccs 15
cts 20
cp 0.75
crap 15.6406
rs 6.6166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @author Gaetano Giunta
4
 * @copyright (C) 2006-2019 G. Giunta
5
 * @license code licensed under the BSD License: see file license.txt
6
 */
7
8
namespace PhpXmlRpc;
9
10
use PhpXmlRpc\Helper\Logger;
11
12
/**
13
 * PHP-XMLRPC "wrapper" class - generate stubs to transparently access xmlrpc methods as php functions and vice-versa.
14
 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
15
 *
16
 * @todo use some better templating system for code generation?
17
 * @todo implement method wrapping with preservation of php objs in calls
18
 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
19
 */
20
class Wrapper
21
{
22
    /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
23
    public static $objHolder = array();
24
25
    /**
26
     * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
27
     * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
28
     * Notes:
29
     * - for php 'resource' types returns empty string, since resources cannot be serialized;
30
     * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
31
     * - for php arrays always return array, even though arrays sometimes serialize as json structs
32
     * - for 'void' and 'null' returns 'undefined'
33
     *
34
     * @param string $phpType
35
     *
36
     * @return string
37
     */
38 488
    public function php2XmlrpcType($phpType)
39
    {
40 488
        switch (strtolower($phpType)) {
41 488
            case 'string':
42 488
                return Value::$xmlrpcString;
43 488
            case 'integer':
44 488
            case Value::$xmlrpcInt: // 'int'
45 488
            case Value::$xmlrpcI4:
46 488
            case Value::$xmlrpcI8:
47 488
                return Value::$xmlrpcInt;
48 488
            case Value::$xmlrpcDouble: // 'double'
49
                return Value::$xmlrpcDouble;
50 488
            case 'bool':
51 488
            case Value::$xmlrpcBoolean: // 'boolean'
52 488
            case 'false':
53 488
            case 'true':
54
                return Value::$xmlrpcBoolean;
55 488
            case Value::$xmlrpcArray: // 'array':
56
                return Value::$xmlrpcArray;
57 488
            case 'object':
58 488
            case Value::$xmlrpcStruct: // 'struct'
59
                return Value::$xmlrpcStruct;
60 488
            case Value::$xmlrpcBase64:
61
                return Value::$xmlrpcBase64;
62 488
            case 'resource':
63
                return '';
64
            default:
65 488
                if (class_exists($phpType)) {
66 488
                    return Value::$xmlrpcStruct;
67
                } else {
68
                    // unknown: might be any 'extended' xmlrpc type
69 488
                    return Value::$xmlrpcValue;
70
                }
71
        }
72
    }
73
74
    /**
75
     * Given a string defining a phpxmlrpc type return the corresponding php type.
76
     *
77
     * @param string $xmlrpcType
78
     *
79
     * @return string
80
     */
81 77
    public function xmlrpc2PhpType($xmlrpcType)
82
    {
83 77
        switch (strtolower($xmlrpcType)) {
84 77
            case 'base64':
85 77
            case 'datetime.iso8601':
86 77
            case 'string':
87 58
                return Value::$xmlrpcString;
88 77
            case 'int':
89 20
            case 'i4':
90 20
            case 'i8':
91 58
                return 'integer';
92 20
            case 'struct':
93 20
            case 'array':
94
                return 'array';
95 20
            case 'double':
96
                return 'float';
97 20
            case 'undefined':
98 20
                return 'mixed';
99
            case 'boolean':
100
            case 'null':
101
            default:
102
                // unknown: might be any xmlrpc type
103
                return strtolower($xmlrpcType);
104
        }
105
    }
106
107
    /**
108
     * Given a user-defined PHP function, create a PHP 'wrapper' function that can
109
     * be exposed as xmlrpc method from an xmlrpc server object and called from remote
110
     * clients (as well as its corresponding signature info).
111
     *
112
     * Since php is a typeless language, to infer types of input and output parameters,
113
     * it relies on parsing the javadoc-style comment block associated with the given
114
     * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
115
     * in the '@param' tag is also allowed, if you need the php function to receive/send
116
     * data in that particular format (note that base64 encoding/decoding is transparently
117
     * carried out by the lib, while datetime vals are passed around as strings)
118
     *
119
     * Known limitations:
120
     * - only works for user-defined functions, not for PHP internal functions
121
     *   (reflection does not support retrieving number/type of params for those)
122
     * - functions returning php objects will generate special structs in xmlrpc responses:
123
     *   when the xmlrpc decoding of those responses is carried out by this same lib, using
124
     *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
125
     *   In short: php objects can be serialized, too (except for their resource members),
126
     *   using this function.
127
     *   Other libs might choke on the very same xml that will be generated in this case
128
     *   (i.e. it has a nonstandard attribute on struct element tags)
129
     *
130
     * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
131
     * php functions (ie. functions not expecting a single Request obj as parameter)
132
     * is by making use of the functions_parameters_type class member.
133
     *
134
     * @param callable $callable the PHP user function to be exposed as xmlrpc method/ a closure, function name, array($obj, 'methodname') or array('class', 'methodname') are ok
135
     * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
136
     * @param array $extraOptions (optional) array of options for conversion. valid values include:
137
     *                            - bool return_source     when true, php code w. function definition will be returned, instead of a closure
138
     *                            - bool encode_php_objs   let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
139
     *                            - bool decode_php_objs   --- WARNING !!! possible security hazard. only use it with trusted servers ---
140
     *                            - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
141
     *
142
     * @return array|false false on error, or an array containing the name of the new php function,
143
     *                     its signature and docs, to be used in the server dispatch map
144
     *
145
     * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
146
     * @todo finish using phpdoc info to build method sig if all params are named but out of order
147
     * @todo add a check for params of 'resource' type
148
     * @todo add some trigger_errors / error_log when returning false?
149
     * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
150
     * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
151
     * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
152
     * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
153
     */
154 488
    public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
155
    {
156 488
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
157
158 488
        if (is_string($callable) && strpos($callable, '::') !== false) {
159 488
            $callable = explode('::', $callable);
160
        }
161 488
        if (is_array($callable)) {
162 488
            if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
163
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
164
                return false;
165
            }
166 488 View Code Duplication
            if (is_string($callable[0])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167 488
                $plainFuncName = implode('::', $callable);
168 488
            } elseif (is_object($callable[0])) {
169 488
                $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
170
            }
171 488
            $exists = method_exists($callable[0], $callable[1]);
172 488
        } else if ($callable instanceof \Closure) {
173
            // we do not support creating code which wraps closures, as php does not allow to serialize them
174 488
            if (!$buildIt) {
175
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
176
                return false;
177
            }
178
179 488
            $plainFuncName = 'Closure';
180 488
            $exists = true;
181
        } else {
182 488
            $plainFuncName = $callable;
183 488
            $exists = function_exists($callable);
184
        }
185
186 488 View Code Duplication
        if (!$exists) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName);
0 ignored issues
show
Bug introduced by
The variable $plainFuncName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
188
            return false;
189
        }
190
191 488
        $funcDesc = $this->introspectFunction($callable, $plainFuncName);
0 ignored issues
show
Documentation introduced by
$plainFuncName is of type callable, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
192 488
        if (!$funcDesc) {
193
            return false;
194
        }
195
196 488
        $funcSigs = $this->buildMethodSignatures($funcDesc);
197
198 488
        if ($buildIt) {
199 488
            $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
0 ignored issues
show
Documentation introduced by
$plainFuncName is of type callable, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
200
        } else {
201 488
            $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
202 488
            $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
0 ignored issues
show
Documentation introduced by
$plainFuncName is of type callable, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
203
        }
204
205
        $ret = array(
206 488
            'function' => $callable,
207 488
            'signature' => $funcSigs['sigs'],
208 488
            'docstring' => $funcDesc['desc'],
209 488
            'signature_docs' => $funcSigs['sigsDocs'],
210
        );
211 488
        if (!$buildIt) {
212 488
            $ret['function'] = $newFuncName;
213 488
            $ret['source'] = $code;
0 ignored issues
show
Bug introduced by
The variable $code does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
214
        }
215 488
        return $ret;
216
    }
217
218
    /**
219
     * Introspect a php callable and its phpdoc block and extract information about its signature
220
     *
221
     * @param callable $callable
222
     * @param string $plainFuncName
223
     * @return array|false
224
     */
225 488
    protected function introspectFunction($callable, $plainFuncName)
226
    {
227
        // start to introspect PHP code
228 488
        if (is_array($callable)) {
229 488
            $func = new \ReflectionMethod($callable[0], $callable[1]);
230 488 View Code Duplication
            if ($func->isPrivate()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
231
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
232
                return false;
233
            }
234 488 View Code Duplication
            if ($func->isProtected()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
236
                return false;
237
            }
238 488 View Code Duplication
            if ($func->isConstructor()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
240
                return false;
241
            }
242 488 View Code Duplication
            if ($func->isDestructor()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
243
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
244
                return false;
245
            }
246 488 View Code Duplication
            if ($func->isAbstract()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
247
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
248
                return false;
249
            }
250
            /// @todo add more checks for static vs. nonstatic?
251
        } else {
252 488
            $func = new \ReflectionFunction($callable);
253
        }
254 488 View Code Duplication
        if ($func->isInternal()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
255
            // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
256
            // instead of getparameters to fully reflect internal php functions ?
257
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
258
            return false;
259
        }
260
261
        // retrieve parameter names, types and description from javadoc comments
262
263
        // function description
264 488
        $desc = '';
265
        // type of return val: by default 'any'
266 488
        $returns = Value::$xmlrpcValue;
267
        // desc of return val
268 488
        $returnsDocs = '';
269
        // type + name of function parameters
270 488
        $paramDocs = array();
271
272 488
        $docs = $func->getDocComment();
273 488
        if ($docs != '') {
274 488
            $docs = explode("\n", $docs);
275 488
            $i = 0;
276 488
            foreach ($docs as $doc) {
277 488
                $doc = trim($doc, " \r\t/*");
278 488
                if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
279 488
                    if ($desc) {
280 488
                        $desc .= "\n";
281
                    }
282 488
                    $desc .= $doc;
283 488
                } elseif (strpos($doc, '@param') === 0) {
284
                    // syntax: @param type $name [desc]
285 488
                    if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
286 488
                        $name = strtolower(trim($matches[2]));
287
                        //$paramDocs[$name]['name'] = trim($matches[2]);
288 488
                        $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
289 488
                        $paramDocs[$name]['type'] = $matches[1];
290
                    }
291 488
                    $i++;
292 488
                } elseif (strpos($doc, '@return') === 0) {
293
                    // syntax: @return type [desc]
294 488
                    if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
295 488
                        $returns = $matches[1];
296 488
                        if (isset($matches[2])) {
297 488
                            $returnsDocs = trim($matches[2]);
298
                        }
299
                    }
300
                }
301
            }
302
        }
303
304
        // execute introspection of actual function prototype
305 488
        $params = array();
306 488
        $i = 0;
307 488
        foreach ($func->getParameters() as $paramObj) {
308 488
            $params[$i] = array();
309 488
            $params[$i]['name'] = '$' . $paramObj->getName();
310 488
            $params[$i]['isoptional'] = $paramObj->isOptional();
311 488
            $i++;
312
        }
313
314
        return array(
315 488
            'desc' => $desc,
316 488
            'docs' => $docs,
317 488
            'params' => $params, // array, positionally indexed
318 488
            'paramDocs' => $paramDocs, // array, indexed by name
319 488
            'returns' => $returns,
320 488
            'returnsDocs' =>$returnsDocs,
321
        );
322
    }
323
324
    /**
325
     * Given the method description given by introspection, create method signature data
326
     *
327
     * @todo support better docs with multiple types separated by pipes by creating multiple signatures
328
     *       (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
329
     *
330
     * @param array $funcDesc as generated by self::introspectFunction()
331
     *
332
     * @return array
333
     */
334 488
    protected function buildMethodSignatures($funcDesc)
335
    {
336 488
        $i = 0;
337 488
        $parsVariations = array();
338 488
        $pars = array();
339 488
        $pNum = count($funcDesc['params']);
340 488 View Code Duplication
        foreach ($funcDesc['params'] as $param) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
341
            /* // match by name real param and documented params
342
            $name = strtolower($param['name']);
343
            if (!isset($funcDesc['paramDocs'][$name])) {
344
                $funcDesc['paramDocs'][$name] = array();
345
            }
346
            if (!isset($funcDesc['paramDocs'][$name]['type'])) {
347
                $funcDesc['paramDocs'][$name]['type'] = 'mixed';
348
            }*/
349
350 488
            if ($param['isoptional']) {
351
                // this particular parameter is optional. save as valid previous list of parameters
352
                $parsVariations[] = $pars;
353
            }
354
355 488
            $pars[] = "\$p$i";
356 488
            $i++;
357 488
            if ($i == $pNum) {
358
                // last allowed parameters combination
359 488
                $parsVariations[] = $pars;
360
            }
361
        }
362
363 488
        if (count($parsVariations) == 0) {
364
            // only known good synopsis = no parameters
365 488
            $parsVariations[] = array();
366
        }
367
368 488
        $sigs = array();
369 488
        $sigsDocs = array();
370 488
        foreach ($parsVariations as $pars) {
371
            // build a signature
372 488
            $sig = array($this->php2XmlrpcType($funcDesc['returns']));
373 488
            $pSig = array($funcDesc['returnsDocs']);
374 488
            for ($i = 0; $i < count($pars); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
375 488
                $name = strtolower($funcDesc['params'][$i]['name']);
376 488
                if (isset($funcDesc['paramDocs'][$name]['type'])) {
377 488
                    $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
378
                } else {
379 488
                    $sig[] = Value::$xmlrpcValue;
380
                }
381 488
                $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
382
            }
383 488
            $sigs[] = $sig;
384 488
            $sigsDocs[] = $pSig;
385
        }
386
387
        return array(
388 488
            'sigs' => $sigs,
389 488
            'sigsDocs' => $sigsDocs
390
        );
391
    }
392
393
    /**
394
     * Creates a closure that will execute $callable
395
     * @todo validate params? In theory all validation is left to the dispatch map...
396
     * @todo add support for $catchWarnings
397
     *
398
     * @param $callable
399
     * @param array $extraOptions
400
     * @param string $plainFuncName
401
     * @param array $funcDesc
402
     * @return \Closure
403
     */
404
    protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
0 ignored issues
show
Unused Code introduced by
The parameter $plainFuncName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
405
    {
406
        /**
407
         * @param Request $req
408
         * @return mixed
409
         */
410 488
        $function = function($req) use($callable, $extraOptions, $funcDesc)
411
        {
412 79
            $nameSpace = '\\PhpXmlRpc\\';
413 79
            $encoderClass = $nameSpace.'Encoder';
414 79
            $responseClass = $nameSpace.'Response';
415 79
            $valueClass = $nameSpace.'Value';
416
417
            // validate number of parameters received
418
            // this should be optional really, as we assume the server does the validation
419 79
            $minPars = count($funcDesc['params']);
420 79
            $maxPars = $minPars;
421 79
            foreach ($funcDesc['params'] as $i => $param) {
422 79
                if ($param['isoptional']) {
423
                    // this particular parameter is optional. We assume later ones are as well
424
                    $minPars = $i;
425
                    break;
426
                }
427
            }
428 79
            $numPars = $req->getNumParams();
429 79
            if ($numPars < $minPars || $numPars > $maxPars) {
430
                return new $responseClass(0, 3, 'Incorrect parameters passed to method');
431
            }
432
433 79
            $encoder = new $encoderClass();
434 79
            $options = array();
435 79
            if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
436
                $options[] = 'decode_php_objs';
437
            }
438 79
            $params = $encoder->decode($req, $options);
439
440 79
            $result = call_user_func_array($callable, $params);
441
442 79
            if (! is_a($result, $responseClass)) {
443 79
                if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
444
                    $result = new $valueClass($result, $funcDesc['returns']);
445
                } else {
446 79
                    $options = array();
447 79
                    if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
448 1
                        $options[] = 'encode_php_objs';
449
                    }
450
451 79
                    $result = $encoder->encode($result, $options);
452
                }
453 79
                $result = new $responseClass($result);
454
            }
455
456 79
            return $result;
457 488
        };
458
459 488
        return $function;
460
    }
461
462
    /**
463
     * Return a name for a new function, based on $callable, insuring its uniqueness
464
     * @param mixed $callable a php callable, or the name of an xmlrpc method
465
     * @param string $newFuncName when not empty, it is used instead of the calculated version
466
     * @return string
467
     */
468 564
    protected function newFunctionName($callable, $newFuncName, $extraOptions)
469
    {
470
        // determine name of new php function
471
472 564
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
473
474 564
        if ($newFuncName == '') {
475 545
            if (is_array($callable)) {
476 488
                if (is_string($callable[0])) {
477 488
                    $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
478
                } else {
479 488
                    $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
480
                }
481
            } else {
482 545
                if ($callable instanceof \Closure) {
483
                    $xmlrpcFuncName = "{$prefix}_closure";
484
                } else {
485 545
                    $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
486 545
                        array('_', ''), $callable);
487 545
                    $xmlrpcFuncName = "{$prefix}_$callable";
488
                }
489
            }
490
        } else {
491 20
            $xmlrpcFuncName = $newFuncName;
492
        }
493
494 564
        while (function_exists($xmlrpcFuncName)) {
495 543
            $xmlrpcFuncName .= 'x';
496
        }
497
498 564
        return $xmlrpcFuncName;
499
    }
500
501
    /**
502
     * @param $callable
503
     * @param string $newFuncName
504
     * @param array $extraOptions
505
     * @param string $plainFuncName
506
     * @param array $funcDesc
507
     * @return string
508
     *
509
     * @todo add a nice phpdoc block in the generated source
510
     */
511 488
    protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
512
    {
513 488
        $namespace = '\\PhpXmlRpc\\';
514
515 488
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
516 488
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
517 488
        $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
518
519 488
        $i = 0;
520 488
        $parsVariations = array();
521 488
        $pars = array();
522 488
        $pNum = count($funcDesc['params']);
523 488 View Code Duplication
        foreach ($funcDesc['params'] as $param) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
524
525 488
            if ($param['isoptional']) {
526
                // this particular parameter is optional. save as valid previous list of parameters
527
                $parsVariations[] = $pars;
528
            }
529
530 488
            $pars[] = "\$p[$i]";
531 488
            $i++;
532 488
            if ($i == $pNum) {
533
                // last allowed parameters combination
534 488
                $parsVariations[] = $pars;
535
            }
536
        }
537
538 488
        if (count($parsVariations) == 0) {
539
            // only known good synopsis = no parameters
540
            $parsVariations[] = array();
541
            $minPars = 0;
542
            $maxPars = 0;
543
        } else {
544 488
            $minPars = count($parsVariations[0]);
545 488
            $maxPars = count($parsVariations[count($parsVariations)-1]);
546
        }
547
548
        // build body of new function
549
550 488
        $innerCode = "\$paramCount = \$req->getNumParams();\n";
551 488
        $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
552
553 488
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
554 488
        if ($decodePhpObjects) {
555
            $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
556
        } else {
557 488
            $innerCode .= "\$p = \$encoder->decode(\$req);\n";
558
        }
559
560
        // since we are building source code for later use, if we are given an object instance,
561
        // we go out of our way and store a pointer to it in a static class var var...
562 488
        if (is_array($callable) && is_object($callable[0])) {
563 488
            self::$objHolder[$newFuncName] = $callable[0];
564 488
            $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
565 488
            $realFuncName = '$obj->' . $callable[1];
566
        } else {
567 488
            $realFuncName = $plainFuncName;
568
        }
569 488
        foreach ($parsVariations as $i => $pars) {
570 488
            $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
571 488
            if ($i < (count($parsVariations) - 1))
572
                $innerCode .= "else\n";
573
        }
574 488
        $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
575 488
        if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
576
            $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
577
        } else {
578 488
            if ($encodePhpObjects) {
579
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
580
            } else {
581 488
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
582
            }
583
        }
584
        // shall we exclude functions returning by ref?
585
        // if($func->returnsReference())
586
        //     return false;
587
588 488
        $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
589
590 488
        return $code;
591
    }
592
593
    /**
594
     * Given a user-defined PHP class or php object, map its methods onto a list of
595
     * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
596
     * object and called from remote clients (as well as their corresponding signature info).
597
     *
598
     * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
599
     * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
600
     *                            - string method_type    'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance
601
     *                            - string method_filter  a regexp used to filter methods to wrap based on their names
602
     *                            - string prefix         used for the names of the xmlrpc methods created
603
     *
604
     * @return array|false false on failure
605
     */
606 488
    public function wrapPhpClass($className, $extraOptions = array())
607
    {
608 488
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
609 488
        $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
610 488
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
611
612 488
        $results = array();
613 488
        $mList = get_class_methods($className);
614 488
        foreach ($mList as $mName) {
615 488
            if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
616 488
                $func = new \ReflectionMethod($className, $mName);
617 488
                if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
618 488
                    if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
619 488
                        (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
620
                    ) {
621 488
                        $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
622 488
                        if ($methodWrap) {
623 488
                            if (is_object($className)) {
624 488
                                $realClassName = get_class($className);
625
                            }else {
626
                                $realClassName = $className;
627
                            }
628 488
                            $results[$prefix."$realClassName.$mName"] = $methodWrap;
629
                        }
630
                    }
631
                }
632
            }
633
        }
634
635 488
        return $results;
636
    }
637
638
    /**
639
     * Given an xmlrpc client and a method name, register a php wrapper function
640
     * that will call it and return results using native php types for both
641
     * params and results. The generated php function will return a Response
642
     * object for failed xmlrpc calls.
643
     *
644
     * Known limitations:
645
     * - server must support system.methodsignature for the wanted xmlrpc method
646
     * - for methods that expose many signatures, only one can be picked (we
647
     *   could in principle check if signatures differ only by number of params
648
     *   and not by type, but it would be more complication than we can spare time)
649
     * - nested xmlrpc params: the caller of the generated php function has to
650
     *   encode on its own the params passed to the php function if these are structs
651
     *   or arrays whose (sub)members include values of type datetime or base64
652
     *
653
     * Notes: the connection properties of the given client will be copied
654
     * and reused for the connection used during the call to the generated
655
     * php function.
656
     * Calling the generated php function 'might' be slow: a new xmlrpc client
657
     * is created on every invocation and an xmlrpc-connection opened+closed.
658
     * An extra 'debug' param is appended to param list of xmlrpc method, useful
659
     * for debugging purposes.
660
     *
661
     * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
662
     * @todo if we can not retrieve method signature, create a php function with varargs
663
     * @todo allow the created function to throw exceptions on method calls failures
664
     * @todo if caller did not specify a specific sig, shall we support all of them?
665
     *       It might be hard (hence slow) to match based on type and number of arguments...
666
     *
667
     * @param Client $client an xmlrpc client set up correctly to communicate with target server
668
     * @param string $methodName the xmlrpc method to be mapped to a php function
669
     * @param array $extraOptions array of options that specify conversion details. Valid options include
670
     *                            - integer signum              the index of the method signature to use in mapping (if method exposes many sigs)
671
     *                            - integer timeout             timeout (in secs) to be used when executing function/calling remote method
672
     *                            - string  protocol            'http' (default), 'http11' or 'https'
673
     *                            - string  new_function_name   the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
674
     *                            - string  return_source       if true return php code w. function definition instead of function itself (closure)
675
     *                            - bool    encode_php_objs     let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
676
     *                            - bool    decode_php_objs     --- WARNING !!! possible security hazard. only use it with trusted servers ---
677
     *                            - mixed   return_on_fault     a php value to be returned when the xmlrpc call fails/returns a fault response (by default the Response object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
678
     *                            - bool    debug               set it to 1 or 2 to see debug results of querying server for method synopsis
679
     *                            - int     simple_client_copy  set it to 1 to have a lightweight copy of the $client object made in the generated code (only used when return_source = true)
680
     *
681
     * @return \closure|array|false false on failure, closure by default and array for return_source = true
682
     */
683 77
    public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
684
    {
685 77
        $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
686
687 77
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
688
689 77
        $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
690 77
        if (!$mSig) {
691
            return false;
692
        }
693
694 77
        if ($buildIt) {
695
            return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
696
        } else {
697
            // if in 'offline' mode, retrieve method description too.
698
            // in online mode, favour speed of operation
699 77
            $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
700
701 77
            $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
702
703 77
            $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
704
            /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
705
                $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
706
                $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
707
                $faultResponse, $namespace);*/
708
709 77
            $results['function'] = $newFuncName;
710
711 77
            return $results;
712
        }
713
714
    }
715
716
    /**
717
     * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
718
     * @param Client $client
719
     * @param string $methodName
720
     * @param array $extraOptions
721
     * @return false|array
722
     */
723 77
    protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
724
    {
725 77
        $namespace = '\\PhpXmlRpc\\';
726 77
        $reqClass = $namespace . 'Request';
727 77
        $valClass = $namespace . 'Value';
728 77
        $decoderClass = $namespace . 'Encoder';
729
730 77
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
731 77
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
732 77
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
733 77
        $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
734
735 77
        $req = new $reqClass('system.methodSignature');
736 77
        $req->addparam(new $valClass($methodName));
737 77
        $client->setDebug($debug);
738 77
        $response = $client->send($req, $timeout, $protocol);
739 77
        if ($response->faultCode()) {
740
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
741
            return false;
742
        }
743
744 77
        $mSig = $response->value();
745 77
        if ($client->return_type != 'phpvals') {
746 77
            $decoder = new $decoderClass();
747 77
            $mSig = $decoder->decode($mSig);
748
        }
749
750 77
        if (!is_array($mSig) || count($mSig) <= $sigNum) {
751
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
752
            return false;
753
        }
754
755 77
        return $mSig[$sigNum];
756
    }
757
758
    /**
759
     * @param Client $client
760
     * @param string $methodName
761
     * @param array $extraOptions
762
     * @return string in case of any error, an empty string is returned, no warnings generated
763
     */
764 77
    protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
765
    {
766 77
        $namespace = '\\PhpXmlRpc\\';
767 77
        $reqClass = $namespace . 'Request';
768 77
        $valClass = $namespace . 'Value';
769
770 77
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
771 77
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
772 77
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
773
774 77
        $mDesc = '';
775
776 77
        $req = new $reqClass('system.methodHelp');
777 77
        $req->addparam(new $valClass($methodName));
778 77
        $client->setDebug($debug);
779 77
        $response = $client->send($req, $timeout, $protocol);
780 77
        if (!$response->faultCode()) {
781 77
            $mDesc = $response->value();
782 77
            if ($client->return_type != 'phpvals') {
783 77
                $mDesc = $mDesc->scalarval();
784
            }
785
        }
786
787 77
        return $mDesc;
788
    }
789
790
    /**
791
     * @param Client $client
792
     * @param string $methodName
793
     * @param array $extraOptions
794
     * @param array $mSig
795
     * @return \Closure
796
     *
797
     * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
798
     */
799
    protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
800
    {
801
        // we clone the client, so that we can modify it a bit independently of the original
802
        $clientClone = clone $client;
803
        $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
804
        {
805
            $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
806
            $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
807
            $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
808
            $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
809 View Code Duplication
            if (isset($extraOptions['return_on_fault'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
810
                $decodeFault = true;
811
                $faultResponse = $extraOptions['return_on_fault'];
812
            } else {
813
                $decodeFault = false;
814
            }
815
816
            $namespace = '\\PhpXmlRpc\\';
817
            $reqClass = $namespace . 'Request';
818
            $encoderClass = $namespace . 'Encoder';
819
            $valueClass = $namespace . 'Value';
820
821
            $encoder = new $encoderClass();
822
            $encodeOptions = array();
823
            if ($encodePhpObjects) {
824
                $encodeOptions[] = 'encode_php_objs';
825
            }
826
            $decodeOptions = array();
827
            if ($decodePhpObjects) {
828
                $decodeOptions[] = 'decode_php_objs';
829
            }
830
831
            /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
832
833
            // support one extra parameter: debug
834
            $maxArgs = count($mSig)-1; // 1st element is the return type
835
            $currentArgs = func_get_args();
836
            if (func_num_args() == ($maxArgs+1)) {
837
                $debug = array_pop($currentArgs);
838
                $clientClone->setDebug($debug);
839
            }
840
841
            $xmlrpcArgs = array();
842
            foreach($currentArgs as $i => $arg) {
843
                if ($i == $maxArgs) {
844
                    break;
845
                }
846
                $pType = $mSig[$i+1];
847
                if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
848
                    $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
849
                ) {
850
                    // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
851
                    // we make sure to honour the xmlrpc signature
852
                    $xmlrpcArgs[] = new $valueClass($arg, $pType);
853
                } else {
854
                    $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
855
                }
856
            }
857
858
            $req = new $reqClass($methodName, $xmlrpcArgs);
859
            // use this to get the maximum decoding flexibility
860
            $clientClone->return_type = 'xmlrpcvals';
861
            $resp = $clientClone->send($req, $timeout, $protocol);
862
            if ($resp->faultcode()) {
863
                if ($decodeFault) {
864
                    if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
865
                            (strpos($faultResponse, '%faultString%') !== false))) {
866
                        $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
867
                            array($resp->faultCode(), $resp->faultString()), $faultResponse);
0 ignored issues
show
Bug introduced by
The variable $faultResponse does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
868
                    }
869
                    return $faultResponse;
870
                } else {
871
                    return $resp;
872
                }
873
            } else {
874
                return $encoder->decode($resp->value(), $decodeOptions);
875
            }
876
        };
877
878
        return $function;
879
    }
880
881
    /**
882
     * @param Client $client
883
     * @param string $methodName
884
     * @param array $extraOptions
885
     * @param string $newFuncName
886
     * @param array $mSig
887
     * @param string $mDesc
888
     * @return array
889
     */
890 77
    public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
891
    {
892 77
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
893 77
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
894 77
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
895 77
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
896 77
        $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
897 77
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
898 77 View Code Duplication
        if (isset($extraOptions['return_on_fault'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
899
            $decodeFault = true;
900
            $faultResponse = $extraOptions['return_on_fault'];
901
        } else {
902 77
            $decodeFault = false;
903 77
            $faultResponse = '';
904
        }
905
906 77
        $namespace = '\\PhpXmlRpc\\';
907
908 77
        $code = "function $newFuncName (";
909 77
        if ($clientCopyMode < 2) {
910
            // client copy mode 0 or 1 == full / partial client copy in emitted code
911 58
            $verbatimClientCopy = !$clientCopyMode;
912 58
            $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
913 58
            $innerCode .= "\$client->setDebug(\$debug);\n";
914 58
            $this_ = '';
915
        } else {
916
            // client copy mode 2 == no client copy in emitted code
917 20
            $innerCode = '';
918 20
            $this_ = 'this->';
919
        }
920 77
        $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
921
922 77
        if ($mDesc != '') {
923
            // take care that PHP comment is not terminated unwillingly by method description
924 77
            $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
925
        } else {
926
            $mDesc = "/**\nFunction $newFuncName\n";
927
        }
928
929
        // param parsing
930 77
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
931 77
        $plist = array();
932 77
        $pCount = count($mSig);
933 77 View Code Duplication
        for ($i = 1; $i < $pCount; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
934 58
            $plist[] = "\$p$i";
935 58
            $pType = $mSig[$i];
936 58
            if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
937 58
                $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
938
            ) {
939
                // only build directly xmlrpc values when type is known and scalar
940 58
                $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
941
            } else {
942
                if ($encodePhpObjects) {
943
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
944
                } else {
945
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
946
                }
947
            }
948 58
            $innerCode .= "\$req->addparam(\$p$i);\n";
949 58
            $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
950
        }
951 77
        if ($clientCopyMode < 2) {
952 58
            $plist[] = '$debug=0';
953 58
            $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
954
        }
955 77
        $plist = implode(', ', $plist);
956 77
        $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
957
958 77
        $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
959 77 View Code Duplication
        if ($decodeFault) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
960
            if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
961
                $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
962
            } else {
963
                $respCode = var_export($faultResponse, true);
964
            }
965
        } else {
966 77
            $respCode = '$res';
967
        }
968 77
        if ($decodePhpObjects) {
969 20
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
970
        } else {
971 58
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
972
        }
973
974 77
        $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
975
976 77
        return array('source' => $code, 'docstring' => $mDesc);
977
    }
978
979
    /**
980
     * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
981
     * all xmlrpc methods exposed by the remote server as own methods.
982
     * For more details see wrapXmlrpcMethod.
983
     *
984
     * For a slimmer alternative, see the code in demo/client/proxy.php
985
     *
986
     * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
987
     *
988
     * @param Client $client the client obj all set to query the desired server
989
     * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
990
     *              - string method_filter      regular expression
991
     *              - string new_class_name
992
     *              - string prefix
993
     *              - bool   simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
994
     *
995
     * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriate option is set in extra_options)
996
     */
997 20
    public function wrapXmlrpcServer($client, $extraOptions = array())
998
    {
999 20
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
1000 20
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
1001 20
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
1002 20
        $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
1003 20
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
1004 20
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
1005 20
        $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1006 20
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1007 20
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1008 20
        $namespace = '\\PhpXmlRpc\\';
1009
1010 20
        $reqClass = $namespace . 'Request';
1011 20
        $decoderClass = $namespace . 'Encoder';
1012
1013 20
        $req = new $reqClass('system.listMethods');
1014 20
        $response = $client->send($req, $timeout, $protocol);
1015 20
        if ($response->faultCode()) {
1016
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1017
1018
            return false;
1019
        } else {
1020 20
            $mList = $response->value();
1021 20
            if ($client->return_type != 'phpvals') {
1022 20
                $decoder = new $decoderClass();
1023 20
                $mList = $decoder->decode($mList);
1024
            }
1025 20
            if (!is_array($mList) || !count($mList)) {
1026
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1027
1028
                return false;
1029
            } else {
1030
                // pick a suitable name for the new function, avoiding collisions
1031 20
                if ($newClassName != '') {
1032
                    $xmlrpcClassName = $newClassName;
1033
                } else {
1034 20
                    $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1035 20
                            array('_', ''), $client->server) . '_client';
1036
                }
1037 20
                while ($buildIt && class_exists($xmlrpcClassName)) {
1038 19
                    $xmlrpcClassName .= 'x';
1039
                }
1040
1041
                /// @todo add function setdebug() to new class, to enable/disable debugging
1042 20
                $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1043 20
                $source .= "function __construct()\n{\n";
1044 20
                $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1045 20
                $source .= "\$this->client = \$client;\n}\n\n";
1046
                $opts = array(
1047 20
                    'return_source' => true,
1048 20
                    'simple_client_copy' => 2, // do not produce code to copy the client object
1049 20
                    'timeout' => $timeout,
1050 20
                    'protocol' => $protocol,
1051 20
                    'encode_php_objs' => $encodePhpObjects,
1052 20
                    'decode_php_objs' => $decodePhpObjects,
1053 20
                    'prefix' => $prefix,
1054
                );
1055
                /// @todo build phpdoc for class definition, too
1056 20
                foreach ($mList as $mName) {
1057 20
                    if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1058
                        // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1059 20
                        $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1060 20
                            array('_', ''), $mName);
1061 20
                        $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1062 20
                        if ($methodWrap) {
1063 20
                            if (!$buildIt) {
1064
                                $source .= $methodWrap['docstring'];
1065
                            }
1066 20
                            $source .= $methodWrap['source'] . "\n";
1067
                        } else {
1068
                            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1069
                        }
1070
                    }
1071
                }
1072 20
                $source .= "}\n";
1073 20
                if ($buildIt) {
1074 20
                    $allOK = 0;
1075 20
                    eval($source . '$allOK=1;');
1076 20
                    if ($allOK) {
1077 20
                        return $xmlrpcClassName;
1078
                    } else {
1079
                        Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1080
                        return false;
1081
                    }
1082
                } else {
1083
                    return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1084
                }
1085
            }
1086
        }
1087
    }
1088
1089
    /**
1090
     * Given necessary info, generate php code that will build a client object just like the given one.
1091
     * Take care that no full checking of input parameters is done to ensure that
1092
     * valid php code is emitted.
1093
     * @param Client $client
1094
     * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1095
     * @param string $prefix used for the return_type of the created client
1096
     * @param string $namespace
1097
     *
1098
     * @return string
1099
     */
1100 77 View Code Duplication
    protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1101
    {
1102 77
        $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1103 77
            "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1104
1105
        // copy all client fields to the client that will be generated runtime
1106
        // (this provides for future expansion or subclassing of client obj)
1107 77
        if ($verbatimClientCopy) {
1108 77
            foreach ($client as $fld => $val) {
0 ignored issues
show
Bug introduced by
The expression $client of type object<PhpXmlRpc\Client> is not traversable.
Loading history...
1109 77
                if ($fld != 'debug' && $fld != 'return_type') {
1110 77
                    $val = var_export($val, true);
1111 77
                    $code .= "\$client->$fld = $val;\n";
1112
                }
1113
            }
1114
        }
1115
        // only make sure that client always returns the correct data type
1116 77
        $code .= "\$client->return_type = '{$prefix}vals';\n";
1117
        //$code .= "\$client->setDebug(\$debug);\n";
1118 77
        return $code;
1119
    }
1120
}
1121