-
Notifications
You must be signed in to change notification settings - Fork 123
/
PestXML.php
81 lines (72 loc) · 2.23 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?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)
*/
require_once 'Pest.php';
class PestXML extends Pest
{
/**
* Process error
* @param string $body
* @return string
*/
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;
}
}
/**
* Process body
*
* @todo This should always return a SimpleXMLElement
* @param string $body
* @return null|SimpleXMLElement|string
* @throws PestXML_Exception
*/
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();
libxml_clear_errors();
if (!empty($xml_errors)) {
foreach ($xml_errors as $xml_err)
$err .= "\n - " . $xml_err->message;
$err .= "\nThe response was:\n";
$err .= $body;
throw new PestXML_Exception($err);
}
}
return $xml;
}
}
class PestXML_Exception extends Pest_Exception
{}