3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
19 use Zend\Server\Server
as ZendServerServer
;
20 use Zend\Stdlib\ArrayUtils
;
22 class Server
implements ZendServerServer
31 * Class registered with this server
37 * Arguments to pass to {@link $class} constructor
40 protected $classArgs = array();
43 * Array of SOAP type => PHP class pairings for handling return/incoming values
55 * Registered fault exceptions
58 protected $faultExceptions = array();
61 * SOAP Server Features
67 * Functions registered with this server; may be either an array or the SOAP_FUNCTIONS_ALL constant
70 protected $functions = array();
73 * Object registered with this server
78 * Persistence mode; should be one of the SOAP persistence constants
81 protected $persistence;
96 * Flag: whether or not {@link handle()} should return a response instead of automatically emitting it.
99 protected $returnResponse = false;
102 * SOAP version to use; SOAP_1_2 by default, to allow processing of headers
105 protected $soapVersion = SOAP_1_2
;
108 * Array of type mappings
114 * URI namespace for SOAP server
120 * URI or path to WSDL
126 * WSDL Caching Options of SOAP Server
129 protected $wsdlCache;
134 * Sets display_errors INI setting to off (prevent client errors due to bad
135 * XML in response). Registers {@link handlePhpErrors()} as error handler
138 * If $wsdl is provided, it is passed on to {@link setWSDL()}; if any
139 * options are specified, they are passed on to {@link setOptions()}.
141 * @param string $wsdl
142 * @param array $options
143 * @throws Exception\ExtensionNotLoadedException
145 public function __construct($wsdl = null, array $options = null)
147 if (!extension_loaded('soap')) {
148 throw new Exception\
ExtensionNotLoadedException('SOAP extension is not loaded.');
151 if (null !== $wsdl) {
152 $this->setWSDL($wsdl);
155 if (null !== $options) {
156 $this->setOptions($options);
163 * Allows setting options as an associative array of option => value pairs.
165 * @param array|\Traversable $options
168 public function setOptions($options)
170 if ($options instanceof Traversable
) {
171 $options = ArrayUtils
::iteratorToArray($options);
174 foreach ($options as $key => $value) {
175 switch (strtolower($key)) {
177 $this->setActor($value);
182 $this->setClassmap($value);
187 $this->setTypemap($value);
191 $this->setEncoding($value);
196 $this->setSoapVersion($value);
200 $this->setUri($value);
204 $this->setWSDL($value);
208 $this->setWSDLCache($value);
212 $this->setSoapFeatures($value);
224 * Return array of options suitable for using with SoapServer constructor
228 public function getOptions()
231 if (null !== $this->actor
) {
232 $options['actor'] = $this->getActor();
235 if (null !== $this->classmap
) {
236 $options['classmap'] = $this->getClassmap();
239 if (null !== $this->typemap
) {
240 $options['typemap'] = $this->getTypemap();
243 if (null !== $this->encoding
) {
244 $options['encoding'] = $this->getEncoding();
247 if (null !== $this->soapVersion
) {
248 $options['soap_version'] = $this->getSoapVersion();
251 if (null !== $this->uri
) {
252 $options['uri'] = $this->getUri();
255 if (null !== $this->features
) {
256 $options['features'] = $this->getSoapFeatures();
259 if (null !== $this->wsdlCache
) {
260 $options['cache_wsdl'] = $this->getWSDLCache();
269 * @param string $encoding
271 * @throws Exception\InvalidArgumentException with invalid encoding argument
273 public function setEncoding($encoding)
275 if (!is_string($encoding)) {
276 throw new Exception\
InvalidArgumentException('Invalid encoding specified');
279 $this->encoding
= $encoding;
288 public function getEncoding()
290 return $this->encoding
;
296 * @param int $version One of the SOAP_1_1 or SOAP_1_2 constants
298 * @throws Exception\InvalidArgumentException with invalid soap version argument
300 public function setSoapVersion($version)
302 if (!in_array($version, array(SOAP_1_1
, SOAP_1_2
))) {
303 throw new Exception\
InvalidArgumentException('Invalid soap version specified');
306 $this->soapVersion
= $version;
315 public function getSoapVersion()
317 return $this->soapVersion
;
321 * Check for valid URN
325 * @throws Exception\InvalidArgumentException on invalid URN
327 public function validateUrn($urn)
329 $scheme = parse_url($urn, PHP_URL_SCHEME
);
330 if ($scheme === false ||
$scheme === null) {
331 throw new Exception\
InvalidArgumentException('Invalid URN');
340 * Actor is the actor URI for the server.
342 * @param string $actor
345 public function setActor($actor)
347 $this->validateUrn($actor);
348 $this->actor
= $actor;
357 public function getActor()
365 * URI in SoapServer is actually the target namespace, not a URI; $uri must begin with 'urn:'.
370 public function setUri($uri)
372 $this->validateUrn($uri);
382 public function getUri()
390 * @param array $classmap
392 * @throws Exception\InvalidArgumentException for any invalid class in the class map
394 public function setClassmap($classmap)
396 if (!is_array($classmap)) {
397 throw new Exception\
InvalidArgumentException('Classmap must be an array');
399 foreach ($classmap as $class) {
400 if (!class_exists($class)) {
401 throw new Exception\
InvalidArgumentException('Invalid class in class map');
405 $this->classmap
= $classmap;
414 public function getClassmap()
416 return $this->classmap
;
420 * Set typemap with xml to php type mappings with appropriate validation.
422 * @param array $typeMap
424 * @throws Exception\InvalidArgumentException
426 public function setTypemap($typeMap)
428 if (!is_array($typeMap)) {
429 throw new Exception\
InvalidArgumentException('Typemap must be an array');
432 foreach ($typeMap as $type) {
433 if (!is_callable($type['from_xml'])) {
434 throw new Exception\
InvalidArgumentException('Invalid from_xml callback for type: ' . $type['type_name']);
436 if (!is_callable($type['to_xml'])) {
437 throw new Exception\
InvalidArgumentException('Invalid to_xml callback for type: ' . $type['type_name']);
441 $this->typemap
= $typeMap;
450 public function getTypemap()
452 return $this->typemap
;
458 * @param string $wsdl URI or path to a WSDL
461 public function setWSDL($wsdl)
472 public function getWSDL()
478 * Set the SOAP Feature options.
480 * @param string|int $feature
483 public function setSoapFeatures($feature)
485 $this->features
= $feature;
490 * Return current SOAP Features options
494 public function getSoapFeatures()
496 return $this->features
;
500 * Set the SOAP WSDL Caching Options
502 * @param string|int|bool $options
505 public function setWSDLCache($options)
507 $this->wsdlCache
= $options;
512 * Get current SOAP WSDL Caching option
514 public function getWSDLCache()
516 return $this->wsdlCache
;
520 * Attach a function as a server method
522 * @param array|string $function Function name, array of function names to attach,
523 * or SOAP_FUNCTIONS_ALL to attach all functions
524 * @param string $namespace Ignored
526 * @throws Exception\InvalidArgumentException on invalid functions
528 public function addFunction($function, $namespace = '')
530 // Bail early if set to SOAP_FUNCTIONS_ALL
531 if ($this->functions
== SOAP_FUNCTIONS_ALL
) {
535 if (is_array($function)) {
536 foreach ($function as $func) {
537 if (is_string($func) && function_exists($func)) {
538 $this->functions
[] = $func;
540 throw new Exception\
InvalidArgumentException('One or more invalid functions specified in array');
544 } elseif (is_string($function) && function_exists($function)) {
545 $this->functions
[] = $function;
547 } elseif ($function == SOAP_FUNCTIONS_ALL
) {
548 $this->functions
= SOAP_FUNCTIONS_ALL
;
551 throw new Exception\
InvalidArgumentException('Invalid function specified');
554 if (is_array($this->functions
)) {
555 $this->functions
= array_unique($this->functions
);
562 * Attach a class to a server
564 * Accepts a class name to use when handling requests. Any additional
565 * arguments will be passed to that class' constructor when instantiated.
567 * See {@link setObject()} to set pre-configured object instances as request handlers.
569 * @param string|object $class Class name or object instance which executes
570 * SOAP Requests at endpoint.
571 * @param string $namespace
572 * @param null|array $argv
574 * @throws Exception\InvalidArgumentException if called more than once, or if class does not exist
576 public function setClass($class, $namespace = '', $argv = null)
578 if (isset($this->class)) {
579 throw new Exception\
InvalidArgumentException('A class has already been registered with this soap server instance');
582 if (is_object($class)) {
583 return $this->setObject($class);
586 if (!is_string($class)) {
587 throw new Exception\
InvalidArgumentException(sprintf(
588 'Invalid class argument (%s)',
593 if (!class_exists($class)) {
594 throw new Exception\
InvalidArgumentException(sprintf(
595 'Class "%s" does not exist',
600 $this->class = $class;
601 if (2 < func_num_args()) {
602 $argv = func_get_args();
603 $this->classArgs
= array_slice($argv, 2);
610 * Attach an object to a server
612 * Accepts an instantiated object to use when handling requests.
614 * @param object $object
616 * @throws Exception\InvalidArgumentException
618 public function setObject($object)
620 if (!is_object($object)) {
621 throw new Exception\
InvalidArgumentException(sprintf(
622 'Invalid object argument (%s)',
627 if (isset($this->object)) {
628 throw new Exception\
InvalidArgumentException(
629 'An object has already been registered with this soap server instance'
633 $this->object = $object;
638 * Return a server definition array
640 * Returns a list of all functions registered with {@link addFunction()},
641 * merged with all public methods of the class set with {@link setClass()}
646 public function getFunctions()
648 $functions = array();
649 if (null !== $this->class) {
650 $functions = get_class_methods($this->class);
651 } elseif (null !== $this->object) {
652 $functions = get_class_methods($this->object);
655 return array_merge((array) $this->functions
, $functions);
659 * Unimplemented: Load server definition
661 * @param array $definition
662 * @throws Exception\RuntimeException Unimplemented
664 public function loadFunctions($definition)
666 throw new Exception\
RuntimeException('Unimplemented method.');
670 * Set server persistence
672 * @param int $mode SOAP_PERSISTENCE_SESSION or SOAP_PERSISTENCE_REQUEST constants
674 * @throws Exception\InvalidArgumentException
676 public function setPersistence($mode)
678 if (!in_array($mode, array(SOAP_PERSISTENCE_SESSION
, SOAP_PERSISTENCE_REQUEST
))) {
679 throw new Exception\
InvalidArgumentException('Invalid persistence mode specified');
682 $this->persistence
= $mode;
687 * Get server persistence
691 public function getPersistence()
693 return $this->persistence
;
699 * $request may be any of:
700 * - DOMDocument; if so, then cast to XML
701 * - DOMNode; if so, then grab owner document and cast to XML
702 * - SimpleXMLElement; if so, then cast to XML
703 * - stdClass; if so, calls __toString() and verifies XML
704 * - string; if so, verifies XML
706 * @param DOMDocument|DOMNode|SimpleXMLElement|stdClass|string $request
708 * @throws Exception\InvalidArgumentException
710 protected function _setRequest($request)
714 if ($request instanceof DOMDocument
) {
715 $xml = $request->saveXML();
717 } elseif ($request instanceof DOMNode
) {
718 $xml = $request->ownerDocument
->saveXML();
720 } elseif ($request instanceof SimpleXMLElement
) {
721 $xml = $request->asXML();
723 } elseif (is_object($request) ||
is_string($request)) {
724 if (is_object($request)) {
725 $xml = $request->__toString();
731 libxml_disable_entity_loader(true);
733 $dom = new DOMDocument();
734 $loadStatus = $dom->loadXML($xml);
736 // @todo check libxml errors ? validate document ?
737 if (strlen($xml) == 0 ||
!$loadStatus) {
738 throw new Exception\
InvalidArgumentException('Invalid XML');
741 foreach ($dom->childNodes
as $child) {
742 if ($child->nodeType
=== XML_DOCUMENT_TYPE_NODE
) {
743 throw new Exception\
InvalidArgumentException('Invalid XML: Detected use of illegal DOCTYPE');
746 libxml_disable_entity_loader(false);
749 $this->request
= $xml;
754 * Retrieve request XML
758 public function getLastRequest()
760 return $this->request
;
764 * Set return response flag
766 * If true, {@link handle()} will return the response instead of
767 * automatically sending it back to the requesting client.
769 * The response is always available via {@link getResponse()}.
774 public function setReturnResponse($flag = true)
776 $this->returnResponse
= ($flag) ?
true : false;
781 * Retrieve return response flag
785 public function getReturnResponse()
787 return $this->returnResponse
;
795 public function getResponse()
797 return $this->response
;
801 * Get SoapServer object
803 * Uses {@link $wsdl} and return value of {@link getOptions()} to instantiate
804 * SoapServer object, and then registers any functions or class with it, as
805 * well as persistence.
809 protected function _getSoap()
811 $options = $this->getOptions();
812 $server = new SoapServer($this->wsdl
, $options);
814 if (!empty($this->functions
)) {
815 $server->addFunction($this->functions
);
818 if (!empty($this->class)) {
819 $args = $this->classArgs
;
820 array_unshift($args, $this->class);
821 call_user_func_array(array($server, 'setClass'), $args);
824 if (!empty($this->object)) {
825 $server->setObject($this->object);
828 if (null !== $this->persistence
) {
829 $server->setPersistence($this->persistence
);
838 * Instantiates SoapServer object with options set in object, and
839 * dispatches its handle() method.
841 * $request may be any of:
842 * - DOMDocument; if so, then cast to XML
843 * - DOMNode; if so, then grab owner document and cast to XML
844 * - SimpleXMLElement; if so, then cast to XML
845 * - stdClass; if so, calls __toString() and verifies XML
846 * - string; if so, verifies XML
848 * If no request is passed, pulls request using php:://input (for
849 * cross-platform compatibility purposes).
851 * @param DOMDocument|DOMNode|SimpleXMLElement|stdClass|string $request Optional request
852 * @return void|string
854 public function handle($request = null)
856 if (null === $request) {
857 $request = file_get_contents('php://input');
860 // Set Server error handler
861 $displayErrorsOriginalState = $this->_initializeSoapErrorContext();
863 $setRequestException = null;
865 $this->_setRequest($request);
866 } catch (\Exception
$e) {
867 $setRequestException = $e;
870 $soap = $this->_getSoap();
873 $this->response
= '';
875 if ($setRequestException instanceof \Exception
) {
876 // Create SOAP fault message if we've caught a request exception
877 $fault = $this->fault($setRequestException->getMessage(), 'Sender');
881 $soap->handle($this->request
);
882 } catch (\Exception
$e) {
883 $fault = $this->fault($e);
885 $this->response
= ob_get_clean();
888 // Restore original error handler
889 restore_error_handler();
890 ini_set('display_errors', $displayErrorsOriginalState);
892 // Send a fault, if we have one
893 if ($fault instanceof SoapFault
&& !$this->returnResponse
) {
894 $soap->fault($fault->faultcode
, $fault->getMessage());
899 // Echo the response, if we're not returning it
900 if (!$this->returnResponse
) {
901 echo $this->response
;
906 // Return a fault, if we have it
907 if ($fault instanceof SoapFault
) {
911 // Return the response
912 return $this->response
;
916 * Method initializes the error context that the SOAPServer environment will run in.
918 * @return bool display_errors original value
920 protected function _initializeSoapErrorContext()
922 $displayErrorsOriginalState = ini_get('display_errors');
923 ini_set('display_errors', false);
924 set_error_handler(array($this, 'handlePhpErrors'), E_USER_ERROR
);
925 return $displayErrorsOriginalState;
929 * Validate and register fault exception
931 * @param string|array $class Exception class or array of exception classes
933 * @throws Exception\InvalidArgumentException
935 public function registerFaultException($class)
937 if (is_array($class)) {
938 foreach($class as $row) {
939 $this->registerFaultException($row);
942 } elseif (is_string($class) && class_exists($class) && (is_subclass_of($class, 'Exception') ||
'Exception' === $class)) {
943 $ref = new ReflectionClass($class);
945 $this->faultExceptions
[] = $ref->getName();
946 $this->faultExceptions
= array_unique($this->faultExceptions
);
948 throw new Exception\
InvalidArgumentException(
949 'Argument for Zend\Soap\Server::registerFaultException should be string or array of strings with valid exception names'
957 * Checks if provided fault name is registered as valid in this server.
959 * @param $fault Name of a fault class
962 public function isRegisteredAsFaultException($fault)
964 $ref = new ReflectionClass($fault);
965 $classNames = $ref->getName();
966 return in_array($classNames, $this->faultExceptions
);
970 * Deregister a fault exception from the fault exception stack
972 * @param string $class
975 public function deregisterFaultException($class)
977 if (in_array($class, $this->faultExceptions
, true)) {
978 $index = array_search($class, $this->faultExceptions
);
979 unset($this->faultExceptions
[$index]);
987 * Return fault exceptions list
991 public function getFaultExceptions()
993 return $this->faultExceptions
;
997 * Generate a server fault
999 * Note that the arguments are reverse to those of SoapFault.
1001 * If an exception is passed as the first argument, its message and code
1002 * will be used to create the fault object if it has been registered via
1003 * {@Link registerFaultException()}.
1005 * @link http://www.w3.org/TR/soap12-part1/#faultcodes
1006 * @param string|\Exception $fault
1007 * @param string $code SOAP Fault Codes
1010 public function fault($fault = null, $code = 'Receiver')
1012 if ($fault instanceof \Exception
) {
1013 if ($this->isRegisteredAsFaultException($fault)) {
1014 $message = $fault->getMessage();
1015 $eCode = $fault->getCode();
1016 $code = empty($eCode) ?
$code : $eCode;
1018 $message = 'Unknown error';
1020 } elseif (is_string($fault)) {
1023 $message = 'Unknown error';
1026 $allowedFaultModes = array('VersionMismatch', 'MustUnderstand', 'DataEncodingUnknown', 'Sender', 'Receiver', 'Server');
1027 if (!in_array($code, $allowedFaultModes)) {
1031 return new SoapFault($code, $message);
1035 * Throw PHP errors as SoapFaults
1038 * @param string $errstr
1039 * @param string $errfile
1040 * @param int $errline
1041 * @param array $errcontext
1044 public function handlePhpErrors($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null)
1046 throw $this->fault($errstr, 'Receiver');