forked from educoder/pest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PestXML.php
66 lines (56 loc) · 1.77 KB
/
PestXML.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
require_once 'Pest.php';
/**
* Pest is a REST client for PHP.
* PestXML adds XML-specific functionality to Pest, automatically converting
* XML data resturned from REST services into SimpleXML objects.
*
* In other words, while Pest's get/post/put/delete calls return raw strings,
* PestXML's return SimpleXML objects.
*
* PestXML also attempts to derive error messages from the body of erroneous
* responses, expecting that these too are in XML (i.e. the contents of
* the first <error></error> tag in the response is assumed to be the error mssage)
*
* See http://github.com/educoder/pest for details.
*
* This code is licensed for use, modification, and distribution
* under the terms of the MIT License (see http://en.wikipedia.org/wiki/MIT_License)
*/
class PestXML extends Pest {
public function processBody($body) {
libxml_use_internal_errors(true);
if (empty($body) || preg_match('/^\s+$/', $body))
return null;
$xml = simplexml_load_string($body);
if (!$xml) {
$err = "Couldn't parse XML response because:\n";
$xml_errors = libxml_get_errors();
if(!empty($xml_errors))
{
foreach(libxml_get_errors() as $xml_err)
$err .= "\n - " . $xml_err->message;
$err .= "\nThe response was:\n";
$err .= $body;
throw new PestXML_Exception($err);
}
}
return $xml;
}
public function processError($body) {
try {
$xml = $this->processBody($body);
if (!$xml)
return $body;
$error = $xml->xpath('//error');
if ($error && $error[0])
return strval($error[0]);
else
return $body;
} catch (PestXML_Exception $e) {
return $body;
}
}
}
class PestXML_Exception extends Pest_Exception { }
?>