Completed
Push — develop ( 32b87a...aef89e )
by Mikaël
02:09
created

AbstractSoapClientBase::setSoapHeader()   B

Complexity

Conditions 7
Paths 25

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 16
cts 16
cp 1
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 14
nc 25
nop 5
crap 7
1
<?php
2
3
namespace WsdlToPhp\PackageBase;
4
5
abstract class AbstractSoapClientBase implements SoapClientInterface
6
{
7
    /**
8
     * Soapclient called to communicate with the actual SOAP Service
9
     * @var \SoapClient
10
     */
11
    private $soapClient;
12
    /**
13
     * Contains Soap call result
14
     * @var mixed
15
     */
16
    private $result;
17
    /**
18
     * Contains last errors
19
     * @var array
20
     */
21
    private $lastError;
22
    /**
23
     * Constructor
24
     * @uses AbstractSoapClientBase::setLastError()
25
     * @uses AbstractSoapClientBase::initSoapClient()
26
     * @param array $wsdlOptions
27
     */
28 130
    public function __construct(array $wsdlOptions = [])
29
    {
30 130
        $this->setLastError([]);
31
        /**
32
         * Init soap Client
33
         * Set default values
34
         */
35 130
        $this->initSoapClient($wsdlOptions);
36 130
    }
37
    /**
38
     * Method getting current SoapClient
39
     * @return \SoapClient
40
     */
41 120
    public function getSoapClient()
42
    {
43 120
        return $this->soapClient;
44
    }
45
    /**
46
     * Method setting current SoapClient
47
     * @param \SoapClient $soapClient
48
     * @return \SoapClient
49
     */
50 120
    public function setSoapClient(\SoapClient $soapClient)
51
    {
52 120
        return ($this->soapClient = $soapClient);
53
    }
54
    /**
55
     * Method initiating SoapClient
56
     * @uses ApiClassMap::classMap()
57
     * @uses AbstractSoapClientBase::getDefaultWsdlOptions()
58
     * @uses AbstractSoapClientBase::getSoapClientClassName()
59
     * @uses AbstractSoapClientBase::setSoapClient()
60
     * @param array $options WSDL options
61
     * @return void
62
     */
63 130
    public function initSoapClient(array $options)
64
    {
65 130
        $wsdlOptions = [];
66 130
        $defaultWsdlOptions = static::getDefaultWsdlOptions();
67 130
        foreach ($defaultWsdlOptions as $optionName => $optionValue) {
68 130
            if (array_key_exists($optionName, $options) && !is_null($options[$optionName])) {
69 120
                $wsdlOptions[str_replace(self::OPTION_PREFIX, '', $optionName)] = $options[$optionName];
70 130
            } elseif (!is_null($optionValue)) {
71 130
                $wsdlOptions[str_replace(self::OPTION_PREFIX, '', $optionName)] = $optionValue;
72 52
            }
73 52
        }
74 130
        if (array_key_exists(str_replace(self::OPTION_PREFIX, '', self::WSDL_URL), $wsdlOptions)) {
75 120
            $wsdlUrl = $wsdlOptions[str_replace(self::OPTION_PREFIX, '', self::WSDL_URL)];
76 120
            unset($wsdlOptions[str_replace(self::OPTION_PREFIX, '', self::WSDL_URL)]);
77 120
            $soapClientClassName = $this->getSoapClientClassName();
78 120
            $this->setSoapClient(new $soapClientClassName($wsdlUrl, $wsdlOptions));
79 48
        }
80 130
    }
81
    /**
82
     * Returns the SoapClient class name to use to create the instance of the SoapClient.
83
     * The SoapClient class is determined based on the package name.
84
     * If a class is named as {Api}SoapClient, then this is the class that will be used.
85
     * Be sure that this class inherits from the native PHP SoapClient class and this class has been loaded or can be loaded.
86
     * The goal is to allow the override of the SoapClient without having to modify this generated class.
87
     * Then the overridding SoapClient class can override for example the SoapClient::__doRequest() method if it is needed.
88
     * @return string
89
     */
90 130
    public function getSoapClientClassName($soapClientClassName = null)
91
    {
92 130
        $className = self::DEFAULT_SOAP_CLIENT_CLASS;
93 130
        if (!empty($soapClientClassName) && is_subclass_of($soapClientClassName, '\SoapClient')) {
94 125
            $className = $soapClientClassName;
95 50
        }
96 130
        return $className;
97
    }
98
    /**
99
     * Method returning all default options values
100
     * @uses AbstractSoapClientBase::WSDL_CLASSMAP
101
     * @uses AbstractSoapClientBase::WSDL_CACHE_WSDL
102
     * @uses AbstractSoapClientBase::WSDL_COMPRESSION
103
     * @uses AbstractSoapClientBase::WSDL_CONNECTION_TIMEOUT
104
     * @uses AbstractSoapClientBase::WSDL_ENCODING
105
     * @uses AbstractSoapClientBase::WSDL_EXCEPTIONS
106
     * @uses AbstractSoapClientBase::WSDL_FEATURES
107
     * @uses AbstractSoapClientBase::WSDL_LOCATION
108
     * @uses AbstractSoapClientBase::WSDL_LOGIN
109
     * @uses AbstractSoapClientBase::WSDL_PASSWORD
110
     * @uses AbstractSoapClientBase::WSDL_SOAP_VERSION
111
     * @uses AbstractSoapClientBase::WSDL_STREAM_CONTEXT
112
     * @uses AbstractSoapClientBase::WSDL_TRACE
113
     * @uses AbstractSoapClientBase::WSDL_TYPEMAP
114
     * @uses AbstractSoapClientBase::WSDL_URL
115
     * @uses AbstractSoapClientBase::VALUE_WSDL_URL
116
     * @uses AbstractSoapClientBase::WSDL_USER_AGENT
117
     * @uses AbstractSoapClientBase::WSDL_PROXY_HOST
118
     * @uses AbstractSoapClientBase::WSDL_PROXY_PORT
119
     * @uses AbstractSoapClientBase::WSDL_PROXY_LOGIN
120
     * @uses AbstractSoapClientBase::WSDL_PROXY_PASSWORD
121
     * @uses AbstractSoapClientBase::WSDL_LOCAL_CERT
122
     * @uses AbstractSoapClientBase::WSDL_PASSPHRASE
123
     * @uses AbstractSoapClientBase::WSDL_AUTHENTICATION
124
     * @uses AbstractSoapClientBase::WSDL_SSL_METHOD
125
     * @uses SOAP_SINGLE_ELEMENT_ARRAYS
126
     * @uses SOAP_USE_XSI_ARRAY_TYPE
127
     * @return array
128
     */
129 130
    public static function getDefaultWsdlOptions()
130
    {
131
        return [
132 130
            self::WSDL_CLASSMAP => null,
133 130
            self::WSDL_CACHE_WSDL => WSDL_CACHE_NONE,
134 130
            self::WSDL_COMPRESSION => null,
135 130
            self::WSDL_CONNECTION_TIMEOUT => null,
136 130
            self::WSDL_ENCODING => null,
137 130
            self::WSDL_EXCEPTIONS => true,
138 130
            self::WSDL_FEATURES => SOAP_SINGLE_ELEMENT_ARRAYS | SOAP_USE_XSI_ARRAY_TYPE,
139 130
            self::WSDL_LOCATION => null,
140 130
            self::WSDL_LOGIN => null,
141 130
            self::WSDL_PASSWORD => null,
142 130
            self::WSDL_SOAP_VERSION => null,
143 130
            self::WSDL_STREAM_CONTEXT => null,
144 130
            self::WSDL_TRACE => true,
145 130
            self::WSDL_TYPEMAP => null,
146 130
            self::WSDL_URL => null,
147 130
            self::WSDL_USER_AGENT => null,
148 130
            self::WSDL_PROXY_HOST => null,
149 130
            self::WSDL_PROXY_PORT => null,
150 130
            self::WSDL_PROXY_LOGIN => null,
151 130
            self::WSDL_PROXY_PASSWORD => null,
152 130
            self::WSDL_LOCAL_CERT => null,
153 130
            self::WSDL_PASSPHRASE => null,
154 130
            self::WSDL_AUTHENTICATION => null,
155 130
            self::WSDL_SSL_METHOD => null,
156 52
        ];
157
    }
158
    /**
159
     * Allows to set the SoapClient location to call
160
     * @uses AbstractSoapClientBase::getSoapClient()
161
     * @uses SoapClient::__setLocation()
162
     * @param string $location
163
     * @return AbstractSoapClientBase
164
     */
165 5
    public function setLocation($location)
166
    {
167 5
        if ($this->getSoapClient() instanceof \SoapClient) {
168 5
            $this->getSoapClient()->__setLocation($location);
169 2
        }
170 5
        return $this;
171
    }
172
    /**
173
     * Returns the last request content as a DOMDocument or as a formated XML String
174
     * @see SoapClient::__getLastRequest()
175
     * @uses AbstractSoapClientBase::getSoapClient()
176
     * @uses AbstractSoapClientBase::getFormatedXml()
177
     * @uses SoapClient::__getLastRequest()
178
     * @param bool $asDomDocument
179
     * @return \DOMDocument|string|null
180
     */
181 10
    public function getLastRequest($asDomDocument = false)
182
    {
183 10
        return $this->getLastXml('__getLastRequest', $asDomDocument);
184
    }
185
    /**
186
     * Returns the last response content as a DOMDocument or as a formated XML String
187
     * @see SoapClient::__getLastResponse()
188
     * @uses AbstractSoapClientBase::getSoapClient()
189
     * @uses AbstractSoapClientBase::getFormatedXml()
190
     * @uses SoapClient::__getLastResponse()
191
     * @param bool $asDomDocument
192
     * @return \DOMDocument|string|null
193
     */
194 10
    public function getLastResponse($asDomDocument = false)
195
    {
196 10
        return $this->getLastXml('__getLastResponse', $asDomDocument);
197
    }
198
    /**
199
     * @param string $method
200
     * @param bool $asDomDocument
201
     * @return \DOMDocument|string|null
202
     */
203 20
    protected function getLastXml($method, $asDomDocument = false)
204
    {
205 20
        $xml = null;
206 20
        if ($this->getSoapClient() instanceof \SoapClient) {
207 20
            $xml = static::getFormatedXml($this->getSoapClient()->$method(), $asDomDocument);
208 8
        }
209 20
        return $xml;
210
    }
211
    /**
212
     * Returns the last request headers used by the SoapClient object as the original value or an array
213
     * @see SoapClient::__getLastRequestHeaders()
214
     * @uses AbstractSoapClientBase::getSoapClient()
215
     * @uses AbstractSoapClientBase::convertStringHeadersToArray()
216
     * @uses SoapClient::__getLastRequestHeaders()
217
     * @param bool $asArray allows to get the headers in an associative array
218
     * @return null|string|array
219
     */
220 10
    public function getLastRequestHeaders($asArray = false)
221
    {
222 10
        return $this->getLastHeaders('__getLastRequestHeaders', $asArray);
223
    }
224
    /**
225
     * Returns the last response headers used by the SoapClient object as the original value or an array
226
     * @see SoapClient::__getLastResponseHeaders()
227
     * @uses AbstractSoapClientBase::getSoapClient()
228
     * @uses AbstractSoapClientBase::convertStringHeadersToArray()
229
     * @uses SoapClient::__getLastRequestHeaders()
230
     * @param bool $asArray allows to get the headers in an associative array
231
     * @return null|string|array
232
     */
233 10
    public function getLastResponseHeaders($asArray = false)
234
    {
235 10
        return $this->getLastHeaders('__getLastResponseHeaders', $asArray);
236
    }
237
    /**
238
     * @param string $method
239
     * @param bool $asArray allows to get the headers in an associative array
240
     * @return string[]|null
241
     */
242 20
    protected function getLastHeaders($method, $asArray)
243
    {
244 20
        $headers = $this->getSoapClient() instanceof \SoapClient ? $this->getSoapClient()->$method() : null;
245 20
        if (is_string($headers) && $asArray) {
246 10
            return static::convertStringHeadersToArray($headers);
247
        }
248 10
        return $headers;
249
    }
250
    /**
251
     * Returns a XML string content as a DOMDocument or as a formated XML string
252
     * @uses \DOMDocument::loadXML()
253
     * @uses \DOMDocument::saveXML()
254
     * @param string $string
255
     * @param bool $asDomDocument
256
     * @return \DOMDocument|string|null
257
     */
258 20
    public static function getFormatedXml($string, $asDomDocument = false)
259
    {
260 20
        return Utils::getFormatedXml($string, $asDomDocument);
261
    }
262
    /**
263
     * Returns an associative array between the headers name and their respective values
264
     * @param string $headers
265
     * @return string[]
266
     */
267 10
    public static function convertStringHeadersToArray($headers)
268
    {
269 10
        $lines = explode("\r\n", $headers);
270 10
        $headers = [];
271 10
        foreach ($lines as $line) {
272 10
            if (strpos($line, ':')) {
273 10
                $headerParts = explode(':', $line);
274 10
                $headers[$headerParts[0]] = trim(implode(':', array_slice($headerParts, 1)));
275 4
            }
276 4
        }
277 10
        return $headers;
278
    }
279
    /**
280
     * Sets a SoapHeader to send
281
     * For more information, please read the online documentation on {@link http://www.php.net/manual/en/class.soapheader.php}
282
     * @uses AbstractSoapClientBase::getSoapClient()
283
     * @uses SoapClient::__setSoapheaders()
284
     * @param string $nameSpace SoapHeader namespace
285
     * @param string $name SoapHeader name
286
     * @param mixed $data SoapHeader data
287
     * @param bool $mustUnderstand
288
     * @param string $actor
289
     * @return AbstractSoapClientBase
290
     */
291 15
    public function setSoapHeader($nameSpace, $name, $data, $mustUnderstand = false, $actor = null)
292
    {
293 15
        if ($this->getSoapClient()) {
294 15
            $defaultHeaders = (isset($this->getSoapClient()->__default_headers) && is_array($this->getSoapClient()->__default_headers)) ? $this->getSoapClient()->__default_headers : [];
0 ignored issues
show
Bug introduced by
The property __default_headers does not seem to exist in SoapClient.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
295 15
            foreach ($defaultHeaders as $index => $soapHeader) {
296 5
                if ($soapHeader->name === $name) {
297 5
                    unset($defaultHeaders[$index]);
298 5
                    break;
299
                }
300 6
            }
301 15
            $this->getSoapClient()->__setSoapheaders(null);
302 15
            if (!empty($actor)) {
303 5
                array_push($defaultHeaders, new \SoapHeader($nameSpace, $name, $data, $mustUnderstand, $actor));
304 2
            } else {
305 10
                array_push($defaultHeaders, new \SoapHeader($nameSpace, $name, $data, $mustUnderstand));
306
            }
307 15
            $this->getSoapClient()->__setSoapheaders($defaultHeaders);
308 6
        }
309 15
        return $this;
310
    }
311
    /**
312
     * Sets the SoapClient Stream context HTTP Header name according to its value
313
     * If a context already exists, it tries to modify it
314
     * It the context does not exist, it then creates it with the header name and its value
315
     * @uses AbstractSoapClientBase::getSoapClient()
316
     * @param string $headerName
317
     * @param mixed $headerValue
318
     * @return bool
319
     */
320 30
    public function setHttpHeader($headerName, $headerValue)
321
    {
322 30
        $state = false;
323 30
        if ($this->getSoapClient() && !empty($headerName)) {
324 30
            $streamContext = $this->getStreamContext();
325 30
            if ($streamContext === null) {
326 6
                $options = [];
327 6
                $options['http'] = [];
328 6
                $options['http']['header'] = '';
329 6
            } else {
330 26
                $options = stream_context_get_options($streamContext);
331 26
                if (!array_key_exists('http', $options) || !is_array($options['http'])) {
332
                    $options['http'] = [];
333
                    $options['http']['header'] = '';
334 26
                } elseif (!array_key_exists('header', $options['http'])) {
335
                    $options['http']['header'] = '';
336
                }
337
            }
338 30
            if (count($options) && array_key_exists('http', $options) && is_array($options['http']) && array_key_exists('header', $options['http']) && is_string($options['http']['header'])) {
339 30
                $lines = explode("\r\n", $options['http']['header']);
340
                /**
341
                 * Ensure there is only one header entry for this header name
342
                 */
343 30
                $newLines = [];
344 30
                foreach ($lines as $line) {
345 30
                    if (!empty($line) && strpos($line, $headerName) === false) {
346 26
                        array_push($newLines, $line);
347 8
                    }
348 12
                }
349
                /**
350
                 * Add new header entry
351
                 */
352 30
                array_push($newLines, "$headerName: $headerValue");
353
                /**
354
                 * Set the context http header option
355
                 */
356 30
                $options['http']['header'] = implode("\r\n", $newLines);
357
                /**
358
                 * Create context if it does not exist
359
                 */
360 30
                if ($streamContext === null) {
361 6
                    $state = ($this->getSoapClient()->_stream_context = stream_context_create($options)) ? true : false;
0 ignored issues
show
Bug introduced by
The property _stream_context does not seem to exist in SoapClient.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
362 6
                } else {
363
                    /**
364
                     * Set the new context http header option
365
                     */
366 26
                    $state = stream_context_set_option($this->getSoapClient()->_stream_context, 'http', 'header', $options['http']['header']);
367
                }
368 12
            }
369 12
        }
370 30
        return $state;
371
    }
372
    /**
373
     * Returns current \SoapClient::_stream_context resource or null
374
     * @return resource|null
375
     */
376 35
    public function getStreamContext()
377
    {
378 35
        return ($this->getSoapClient() && isset($this->getSoapClient()->_stream_context) && is_resource($this->getSoapClient()->_stream_context)) ? $this->getSoapClient()->_stream_context : null;
0 ignored issues
show
Bug introduced by
The property _stream_context does not seem to exist in SoapClient.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
379
    }
380
    /**
381
     * Returns current \SoapClient::_stream_context resource options or empty array
382
     * @return array
383
     */
384 5
    public function getStreamContextOptions()
385
    {
386 5
        $options = [];
387 5
        $context = $this->getStreamContext();
388 5
        if ($context !== null) {
389 5
            $options = stream_context_get_options($context);
390 2
        }
391 5
        return $options;
392
    }
393
    /**
394
     * Method returning last errors occured during the calls
395
     * @return array
396
     */
397 5
    public function getLastError()
398
    {
399 5
        return $this->lastError;
400
    }
401
    /**
402
     * Method setting last errors occured during the calls
403
     * @param array $lastError
404
     * @return AbstractSoapClientBase
405
     */
406 130
    private function setLastError($lastError)
407
    {
408 130
        $this->lastError = $lastError;
409 130
        return $this;
410
    }
411
    /**
412
     * Method saving the last error returned by the SoapClient
413
     * @param string $methodName the method called when the error occurred
414
     * @param \SoapFault $soapFault l'objet de l'erreur
415
     * @return AbstractSoapClientBase
416
     */
417 15
    public function saveLastError($methodName, \SoapFault $soapFault)
418
    {
419 15
        $this->lastError[$methodName] = $soapFault;
420 15
        return $this;
421
    }
422
    /**
423
     * Method getting the last error for a certain method
424
     * @param string $methodName method name to get error from
425
     * @return \SoapFault|null
426
     */
427 5
    public function getLastErrorForMethod($methodName)
428
    {
429 5
        return array_key_exists($methodName, $this->lastError) ? $this->lastError[$methodName] : null;
430
    }
431
    /**
432
     * Method returning current result from Soap call
433
     * @return mixed
434
     */
435 5
    public function getResult()
436
    {
437 5
        return $this->result;
438
    }
439
    /**
440
     * Method setting current result from Soap call
441
     * @param mixed $result
442
     * @return AbstractSoapClientBase
443
     */
444 15
    public function setResult($result)
445
    {
446 15
        $this->result = $result;
447 15
        return $this;
448
    }
449
}
450