Completed
Push — master ( bf000c...13cb67 )
by Mohamed
01:33
created

ParallelSoapClient::getMultiResponses()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.1755

Importance

Changes 0
Metric Value
cc 4
eloc 18
nc 6
nop 1
dl 0
loc 33
ccs 14
cts 18
cp 0.7778
crap 4.1755
rs 8.5806
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
    protected $debugFn;
60
61
    /** @var \Closure */
62
    protected $resFn;
63
64
    /** @var \Closure */
65
    protected $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
     * @return \Closure
190
     */
191
    public function getResFn()
192
    {
193
        return $this->resFn;
194
    }
195
196
    /**
197
     * @param \Closure $resFn
198
     * @return ParallelSoapClient
199
     */
200
    public function setResFn(\Closure $resFn)
201
    {
202
        $this->resFn = $resFn;
203
        return $this;
204
    }
205
206
    /**
207
     * @return \Closure
208
     */
209
    public function getSoapActionFn()
210
    {
211
        return $this->soapActionFn;
212
    }
213
214
    /**
215
     * @param \Closure $soapActionFn
216
     * @return ParallelSoapClient
217
     */
218
    public function setSoapActionFn(\Closure $soapActionFn)
219
    {
220
        $this->soapActionFn = $soapActionFn;
221
        return $this;
222
    }
223
224
225 8
    public function __construct($wsdl, array $options = null)
226
    {
227
        parent::__construct($wsdl, $options);
228
229
        // logger
230
        $logger = $options['logger'] ?? new NullLogger();
231
        $this->setLogger($logger);
232
233
        // debug function to add headers / last request / response / etc...
234 8
        $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

234
        $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

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

475
                    throw new \SoapFault("HTTP", /** @scrutinizer ignore-type */ curl_error($ch));
Loading history...
476
                }
477
            } catch (\Exception $e) {
478
                $soapResponses[$id] = $e;
479
            }
480 8
            curl_multi_remove_handle($mh, $ch);
481 8
            curl_close($ch);
482
        }
483 8
        curl_multi_close($mh);
484
485
        /** unset the request performed from the class instance variable $soapRequests so we don't request them again */
486 8
        if (!$partial) {
487 4
            $soapRequests = [];
488
        }
489 8
        foreach ($soapRequests as $id => $ch) {
490 5
            unset($allSoapRequests[$id]);
491
        }
492 8
    }
493
494
    /**
495
     * Main method to perform all or some Soap requests
496
     *
497
     * @param array $requestIds
498
     *
499
     * @return string $res
500
     */
501 8
    public function run($requestIds = [])
502
    {
503 8
        $partial = false;
504
505 8
        if (is_array($requestIds) && count($requestIds)) {
506 5
            $partial = true;
507
        }
508 8
        $allSoapResponses = &$this->soapResponses;
509
510
        /** perform all the request */
511 8
        $this->doRequests($requestIds, $partial);
512
513
        /** reset the class to synchronous mode */
514 8
        $this->setMulti(false);
515
516
        /** parse return response of the performed requests  */
517 8
        if ($partial) {
518 5
            $soapResponses = array_intersect_key($allSoapResponses, array_flip($requestIds));
519
        } else {
520 4
            $soapResponses = &$this->soapResponses;
521
        }
522
        /** if its one request return the first element in the array */
523 8
        if ($partial && count($requestIds) == 1) {
524 5
            $res = $soapResponses[$requestIds[0]];
525 5
            unset($allSoapResponses[$requestIds[0]]);
526
        } else {
527 4
            $res = $this->getMultiResponses($soapResponses);
528
        }
529
530 8
        return $res;
531
    }
532
533
    /**
534
     * Parse Response of Soap Requests with parent::__doRequest()
535
     *
536
     * @param array $responses
537
     *
538
     * @return mixed $resArr
539
     */
540 4
    public function getMultiResponses($responses = [])
541
    {
542 4
        $resArr = [];
543 4
        $this->soapMethod = static::GET_RESPONSE_CONST;
544
545 4
        foreach ($responses as $id => $ch) {
546
            try {
547 4
                $this->xmlResponse = $ch;
548 4
                if ($ch instanceof \Exception) {
549
                    throw $ch;
550
                }
551 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

551
                $res = parent::__call($this->soapMethodArr[$id], /** @scrutinizer ignore-type */ []);
Loading history...
552
                /**
553
                 * Return the Request ID to the calling method
554
                 * This next lines should be custom implementation based on your solution.
555
                 *
556
                 * @var $resArr string ,On multiple calls Simulate the response from Soap API to return the request Id of each call
557
                 * to be able to get the response with it
558
                 * @note check the example file to understand what to write here
559
                 */
560 4
                $resFn = $this->resFn;
561 4
                $resArr[$id] = $resFn($this->soapMethodArr[$id], $res);
562 4
                $this->addDebugData($res, $id);
563
            } catch (\Exception $ex) {
564
                $this->addDebugData($ex, $this->lastRequestId);
565
                $resArr[$id] = $ex;
566
            }
567 4
            unset($this->soapResponses[$id]);
568
        }
569 4
        $this->xmlResponse = '';
570 4
        $this->soapMethod = '';
571
572 4
        return $resArr;
573
    }
574
575
    /**
576
     * Parse Response of Soap Requests with parent::__doRequest()
577
     *
578
     * @param string $method
579
     * @param string|array $args
580
     *
581
     * @throws \Exception|\SoapFault|
582
     * @return string $res
583
     */
584 5
    public function getResponseResult($method, $args)
585
    {
586 5
        $this->soapMethod = static::GET_RESPONSE_CONST;
587
588
        try {
589 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

589
            $res = parent::__call($method, /** @scrutinizer ignore-type */ $args);
Loading history...
590
591 4
            $id = $this->lastRequestId;
592 4
            $this->addDebugData($res, $id);
593 1
        } catch (\Exception $ex) {
594 1
            $this->addDebugData($ex, $this->lastRequestId);
595 1
            throw $ex;
596
        }
597 4
        $this->soapMethod = '';
598
599 4
        $resFn = $this->resFn;
600 4
        return $resFn($method, $res);
601
    }
602
603
604
    /**
605
     * Add curl info to response object
606
     *
607
     * @param $res
608
     * @param $id
609
     *
610
     * @author Mohamed Meabed <[email protected]>
611
     *
612
     */
613 8
    public function addDebugData($res, $id)
614
    {
615 8
        $fn = $this->debugFn;
616 8
        $fn($res, $id);
617 8
    }
618
619
    /**
620
     * Print pretty xml
621
     *
622
     * @param $request
623
     *
624
     * @return string
625
     *
626
     * @author Mohamed Meabed <[email protected]>
627
     *
628
     */
629
    public function prettyXml($request)
630
    {
631
        $dom = new \DOMDocument();
632
        $dom->preserveWhiteSpace = false;
633
        $dom->loadXML($request);
634
        $dom->formatOutput = true;
635
636
        return $dom->saveXml();
637
    }
638
}
639