Passed
Push — master ( b7c304...bf000c )
by Mohamed
01:44
created

ParallelSoapClient::isLogPrettyXml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Soap;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\NullLogger;
7
8
/**
9
 * Single/Parallel Soap Class
10
 *
11
 * Implements soap with multi server-to-server calls using curl module.
12
 *
13
 * @author Mohamed Meabed <[email protected]>
14
 * @link   https://github.com/Meabed/php-parallel-soap
15
 * @note   Check the Example files and read the documentation carefully
16
 */
17
class ParallelSoapClient extends \SoapClient
18
{
19
    /**  array of all responses in the client */
20
    public $soapResponses = [];
21
22
    /**  array of all requests in the client */
23
    public $soapRequests = [];
24
25
    /**  array of all requests xml in the client */
26
    public $requestXmlArr = [];
27
28
    /**  string the xml returned from soap call */
29
    public $xmlResponse;
30
31
    /**  string current method call  */
32
    public $soapMethod;
33
34
    /** @var []string array of all requests soap methods in the client */
0 ignored issues
show
Documentation Bug introduced by
The doc comment []string at position 0 could not be parsed: Unknown type name '[' at position 0 in []string.
Loading history...
35
    public $soapMethodArr = [];
36
37
    /**  array of all requestIds  */
38
    public $requestIds;
39
40
    /**  string last request id  */
41
    public $lastRequestId;
42
43
    /**  bool soap parallel flag  */
44
    public $multi = false;
45
46
    /** @var bool log soap request */
47
    public $logSoapRequest = false;
48
49
    /** @var bool log pretty xml */
50
    public $logPrettyXml = false;
51
52
    /**  array of all curl_info in the client */
53
    public $curlInfo = [];
54
55
    /** @var array curl options */
56
    public $curlOptions = [];
57
58
    /** @var \Closure */
59
    public $debugFn;
60
61
    /** @var \Closure */
62
    public $resFn;
63
64
    /** @var \Closure */
65
    public $soapActionFn;
66
67
    /** @var LoggerInterface */
68
    public $logger;
69
70
    /**
71
     * @var array
72
     */
73
    public $sharedCurlData = [];
74
75
    /**  getRequestResponse action constant used for parsing the xml with from parent::__doRequest */
76
    const GET_RESPONSE_CONST = 'getRequestResponseMethod';
77
    const ERROR_STR = '*ERROR*';
78
79
80
    /**
81
     * @return mixed
82
     */
83
    public function getMulti()
84
    {
85
        return $this->multi;
86
    }
87
88
    /**
89
     * @param mixed $multi
90
     * @return ParallelSoapClient
91
     */
92 8
    public function setMulti($multi)
93
    {
94 8
        $this->multi = $multi;
95 8
        return $this;
96
    }
97
98
    /**
99
     * @return array
100
     */
101
    public function getCurlOptions()
102
    {
103
        return $this->curlOptions;
104
    }
105
106
    /**
107
     * @param array $curlOptions
108
     * @return ParallelSoapClient
109
     */
110
    public function setCurlOptions(array $curlOptions)
111
    {
112
        $this->curlOptions = $curlOptions;
113
        return $this;
114
    }
115
116
    /**
117
     * @return LoggerInterface
118
     */
119
    public function getLogger()
120
    {
121
        return $this->logger;
122
    }
123
124
    /**
125
     * @param LoggerInterface $logger
126
     * @return ParallelSoapClient
127
     */
128
    public function setLogger(LoggerInterface $logger)
129
    {
130
        $this->logger = $logger;
131
        return $this;
132
    }
133
134
    /**
135
     * @return bool
136
     */
137
    public function isLogSoapRequest()
138
    {
139
        return $this->logSoapRequest;
140
    }
141
142
    /**
143
     * @param bool $logSoapRequest
144
     * @return ParallelSoapClient
145
     */
146
    public function setLogSoapRequest(bool $logSoapRequest)
147
    {
148
        $this->logSoapRequest = $logSoapRequest;
149
        return $this;
150
    }
151
152
    /**
153
     * @return bool
154
     */
155
    public function isLogPrettyXml()
156
    {
157
        return $this->logPrettyXml;
158
    }
159
160
    /**
161
     * @param bool $logPrettyXml
162
     * @return ParallelSoapClient
163
     */
164
    public function setLogPrettyXml(bool $logPrettyXml)
165
    {
166
        $this->logPrettyXml = $logPrettyXml;
167
        return $this;
168
    }
169
170
    /**
171
     * @return \Closure
172
     */
173
    public function getDebugFn()
174
    {
175
        return $this->debugFn;
176
    }
177
178
    /**
179
     * @param \Closure $debugFn
180
     * @return ParallelSoapClient
181
     */
182
    public function setDebugFn(\Closure $debugFn)
183
    {
184
        $this->debugFn = $debugFn;
185
        return $this;
186
    }
187
188
189 8
    public function __construct($wsdl, array $options = null)
190
    {
191
        parent::__construct($wsdl, $options);
192
        $this->logger = $options['logger'] ?? new NullLogger();
193 8
        $this->debugFn = $options['debugFn'] ?? function ($res, $id) {
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

193
        $this->debugFn = $options['debugFn'] ?? function ($res, /** @scrutinizer ignore-unused */ $id) {

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

Loading history...
Unused Code introduced by
The parameter $res is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

193
        $this->debugFn = $options['debugFn'] ?? function (/** @scrutinizer ignore-unused */ $res, $id) {

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

Loading history...
194 8
            };
195
        $this->resFn = $options['resFn'] ?? function ($method, $res) {
196
                return $res;
197
            };
198
        $this->soapActionFn = $options['soapActionFn'] ?? function ($action, $headers) {
199
                $headers[] = 'SOAPAction: "' . $action . '"';
200
                // 'SOAPAction: "' . $soapAction . '"', pass the soap action in every request from the WSDL if required
201
                return $headers;
202
            };
203
204
        // cleanup
205
        unset($options['logger']);
206
        unset($options['debugFn']);
207
        unset($options['resFn']);
208
        unset($options['soapActionFn']);
209
    }
210
211
    /**
212
     * Soap __doRequest() Method with CURL Implementation
213
     *
214
     * @param string $request The XML SOAP request
215
     * @param string $location The URL to request
216
     * @param string $action The SOAP action
217
     * @param int $version The SOAP version
218
     * @param int $one_way If one_way is set to 1, this method returns nothing. Use this where a response is not expected
219
     *
220
     * @return string
221
     * @throws \SoapFault
222
     */
223 8
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
224
    {
225 8
        $shouldGetResponse = ($this->soapMethod == static::GET_RESPONSE_CONST);
226
227
        // print xml for debugging testing
228 8
        if ($this->logSoapRequest) {
229
            // debug the request here
230
            if ($this->isLogPrettyXml()) {
231
                $this->logger->debug($this->prettyXml($request));
232
            } else {
233
                $this->logger->debug($request);
234
            }
235
        }
236
        // some .NET Servers only accept action method with ns url!! uncomment it if you get error wrong command
237
        /** return the xml response as its coming from normal soap call */
238 8
        if ($shouldGetResponse && $this->xmlResponse) {
239 8
            return $this->xmlResponse;
240
        }
241
242 8
        $soapResponses = &$this->soapResponses;
243 8
        $soapRequests = &$this->soapRequests;
244
245
        /** @var $id string represent hashId of each request based on the request body
246
         * to avoid multiple calls for the same request if exists
247
         */
248 8
        $id = sha1($location . $request);
249
        /** return response if soap method called for second time with same parameters */
250 8
        if (isset($soapResponses[$id])) {
251
            $data = $soapResponses[$id];
252
            unset($soapResponses[$id]);
253
            if ($data instanceof \SoapFault) {
254
                throw $data;
255
            }
256
257
            return $data;
258
        }
259
260
        /** @var $headers array of headers to be sent with request */
261
        $defaultHeaders = [
262 8
            'Content-type: text/xml',
263 8
            'charset=utf-8',
264 8
            "Accept: text/xml",
265 8
            "Content-length: " . strlen($request),
266
        ];
267
268
        // pass the soap action in every request from the WSDL if required
269 8
        $soapActionFn = $this->soapActionFn;
270 8
        $headers = $soapActionFn($action, $defaultHeaders);
271
272
        // ssl connection sharing
273 8
        if (empty($this->sharedCurlData[$location])) {
274 8
            $shOpt = curl_share_init();
275 8
            curl_share_setopt($shOpt, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
276 8
            curl_share_setopt($shOpt, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
277 8
            curl_share_setopt($shOpt, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
278 8
            $this->sharedCurlData[$location] = $shOpt;
279
        }
280
281 8
        $sh = $this->sharedCurlData[$location];
282
283 8
        $ch = curl_init();
284
        /** CURL_OPTIONS  */
285 8
        curl_setopt($ch, CURLOPT_URL, $location);
286 8
        curl_setopt($ch, CURLOPT_POST, true);
287 8
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
288 8
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
289 8
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
290 8
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
291 8
        curl_setopt($ch, CURLOPT_SHARE, $sh);
292
293
        // assign curl options
294 8
        foreach ($this->curlOptions as $key => $value) {
295
            curl_setopt($ch, $key, $value);
296
        }
297
298 8
        $soapRequests[$id] = $ch;
299
300 8
        $this->requestIds[$id] = $id;
301 8
        $this->soapMethodArr[$id] = $this->soapMethod;
302 8
        $this->requestXmlArr[$id] = $request;
303 8
        $this->lastRequestId = $id;
304
305 8
        return "";
306
    }
307
308
    /**
309
     * Call Sync method, act like normal soap method with extra implementation if needed
310
     * @param string $method
311
     * @param string $args
312
     * @throws \Exception|\SoapFault
313
     * @return string|mixed
314
     */
315 8
    public function callOne($method, $args)
316
    {
317
        try {
318 8
            parent::__call($method, $args);
319
            /** parse the xml response or throw an exception */
320 5
            $this->xmlResponse = $this->run([$this->lastRequestId]);
321 5
            $res = $this->getResponseResult($method, $args);
322 4
        } catch (\Exception $e) {
323 4
            throw $e;
324
        }
325
326 4
        return $res;
327
    }
328
329
    /**
330
     * Call Parallel method, suppress exception and convert to string
331
     * @param string $method
332
     * @param string $args
333
     * @return string|mixed
334
     */
335 5
    public function callParallel($method, $args)
336
    {
337
        /** generate curl session and add the soap requests to execute it later  */
338
        try {
339 5
            parent::__call($method, $args);
340
            /**
341
             * Return the Request ID to the calling method
342
             * This next 2 lines should be custom implementation based on your solution.
343
             *
344
             * @var $res string ,On multiple calls Simulate the response from Soap API to return the request Id of each call
345
             * to be able to get the response with it
346
             * @note check the example file to understand what to write here
347
             */
348 4
            $res = $this->lastRequestId;
349 1
        } catch (\Exception $ex) {
350
            /** catch any SoapFault [is not a valid method for this service] and return null */
351 1
            $res = self::ERROR_STR . ':' . $method . ' - ' . $ex->getCode() . ' - ' . $ex->getMessage() . ' - rand::' . rand();
352
        }
353
354 5
        return $res;
355
    }
356
357
    /**
358
     * __call Magic method to allow one and Parallel Soap calls with exception handling
359
     *
360
     * @param string $method
361
     * @param string $args
362
     *
363
     * @return string|mixed
364
     * @throws \Exception
365
     * @throws \SoapFault
366
     */
367 12
    public function __call($method, $args)
368
    {
369
        /** set current action to the current method call */
370 12
        $this->soapMethod = $method;
371
372 12
        if (!$this->multi) {
373 8
            return $this->callOne($method, $args);
374
        } else {
375 5
            return $this->callParallel($method, $args);
376
        }
377
    }
378
379
    /**
380
     * Execute all or some items from $this->soapRequests
381
     *
382
     * @param mixed $requestIds
383
     * @param bool $partial
384
     */
385 8
    public function doRequests($requestIds = [], $partial = false)
386
    {
387 8
        $allSoapRequests = &$this->soapRequests;
388 8
        $soapResponses = &$this->soapResponses;
389
390
        /** Determine if its partial call to execute some requests or execute all the request in $soapRequests array otherwise */
391 8
        if ($partial) {
392 5
            $soapRequests = array_intersect_key($allSoapRequests, array_flip($requestIds));
393
        } else {
394 4
            $soapRequests = &$this->soapRequests;
395
        }
396
397
        /** Initialise curl multi handler and execute the requests  */
398 8
        $mh = curl_multi_init();
399 8
        foreach ($soapRequests as $ch) {
400 8
            curl_multi_add_handle($mh, $ch);
401
        }
402
403 8
        $active = null;
404
        do {
405 8
            $mrc = curl_multi_exec($mh, $active);
406 8
        } while ($mrc === CURLM_CALL_MULTI_PERFORM || $active);
407
408 8
        while ($active && $mrc == CURLM_OK) {
409
            if (curl_multi_select($mh) != -1) {
410
                do {
411
                    $mrc = curl_multi_exec($mh, $active);
412
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
413
            }
414
        }
415
        /** assign the responses for all requests has been performed */
416 8
        foreach ($soapRequests as $id => $ch) {
417
            try {
418 8
                $soapResponses[$id] = curl_multi_getcontent($ch);
419
                // todo if config
420 8
                $curlInfo = curl_getinfo($ch);
421 8
                if ($curlInfo) {
422 8
                    $this->curlInfo[$id] = (object)$curlInfo;
423
                }
424
425
                // @link http://stackoverflow.com/questions/14319696/soap-issue-soapfault-exception-client-looks-like-we-got-no-xml-document
426 8
                if ($soapResponses[$id] === null) {
427 8
                    throw new \SoapFault("HTTP", curl_error($ch));
0 ignored issues
show
Bug introduced by
curl_error($ch) of type string is incompatible with the type integer expected by parameter $code of SoapFault::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

427
                    throw new \SoapFault("HTTP", /** @scrutinizer ignore-type */ curl_error($ch));
Loading history...
428
                }
429
            } catch (\Exception $e) {
430
                $soapResponses[$id] = $e;
431
            }
432 8
            curl_multi_remove_handle($mh, $ch);
433 8
            curl_close($ch);
434
        }
435 8
        curl_multi_close($mh);
436
437
        /** unset the request performed from the class instance variable $soapRequests so we don't request them again */
438 8
        if (!$partial) {
439 4
            $soapRequests = [];
440
        }
441 8
        foreach ($soapRequests as $id => $ch) {
442 5
            unset($allSoapRequests[$id]);
443
        }
444 8
    }
445
446
    /**
447
     * Main method to perform all or some Soap requests
448
     *
449
     * @param array $requestIds
450
     *
451
     * @return string $res
452
     */
453 8
    public function run($requestIds = [])
454
    {
455 8
        $partial = false;
456
457 8
        if (is_array($requestIds) && count($requestIds)) {
458 5
            $partial = true;
459
        }
460 8
        $allSoapResponses = &$this->soapResponses;
461
462
        /** perform all the request */
463 8
        $this->doRequests($requestIds, $partial);
464
465
        /** reset the class to synchronous mode */
466 8
        $this->setMulti(false);
467
468
        /** parse return response of the performed requests  */
469 8
        if ($partial) {
470 5
            $soapResponses = array_intersect_key($allSoapResponses, array_flip($requestIds));
471
        } else {
472 4
            $soapResponses = &$this->soapResponses;
473
        }
474
        /** if its one request return the first element in the array */
475 8
        if ($partial && count($requestIds) == 1) {
476 5
            $res = $soapResponses[$requestIds[0]];
477 5
            unset($allSoapResponses[$requestIds[0]]);
478
        } else {
479 4
            $res = $this->getMultiResponses($soapResponses);
480
        }
481
482 8
        return $res;
483
    }
484
485
    /**
486
     * Parse Response of Soap Requests with parent::__doRequest()
487
     *
488
     * @param array $responses
489
     *
490
     * @return mixed $resArr
491
     */
492 4
    public function getMultiResponses($responses = [])
493
    {
494 4
        $resArr = [];
495 4
        $this->soapMethod = static::GET_RESPONSE_CONST;
496
497 4
        foreach ($responses as $id => $ch) {
498
            try {
499 4
                $this->xmlResponse = $ch;
500 4
                if ($ch instanceof \Exception) {
501
                    throw $ch;
502
                }
503 4
                $res = parent::__call($this->soapMethodArr[$id], []);
0 ignored issues
show
Bug introduced by
array() of type array is incompatible with the type string expected by parameter $arguments of SoapClient::__call(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

503
                $res = parent::__call($this->soapMethodArr[$id], /** @scrutinizer ignore-type */ []);
Loading history...
504
                /**
505
                 * Return the Request ID to the calling method
506
                 * This next lines should be custom implementation based on your solution.
507
                 *
508
                 * @var $resArr string ,On multiple calls Simulate the response from Soap API to return the request Id of each call
509
                 * to be able to get the response with it
510
                 * @note check the example file to understand what to write here
511
                 */
512 4
                $resFn = $this->resFn;
513 4
                $resArr[$id] = $resFn($this->soapMethodArr[$id], $res);
514 4
                $this->addDebugData($res, $id);
515
            } catch (\Exception $ex) {
516
                $this->addDebugData($ex, $this->lastRequestId);
517
                $resArr[$id] = $ex;
518
            }
519 4
            unset($this->soapResponses[$id]);
520
        }
521 4
        $this->xmlResponse = '';
522 4
        $this->soapMethod = '';
523
524 4
        return $resArr;
525
    }
526
527
    /**
528
     * Parse Response of Soap Requests with parent::__doRequest()
529
     *
530
     * @param string $method
531
     * @param string|array $args
532
     *
533
     * @throws \Exception|\SoapFault|
534
     * @return string $res
535
     */
536 5
    public function getResponseResult($method, $args)
537
    {
538 5
        $this->soapMethod = static::GET_RESPONSE_CONST;
539
540
        try {
541 5
            $res = parent::__call($method, $args);
0 ignored issues
show
Bug introduced by
It seems like $args can also be of type array; however, parameter $arguments of SoapClient::__call() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

541
            $res = parent::__call($method, /** @scrutinizer ignore-type */ $args);
Loading history...
542
543 4
            $id = $this->lastRequestId;
544 4
            $this->addDebugData($res, $id);
545 1
        } catch (\Exception $ex) {
546 1
            $this->addDebugData($ex, $this->lastRequestId);
547 1
            throw $ex;
548
        }
549 4
        $this->soapMethod = '';
550
551 4
        $resFn = $this->resFn;
552 4
        return $resFn($method, $res);
553
    }
554
555
556
    /**
557
     * Add curl info to response object
558
     *
559
     * @param $res
560
     * @param $id
561
     *
562
     * @author Mohamed Meabed <[email protected]>
563
     *
564
     */
565 8
    public function addDebugData($res, $id)
566
    {
567 8
        $fn = $this->debugFn;
568 8
        $fn($res, $id);
569 8
    }
570
571
    /**
572
     * Print pretty xml
573
     *
574
     * @param $request
575
     *
576
     * @return string
577
     *
578
     * @author Mohamed Meabed <[email protected]>
579
     *
580
     */
581
    public function prettyXml($request)
582
    {
583
        $dom = new \DOMDocument();
584
        $dom->preserveWhiteSpace = false;
585
        $dom->loadXML($request);
586
        $dom->formatOutput = true;
587
588
        return $dom->saveXml();
589
    }
590
}
591