Passed
Push — master ( 5828d3...9ed262 )
by Mohamed
01:44
created

ParallelSoapClient::getLogger()   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\LoggerAwareInterface;
6
use Psr\Log\LoggerAwareTrait;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
10
/**
11
 * Single/Parallel Soap Class
12
 *
13
 * Implements soap with multi server-to-server calls using curl module.
14
 *
15
 * @author Mohamed Meabed <[email protected]>
16
 * @link   https://github.com/Meabed/php-parallel-soap
17
 * @note   Check the Example files and read the documentation carefully
18
 */
19
class ParallelSoapClient extends \SoapClient implements LoggerAwareInterface
20
{
21
    use LoggerAwareTrait;
22
    /** @var array of all responses in the client */
23
    public $soapResponses = [];
24
25
    /** @var array of all requests in the client */
26
    public $soapRequests = [];
27
28
    /** @var array of all requests xml in the client */
29
    public $requestXmlArr = [];
30
31
    /** @var string the xml returned from soap call */
32
    public $xmlResponse;
33
34
    /** @var string current method call */
35
    public $soapMethod;
36
37
    /** @var array of all requests soap methods in the client */
38
    public $soapMethodArr = [];
39
40
    /** @var array of all requestIds */
41
    public $requestIds;
42
43
    /** @var string last request id */
44
    public $lastRequestId;
45
46
    /** @var bool soap parallel flag */
47
    public $multi = false;
48
49
    /** @var bool log soap request */
50
    public $logSoapRequest = false;
51
52
    /** @var 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 $formatXmlFn;
63
64
    /** @var \Closure */
65
    protected $resFn;
66
67
    /** @var \Closure */
68
    protected $soapActionFn;
69
70
    /** @var array curl share ssl */
71
    public $sharedCurlData = [];
72
73
    /** @var string getRequestResponse action constant used for parsing the xml with from parent::__doRequest */
74
    const GET_RESPONSE_CONST = 'getRequestResponseMethod';
75
    /** @var string text prefix, if error happen due to SOAP error before its executed ex:invalid method */
76
    const ERROR_STR = '*ERROR*';
77
78
    /**
79
     * @return mixed
80
     */
81
    public function getMulti()
82
    {
83
        return $this->multi;
84
    }
85
86
    /**
87
     * @param mixed $multi
88
     * @return ParallelSoapClient
89
     */
90 8
    public function setMulti($multi)
91
    {
92 8
        $this->multi = $multi;
93 8
        return $this;
94
    }
95
96
    /**
97
     * @return array
98
     */
99
    public function getCurlOptions()
100
    {
101
        return $this->curlOptions;
102
    }
103
104
    /**
105
     * @param array $curlOptions
106
     * @return ParallelSoapClient
107
     */
108
    public function setCurlOptions(array $curlOptions)
109
    {
110
        $this->curlOptions = $curlOptions;
111
        return $this;
112
    }
113
114
    /**
115
     * @return bool
116
     */
117
    public function isLogSoapRequest()
118
    {
119
        return $this->logSoapRequest;
120
    }
121
122
    /**
123
     * @param bool $logSoapRequest
124
     * @return ParallelSoapClient
125
     */
126
    public function setLogSoapRequest(bool $logSoapRequest)
127
    {
128
        $this->logSoapRequest = $logSoapRequest;
129
        return $this;
130
    }
131
132
    /**
133
     * @return \Closure
134
     */
135
    public function getDebugFn()
136
    {
137
        return $this->debugFn;
138
    }
139
140
    /**
141
     * @param \Closure $debugFn
142
     * @return ParallelSoapClient
143
     */
144
    public function setDebugFn(\Closure $debugFn)
145
    {
146
        $this->debugFn = $debugFn;
147
        return $this;
148
    }
149
150
    /**
151
     * @return \Closure
152
     */
153
    public function getFormatXmlFn()
154
    {
155
        return $this->formatXmlFn;
156
    }
157
158
    /**
159
     * @param \Closure $formatXmlFn
160
     * @return ParallelSoapClient
161
     */
162
    public function setFormatXmlFn(\Closure $formatXmlFn)
163
    {
164
        $this->formatXmlFn = $formatXmlFn;
165
        return $this;
166
    }
167
168
    /**
169
     * @return \Closure
170
     */
171
    public function getResFn()
172
    {
173
        return $this->resFn;
174
    }
175
176
    /**
177
     * @param \Closure $resFn
178
     * @return ParallelSoapClient
179
     */
180
    public function setResFn(\Closure $resFn)
181
    {
182
        $this->resFn = $resFn;
183
        return $this;
184
    }
185
186
    /**
187
     * @return \Closure
188
     */
189
    public function getSoapActionFn()
190
    {
191
        return $this->soapActionFn;
192
    }
193
194
    /**
195
     * @param \Closure $soapActionFn
196
     * @return ParallelSoapClient
197
     */
198
    public function setSoapActionFn(\Closure $soapActionFn)
199
    {
200
        $this->soapActionFn = $soapActionFn;
201
        return $this;
202
    }
203
204
205 8
    public function __construct($wsdl, array $options = null)
206
    {
207
        // logger
208
        $logger = $options['logger'] ?? new NullLogger();
209
        $this->setLogger($logger);
210
211
        // debug function to add headers / last request / response / etc...
212 8
        $debugFn = $options['debugFn'] ?? function ($res, $id) {
0 ignored issues
show
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

212
        $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...
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

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

450
                    throw new \SoapFault("HTTP", /** @scrutinizer ignore-type */ curl_error($ch));
Loading history...
451
                }
452
            } catch (\Exception $e) {
453
                $soapResponses[$id] = $e;
454
            }
455 8
            curl_multi_remove_handle($mh, $ch);
456 8
            curl_close($ch);
457
        }
458 8
        curl_multi_close($mh);
459
460
        /** unset the request performed from the class instance variable $soapRequests so we don't request them again */
461 8
        if (!$partial) {
462 4
            $soapRequests = [];
463
        }
464 8
        foreach ($soapRequests as $id => $ch) {
465 5
            unset($allSoapRequests[$id]);
466
        }
467 8
    }
468
469
    /**
470
     * Main method to perform all or some Soap requests
471
     *
472
     * @param array $requestIds
473
     *
474
     * @return string $res
475
     */
476 8
    public function run($requestIds = [])
477
    {
478 8
        $partial = false;
479
480 8
        if (is_array($requestIds) && count($requestIds)) {
481 5
            $partial = true;
482
        }
483 8
        $allSoapResponses = &$this->soapResponses;
484
485
        /** perform all the request */
486 8
        $this->doRequests($requestIds, $partial);
487
488
        /** reset the class to synchronous mode */
489 8
        $this->setMulti(false);
490
491
        /** parse return response of the performed requests  */
492 8
        if ($partial) {
493 5
            $soapResponses = array_intersect_key($allSoapResponses, array_flip($requestIds));
494
        } else {
495 4
            $soapResponses = &$this->soapResponses;
496
        }
497
        /** if its one request return the first element in the array */
498 8
        if ($partial && count($requestIds) == 1) {
499 5
            $res = $soapResponses[$requestIds[0]];
500 5
            unset($allSoapResponses[$requestIds[0]]);
501
        } else {
502 4
            $res = $this->getMultiResponses($soapResponses);
503
        }
504
505 8
        return $res;
506
    }
507
508
    /**
509
     * Parse Response of Soap Requests with parent::__doRequest()
510
     *
511
     * @param array $responses
512
     *
513
     * @return mixed $resArr
514
     */
515 4
    public function getMultiResponses($responses = [])
516
    {
517 4
        $resArr = [];
518 4
        $this->soapMethod = static::GET_RESPONSE_CONST;
519
520 4
        foreach ($responses as $id => $ch) {
521
            try {
522 4
                $this->xmlResponse = $ch;
523 4
                if ($ch instanceof \Exception) {
524
                    throw $ch;
525
                }
526 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

526
                $res = parent::__call($this->soapMethodArr[$id], /** @scrutinizer ignore-type */ []);
Loading history...
527
                /**
528
                 * Return the Request ID to the calling method
529
                 * This next lines should be custom implementation based on your solution.
530
                 *
531
                 * @var $resArr string ,On multiple calls Simulate the response from Soap API to return the request Id of each call
532
                 * to be able to get the response with it
533
                 * @note check the example file to understand what to write here
534
                 */
535 4
                $resFn = $this->resFn;
536 4
                $resArr[$id] = $resFn($this->soapMethodArr[$id], $res);
537 4
                $this->addDebugData($res, $id);
538
            } catch (\Exception $ex) {
539
                $this->addDebugData($ex, $this->lastRequestId);
540
                $resArr[$id] = $ex;
541
            }
542 4
            unset($this->soapResponses[$id]);
543
        }
544 4
        $this->xmlResponse = '';
545 4
        $this->soapMethod = '';
546
547 4
        return $resArr;
548
    }
549
550
    /**
551
     * Parse Response of Soap Requests with parent::__doRequest()
552
     *
553
     * @param string $method
554
     * @param string|array $args
555
     *
556
     * @throws \Exception|\SoapFault|
557
     * @return string $res
558
     */
559 5
    public function getResponseResult($method, $args)
560
    {
561 5
        $this->soapMethod = static::GET_RESPONSE_CONST;
562
563
        try {
564 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

564
            $res = parent::__call($method, /** @scrutinizer ignore-type */ $args);
Loading history...
565
566 4
            $id = $this->lastRequestId;
567 4
            $this->addDebugData($res, $id);
568 1
        } catch (\Exception $ex) {
569 1
            $this->addDebugData($ex, $this->lastRequestId);
570 1
            throw $ex;
571
        }
572 4
        $this->soapMethod = '';
573
574 4
        $resFn = $this->resFn;
575 4
        return $resFn($method, $res);
576
    }
577
578
579
    /**
580
     * Add curl info to response object
581
     *
582
     * @param $res
583
     * @param $id
584
     *
585
     * @author Mohamed Meabed <[email protected]>
586
     * @return mixed
587
     */
588 8
    public function addDebugData($res, $id)
589
    {
590 8
        $fn = $this->debugFn;
591 8
        return $fn($res, $id);
592
    }
593
594
    /**
595
     * format xml
596
     *
597
     * @param $request
598
     * @author Mohamed Meabed <[email protected]>
599
     * @return mixed
600
     */
601 6
    public function formatXml($request)
602
    {
603 6
        $fn = $this->formatXmlFn;
604 6
        return $fn($request);
605
    }
606
}
607