5 use PhpXmlRpc\Exception\StateErrorException
;
6 use PhpXmlRpc\Exception\TypeErrorException
;
7 use PhpXmlRpc\Exception\ValueErrorException
;
8 use PhpXmlRpc\Traits\CharsetEncoderAware
;
9 use PhpXmlRpc\Traits\DeprecationLogger
;
12 * This class enables the creation of values for XML-RPC, by encapsulating plain php values.
14 * @property Value[]|mixed $me deprecated - public access left in purely for BC. Access via scalarVal()/__construct()
15 * @property int $params $mytype - public access left in purely for BC. Access via kindOf()/__construct()
16 * @property string|null $_php_class deprecated - public access left in purely for BC.
18 class Value
implements \Countable
, \IteratorAggregate
, \ArrayAccess
20 use CharsetEncoderAware
;
21 use DeprecationLogger
;
23 public static $xmlrpcI4 = "i4";
24 public static $xmlrpcI8 = "i8";
25 public static $xmlrpcInt = "int";
26 public static $xmlrpcBoolean = "boolean";
27 public static $xmlrpcDouble = "double";
28 public static $xmlrpcString = "string";
29 public static $xmlrpcDateTime = "dateTime.iso8601";
30 public static $xmlrpcBase64 = "base64";
31 public static $xmlrpcArray = "array";
32 public static $xmlrpcStruct = "struct";
33 public static $xmlrpcValue = "undefined";
34 public static $xmlrpcNull = "null";
36 public static $xmlrpcTypes = array(
43 "dateTime.iso8601" => 1,
50 /** @var Value[]|mixed */
51 protected $me = array();
53 * @var int 0 for undef, 1 for scalar, 2 for array, 3 for struct
55 protected $mytype = 0;
56 /** @var string|null */
57 protected $_php_class = null;
60 * Build an xml-rpc value.
62 * When no value or type is passed in, the value is left uninitialized, and the value can be added later.
64 * @param Value[]|mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
65 * @param string $type any valid xml-rpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
66 * base64, array, struct, null.
67 * If null, 'string' is assumed.
68 * You should refer to http://xmlrpc.com/spec.md for more information on what each of these mean.
70 public function __construct($val = -1, $type = '')
72 // optimization creep - do not call addXX, do it all inline.
73 // downside: booleans will not be coerced anymore
74 if ($val !== -1 ||
$type != '') {
78 $this->me
['string'] = $val;
86 case 'dateTime.iso8601':
90 $this->me
[$type] = $val;
94 $this->me
['array'] = $val;
98 $this->me
['struct'] = $val;
101 $this->getLogger()->error("XML-RPC: " . __METHOD__
. ": not a known type ($type)");
107 * Add a single php value to an xml-rpc value.
109 * If the xml-rpc value is an array, the php value is added as its last element.
110 * If the xml-rpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
111 * Fails if the xml-rpc value is not an array (i.e. a struct or a scalar) and already initialized.
114 * @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
115 * @return int 1 or 0 on failure
117 * @todo arguably, as we have addArray to add elements to an Array value, and addStruct to add elements to a Struct
118 * value, we should not allow this method to add values to an Array. The 'scalar' in the method name refers to
119 * the expected state of the target object, not to the type of $val. Also, this works differently from
120 * addScalar/addStruct in that, when adding an element to an array, it wraps it into a new Value
123 public function addScalar($val, $type = 'string')
126 if (isset(static::$xmlrpcTypes[$type])) {
127 $typeOf = static::$xmlrpcTypes[$type];
131 $this->getLogger()->error("XML-RPC: " . __METHOD__
. ": not a scalar type ($type)");
135 // coerce booleans into correct values
136 /// @todo we should either do it for datetimes, integers, i8 and doubles, too, or just plain remove this check,
137 /// implemented on booleans only...
138 if ($type == static::$xmlrpcBoolean) {
139 if (strcasecmp($val, 'true') == 0 ||
$val == 1 ||
($val == true && strcasecmp($val, 'false'))) {
146 switch ($this->mytype
) {
148 $this->getLogger()->error('XML-RPC: ' . __METHOD__
. ': scalar xmlrpc value can have only one value');
151 $this->getLogger()->error('XML-RPC: ' . __METHOD__
. ': cannot add anonymous scalar to struct xmlrpc value');
154 // we're adding a scalar value to an array here
155 /// @todo should we try avoiding re-wrapping Value objects?
156 $class = get_class($this);
157 $this->me
['array'][] = new $class($val, $type);
161 // a scalar, so set the value and remember we're scalar
162 $this->me
[$type] = $val;
163 $this->mytype
= $typeOf;
170 * Add an array of xml-rpc value objects to an xml-rpc value.
172 * If the xml-rpc value is an array, the elements are appended to the existing ones.
173 * If the xml-rpc value is empty (uninitialized), this method makes it an array value, and sets that value.
176 * @param Value[] $values
177 * @return int 1 or 0 on failure
179 * @todo add some checking for $values to be an array of xml-rpc values?
180 * @todo rename to addToArray?
182 public function addArray($values)
184 if ($this->mytype
== 0) {
185 $this->mytype
= static::$xmlrpcTypes['array'];
186 $this->me
['array'] = $values;
189 } elseif ($this->mytype
== 2) {
190 // we're adding to an array here
191 $this->me
['array'] = array_merge($this->me
['array'], $values);
195 $this->getLogger()->error('XML-RPC: ' . __METHOD__
. ': already initialized as a [' . $this->kindOf() . ']');
201 * Merges an array of named xml-rpc value objects into an xml-rpc value.
203 * If the xml-rpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
204 * If the xml-rpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
207 * @param Value[] $values
208 * @return int 1 or 0 on failure
210 * @todo add some checking for $values to be an array of xml-rpc values?
211 * @todo rename to addToStruct?
213 public function addStruct($values)
215 if ($this->mytype
== 0) {
216 $this->mytype
= static::$xmlrpcTypes['struct'];
217 $this->me
['struct'] = $values;
220 } elseif ($this->mytype
== 3) {
221 // we're adding to a struct here
222 $this->me
['struct'] = array_merge($this->me
['struct'], $values);
226 $this->getLogger()->error('XML-RPC: ' . __METHOD__
. ': already initialized as a [' . $this->kindOf() . ']');
232 * Returns a string describing the base type of the value.
234 * @return string either "struct", "array", "scalar" or "undef"
236 public function kindOf()
238 switch ($this->mytype
) {
252 * Returns the value of a scalar xml-rpc value (base 64 decoding is automatically handled here)
256 public function scalarVal()
258 $b = reset($this->me
);
264 * Returns the type of the xml-rpc value.
266 * @return string For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and
269 public function scalarTyp()
273 if ($a == static::$xmlrpcI4) {
274 $a = static::$xmlrpcInt;
281 * Returns the xml representation of the value. XML prologue not included.
283 * @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed
286 public function serialize($charsetEncoding = '')
288 $val = reset($this->me
);
289 $typ = key($this->me
);
291 return '<value>' . $this->serializeData($typ, $val, $charsetEncoding) . "</value>\n";
296 * @param Value[]|mixed $val
297 * @param string $charsetEncoding
300 * @deprecated this should be folded back into serialize()
302 protected function serializeData($typ, $val, $charsetEncoding = '')
304 $this->logDeprecationUnlessCalledBy('serialize');
306 if (!isset(static::$xmlrpcTypes[$typ])) {
310 switch (static::$xmlrpcTypes[$typ]) {
313 case static::$xmlrpcBase64:
314 $rs = "<{$typ}>" . base64_encode($val) . "</{$typ}>";
316 case static::$xmlrpcBoolean:
317 $rs = "<{$typ}>" . ($val ?
'1' : '0') . "</{$typ}>";
319 case static::$xmlrpcString:
320 // Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
321 $rs = "<{$typ}>" . $this->getCharsetEncoder()->encodeEntities($val, PhpXmlRpc
::$xmlrpc_internalencoding, $charsetEncoding) . "</{$typ}>";
323 case static::$xmlrpcInt:
324 case static::$xmlrpcI4:
325 case static::$xmlrpcI8:
326 $rs = "<{$typ}>" . (int)$val . "</{$typ}>";
328 case static::$xmlrpcDouble:
329 // avoid using standard conversion of float to string because it is locale-dependent,
330 // and also because the xml-rpc spec forbids exponential notation.
331 // sprintf('%F') could be most likely ok, but it fails e.g. on 2e-14.
332 // The code below tries its best at keeping max precision while avoiding exp notation,
333 // but there is of course no limit in the number of decimal places to be used...
334 $rs = "<{$typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, PhpXmlRpc
::$xmlpc_double_precision, '.', '')) . "</{$typ}>";
336 case static::$xmlrpcDateTime:
337 if (is_string($val)) {
338 $rs = "<{$typ}>{$val}</{$typ}>";
339 // DateTimeInterface is not present in php 5.4...
340 } elseif (is_a($val, 'DateTimeInterface') ||
is_a($val, 'DateTime')) {
341 $rs = "<{$typ}>" . $val->format('Ymd\TH:i:s') . "</{$typ}>";
342 } elseif (is_int($val)) {
343 $rs = "<{$typ}>" . date('Ymd\TH:i:s', $val) . "</{$typ}>";
345 // not really a good idea here: but what should we output anyway? left for backward compat...
346 $rs = "<{$typ}>{$val}</{$typ}>";
349 case static::$xmlrpcNull:
350 if (PhpXmlRpc
::$xmlrpc_null_apache_encoding) {
357 // no standard type value should arrive here, but provide a possibility
358 // for xml-rpc values of unknown type...
359 $rs = "<{$typ}>{$val}</{$typ}>";
364 if ($this->_php_class
) {
365 $rs = '<struct php_class="' . $this->_php_class
. "\">\n";
369 $charsetEncoder = $this->getCharsetEncoder();
370 /** @var Value $val2 */
371 foreach ($val as $key2 => $val2) {
372 $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc
::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
373 $rs .= $val2->serialize($charsetEncoding);
374 $rs .= "</member>\n";
380 $rs = "<array>\n<data>\n";
381 /** @var Value $element */
382 foreach ($val as $element) {
383 $rs .= $element->serialize($charsetEncoding);
385 $rs .= "</data>\n</array>";
388 /// @todo log a warning?
397 * Returns the number of members in an xml-rpc value:
398 * - 0 for uninitialized values
399 * - 1 for scalar values
400 * - the number of elements for struct and array values
404 #[\ReturnTypeWillChange]
405 public function count()
407 switch ($this->mytype
) {
409 return count($this->me
['struct']);
411 return count($this->me
['array']);
420 * Implements the IteratorAggregate interface
421 * @internal required to be public to implement an Interface
423 * @return \ArrayIterator
425 #[\ReturnTypeWillChange]
426 public function getIterator()
428 switch ($this->mytype
) {
430 return new \
ArrayIterator($this->me
['struct']);
432 return new \
ArrayIterator($this->me
['array']);
434 return new \
ArrayIterator($this->me
);
436 return new \
ArrayIterator();
441 * @internal required to be public to implement an Interface
443 * @param mixed $offset
444 * @param mixed $value
447 * @throws ValueErrorException|TypeErrorException
449 #[\ReturnTypeWillChange]
450 public function offsetSet($offset, $value)
452 switch ($this->mytype
) {
454 if (!($value instanceof Value
)) {
455 throw new TypeErrorException('It is only possible to add Value objects to an XML-RPC Struct');
457 if (is_null($offset)) {
458 // disallow struct members with empty names
459 throw new ValueErrorException('It is not possible to add anonymous members to an XML-RPC Struct');
461 $this->me
['struct'][$offset] = $value;
465 if (!($value instanceof Value
)) {
466 throw new TypeErrorException('It is only possible to add Value objects to an XML-RPC Array');
468 if (is_null($offset)) {
469 $this->me
['array'][] = $value;
471 // nb: we are not checking that $offset is above the existing array range...
472 $this->me
['array'][$offset] = $value;
476 /// @todo: should we handle usage of i4 to retrieve int (in both set/unset/isset)? After all we consider
477 /// 'int' to be the preferred form, as evidenced in scalarTyp()
479 $type = key($this->me
);
480 if ($type != $offset && ($type != 'i4' ||
$offset != 'int')) {
481 throw new ValueErrorException('...');
483 $this->me
[$type] = $value;
486 // it would be nice to allow empty values to be turned into non-empty ones this way, but we miss info to do so
487 throw new ValueErrorException("XML-RPC Value is of type 'undef' and its value can not be set using array index");
492 * @internal required to be public to implement an Interface
494 * @param mixed $offset
497 #[\ReturnTypeWillChange]
498 public function offsetExists($offset)
500 switch ($this->mytype
) {
502 return isset($this->me
['struct'][$offset]);
504 return isset($this->me
['array'][$offset]);
507 if ($offset == 'i4') {
508 // to be consistent with set and unset, we disallow usage of i4 to check for int
510 return $offset == key($this->me
);
512 return $offset == $this->scalarTyp();
520 * @internal required to be public to implement an Interface
522 * @param mixed $offset
525 * @throws ValueErrorException|StateErrorException
527 #[\ReturnTypeWillChange]
528 public function offsetUnset($offset)
530 switch ($this->mytype
) {
532 unset($this->me
['struct'][$offset]);
535 unset($this->me
['array'][$offset]);
538 // can not remove value from a scalar
539 /// @todo feature creep - allow this to move back the value to 'undef' state?
540 throw new StateErrorException("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
542 throw new StateErrorException("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
547 * @internal required to be public to implement an Interface
549 * @param mixed $offset
550 * @return mixed|Value|null
551 * @throws StateErrorException
553 #[\ReturnTypeWillChange]
554 public function offsetGet($offset)
556 switch ($this->mytype
) {
558 return isset($this->me
['struct'][$offset]) ?
$this->me
['struct'][$offset] : null;
560 return isset($this->me
['array'][$offset]) ?
$this->me
['array'][$offset] : null;
562 /// @todo what to return on bad type: null or exception?
563 $value = reset($this->me
);
564 $type = key($this->me
);
565 return $type == $offset ?
$value : (($type == 'i4' && $offset == 'int') ?
$value : null);
567 // return null or exception?
568 throw new StateErrorException("XML-RPC Value is of type 'undef' and can not be accessed using array index");
575 * Checks whether a struct member with a given name is present.
577 * Works only on xml-rpc values of type struct.
579 * @param string $key the name of the struct member to be looked up
582 * @deprecated use array access, e.g. isset($val[$key])
584 public function structMemExists($key)
586 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
588 return array_key_exists($key, $this->me
['struct']);
592 * Returns the value of a given struct member (an xml-rpc value object in itself).
593 * Will raise a php warning if struct member of given name does not exist.
595 * @param string $key the name of the struct member to be looked up
598 * @deprecated use array access, e.g. $val[$key]
600 public function structMem($key)
602 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
604 return $this->me
['struct'][$key];
608 * Reset internal pointer for xml-rpc values of type struct.
611 * @deprecated iterate directly over the object using foreach instead
613 public function structReset()
615 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
617 reset($this->me
['struct']);
621 * Return next member element for xml-rpc values of type struct.
623 * @return array having the same format as PHP's `each` method
625 * @deprecated iterate directly over the object using foreach instead
627 public function structEach()
629 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
631 $key = key($this->me
['struct']);
632 $value = current($this->me
['struct']);
633 next($this->me
['struct']);
634 return array(1 => $value, 'value' => $value, 0 => $key, 'key' => $key);
638 * Returns the n-th member of an xml-rpc value of array type.
640 * @param integer $key the index of the value to be retrieved (zero based)
644 * @deprecated use array access, e.g. $val[$key]
646 public function arrayMem($key)
648 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
650 return $this->me
['array'][$key];
654 * Returns the number of members in an xml-rpc value of array type.
658 * @deprecated use count() instead
660 public function arraySize()
662 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
664 return count($this->me
['array']);
668 * Returns the number of members in an xml-rpc value of struct type.
672 * @deprecated use count() instead
674 public function structSize()
676 $this->logDeprecation('Method ' . __METHOD__
. ' is deprecated');
678 return count($this->me
['struct']);
681 // we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
682 public function &__get($name)
688 $this->logDeprecation('Getting property Value::' . $name . ' is deprecated');
691 /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
692 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 1);
693 trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING
);
699 public function __set($name, $value)
705 $this->logDeprecation('Setting property Value::' . $name . ' is deprecated');
706 $this->$name = $value;
709 /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
710 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 1);
711 trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING
);
715 public function __isset($name)
721 $this->logDeprecation('Checking property Value::' . $name . ' is deprecated');
722 return isset($this->$name);
728 public function __unset($name)
734 $this->logDeprecation('Unsetting property Value::' . $name . ' is deprecated');
738 /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
739 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 1);
740 trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING
);