Skip to content

Instantly share code, notes, and snippets.

@dccampbell
Created April 19, 2016 00:41
Show Gist options
  • Select an option

  • Save dccampbell/01beee2f1dfda617813ca5587f734b18 to your computer and use it in GitHub Desktop.

Select an option

Save dccampbell/01beee2f1dfda617813ca5587f734b18 to your computer and use it in GitHub Desktop.
<?php
/**
* A generic SoapClient wrapper class with conveniences.
*
* Forces some default SoapClient options (trace/version/cache/etc),
* and provides the ability to set default options, callbacks, and custom response classes.
*
* @author DCCampbell
* @package AdvancedSoapClient
*/
class AdvancedSoapClient extends \SoapClient {
protected $args; /** @var array $args */
protected $callback; /** @var callable $callback */
protected $responseClass; /** @var mixed $responseClass */
/**
* Setup client with options and store default arguments.
* @param string $wsdl Path/URL to WSDL file
* @param array $args Default arguments to pass to every SOAP call
*/
public function __construct($wsdl, $args=array()) {
$this->args = $args;
$options = array(
'trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_2,
'cache_wsdl' => WSDL_CACHE_NONE,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
);
parent::__construct($wsdl, $options);
}
/**
* Wraps the standard SoapClient __call.
* Merges default arguments, triggers callback, and cast the return object type.
* @param string $function_name
* @param array $arguments
* @return stdClass|mixed
*/
public function __call($function_name, $arguments) {
$args = array_merge($this->args, $arguments);
$response = parent::__call($function_name, array($function_name => $args));
if(is_callable($this->callback)) {
call_user_func($this->callback, $this, $function_name, $args, $response);
}
if(class_exists($this->responseClass, true)) {
$response = new $this->responseClass($response);
}
return $response;
}
/**
* Specify a class to return the response as (default is stdClass).
* The stdClass response will be constructed with the stdClass response as a parameter.
* @param string $className
*/
public function setResponseClass($className) {
$this->responseClass = $className;
}
/**
* Set a function to be called following each SOAP call.
* @param callable $callable parameters: $this, $function_name, $args, $response
*/
public function setCallback($callable) {
$this->callback = $callable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment