Completed
Push — master ( dca322...47e653 )
by Julito
08:54
created

nusoap_xmlschema::schemaStartElement()   F

Complexity

Conditions 79
Paths 6648

Size

Total Lines 317
Code Lines 222

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 79
eloc 222
nc 6648
nop 3
dl 0
loc 317
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
* parses an XML Schema, allows access to it's data, other utility methods.
5
* imperfect, no validation... yet, but quite functional.
6
*
7
* @author   Dietrich Ayala <[email protected]>
8
* @author   Scott Nichol <[email protected]>
9
* @version  $Id: class.xmlschema.php,v 1.53 2010/04/26 20:15:08 snichol Exp $
10
* @access   public
11
*/
12
class nusoap_xmlschema extends nusoap_base
13
{
14
	// files
15
	var $schema = '';
16
	var $xml = '';
17
	// namespaces
18
	var $enclosingNamespaces;
19
	// schema info
20
	var $schemaInfo = array();
21
	var $schemaTargetNamespace = '';
22
	// types, elements, attributes defined by the schema
23
	var $attributes = array();
24
	var $complexTypes = array();
25
	var $complexTypeStack = array();
26
	var $currentComplexType = null;
27
	var $elements = array();
28
	var $elementStack = array();
29
	var $currentElement = null;
30
	var $simpleTypes = array();
31
	var $simpleTypeStack = array();
32
	var $currentSimpleType = null;
33
	// imports
34
	var $imports = array();
35
	// parser vars
36
	var $parser;
37
	var $position = 0;
38
	var $depth = 0;
39
	var $depth_array = array();
40
	var $message = array();
41
	var $defaultNamespace = array();
42
43
	/**
44
	* constructor
45
	*
46
	* @param    string $schema schema document URI
47
	* @param    string $xml xml document URI
48
	* @param	string $namespaces namespaces defined in enclosing XML
49
	* @access   public
50
	*/
51
	function __construct($schema='',$xml='',$namespaces=array()){
52
		parent::__construct();
53
		$this->debug('nusoap_xmlschema class instantiated, inside constructor');
54
		// files
55
		$this->schema = $schema;
56
		$this->xml = $xml;
57
58
		// namespaces
59
		$this->enclosingNamespaces = $namespaces;
60
		$this->namespaces = array_merge($this->namespaces, $namespaces);
61
62
		// parse schema file
63
		if($schema != ''){
64
			$this->debug('initial schema file: '.$schema);
65
			$this->parseFile($schema, 'schema');
66
		}
67
68
		// parse xml file
69
		if($xml != ''){
70
			$this->debug('initial xml file: '.$xml);
71
			$this->parseFile($xml, 'xml');
72
		}
73
74
	}
75
76
    /**
77
    * parse an XML file
78
    *
79
    * @param string $xml path/URL to XML file
80
    * @param string $type (schema | xml)
81
	* @return boolean
82
    * @access public
83
    */
84
	function parseFile($xml,$type){
85
		// parse xml file
86
		if($xml != ""){
87
			$xmlStr = @join("",@file($xml));
88
			if($xmlStr == ""){
89
				$msg = 'Error reading XML from '.$xml;
90
				$this->setError($msg);
91
				$this->debug($msg);
92
			return false;
93
			} else {
94
				$this->debug("parsing $xml");
95
				$this->parseString($xmlStr,$type);
96
				$this->debug("done parsing $xml");
97
			return true;
98
			}
99
		}
100
		return false;
101
	}
102
103
	/**
104
	* parse an XML string
105
	*
106
	* @param    string $xml path or URL
107
    * @param	string $type (schema|xml)
108
	* @access   private
109
	*/
110
	function parseString($xml,$type){
111
		// parse xml string
112
		if($xml != ""){
113
114
	    	// Create an XML parser.
115
	    	$this->parser = xml_parser_create();
116
	    	// Set the options for parsing the XML data.
117
	    	xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
118
119
	    	// Set the object for the parser.
120
	    	xml_set_object($this->parser, $this);
121
122
	    	// Set the element handlers for the parser.
123
			if($type == "schema"){
124
		    	xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
125
		    	xml_set_character_data_handler($this->parser,'schemaCharacterData');
126
			} elseif($type == "xml"){
127
				xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
128
		    	xml_set_character_data_handler($this->parser,'xmlCharacterData');
129
			}
130
131
		    // Parse the XML file.
132
		    if(!xml_parse($this->parser,$xml,true)){
133
			// Display an error message.
134
				$errstr = sprintf('XML error parsing XML schema on line %d: %s',
135
				xml_get_current_line_number($this->parser),
136
				xml_error_string(xml_get_error_code($this->parser))
137
				);
138
				$this->debug($errstr);
139
				$this->debug("XML payload:\n" . $xml);
140
				$this->setError($errstr);
141
	    	}
142
143
			xml_parser_free($this->parser);
144
		} else{
145
			$this->debug('no xml passed to parseString()!!');
146
			$this->setError('no xml passed to parseString()!!');
147
		}
148
	}
149
150
	/**
151
	 * gets a type name for an unnamed type
152
	 *
153
	 * @param	string	Element name
154
	 * @return	string	A type name for an unnamed type
155
	 * @access	private
156
	 */
157
	function CreateTypeName($ename) {
158
		$scope = '';
159
		for ($i = 0; $i < count($this->complexTypeStack); $i++) {
160
			$scope .= $this->complexTypeStack[$i] . '_';
161
		}
162
		return $scope . $ename . '_ContainedType';
163
	}
164
165
	/**
166
	* start-element handler
167
	*
168
	* @param    string $parser XML parser object
169
	* @param    string $name element name
170
	* @param    string $attrs associative array of attributes
171
	* @access   private
172
	*/
173
	function schemaStartElement($parser, $name, $attrs) {
174
175
		// position in the total number of elements, starting from 0
176
		$pos = $this->position++;
177
		$depth = $this->depth++;
178
		// set self as current value for this depth
179
		$this->depth_array[$depth] = $pos;
180
		$this->message[$pos] = array('cdata' => '');
181
		if ($depth > 0) {
182
			$this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
183
		} else {
184
			$this->defaultNamespace[$pos] = false;
185
		}
186
187
		// get element prefix
188
		if($prefix = $this->getPrefix($name)){
189
			// get unqualified name
190
			$name = $this->getLocalPart($name);
191
		} else {
192
        	$prefix = '';
193
        }
194
195
        // loop thru attributes, expanding, and registering namespace declarations
196
        if(count($attrs) > 0){
197
        	foreach($attrs as $k => $v){
198
                // if ns declarations, add to class level array of valid namespaces
199
				if(preg_match('/^xmlns/',$k)){
200
                	//$this->xdebug("$k: $v");
201
                	//$this->xdebug('ns_prefix: '.$this->getPrefix($k));
202
                	if($ns_prefix = substr(strrchr($k,':'),1)){
203
                		//$this->xdebug("Add namespace[$ns_prefix] = $v");
204
						$this->namespaces[$ns_prefix] = $v;
205
					} else {
206
						$this->defaultNamespace[$pos] = $v;
207
						if (! $this->getPrefixFromNamespace($v)) {
208
							$this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
209
						}
210
					}
211
					if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
212
						$this->XMLSchemaVersion = $v;
213
						$this->namespaces['xsi'] = $v.'-instance';
214
					}
215
				}
216
        	}
217
        	foreach($attrs as $k => $v){
218
                // expand each attribute
219
                $k = strpos($k,':') ? $this->expandQname($k) : $k;
220
                $v = strpos($v,':') ? $this->expandQname($v) : $v;
221
        		$eAttrs[$k] = $v;
222
        	}
223
        	$attrs = $eAttrs;
224
        } else {
225
        	$attrs = array();
226
        }
227
		// find status, register data
228
		switch($name){
229
			case 'all':			// (optional) compositor content for a complexType
230
			case 'choice':
231
			case 'group':
232
			case 'sequence':
233
				//$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
234
				$this->complexTypes[$this->currentComplexType]['compositor'] = $name;
235
				//if($name == 'all' || $name == 'sequence'){
236
				//	$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
237
				//}
238
			break;
239
			case 'attribute':	// complexType attribute
240
            	//$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
241
            	$this->xdebug("parsing attribute:");
242
            	$this->appendDebug($this->varDump($attrs));
243
				if (!isset($attrs['form'])) {
244
					// TODO: handle globals
245
					$attrs['form'] = $this->schemaInfo['attributeFormDefault'];
246
				}
247
            	if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
248
					$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
249
					if (!strpos($v, ':')) {
250
						// no namespace in arrayType attribute value...
251
						if ($this->defaultNamespace[$pos]) {
252
							// ...so use the default
253
							$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
254
						}
255
					}
256
            	}
257
                if(isset($attrs['name'])){
258
					$this->attributes[$attrs['name']] = $attrs;
259
					$aname = $attrs['name'];
260
				} elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
261
					if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
262
	                	$aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
263
	                } else {
264
	                	$aname = '';
265
	                }
266
				} elseif(isset($attrs['ref'])){
267
					$aname = $attrs['ref'];
268
                    $this->attributes[$attrs['ref']] = $attrs;
269
				}
270
271
				if($this->currentComplexType){	// This should *always* be
272
					$this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
273
				}
274
				// arrayType attribute
275
				if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
276
					$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
277
                	$prefix = $this->getPrefix($aname);
278
					if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
279
						$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
280
					} else {
281
						$v = '';
282
					}
283
                    if(strpos($v,'[,]')){
284
                        $this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
285
                    }
286
                    $v = substr($v,0,strpos($v,'[')); // clip the []
287
                    if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
288
                        $v = $this->XMLSchemaVersion.':'.$v;
289
                    }
290
                    $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
291
				}
292
			break;
293
			case 'complexContent':	// (optional) content for a complexType
294
				$this->xdebug("do nothing for element $name");
295
			break;
296
			case 'complexType':
297
				array_push($this->complexTypeStack, $this->currentComplexType);
298
				if(isset($attrs['name'])){
299
					// TODO: what is the scope of named complexTypes that appear
300
					//       nested within other c complexTypes?
301
					$this->xdebug('processing named complexType '.$attrs['name']);
302
					//$this->currentElement = false;
303
					$this->currentComplexType = $attrs['name'];
304
					$this->complexTypes[$this->currentComplexType] = $attrs;
305
					$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
306
					// This is for constructs like
307
					//           <complexType name="ListOfString" base="soap:Array">
308
					//                <sequence>
309
					//                    <element name="string" type="xsd:string"
310
					//                        minOccurs="0" maxOccurs="unbounded" />
311
					//                </sequence>
312
					//            </complexType>
313
					if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
314
						$this->xdebug('complexType is unusual array');
315
						$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
316
					} else {
317
						$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
318
					}
319
				} else {
320
					$name = $this->CreateTypeName($this->currentElement);
321
					$this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name);
322
					$this->currentComplexType = $name;
323
					//$this->currentElement = false;
324
					$this->complexTypes[$this->currentComplexType] = $attrs;
325
					$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
326
					// This is for constructs like
327
					//           <complexType name="ListOfString" base="soap:Array">
328
					//                <sequence>
329
					//                    <element name="string" type="xsd:string"
330
					//                        minOccurs="0" maxOccurs="unbounded" />
331
					//                </sequence>
332
					//            </complexType>
333
					if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
334
						$this->xdebug('complexType is unusual array');
335
						$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
336
					} else {
337
						$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
338
					}
339
				}
340
				$this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false';
341
			break;
342
			case 'element':
343
				array_push($this->elementStack, $this->currentElement);
344
				if (!isset($attrs['form'])) {
345
					if ($this->currentComplexType) {
346
						$attrs['form'] = $this->schemaInfo['elementFormDefault'];
347
					} else {
348
						// global
349
						$attrs['form'] = 'qualified';
350
					}
351
				}
352
				if(isset($attrs['type'])){
353
					$this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
354
					if (! $this->getPrefix($attrs['type'])) {
355
						if ($this->defaultNamespace[$pos]) {
356
							$attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
357
							$this->xdebug('used default namespace to make type ' . $attrs['type']);
358
						}
359
					}
360
					// This is for constructs like
361
					//           <complexType name="ListOfString" base="soap:Array">
362
					//                <sequence>
363
					//                    <element name="string" type="xsd:string"
364
					//                        minOccurs="0" maxOccurs="unbounded" />
365
					//                </sequence>
366
					//            </complexType>
367
					if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
368
						$this->xdebug('arrayType for unusual array is ' . $attrs['type']);
369
						$this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
370
					}
371
					$this->currentElement = $attrs['name'];
372
					$ename = $attrs['name'];
373
				} elseif(isset($attrs['ref'])){
374
					$this->xdebug("processing element as ref to ".$attrs['ref']);
375
					$this->currentElement = "ref to ".$attrs['ref'];
376
					$ename = $this->getLocalPart($attrs['ref']);
377
				} else {
378
					$type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']);
379
					$this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type);
380
					$this->currentElement = $attrs['name'];
381
					$attrs['type'] = $this->schemaTargetNamespace . ':' . $type;
382
					$ename = $attrs['name'];
383
				}
384
				if (isset($ename) && $this->currentComplexType) {
385
					$this->xdebug("add element $ename to complexType $this->currentComplexType");
386
					$this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
387
				} elseif (!isset($attrs['ref'])) {
388
					$this->xdebug("add element $ename to elements array");
389
					$this->elements[ $attrs['name'] ] = $attrs;
390
					$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
391
				}
392
			break;
393
			case 'enumeration':	//	restriction value list member
394
				$this->xdebug('enumeration ' . $attrs['value']);
395
				if ($this->currentSimpleType) {
396
					$this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
397
				} elseif ($this->currentComplexType) {
398
					$this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
399
				}
400
			break;
401
			case 'extension':	// simpleContent or complexContent type extension
402
				$this->xdebug('extension ' . $attrs['base']);
403
				if ($this->currentComplexType) {
404
					$ns = $this->getPrefix($attrs['base']);
405
					if ($ns == '') {
406
						$this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base'];
407
					} else {
408
						$this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
409
					}
410
				} else {
411
					$this->xdebug('no current complexType to set extensionBase');
412
				}
413
			break;
414
			case 'import':
415
			    if (isset($attrs['schemaLocation'])) {
416
					$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
417
                    $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
418
				} else {
419
					$this->xdebug('import namespace ' . $attrs['namespace']);
420
                    $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
421
					if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
422
						$this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
423
					}
424
				}
425
			break;
426
			case 'include':
427
			    if (isset($attrs['schemaLocation'])) {
428
					$this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']);
429
                    $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
430
				} else {
431
					$this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute');
432
				}
433
			break;
434
			case 'list':	// simpleType value list
435
				$this->xdebug("do nothing for element $name");
436
			break;
437
			case 'restriction':	// simpleType, simpleContent or complexContent value restriction
438
				$this->xdebug('restriction ' . $attrs['base']);
439
				if($this->currentSimpleType){
440
					$this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
441
				} elseif($this->currentComplexType){
442
					$this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
443
					if(strstr($attrs['base'],':') == ':Array'){
444
						$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
445
					}
446
				}
447
			break;
448
			case 'schema':
449
				$this->schemaInfo = $attrs;
450
				$this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
451
				if (isset($attrs['targetNamespace'])) {
452
					$this->schemaTargetNamespace = $attrs['targetNamespace'];
453
				}
454
				if (!isset($attrs['elementFormDefault'])) {
455
					$this->schemaInfo['elementFormDefault'] = 'unqualified';
456
				}
457
				if (!isset($attrs['attributeFormDefault'])) {
458
					$this->schemaInfo['attributeFormDefault'] = 'unqualified';
459
				}
460
			break;
461
			case 'simpleContent':	// (optional) content for a complexType
462
				if ($this->currentComplexType) {	// This should *always* be
463
					$this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true';
464
				} else {
465
					$this->xdebug("do nothing for element $name because there is no current complexType");
466
				}
467
			break;
468
			case 'simpleType':
469
				array_push($this->simpleTypeStack, $this->currentSimpleType);
470
				if(isset($attrs['name'])){
471
					$this->xdebug("processing simpleType for name " . $attrs['name']);
472
					$this->currentSimpleType = $attrs['name'];
473
					$this->simpleTypes[ $attrs['name'] ] = $attrs;
474
					$this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
475
					$this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
476
				} else {
477
					$name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement);
478
					$this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name);
479
					$this->currentSimpleType = $name;
480
					//$this->currentElement = false;
481
					$this->simpleTypes[$this->currentSimpleType] = $attrs;
482
					$this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
483
				}
484
			break;
485
			case 'union':	// simpleType type list
486
				$this->xdebug("do nothing for element $name");
487
			break;
488
			default:
489
				$this->xdebug("do not have any logic to process element $name");
490
		}
491
	}
492
493
	/**
494
	* end-element handler
495
	*
496
	* @param    string $parser XML parser object
497
	* @param    string $name element name
498
	* @access   private
499
	*/
500
	function schemaEndElement($parser, $name) {
501
		// bring depth down a notch
502
		$this->depth--;
503
		// position of current element is equal to the last value left in depth_array for my depth
504
		if(isset($this->depth_array[$this->depth])){
505
        	$pos = $this->depth_array[$this->depth];
506
        }
507
		// get element prefix
508
		if ($prefix = $this->getPrefix($name)){
509
			// get unqualified name
510
			$name = $this->getLocalPart($name);
511
		} else {
512
        	$prefix = '';
513
        }
514
		// move on...
515
		if($name == 'complexType'){
516
			$this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
517
			$this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType]));
518
			$this->currentComplexType = array_pop($this->complexTypeStack);
519
			//$this->currentElement = false;
520
		}
521
		if($name == 'element'){
522
			$this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
523
			$this->currentElement = array_pop($this->elementStack);
524
		}
525
		if($name == 'simpleType'){
526
			$this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
527
			$this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType]));
528
			$this->currentSimpleType = array_pop($this->simpleTypeStack);
529
		}
530
	}
531
532
	/**
533
	* element content handler
534
	*
535
	* @param    string $parser XML parser object
536
	* @param    string $data element content
537
	* @access   private
538
	*/
539
	function schemaCharacterData($parser, $data){
540
		$pos = $this->depth_array[$this->depth - 1];
541
		$this->message[$pos]['cdata'] .= $data;
542
	}
543
544
	/**
545
	* serialize the schema
546
	*
547
	* @access   public
548
	*/
549
	function serializeSchema(){
550
551
		$schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
552
		$xml = '';
553
		// imports
554
		if (sizeof($this->imports) > 0) {
555
			foreach($this->imports as $ns => $list) {
556
				foreach ($list as $ii) {
557
					if ($ii['location'] != '') {
558
						$xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
559
					} else {
560
						$xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
561
					}
562
				}
563
			}
564
		}
565
		// complex types
566
		foreach($this->complexTypes as $typeName => $attrs){
567
			$contentStr = '';
568
			// serialize child elements
569
			if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
570
				foreach($attrs['elements'] as $element => $eParts){
571
					if(isset($eParts['ref'])){
572
						$contentStr .= "   <$schemaPrefix:element ref=\"$element\"/>\n";
573
					} else {
574
						$contentStr .= "   <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
575
						foreach ($eParts as $aName => $aValue) {
576
							// handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
577
							if ($aName != 'name' && $aName != 'type') {
578
								$contentStr .= " $aName=\"$aValue\"";
579
							}
580
						}
581
						$contentStr .= "/>\n";
582
					}
583
				}
584
				// compositor wraps elements
585
				if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
586
					$contentStr = "  <$schemaPrefix:$attrs[compositor]>\n".$contentStr."  </$schemaPrefix:$attrs[compositor]>\n";
587
				}
588
			}
589
			// attributes
590
			if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
591
				foreach($attrs['attrs'] as $attr => $aParts){
592
					$contentStr .= "    <$schemaPrefix:attribute";
593
					foreach ($aParts as $a => $v) {
594
						if ($a == 'ref' || $a == 'type') {
595
							$contentStr .= " $a=\"".$this->contractQName($v).'"';
596
						} elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
597
							$this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
598
							$contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
599
						} else {
600
							$contentStr .= " $a=\"$v\"";
601
						}
602
					}
603
					$contentStr .= "/>\n";
604
				}
605
			}
606
			// if restriction
607
			if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
608
				$contentStr = "   <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr."   </$schemaPrefix:restriction>\n";
609
				// complex or simple content
610
				if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
611
					$contentStr = "  <$schemaPrefix:complexContent>\n".$contentStr."  </$schemaPrefix:complexContent>\n";
612
				}
613
			}
614
			// finalize complex type
615
			if($contentStr != ''){
616
				$contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
617
			} else {
618
				$contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
619
			}
620
			$xml .= $contentStr;
621
		}
622
		// simple types
623
		if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
624
			foreach($this->simpleTypes as $typeName => $eParts){
625
				$xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n  <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n";
626
				if (isset($eParts['enumeration'])) {
627
					foreach ($eParts['enumeration'] as $e) {
628
						$xml .= "  <$schemaPrefix:enumeration value=\"$e\"/>\n";
629
					}
630
				}
631
				$xml .= "  </$schemaPrefix:restriction>\n </$schemaPrefix:simpleType>";
632
			}
633
		}
634
		// elements
635
		if(isset($this->elements) && count($this->elements) > 0){
636
			foreach($this->elements as $element => $eParts){
637
				$xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
638
			}
639
		}
640
		// attributes
641
		if(isset($this->attributes) && count($this->attributes) > 0){
642
			foreach($this->attributes as $attr => $aParts){
643
				$xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
644
			}
645
		}
646
		// finish 'er up
647
		$attr = '';
648
		foreach ($this->schemaInfo as $k => $v) {
649
			if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') {
650
				$attr .= " $k=\"$v\"";
651
			}
652
		}
653
		$el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n";
654
		foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
655
			$el .= " xmlns:$nsp=\"$ns\"";
656
		}
657
		$xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
658
		return $xml;
659
	}
660
661
	/**
662
	* adds debug data to the clas level debug string
663
	*
664
	* @param    string $string debug data
665
	* @access   private
666
	*/
667
	function xdebug($string){
668
		$this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
669
	}
670
671
    /**
672
    * get the PHP type of a user defined type in the schema
673
    * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
674
    * returns false if no type exists, or not w/ the given namespace
675
    * else returns a string that is either a native php type, or 'struct'
676
    *
677
    * @param string $type name of defined type
678
    * @param string $ns namespace of type
679
    * @return mixed
680
    * @access public
681
    * @deprecated
682
    */
683
	function getPHPType($type,$ns){
684
		if(isset($this->typemap[$ns][$type])){
685
			//print "found type '$type' and ns $ns in typemap<br>";
686
			return $this->typemap[$ns][$type];
687
		} elseif(isset($this->complexTypes[$type])){
688
			//print "getting type '$type' and ns $ns from complexTypes array<br>";
689
			return $this->complexTypes[$type]['phpType'];
690
		}
691
		return false;
692
	}
693
694
	/**
695
    * returns an associative array of information about a given type
696
    * returns false if no type exists by the given name
697
    *
698
	*	For a complexType typeDef = array(
699
	*	'restrictionBase' => '',
700
	*	'phpType' => '',
701
	*	'compositor' => '(sequence|all)',
702
	*	'elements' => array(), // refs to elements array
703
	*	'attrs' => array() // refs to attributes array
704
	*	... and so on (see addComplexType)
705
	*	)
706
	*
707
	*   For simpleType or element, the array has different keys.
708
    *
709
    * @param string $type
710
    * @return mixed
711
    * @access public
712
    * @see addComplexType
713
    * @see addSimpleType
714
    * @see addElement
715
    */
716
	function getTypeDef($type){
717
		//$this->debug("in getTypeDef for type $type");
718
		if (substr($type, -1) == '^') {
719
			$is_element = 1;
720
			$type = substr($type, 0, -1);
721
		} else {
722
			$is_element = 0;
723
		}
724
725
		if((! $is_element) && isset($this->complexTypes[$type])){
726
			$this->xdebug("in getTypeDef, found complexType $type");
727
			return $this->complexTypes[$type];
728
		} elseif((! $is_element) && isset($this->simpleTypes[$type])){
729
			$this->xdebug("in getTypeDef, found simpleType $type");
730
			if (!isset($this->simpleTypes[$type]['phpType'])) {
731
				// get info for type to tack onto the simple type
732
				// TODO: can this ever really apply (i.e. what is a simpleType really?)
733
				$uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
734
				$ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
735
				$etype = $this->getTypeDef($uqType);
736
				if ($etype) {
737
					$this->xdebug("in getTypeDef, found type for simpleType $type:");
738
					$this->xdebug($this->varDump($etype));
739
					if (isset($etype['phpType'])) {
740
						$this->simpleTypes[$type]['phpType'] = $etype['phpType'];
741
					}
742
					if (isset($etype['elements'])) {
743
						$this->simpleTypes[$type]['elements'] = $etype['elements'];
744
					}
745
				}
746
			}
747
			return $this->simpleTypes[$type];
748
		} elseif(isset($this->elements[$type])){
749
			$this->xdebug("in getTypeDef, found element $type");
750
			if (!isset($this->elements[$type]['phpType'])) {
751
				// get info for type to tack onto the element
752
				$uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
753
				$ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
754
				$etype = $this->getTypeDef($uqType);
755
				if ($etype) {
756
					$this->xdebug("in getTypeDef, found type for element $type:");
757
					$this->xdebug($this->varDump($etype));
758
					if (isset($etype['phpType'])) {
759
						$this->elements[$type]['phpType'] = $etype['phpType'];
760
					}
761
					if (isset($etype['elements'])) {
762
						$this->elements[$type]['elements'] = $etype['elements'];
763
					}
764
					if (isset($etype['extensionBase'])) {
765
						$this->elements[$type]['extensionBase'] = $etype['extensionBase'];
766
					}
767
				} elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
768
					$this->xdebug("in getTypeDef, element $type is an XSD type");
769
					$this->elements[$type]['phpType'] = 'scalar';
770
				}
771
			}
772
			return $this->elements[$type];
773
		} elseif(isset($this->attributes[$type])){
774
			$this->xdebug("in getTypeDef, found attribute $type");
775
			return $this->attributes[$type];
776
		} elseif (preg_match('/_ContainedType$/', $type)) {
777
			$this->xdebug("in getTypeDef, have an untyped element $type");
778
			$typeDef['typeClass'] = 'simpleType';
779
			$typeDef['phpType'] = 'scalar';
780
			$typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
781
			return $typeDef;
782
		}
783
		$this->xdebug("in getTypeDef, did not find $type");
784
		return false;
785
	}
786
787
	/**
788
    * returns a sample serialization of a given type, or false if no type by the given name
789
    *
790
    * @param string $type name of type
791
    * @return mixed
792
    * @access public
793
    * @deprecated
794
    */
795
    function serializeTypeDef($type){
796
    	//print "in sTD() for type $type<br>";
797
	if($typeDef = $this->getTypeDef($type)){
798
		$str .= '<'.$type;
799
	    if(is_array($typeDef['attrs'])){
800
		foreach($typeDef['attrs'] as $attName => $data){
801
		    $str .= " $attName=\"{type = ".$data['type']."}\"";
802
		}
803
	    }
804
	    $str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
805
	    if(count($typeDef['elements']) > 0){
806
		$str .= ">";
807
		foreach($typeDef['elements'] as $element => $eData){
808
		    $str .= $this->serializeTypeDef($element);
809
		}
810
		$str .= "</$type>";
811
	    } elseif($typeDef['typeClass'] == 'element') {
812
		$str .= "></$type>";
813
	    } else {
814
		$str .= "/>";
815
	    }
816
			return $str;
817
	}
818
    	return false;
819
    }
820
821
    /**
822
    * returns HTML form elements that allow a user
823
    * to enter values for creating an instance of the given type.
824
    *
825
    * @param string $name name for type instance
826
    * @param string $type name of type
827
    * @return string
828
    * @access public
829
    * @deprecated
830
	*/
831
	function typeToForm($name,$type){
832
		// get typedef
833
		if($typeDef = $this->getTypeDef($type)){
834
			// if struct
835
			if($typeDef['phpType'] == 'struct'){
836
				$buffer .= '<table>';
837
				foreach($typeDef['elements'] as $child => $childDef){
838
					$buffer .= "
839
					<tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
840
					<td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
841
				}
842
				$buffer .= '</table>';
843
			// if array
844
			} elseif($typeDef['phpType'] == 'array'){
845
				$buffer .= '<table>';
846
				for($i=0;$i < 3; $i++){
847
					$buffer .= "
848
					<tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
849
					<td><input type='text' name='parameters[".$name."][]'></td></tr>";
850
				}
851
				$buffer .= '</table>';
852
			// if scalar
853
			} else {
854
				$buffer .= "<input type='text' name='parameters[$name]'>";
855
			}
856
		} else {
857
			$buffer .= "<input type='text' name='parameters[$name]'>";
858
		}
859
		return $buffer;
860
	}
861
862
	/**
863
	* adds a complex type to the schema
864
	*
865
	* example: array
866
	*
867
	* addType(
868
	* 	'ArrayOfstring',
869
	* 	'complexType',
870
	* 	'array',
871
	* 	'',
872
	* 	'SOAP-ENC:Array',
873
	* 	array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
874
	* 	'xsd:string'
875
	* );
876
	*
877
	* example: PHP associative array ( SOAP Struct )
878
	*
879
	* addType(
880
	* 	'SOAPStruct',
881
	* 	'complexType',
882
	* 	'struct',
883
	* 	'all',
884
	* 	array('myVar'=> array('name'=>'myVar','type'=>'string')
885
	* );
886
	*
887
	* @param name
888
	* @param typeClass (complexType|simpleType|attribute)
889
	* @param phpType: currently supported are array and struct (php assoc array)
890
	* @param compositor (all|sequence|choice)
891
	* @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
892
	* @param elements = array ( name = array(name=>'',type=>'') )
893
	* @param attrs = array(
894
	* 	array(
895
	*		'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
896
	*		"http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
897
	* 	)
898
	* )
899
	* @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
900
	* @access public
901
	* @see getTypeDef
902
	*/
903
	function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
904
		$this->complexTypes[$name] = array(
905
	    'name'		=> $name,
906
	    'typeClass'	=> $typeClass,
907
	    'phpType'	=> $phpType,
908
		'compositor'=> $compositor,
909
	    'restrictionBase' => $restrictionBase,
910
		'elements'	=> $elements,
911
	    'attrs'		=> $attrs,
912
	    'arrayType'	=> $arrayType
913
		);
914
915
		$this->xdebug("addComplexType $name:");
916
		$this->appendDebug($this->varDump($this->complexTypes[$name]));
917
	}
918
919
	/**
920
	* adds a simple type to the schema
921
	*
922
	* @param string $name
923
	* @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
924
	* @param string $typeClass (should always be simpleType)
925
	* @param string $phpType (should always be scalar)
926
	* @param array $enumeration array of values
927
	* @access public
928
	* @see nusoap_xmlschema
929
	* @see getTypeDef
930
	*/
931
	function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
932
		$this->simpleTypes[$name] = array(
933
	    'name'			=> $name,
934
	    'typeClass'		=> $typeClass,
935
	    'phpType'		=> $phpType,
936
	    'type'			=> $restrictionBase,
937
	    'enumeration'	=> $enumeration
938
		);
939
940
		$this->xdebug("addSimpleType $name:");
941
		$this->appendDebug($this->varDump($this->simpleTypes[$name]));
942
	}
943
944
	/**
945
	* adds an element to the schema
946
	*
947
	* @param array $attrs attributes that must include name and type
948
	* @see nusoap_xmlschema
949
	* @access public
950
	*/
951
	function addElement($attrs) {
952
		if (! $this->getPrefix($attrs['type'])) {
953
			$attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
954
		}
955
		$this->elements[ $attrs['name'] ] = $attrs;
956
		$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
957
958
		$this->xdebug("addElement " . $attrs['name']);
959
		$this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
960
	}
961
}
962
963
/**
964
 * Backward compatibility
965
 */
966
class XMLSchema extends nusoap_xmlschema {
967
}
968
969
970
?>