<?php
namespace Engine\Soap;

// TODO: is this ever used?
class SoapClientCurl extends SoapClient
{
	/**
	 * Set configuration
	 */
	protected function iniSet()
	{
		// SET FLAGS
		ini_set("soap.wsdl_cache_enabled", 1);
		ini_set("soap.wsdl_cache", WSDL_CACHE_DISK);

	}


	/**
	 * (non-PHPdoc)
	 * @see SoapClient::__doRequest()
	 * @see http://php.net/manual/en/function.curl-setopt.php
	 * @see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
	 * @see http://stackoverflow.com/questions/10308915/php-default-curl-timeout-value
	 *
	 * PHP 8.5 added a 6th parameter (?string $uriParserClass) to SoapClient::__doRequest().
	 * We include it here so the override is compatible with PHP 8.5+, while remaining callable on 8.1–8.4.
	 * Note: this implementation does not call parent::__doRequest() — it makes a direct cURL call.
	 */
	public function __doRequest(string $request, string $location, string $action, int $version, bool $oneWay = false, ?string $uriParserClass = null): ?string
	{

		// Call via Curl and use the timeout
		$curl = curl_init ( $location );

		curl_setopt($curl, CURLOPT_VERBOSE, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_POST, TRUE);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
		curl_setopt($curl, CURLOPT_HEADER, FALSE);

		$HTTPheaders = [];
		$HTTPheaders[] = "Content-Type: text/xml";
		foreach ($this->options->HTTPHeaders as $HTTPheader) {
			// escape headers, remove newlines
			$HTTPheaders[] = sprintf("%s: %s", $HTTPheader['key'], str_replace("\n", "", $HTTPheader['value']));
		}
		curl_setopt($curl, CURLOPT_HTTPHEADER, $HTTPheaders);

		if ($this->options->socket_timeout) {
			curl_setopt($curl, CURLOPT_TIMEOUT, $this->options->socket_timeout);
		}
		if ($this->options->connection_timeout) {
			curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->options->connection_timeout);
		}

// 		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); // TODO: to be configured in the future; is this needed/used?
// 		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);

		$response = curl_exec($curl);

		if (curl_errno( $curl )) {
			throw new \SoapFault(sprintf("CURL error %d", curl_errno($curl)), curl_error($curl));
		}

		if ($response === false) {
			throw new \SoapFault("HTTP", "cURL returned no response (curl_exec returned false)");
		}

//		curl_close($curl);

		// Return?
		if (! $oneWay) {
			return ($response);
		}
		return null;

	}
}
