1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: leo108 |
5
|
|
|
* Date: 2016/10/25 |
6
|
|
|
* Time: 15:10 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Leo108\CAS\Responses; |
10
|
|
|
|
11
|
|
|
use Illuminate\Support\Str; |
12
|
|
|
use SimpleXMLElement; |
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
14
|
|
|
|
15
|
|
|
class BaseXmlResponse |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var SimpleXMLElement |
19
|
|
|
*/ |
20
|
|
|
protected $node; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* BaseXmlResponse constructor. |
24
|
|
|
*/ |
25
|
13 |
|
public function __construct() |
26
|
|
|
{ |
27
|
13 |
|
$this->node = $this->getRootNode(); |
28
|
13 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @return SimpleXMLElement |
32
|
|
|
*/ |
33
|
13 |
|
protected function getRootNode() |
34
|
|
|
{ |
35
|
13 |
|
return simplexml_load_string('<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas"/>'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param SimpleXMLElement $xml |
40
|
|
|
* @param string $xpath |
41
|
|
|
*/ |
42
|
9 |
|
protected function removeByXPath(SimpleXMLElement $xml, $xpath) |
43
|
|
|
{ |
44
|
9 |
|
$nodes = $xml->xpath($xpath); |
45
|
9 |
|
foreach ($nodes as $node) { |
46
|
8 |
|
$dom = dom_import_simplexml($node); |
47
|
8 |
|
$dom->parentNode->removeChild($dom); |
48
|
|
|
} |
49
|
9 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* remove the first line of xml string |
53
|
|
|
* @param string $str |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
1 |
|
protected function removeXmlFirstLine($str) |
57
|
|
|
{ |
58
|
1 |
|
$first = '<?xml version="1.0"?>'; |
59
|
1 |
|
if (Str::startsWith($str, $first)) { |
60
|
1 |
|
return trim(substr($str, strlen($first))); |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
return $str; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param mixed $value |
68
|
|
|
* @return false|string |
69
|
|
|
*/ |
70
|
3 |
|
protected function stringify($value) |
71
|
|
|
{ |
72
|
3 |
|
if (is_string($value)) { |
73
|
3 |
|
$str = $value; |
74
|
1 |
|
} else if (is_object($value) && method_exists($value, '__toString')) { |
75
|
1 |
|
$str = $value->__toString(); |
76
|
1 |
|
} else if ($value instanceof \Serializable) { |
77
|
1 |
|
$str = serialize($value); |
78
|
|
|
} else { |
79
|
|
|
//array or object that doesn't have __toString method |
80
|
|
|
//json_encode will return false if encode failed |
81
|
1 |
|
$str = json_encode($value); |
82
|
|
|
} |
83
|
|
|
|
84
|
3 |
|
return $str; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @return Response |
89
|
|
|
*/ |
90
|
1 |
|
public function toResponse() |
91
|
|
|
{ |
92
|
1 |
|
$content = $this->removeXmlFirstLine($this->node->asXML()); |
|
|
|
|
93
|
|
|
|
94
|
1 |
|
return new Response($content, 200, ['Content-Type' => 'application/xml']); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|