Completed
Push — master ( 8f4643...4ef224 )
by Gaetano
07:48 queued 06:06
created

Wrapper::buildWrapFunctionSource()   F

Complexity

Conditions 17
Paths 5760

Size

Total Lines 81

Duplication

Lines 14
Ratio 17.28 %

Code Coverage

Tests 37
CRAP Score 18.6244

Importance

Changes 0
Metric Value
cc 17
nc 5760
nop 5
dl 14
loc 81
ccs 37
cts 45
cp 0.8222
crap 18.6244
rs 1.0499
c 0
b 0
f 0

How to fix   Long Method    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-2015 G. Giunta
5
 * @license code licensed under the BSD License: see file license.txt
6
 */
7
8
namespace PhpXmlRpc;
9
10
/**
11
 * PHP-XMLRPC "wrapper" class - generate stubs to transparently access xmlrpc methods as php functions and vice-versa.
12
 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
13
 *
14
 * @todo use some better templating system for code generation?
15
 * @todo implement method wrapping with preservation of php objs in calls
16
 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
17
 */
18
class Wrapper
19
{
20
    /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
21
    public static $objHolder = array();
22
23
    /**
24
     * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
25
     * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
26
     * Notes:
27
     * - for php 'resource' types returns empty string, since resources cannot be serialized;
28
     * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
29
     * - for php arrays always return array, even though arrays sometimes serialize as json structs
30
     * - for 'void' and 'null' returns 'undefined'
31
     *
32
     * @param string $phpType
33
     *
34
     * @return string
35
     */
36 438
    public function php2XmlrpcType($phpType)
37
    {
38 438
        switch (strtolower($phpType)) {
39 438
            case 'string':
40 438
                return Value::$xmlrpcString;
41 438
            case 'integer':
42 438
            case Value::$xmlrpcInt: // 'int'
43 438
            case Value::$xmlrpcI4:
44 438
            case Value::$xmlrpcI8:
45 438
                return Value::$xmlrpcInt;
46 438
            case Value::$xmlrpcDouble: // 'double'
47
                return Value::$xmlrpcDouble;
48 438
            case 'bool':
49 438
            case Value::$xmlrpcBoolean: // 'boolean'
50 438
            case 'false':
51 438
            case 'true':
52
                return Value::$xmlrpcBoolean;
53 438
            case Value::$xmlrpcArray: // 'array':
54
                return Value::$xmlrpcArray;
55 438
            case 'object':
56 438
            case Value::$xmlrpcStruct: // 'struct'
57
                return Value::$xmlrpcStruct;
58 438
            case Value::$xmlrpcBase64:
59
                return Value::$xmlrpcBase64;
60 438
            case 'resource':
61
                return '';
62
            default:
63 438
                if (class_exists($phpType)) {
64 438
                    return Value::$xmlrpcStruct;
65
                } else {
66
                    // unknown: might be any 'extended' xmlrpc type
67 438
                    return Value::$xmlrpcValue;
68
                }
69
        }
70
    }
71
72
    /**
73
     * Given a string defining a phpxmlrpc type return the corresponding php type.
74
     *
75
     * @param string $xmlrpcType
76
     *
77
     * @return string
78
     */
79 69
    public function xmlrpc2PhpType($xmlrpcType)
80
    {
81 69
        switch (strtolower($xmlrpcType)) {
82 69
            case 'base64':
83 69
            case 'datetime.iso8601':
84 69
            case 'string':
85 52
                return Value::$xmlrpcString;
86 69
            case 'int':
87 18
            case 'i4':
88 18
            case 'i8':
89 52
                return 'integer';
90 18
            case 'struct':
91 18
            case 'array':
92
                return 'array';
93 18
            case 'double':
94
                return 'float';
95 18
            case 'undefined':
96 18
                return 'mixed';
97
            case 'boolean':
98
            case 'null':
99
            default:
100
                // unknown: might be any xmlrpc type
101
                return strtolower($xmlrpcType);
102
        }
103
    }
104
105
    /**
106
     * Given a user-defined PHP function, create a PHP 'wrapper' function that can
107
     * be exposed as xmlrpc method from an xmlrpc server object and called from remote
108
     * clients (as well as its corresponding signature info).
109
     *
110
     * Since php is a typeless language, to infer types of input and output parameters,
111
     * it relies on parsing the javadoc-style comment block associated with the given
112
     * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
113
     * in the '@param' tag is also allowed, if you need the php function to receive/send
114
     * data in that particular format (note that base64 encoding/decoding is transparently
115
     * carried out by the lib, while datetime vals are passed around as strings)
116
     *
117
     * Known limitations:
118
     * - only works for user-defined functions, not for PHP internal functions
119
     *   (reflection does not support retrieving number/type of params for those)
120
     * - functions returning php objects will generate special structs in xmlrpc responses:
121
     *   when the xmlrpc decoding of those responses is carried out by this same lib, using
122
     *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
123
     *   In short: php objects can be serialized, too (except for their resource members),
124
     *   using this function.
125
     *   Other libs might choke on the very same xml that will be generated in this case
126
     *   (i.e. it has a nonstandard attribute on struct element tags)
127
     *
128
     * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
129
     * php functions (ie. functions not expecting a single Request obj as parameter)
130
     * is by making use of the functions_parameters_type class member.
131
     *
132
     * @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
133
     * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
134
     * @param array $extraOptions (optional) array of options for conversion. valid values include:
135
     *                            - bool return_source     when true, php code w. function definition will be returned, instead of a closure
136
     *                            - bool encode_php_objs   let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
137
     *                            - bool decode_php_objs   --- WARNING !!! possible security hazard. only use it with trusted servers ---
138
     *                            - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
139
     *
140
     * @return array|false false on error, or an array containing the name of the new php function,
141
     *                     its signature and docs, to be used in the server dispatch map
142
     *
143
     * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
144
     * @todo finish using phpdoc info to build method sig if all params are named but out of order
145
     * @todo add a check for params of 'resource' type
146
     * @todo add some trigger_errors / error_log when returning false?
147
     * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
148
     * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
149
     * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
150
     * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
151
     */
152 438
    public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
153
    {
154 438
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
155
156 438
        if (is_string($callable) && strpos($callable, '::') !== false) {
157 438
            $callable = explode('::', $callable);
158
        }
159 438
        if (is_array($callable)) {
160 438
            if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
161
                error_log('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
162
                return false;
163
            }
164 438 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...
165 438
                $plainFuncName = implode('::', $callable);
166 438
            } elseif (is_object($callable[0])) {
167 438
                $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
168
            }
169 438
            $exists = method_exists($callable[0], $callable[1]);
170 438
        } else if ($callable instanceof \Closure) {
171
            // we do not support creating code which wraps closures, as php does not allow to serialize them
172 438
            if (!$buildIt) {
173
                error_log('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
174
                return false;
175
            }
176
177 438
            $plainFuncName = 'Closure';
178 438
            $exists = true;
179
        } else {
180 438
            $plainFuncName = $callable;
181 438
            $exists = function_exists($callable);
182
        }
183
184 438
        if (!$exists) {
185
            error_log('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...
186
            return false;
187
        }
188
189 438
        $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...
190 438
        if (!$funcDesc) {
191
            return false;
192
        }
193
194 438
        $funcSigs = $this->buildMethodSignatures($funcDesc);
195
196 438
        if ($buildIt) {
197 438
            $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...
198
        } else {
199 438
            $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
200 438
            $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...
201
        }
202
203
        $ret = array(
204 438
            'function' => $callable,
205 438
            'signature' => $funcSigs['sigs'],
206 438
            'docstring' => $funcDesc['desc'],
207 438
            'signature_docs' => $funcSigs['sigsDocs'],
208
        );
209 438
        if (!$buildIt) {
210 438
            $ret['function'] = $newFuncName;
211 438
            $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...
212
        }
213 438
        return $ret;
214
    }
215
216
    /**
217
     * Introspect a php callable and its phpdoc block and extract information about its signature
218
     *
219
     * @param callable $callable
220
     * @param string $plainFuncName
221
     * @return array|false
222
     */
223 438
    protected function introspectFunction($callable, $plainFuncName)
224
    {
225
        // start to introspect PHP code
226 438
        if (is_array($callable)) {
227 438
            $func = new \ReflectionMethod($callable[0], $callable[1]);
228 438
            if ($func->isPrivate()) {
229
                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
230
                return false;
231
            }
232 438
            if ($func->isProtected()) {
233
                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
234
                return false;
235
            }
236 438
            if ($func->isConstructor()) {
237
                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
238
                return false;
239
            }
240 438
            if ($func->isDestructor()) {
241
                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
242
                return false;
243
            }
244 438
            if ($func->isAbstract()) {
245
                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
246
                return false;
247
            }
248
            /// @todo add more checks for static vs. nonstatic?
249
        } else {
250 438
            $func = new \ReflectionFunction($callable);
251
        }
252 438
        if ($func->isInternal()) {
253
            // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
254
            // instead of getparameters to fully reflect internal php functions ?
255
            error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
256
            return false;
257
        }
258
259
        // retrieve parameter names, types and description from javadoc comments
260
261
        // function description
262 438
        $desc = '';
263
        // type of return val: by default 'any'
264 438
        $returns = Value::$xmlrpcValue;
265
        // desc of return val
266 438
        $returnsDocs = '';
267
        // type + name of function parameters
268 438
        $paramDocs = array();
269
270 438
        $docs = $func->getDocComment();
271 438
        if ($docs != '') {
272 438
            $docs = explode("\n", $docs);
273 438
            $i = 0;
274 438
            foreach ($docs as $doc) {
275 438
                $doc = trim($doc, " \r\t/*");
276 438
                if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
277 438
                    if ($desc) {
278 438
                        $desc .= "\n";
279
                    }
280 438
                    $desc .= $doc;
281 438
                } elseif (strpos($doc, '@param') === 0) {
282
                    // syntax: @param type $name [desc]
283 438
                    if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
284 438
                        $name = strtolower(trim($matches[2]));
285
                        //$paramDocs[$name]['name'] = trim($matches[2]);
286 438
                        $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
287 438
                        $paramDocs[$name]['type'] = $matches[1];
288
                    }
289 438
                    $i++;
290 438
                } elseif (strpos($doc, '@return') === 0) {
291
                    // syntax: @return type [desc]
292 438
                    if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
293 438
                        $returns = $matches[1];
294 438
                        if (isset($matches[2])) {
295 438
                            $returnsDocs = trim($matches[2]);
296
                        }
297
                    }
298
                }
299
            }
300
        }
301
302
        // execute introspection of actual function prototype
303 438
        $params = array();
304 438
        $i = 0;
305 438
        foreach ($func->getParameters() as $paramObj) {
306 438
            $params[$i] = array();
307 438
            $params[$i]['name'] = '$' . $paramObj->getName();
308 438
            $params[$i]['isoptional'] = $paramObj->isOptional();
309 438
            $i++;
310
        }
311
312
        return array(
313 438
            'desc' => $desc,
314 438
            'docs' => $docs,
315 438
            'params' => $params, // array, positionally indexed
316 438
            'paramDocs' => $paramDocs, // array, indexed by name
317 438
            'returns' => $returns,
318 438
            'returnsDocs' =>$returnsDocs,
319
        );
320
    }
321
322
    /**
323
     * Given the method description given by introspection, create method signature data
324
     *
325
     * @todo support better docs with multiple types separated by pipes by creating multiple signatures
326
     *       (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
327
     *
328
     * @param array $funcDesc as generated by self::introspectFunction()
329
     *
330
     * @return array
331
     */
332 438
    protected function buildMethodSignatures($funcDesc)
333
    {
334 438
        $i = 0;
335 438
        $parsVariations = array();
336 438
        $pars = array();
337 438
        $pNum = count($funcDesc['params']);
338 438 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...
339
            /* // match by name real param and documented params
340
            $name = strtolower($param['name']);
341
            if (!isset($funcDesc['paramDocs'][$name])) {
342
                $funcDesc['paramDocs'][$name] = array();
343
            }
344
            if (!isset($funcDesc['paramDocs'][$name]['type'])) {
345
                $funcDesc['paramDocs'][$name]['type'] = 'mixed';
346
            }*/
347
348 438
            if ($param['isoptional']) {
349
                // this particular parameter is optional. save as valid previous list of parameters
350
                $parsVariations[] = $pars;
351
            }
352
353 438
            $pars[] = "\$p$i";
354 438
            $i++;
355 438
            if ($i == $pNum) {
356
                // last allowed parameters combination
357 438
                $parsVariations[] = $pars;
358
            }
359
        }
360
361 438
        if (count($parsVariations) == 0) {
362
            // only known good synopsis = no parameters
363 438
            $parsVariations[] = array();
364
        }
365
366 438
        $sigs = array();
367 438
        $sigsDocs = array();
368 438
        foreach ($parsVariations as $pars) {
369
            // build a signature
370 438
            $sig = array($this->php2XmlrpcType($funcDesc['returns']));
371 438
            $pSig = array($funcDesc['returnsDocs']);
372 438
            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...
373 438
                $name = strtolower($funcDesc['params'][$i]['name']);
374 438
                if (isset($funcDesc['paramDocs'][$name]['type'])) {
375 438
                    $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
376
                } else {
377 438
                    $sig[] = Value::$xmlrpcValue;
378
                }
379 438
                $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
380
            }
381 438
            $sigs[] = $sig;
382 438
            $sigsDocs[] = $pSig;
383
        }
384
385
        return array(
386 438
            'sigs' => $sigs,
387 438
            'sigsDocs' => $sigsDocs
388
        );
389
    }
390
391
    /**
392
     * Creates a closure that will execute $callable
393
     * @todo validate params? In theory all validation is left to the dispatch map...
394
     * @todo add support for $catchWarnings
395
     *
396
     * @param $callable
397
     * @param array $extraOptions
398
     * @param string $plainFuncName
399
     * @param array $funcDesc
400
     * @return \Closure
401
     */
402
    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...
403
    {
404
        /**
405
         * @param Request $req
406
         * @return mixed
407
         */
408 438
        $function = function($req) use($callable, $extraOptions, $funcDesc)
409
        {
410 71
            $nameSpace = '\\PhpXmlRpc\\';
411 71
            $encoderClass = $nameSpace.'Encoder';
412 71
            $responseClass = $nameSpace.'Response';
413 71
            $valueClass = $nameSpace.'Value';
414
415
            // validate number of parameters received
416
            // this should be optional really, as we assume the server does the validation
417 71
            $minPars = count($funcDesc['params']);
418 71
            $maxPars = $minPars;
419 71
            foreach ($funcDesc['params'] as $i => $param) {
420 71
                if ($param['isoptional']) {
421
                    // this particular parameter is optional. We assume later ones are as well
422
                    $minPars = $i;
423
                    break;
424
                }
425
            }
426 71
            $numPars = $req->getNumParams();
427 71
            if ($numPars < $minPars || $numPars > $maxPars) {
428
                return new $responseClass(0, 3, 'Incorrect parameters passed to method');
429
            }
430
431 71
            $encoder = new $encoderClass();
432 71
            $options = array();
433 71
            if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
434
                $options[] = 'decode_php_objs';
435
            }
436 71
            $params = $encoder->decode($req, $options);
437
438 71
            $result = call_user_func_array($callable, $params);
439
440 71
            if (! is_a($result, $responseClass)) {
441 71
                if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
442
                    $result = new $valueClass($result, $funcDesc['returns']);
443
                } else {
444 71
                    $options = array();
445 71
                    if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
446 1
                        $options[] = 'encode_php_objs';
447
                    }
448
449 71
                    $result = $encoder->encode($result, $options);
450
                }
451 71
                $result = new $responseClass($result);
452
            }
453
454 71
            return $result;
455 438
        };
456
457 438
        return $function;
458
    }
459
460
    /**
461
     * Return a name for a new function, based on $callable, insuring its uniqueness
462
     * @param mixed $callable a php callable, or the name of an xmlrpc method
463
     * @param string $newFuncName when not empty, it is used instead of the calculated version
464
     * @return string
465
     */
466 506
    protected function newFunctionName($callable, $newFuncName, $extraOptions)
467
    {
468
        // determine name of new php function
469
470 506
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
471
472 506
        if ($newFuncName == '') {
473 489
            if (is_array($callable)) {
474 438
                if (is_string($callable[0])) {
475 438
                    $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
476
                } else {
477 438
                    $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
478
                }
479
            } else {
480 489
                if ($callable instanceof \Closure) {
481
                    $xmlrpcFuncName = "{$prefix}_closure";
482
                } else {
483 489
                    $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
484 489
                        array('_', ''), $callable);
485 489
                    $xmlrpcFuncName = "{$prefix}_$callable";
486
                }
487
            }
488
        } else {
489 18
            $xmlrpcFuncName = $newFuncName;
490
        }
491
492 506
        while (function_exists($xmlrpcFuncName)) {
493 487
            $xmlrpcFuncName .= 'x';
494
        }
495
496 506
        return $xmlrpcFuncName;
497
    }
498
499
    /**
500
     * @param $callable
501
     * @param string $newFuncName
502
     * @param array $extraOptions
503
     * @param string $plainFuncName
504
     * @param array $funcDesc
505
     * @return string
506
     *
507
     * @todo add a nice phpdoc block in the generated source
508
     */
509 438
    protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
510
    {
511 438
        $namespace = '\\PhpXmlRpc\\';
512
513 438
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
514 438
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
515 438
        $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
516
517 438
        $i = 0;
518 438
        $parsVariations = array();
519 438
        $pars = array();
520 438
        $pNum = count($funcDesc['params']);
521 438 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...
522
523 438
            if ($param['isoptional']) {
524
                // this particular parameter is optional. save as valid previous list of parameters
525
                $parsVariations[] = $pars;
526
            }
527
528 438
            $pars[] = "\$p[$i]";
529 438
            $i++;
530 438
            if ($i == $pNum) {
531
                // last allowed parameters combination
532 438
                $parsVariations[] = $pars;
533
            }
534
        }
535
536 438
        if (count($parsVariations) == 0) {
537
            // only known good synopsis = no parameters
538
            $parsVariations[] = array();
539
            $minPars = 0;
540
            $maxPars = 0;
541
        } else {
542 438
            $minPars = count($parsVariations[0]);
543 438
            $maxPars = count($parsVariations[count($parsVariations)-1]);
544
        }
545
546
        // build body of new function
547
548 438
        $innerCode = "\$paramCount = \$req->getNumParams();\n";
549 438
        $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
550
551 438
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
552 438
        if ($decodePhpObjects) {
553
            $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
554
        } else {
555 438
            $innerCode .= "\$p = \$encoder->decode(\$req);\n";
556
        }
557
558
        // since we are building source code for later use, if we are given an object instance,
559
        // we go out of our way and store a pointer to it in a static class var var...
560 438
        if (is_array($callable) && is_object($callable[0])) {
561 438
            self::$objHolder[$newFuncName] = $callable[0];
562 438
            $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
563 438
            $realFuncName = '$obj->' . $callable[1];
564
        } else {
565 438
            $realFuncName = $plainFuncName;
566
        }
567 438
        foreach ($parsVariations as $i => $pars) {
568 438
            $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
569 438
            if ($i < (count($parsVariations) - 1))
570
                $innerCode .= "else\n";
571
        }
572 438
        $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
573 438
        if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
574
            $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
575
        } else {
576 438
            if ($encodePhpObjects) {
577
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
578
            } else {
579 438
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
580
            }
581
        }
582
        // shall we exclude functions returning by ref?
583
        // if($func->returnsReference())
584
        //     return false;
585
586 438
        $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
587
588 438
        return $code;
589
    }
590
591
    /**
592
     * Given a user-defined PHP class or php object, map its methods onto a list of
593
     * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
594
     * object and called from remote clients (as well as their corresponding signature info).
595
     *
596
     * @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
597
     * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
598
     *                            - 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
599
     *                            - string method_filter  a regexp used to filter methods to wrap based on their names
600
     *                            - string prefix         used for the names of the xmlrpc methods created
601
     *
602
     * @return array|false false on failure
603
     */
604 438
    public function wrapPhpClass($className, $extraOptions = array())
605
    {
606 438
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
607 438
        $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
608 438
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
609
610 438
        $results = array();
611 438
        $mList = get_class_methods($className);
612 438
        foreach ($mList as $mName) {
613 438
            if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
614 438
                $func = new \ReflectionMethod($className, $mName);
615 438
                if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
616 438
                    if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
617 438
                        (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
618
                    ) {
619 438
                        $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
620 438
                        if ($methodWrap) {
621 438
                            if (is_object($className)) {
622 438
                                $realClassName = get_class($className);
623
                            }else {
624
                                $realClassName = $className;
625
                            }
626 438
                            $results[$prefix."$realClassName.$mName"] = $methodWrap;
627
                        }
628
                    }
629
                }
630
            }
631
        }
632
633 438
        return $results;
634
    }
635
636
    /**
637
     * Given an xmlrpc client and a method name, register a php wrapper function
638
     * that will call it and return results using native php types for both
639
     * params and results. The generated php function will return a Response
640
     * object for failed xmlrpc calls.
641
     *
642
     * Known limitations:
643
     * - server must support system.methodsignature for the wanted xmlrpc method
644
     * - for methods that expose many signatures, only one can be picked (we
645
     *   could in principle check if signatures differ only by number of params
646
     *   and not by type, but it would be more complication than we can spare time)
647
     * - nested xmlrpc params: the caller of the generated php function has to
648
     *   encode on its own the params passed to the php function if these are structs
649
     *   or arrays whose (sub)members include values of type datetime or base64
650
     *
651
     * Notes: the connection properties of the given client will be copied
652
     * and reused for the connection used during the call to the generated
653
     * php function.
654
     * Calling the generated php function 'might' be slow: a new xmlrpc client
655
     * is created on every invocation and an xmlrpc-connection opened+closed.
656
     * An extra 'debug' param is appended to param list of xmlrpc method, useful
657
     * for debugging purposes.
658
     *
659
     * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
660
     * @todo if we can not retrieve method signature, create a php function with varargs
661
     * @todo allow the created function to throw exceptions on method calls failures
662
     * @todo if caller did not specify a specific sig, shall we support all of them?
663
     *       It might be hard (hence slow) to match based on type and number of arguments...
664
     *
665
     * @param Client $client an xmlrpc client set up correctly to communicate with target server
666
     * @param string $methodName the xmlrpc method to be mapped to a php function
667
     * @param array $extraOptions array of options that specify conversion details. Valid options include
668
     *                            - integer signum              the index of the method signature to use in mapping (if method exposes many sigs)
669
     *                            - integer timeout             timeout (in secs) to be used when executing function/calling remote method
670
     *                            - string  protocol            'http' (default), 'http11' or 'https'
671
     *                            - string  new_function_name   the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
672
     *                            - string  return_source       if true return php code w. function definition instead of function itself (closure)
673
     *                            - bool    encode_php_objs     let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
674
     *                            - bool    decode_php_objs     --- WARNING !!! possible security hazard. only use it with trusted servers ---
675
     *                            - 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
676
     *                            - bool    debug               set it to 1 or 2 to see debug results of querying server for method synopsis
677
     *                            - 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)
678
     *
679
     * @return \closure|array|false false on failure, closure by default and array for return_source = true
680
     */
681 75
    public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
682
    {
683 75
        $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
684
685 75
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
686
687 75
        $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
688 75
        if (!$mSig) {
689 6
            return false;
690
        }
691
692 69
        if ($buildIt) {
693
            return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
694
        } else {
695
            // if in 'offline' mode, retrieve method description too.
696
            // in online mode, favour speed of operation
697 69
            $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
698
699 69
            $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
700
701 69
            $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
702
            /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
703
                $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
704
                $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
705
                $faultResponse, $namespace);*/
706
707 69
            $results['function'] = $newFuncName;
708
709 69
            return $results;
710
        }
711
712
    }
713
714
    /**
715
     * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
716
     * @param Client $client
717
     * @param string $methodName
718
     * @param array $extraOptions
719
     * @return false|array
720
     */
721 75
    protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
722
    {
723 75
        $namespace = '\\PhpXmlRpc\\';
724 75
        $reqClass = $namespace . 'Request';
725 75
        $valClass = $namespace . 'Value';
726 75
        $decoderClass = $namespace . 'Encoder';
727
728 75
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
729 75
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
730 75
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
731 75
        $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
732
733 75
        $req = new $reqClass('system.methodSignature');
734 75
        $req->addparam(new $valClass($methodName));
735 75
        $client->setDebug($debug);
736 75
        $response = $client->send($req, $timeout, $protocol);
737 75
        if ($response->faultCode()) {
738 6
            error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
739 6
            return false;
740
        }
741
742 69
        $mSig = $response->value();
743 69
        if ($client->return_type != 'phpvals') {
744 69
            $decoder = new $decoderClass();
745 69
            $mSig = $decoder->decode($mSig);
746
        }
747
748 69
        if (!is_array($mSig) || count($mSig) <= $sigNum) {
749
            error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
750
            return false;
751
        }
752
753 69
        return $mSig[$sigNum];
754
    }
755
756
    /**
757
     * @param Client $client
758
     * @param string $methodName
759
     * @param array $extraOptions
760
     * @return string in case of any error, an empty string is returned, no warnings generated
761
     */
762 69
    protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
763
    {
764 69
        $namespace = '\\PhpXmlRpc\\';
765 69
        $reqClass = $namespace . 'Request';
766 69
        $valClass = $namespace . 'Value';
767
768 69
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
769 69
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
770 69
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
771
772 69
        $mDesc = '';
773
774 69
        $req = new $reqClass('system.methodHelp');
775 69
        $req->addparam(new $valClass($methodName));
776 69
        $client->setDebug($debug);
777 69
        $response = $client->send($req, $timeout, $protocol);
778 69
        if (!$response->faultCode()) {
779 69
            $mDesc = $response->value();
780 69
            if ($client->return_type != 'phpvals') {
781 69
                $mDesc = $mDesc->scalarval();
782
            }
783
        }
784
785 69
        return $mDesc;
786
    }
787
788
    /**
789
     * @param Client $client
790
     * @param string $methodName
791
     * @param array $extraOptions
792
     * @param array $mSig
793
     * @return \Closure
794
     *
795
     * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
796
     */
797
    protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
798
    {
799
        // we clone the client, so that we can modify it a bit independently of the original
800
        $clientClone = clone $client;
801
        $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
802
        {
803
            $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
804
            $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
805
            $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
806
            $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
807 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...
808
                $decodeFault = true;
809
                $faultResponse = $extraOptions['return_on_fault'];
810
            } else {
811
                $decodeFault = false;
812
            }
813
814
            $namespace = '\\PhpXmlRpc\\';
815
            $reqClass = $namespace . 'Request';
816
            $encoderClass = $namespace . 'Encoder';
817
            $valueClass = $namespace . 'Value';
818
819
            $encoder = new $encoderClass();
820
            $encodeOptions = array();
821
            if ($encodePhpObjects) {
822
                $encodeOptions[] = 'encode_php_objs';
823
            }
824
            $decodeOptions = array();
825
            if ($decodePhpObjects) {
826
                $decodeOptions[] = 'decode_php_objs';
827
            }
828
829
            /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
830
831
            // support one extra parameter: debug
832
            $maxArgs = count($mSig)-1; // 1st element is the return type
833
            $currentArgs = func_get_args();
834
            if (func_num_args() == ($maxArgs+1)) {
835
                $debug = array_pop($currentArgs);
836
                $clientClone->setDebug($debug);
837
            }
838
839
            $xmlrpcArgs = array();
840
            foreach($currentArgs as $i => $arg) {
841
                if ($i == $maxArgs) {
842
                    break;
843
                }
844
                $pType = $mSig[$i+1];
845
                if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
846
                    $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
847
                ) {
848
                    // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
849
                    // we make sure to honour the xmlrpc signature
850
                    $xmlrpcArgs[] = new $valueClass($arg, $pType);
851
                } else {
852
                    $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
853
                }
854
            }
855
856
            $req = new $reqClass($methodName, $xmlrpcArgs);
857
            // use this to get the maximum decoding flexibility
858
            $clientClone->return_type = 'xmlrpcvals';
859
            $resp = $clientClone->send($req, $timeout, $protocol);
860
            if ($resp->faultcode()) {
861
                if ($decodeFault) {
862
                    if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
863
                            (strpos($faultResponse, '%faultString%') !== false))) {
864
                        $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
865
                            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...
866
                    }
867
                    return $faultResponse;
868
                } else {
869
                    return $resp;
870
                }
871
            } else {
872
                return $encoder->decode($resp->value(), $decodeOptions);
873
            }
874
        };
875
876
        return $function;
877
    }
878
879
    /**
880
     * @param Client $client
881
     * @param string $methodName
882
     * @param array $extraOptions
883
     * @param string $newFuncName
884
     * @param array $mSig
885
     * @param string $mDesc
886
     * @return array
887
     */
888 69
    public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
889
    {
890 69
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
891 69
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
892 69
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
893 69
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
894 69
        $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
895 69
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
896 69 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...
897
            $decodeFault = true;
898
            $faultResponse = $extraOptions['return_on_fault'];
899
        } else {
900 69
            $decodeFault = false;
901 69
            $faultResponse = '';
902
        }
903
904 69
        $namespace = '\\PhpXmlRpc\\';
905
906 69
        $code = "function $newFuncName (";
907 69
        if ($clientCopyMode < 2) {
908
            // client copy mode 0 or 1 == full / partial client copy in emitted code
909 52
            $verbatimClientCopy = !$clientCopyMode;
910 52
            $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
911 52
            $innerCode .= "\$client->setDebug(\$debug);\n";
912 52
            $this_ = '';
913
        } else {
914
            // client copy mode 2 == no client copy in emitted code
915 18
            $innerCode = '';
916 18
            $this_ = 'this->';
917
        }
918 69
        $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
919
920 69
        if ($mDesc != '') {
921
            // take care that PHP comment is not terminated unwillingly by method description
922 69
            $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
923
        } else {
924
            $mDesc = "/**\nFunction $newFuncName\n";
925
        }
926
927
        // param parsing
928 69
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
929 69
        $plist = array();
930 69
        $pCount = count($mSig);
931 69 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...
932 52
            $plist[] = "\$p$i";
933 52
            $pType = $mSig[$i];
934 52
            if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
935 52
                $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
936
            ) {
937
                // only build directly xmlrpc values when type is known and scalar
938 52
                $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
939
            } else {
940
                if ($encodePhpObjects) {
941
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
942
                } else {
943
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
944
                }
945
            }
946 52
            $innerCode .= "\$req->addparam(\$p$i);\n";
947 52
            $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
948
        }
949 69
        if ($clientCopyMode < 2) {
950 52
            $plist[] = '$debug=0';
951 52
            $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
952
        }
953 69
        $plist = implode(', ', $plist);
954 69
        $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
955
956 69
        $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
957 69 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...
958
            if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
959
                $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
960
            } else {
961
                $respCode = var_export($faultResponse, true);
962
            }
963
        } else {
964 69
            $respCode = '$res';
965
        }
966 69
        if ($decodePhpObjects) {
967 18
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
968
        } else {
969 52
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
970
        }
971
972 69
        $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
973
974 69
        return array('source' => $code, 'docstring' => $mDesc);
975
    }
976
977
    /**
978
     * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
979
     * all xmlrpc methods exposed by the remote server as own methods.
980
     * For more details see wrapXmlrpcMethod.
981
     *
982
     * For a slimmer alternative, see the code in demo/client/proxy.php
983
     *
984
     * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
985
     *
986
     * @param Client $client the client obj all set to query the desired server
987
     * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
988
     *              - string method_filter      regular expression
989
     *              - string new_class_name
990
     *              - string prefix
991
     *              - bool   simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
992
     *
993
     * @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)
994
     */
995 20
    public function wrapXmlrpcServer($client, $extraOptions = array())
996
    {
997 20
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
998 20
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
999 20
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
1000 20
        $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
1001 20
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
1002 20
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
1003 20
        $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1004 20
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1005 20
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1006 20
        $namespace = '\\PhpXmlRpc\\';
1007
1008 20
        $reqClass = $namespace . 'Request';
1009 20
        $decoderClass = $namespace . 'Encoder';
1010
1011 20
        $req = new $reqClass('system.listMethods');
1012 20
        $response = $client->send($req, $timeout, $protocol);
1013 20
        if ($response->faultCode()) {
1014 2
            error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1015
1016 2
            return false;
1017
        } else {
1018 18
            $mList = $response->value();
1019 18
            if ($client->return_type != 'phpvals') {
1020 18
                $decoder = new $decoderClass();
1021 18
                $mList = $decoder->decode($mList);
1022
            }
1023 18
            if (!is_array($mList) || !count($mList)) {
1024
                error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1025
1026
                return false;
1027
            } else {
1028
                // pick a suitable name for the new function, avoiding collisions
1029 18
                if ($newClassName != '') {
1030
                    $xmlrpcClassName = $newClassName;
1031
                } else {
1032 18
                    $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1033 18
                            array('_', ''), $client->server) . '_client';
1034
                }
1035 18
                while ($buildIt && class_exists($xmlrpcClassName)) {
1036 17
                    $xmlrpcClassName .= 'x';
1037
                }
1038
1039
                /// @todo add function setdebug() to new class, to enable/disable debugging
1040 18
                $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1041 18
                $source .= "function __construct()\n{\n";
1042 18
                $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1043 18
                $source .= "\$this->client = \$client;\n}\n\n";
1044
                $opts = array(
1045 18
                    'return_source' => true,
1046 18
                    'simple_client_copy' => 2, // do not produce code to copy the client object
1047 18
                    'timeout' => $timeout,
1048 18
                    'protocol' => $protocol,
1049 18
                    'encode_php_objs' => $encodePhpObjects,
1050 18
                    'decode_php_objs' => $decodePhpObjects,
1051 18
                    'prefix' => $prefix,
1052
                );
1053
                /// @todo build phpdoc for class definition, too
1054 18
                foreach ($mList as $mName) {
1055 18
                    if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1056
                        // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1057 18
                        $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1058 18
                            array('_', ''), $mName);
1059 18
                        $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1060 18
                        if ($methodWrap) {
1061 18
                            if (!$buildIt) {
1062
                                $source .= $methodWrap['docstring'];
1063
                            }
1064 18
                            $source .= $methodWrap['source'] . "\n";
1065
                        } else {
1066
                            error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1067
                        }
1068
                    }
1069
                }
1070 18
                $source .= "}\n";
1071 18
                if ($buildIt) {
1072 18
                    $allOK = 0;
1073 18
                    eval($source . '$allOK=1;');
1074 18
                    if ($allOK) {
1075 18
                        return $xmlrpcClassName;
1076
                    } else {
1077
                        error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1078
                        return false;
1079
                    }
1080
                } else {
1081
                    return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1082
                }
1083
            }
1084
        }
1085
    }
1086
1087
    /**
1088
     * Given necessary info, generate php code that will build a client object just like the given one.
1089
     * Take care that no full checking of input parameters is done to ensure that
1090
     * valid php code is emitted.
1091
     * @param Client $client
1092
     * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1093
     * @param string $prefix used for the return_type of the created client
1094
     * @param string $namespace
1095
     *
1096
     * @return string
1097
     */
1098 69 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...
1099
    {
1100 69
        $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1101 69
            "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1102
1103
        // copy all client fields to the client that will be generated runtime
1104
        // (this provides for future expansion or subclassing of client obj)
1105 69
        if ($verbatimClientCopy) {
1106 69
            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...
1107 69
                if ($fld != 'debug' && $fld != 'return_type') {
1108 69
                    $val = var_export($val, true);
1109 69
                    $code .= "\$client->$fld = $val;\n";
1110
                }
1111
            }
1112
        }
1113
        // only make sure that client always returns the correct data type
1114 69
        $code .= "\$client->return_type = '{$prefix}vals';\n";
1115
        //$code .= "\$client->setDebug(\$debug);\n";
1116 69
        return $code;
1117
    }
1118
}
1119