1: <?php
2:
3: namespace webfilesframework\core\datasystem\file\format;
4:
5: use webfilesframework\core\datasystem\file\format\MWebfile;
6: use webfilesframework\MWebfilesFrameworkException;
7:
8: 9: 10: 11: 12: 13:
14: class MWebfileStream
15: {
16:
17: private $webfiles;
18:
19: 20: 21: 22: 23: 24: 25: 26:
27: public function __construct($input)
28: {
29:
30: if (is_array($input)) {
31: $this->validateWebfilesArray($input);
32: $this->webfiles = $input;
33: } else if (is_string($input)) {
34: $this->webfiles = $this->unmarshall($input);
35: } else if ($input instanceof MWebfile) {
36: $this->webfiles = array();
37: array_push($this->webfiles, $input);
38: } else if (isset($input)) {
39: throw new MWebfilesFrameworkException("Cannot handle input for creating webfile stream. input: " . $input);
40: }
41: }
42:
43:
44: 45: 46: 47: 48:
49: private function validateWebfilesArray($webfiles) {
50:
51: foreach ($webfiles as $webfile) {
52: if ( ! $webfile instanceof MWebfile) {
53: throw new MWebfilesFrameworkException("Not all elements in array are from type MWebfile.");
54: }
55: }
56:
57: }
58:
59: private function marshall()
60: {
61:
62: $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
63:
64: $xml .= "<webfilestream><webfiles>";
65: foreach ($this->webfiles as $webfile) {
66: $xml .= $webfile->marshall(false);
67: }
68: $xml .= "</webfiles></webfilestream>";
69: return $xml;
70: }
71:
72: 73: 74: 75: 76: 77: 78:
79: private function unmarshall($input)
80: {
81:
82: $webfilesResultArray = array();
83:
84: $root = $this->parseAndValidateWebfilesStreamXml($input);
85: $webfilesChildren = $root->webfiles->children();
86:
87:
88: foreach ($webfilesChildren as $webfileChild) {
89: array_push(
90: $webfilesResultArray, MWebfile::staticUnmarshall($webfileChild->asXML()));
91: }
92:
93: return $webfilesResultArray;
94: }
95:
96: 97: 98: 99: 100:
101: private function parseAndValidateWebfilesStreamXml($input) {
102:
103: $root = @simplexml_load_string($input);
104:
105: if ( $root == null ) {
106: throw new MWebfilesFrameworkException(
107: "Error on reading xml of webfile stream: No root element given. Input: " . $input);
108: }
109:
110: if ( $root === false ) {
111: throw new MWebfilesFrameworkException(
112: "Error on reading xml of webfile stream: Input: " . $input);
113: }
114:
115: $rootChildren = $root->children();
116:
117: if ( count($rootChildren) != 1 ) {
118: throw new MWebfilesFrameworkException("Root element has not exactly one child. Input: " . $input);
119: }
120:
121:
122: foreach ($rootChildren as $rootChild) {
123: if ( $rootChild->getName() != "webfiles" ) {
124: throw new MWebfilesFrameworkException("No webfiles child exists on root element. Input: " . $input);
125: }
126: }
127:
128: return $root;
129: }
130:
131:
132: public function getXML()
133: {
134: return $this->marshall();
135: }
136:
137: public function getWebfiles()
138: {
139: return $this->webfiles;
140: }
141: }
142: