<?php declare(strict_types=1);
namespace Uandi\UandiEfbErpSynchronization\Service\Api;
use Exception;
use SoapFault;
class SoapClient extends \SoapClient {
public ?string $username = null;
public ?string $password = null;
/**
*
* @param string $wsdl
* @param array|null $options
* @throws SoapFault
*/
public function __construct($wsdl, ?array $options = null) {
$wrappers = stream_get_wrappers();
stream_wrapper_unregister('http');
stream_wrapper_register('http', 'Uandi\UandiEfbErpSynchronization\Service\Api\StreamWrapperHttpAuth');
if (in_array("https", $wrappers)) {
stream_wrapper_unregister('https');
stream_wrapper_register('https', 'Uandi\UandiEfbErpSynchronization\Service\Api\StreamWrapperHttpAuth');
}
if ($options) {
$this->username = $options['user'];
StreamWrapperHttpAuth::$username = $this->username;
$this->password = $options['password'];
StreamWrapperHttpAuth::$password = $this->password;
}
parent::__construct($wsdl, ($options ?: array()));
stream_wrapper_restore('http');
if (in_array("https", $wrappers)) stream_wrapper_restore('https');
}
/**
* @param string $request
* @param string $location
* @param string $action
* @param int $version
* @param bool $oneWay
* @return string|null
* @throws Exception
*/
public function __doRequest(string $request, string $location, string $action, int $version, bool $oneWay = false): ?string
{
$headers = array(
'User-Agent: PHP-SOAP',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "' . $action . '"',
'Expect: 100-continue',
'Connection: Keep-Alive'
);
$this->__last_request_headers = $headers;
$location = $this->sanitizeUrl($location);
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (($info = curl_getinfo($ch)) && $info['http_code'] == 200) {
return $response;
}
else {
if ($info['http_code'] == 401) {
throw new Exception ('Access Denied', 401);
}
else {
if (curl_errno($ch) != 0) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
else {
throw new Exception($response, $info['http_code']);
}
}
}
}
/**
* Sanitize URL to request to Sharepoint
*
* @param string $url
* @return string
*/
protected function sanitizeUrl(string $url): string
{
return str_replace(" ", "%20", $url);
}
}