5 use PhpXmlRpc\Helper\Charset;
7 class Value implements \Countable, \IteratorAggregate, \ArrayAccess
9 public static $xmlrpcI4 = "i4";
10 public static $xmlrpcInt = "int";
11 public static $xmlrpcBoolean = "boolean";
12 public static $xmlrpcDouble = "double";
13 public static $xmlrpcString = "string";
14 public static $xmlrpcDateTime = "dateTime.iso8601";
15 public static $xmlrpcBase64 = "base64";
16 public static $xmlrpcArray = "array";
17 public static $xmlrpcStruct = "struct";
18 public static $xmlrpcValue = "undefined";
19 public static $xmlrpcNull = "null";
21 public static $xmlrpcTypes = array(
27 "dateTime.iso8601" => 1,
34 /// @todo: do these need to be public?
37 public $_php_class = null;
40 * Build an xmlrpc value.
41 * When no value or type is passed in, the value is left uninitialized, and the value can be added later
44 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
46 public function __construct($val = -1, $type = '')
48 // optimization creep - do not call addXX, do it all inline.
49 // downside: booleans will not be coerced anymore
50 if ($val !== -1 || $type != '') {
54 $this->me['string'] = $val;
61 case 'dateTime.iso8601':
65 $this->me[$type] = $val;
69 $this->me['array'] = $val;
73 $this->me['struct'] = $val;
76 error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
82 * Add a single php value to an (uninitialized) xmlrpc value.
87 * @return int 1 or 0 on failure
89 public function addScalar($val, $type = 'string')
92 if (isset(static::$xmlrpcTypes[$type])) {
93 $typeOf = static::$xmlrpcTypes[$type];
97 error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
101 // coerce booleans into correct values
102 // NB: we should either do it for datetimes, integers and doubles, too,
103 // or just plain remove this check, implemented on booleans only...
104 if ($type == static::$xmlrpcBoolean) {
105 if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
112 switch ($this->mytype) {
114 error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
117 error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
120 // we're adding a scalar value to an array here
121 $this->me['array'][] = new Value($val, $type);
125 // a scalar, so set the value and remember we're scalar
126 $this->me[$type] = $val;
127 $this->mytype = $typeOf;
134 * Add an array of xmlrpc values objects to an xmlrpc value.
136 * @param Value[] $values
138 * @return int 1 or 0 on failure
140 * @todo add some checking for $values to be an array of xmlrpc values?
142 public function addArray($values)
144 if ($this->mytype == 0) {
145 $this->mytype = static::$xmlrpcTypes['array'];
146 $this->me['array'] = $values;
149 } elseif ($this->mytype == 2) {
150 // we're adding to an array here
151 $this->me['array'] = array_merge($this->me['array'], $values);
155 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
161 * Add an array of named xmlrpc value objects to an xmlrpc value.
163 * @param Value[] $values
165 * @return int 1 or 0 on failure
167 * @todo add some checking for $values to be an array?
169 public function addStruct($values)
171 if ($this->mytype == 0) {
172 $this->mytype = static::$xmlrpcTypes['struct'];
173 $this->me['struct'] = $values;
176 } elseif ($this->mytype == 3) {
177 // we're adding to a struct here
178 $this->me['struct'] = array_merge($this->me['struct'], $values);
182 error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
188 * Returns a string containing "struct", "array", "scalar" or "undef" describing the base type of the value.
192 public function kindOf()
194 switch ($this->mytype) {
209 protected function serializedata($typ, $val, $charsetEncoding = '')
213 if (!isset(static::$xmlrpcTypes[$typ])) {
217 switch (static::$xmlrpcTypes[$typ]) {
220 case static::$xmlrpcBase64:
221 $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
223 case static::$xmlrpcBoolean:
224 $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
226 case static::$xmlrpcString:
227 // G. Giunta 2005/2/13: do NOT use htmlentities, since
228 // it will produce named html entities, which are invalid xml
229 $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
231 case static::$xmlrpcInt:
232 case static::$xmlrpcI4:
233 $rs .= "<${typ}>" . (int)$val . "</${typ}>";
235 case static::$xmlrpcDouble:
236 // avoid using standard conversion of float to string because it is locale-dependent,
237 // and also because the xmlrpc spec forbids exponential notation.
238 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
239 // The code below tries its best at keeping max precision while avoiding exp notation,
240 // but there is of course no limit in the number of decimal places to be used...
241 $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
243 case static::$xmlrpcDateTime:
244 if (is_string($val)) {
245 $rs .= "<${typ}>${val}</${typ}>";
246 } elseif (is_a($val, 'DateTime')) {
247 $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
248 } elseif (is_int($val)) {
249 $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
251 // not really a good idea here: but what shall we output anyway? left for backward compat...
252 $rs .= "<${typ}>${val}</${typ}>";
255 case static::$xmlrpcNull:
256 if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
263 // no standard type value should arrive here, but provide a possibility
264 // for xmlrpc values of unknown type...
265 $rs .= "<${typ}>${val}</${typ}>";
270 if ($this->_php_class) {
271 $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
275 $charsetEncoder = Charset::instance();
276 foreach ($val as $key2 => $val2) {
277 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
278 //$rs.=$this->serializeval($val2);
279 $rs .= $val2->serialize($charsetEncoding);
280 $rs .= "</member>\n";
286 $rs .= "<array>\n<data>\n";
287 foreach ($val as $element) {
288 //$rs.=$this->serializeval($val[$i]);
289 $rs .= $element->serialize($charsetEncoding);
291 $rs .= "</data>\n</array>";
301 * Returns xml representation of the value. XML prologue not included.
303 * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
307 public function serialize($charsetEncoding = '')
309 // add check? slower, but helps to avoid recursion in serializing broken xmlrpc values...
310 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
313 list($typ, $val) = each($this->me);
315 return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
320 * Checks whether a struct member with a given name is present.
321 * Works only on xmlrpc values of type struct.
323 * @param string $key the name of the struct member to be looked up
327 * @deprecated use array access, e.g. isset($val[$key])
329 public function structmemexists($key)
331 return array_key_exists($key, $this->me['struct']);
335 * Returns the value of a given struct member (an xmlrpc value object in itself).
336 * Will raise a php warning if struct member of given name does not exist.
338 * @param string $key the name of the struct member to be looked up
342 * @deprecated use array access, e.g. $val[$key]
344 public function structmem($key)
346 return $this->me['struct'][$key];
350 * Reset internal pointer for xmlrpc values of type struct.
351 * @deprecated iterate directly over the object using foreach instead
353 public function structreset()
355 reset($this->me['struct']);
359 * Return next member element for xmlrpc values of type struct.
363 * @deprecated iterate directly over the object using foreach instead
365 public function structeach()
367 return each($this->me['struct']);
371 * Returns the value of a scalar xmlrpc value.
375 public function scalarval()
378 list(, $b) = each($this->me);
384 * Returns the type of the xmlrpc value.
385 * For integers, 'int' is always returned in place of 'i4'.
389 public function scalartyp()
392 list($a,) = each($this->me);
393 if ($a == static::$xmlrpcI4) {
394 $a = static::$xmlrpcInt;
401 * Returns the m-th member of an xmlrpc value of struct type.
403 * @param integer $key the index of the value to be retrieved (zero based)
407 * @deprecated use array access, e.g. $val[$key]
409 public function arraymem($key)
411 return $this->me['array'][$key];
415 * Returns the number of members in an xmlrpc value of array type.
419 * @deprecated use count() instead
421 public function arraysize()
423 return count($this->me['array']);
427 * Returns the number of members in an xmlrpc value of struct type.
431 * @deprecated use count() instead
433 public function structsize()
435 return count($this->me['struct']);
439 * Returns the number of members in an xmlrpc value:
440 * - 0 for uninitialized values
442 * - the number of elements for structs and arrays
446 public function count()
448 switch ($this->mytype) {
450 return count($this->me['struct']);
452 return count($this->me['array']);
461 * Implements the IteratorAggregate interface
463 * @return ArrayIterator
465 public function getIterator() {
466 switch ($this->mytype) {
468 return new \ArrayIterator($this->me['struct']);
470 return new \ArrayIterator($this->me['array']);
472 return new \ArrayIterator($this->me);
474 return new \ArrayIterator();
476 return new \ArrayIterator();
480 public function offsetSet($offset, $value) {
482 switch ($this->mytype) {
484 if (!($value instanceof \PhpXmlRpc\Value)) {
485 throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
487 if (is_null($offset)) {
488 // disallow struct members with empty names
489 throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
491 $this->me['struct'][$offset] = $value;
495 if (!($value instanceof \PhpXmlRpc\Value)) {
496 throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
498 if (is_null($offset)) {
499 $this->me['array'][] = $value;
501 // nb: we are not checking that $offset is above the existing array range...
502 $this->me['array'][$offset] = $value;
506 // todo: handle i4 vs int
508 list($type,) = each($this->me);
509 if ($type != $offset) {
510 throw new \Exception('');
512 $this->me[$type] = $value;
515 // it would be nice to allow empty values to be be turned into non-empty ones this way, but we miss info to do so
516 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
520 public function offsetExists($offset) {
521 switch ($this->mytype) {
523 return isset($this->me['struct'][$offset]);
525 return isset($this->me['array'][$offset]);
527 // todo: handle i4 vs int
528 return $offset == $this->scalartyp();
534 public function offsetUnset($offset) {
535 switch ($this->mytype) {
537 unset($this->me['struct'][$offset]);
540 unset($this->me['array'][$offset]);
543 // can not remove value from a scalar
544 throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
546 throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
550 public function offsetGet($offset) {
551 switch ($this->mytype) {
553 return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
555 return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
557 // on bad type: null or exception?
559 list($type, $value) = each($this->me);
560 return $type == $offset ? $value : null;
562 // return null or exception?
563 throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");