XRL  latest
Simple XML-RPC Library (both client and server)
AbstractDateTime.php
1 <?php
2 /*
3  * This file is part of XRL, a simple XML-RPC Library for PHP.
4  *
5  * Copyright (c) 2012, XRL Team. All rights reserved.
6  * XRL is licensed under the 3-clause BSD License.
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11 
12 namespace fpoirotte\XRL\Types;
13 
21 {
23  public function __toString()
24  {
25  return $this->value->format(static::XMLRPC_FORMAT);
26  }
27 
29  public function set($value)
30  {
31  if (!is_object($value) || !($value instanceof \DateTime)) {
32  throw new \InvalidArgumentException('A date and time value was expected');
33  }
34  $this->value = $value;
35  }
36 
38  public function write(\XMLWriter $writer, \DateTimeZone $timezone, $stringTag)
39  {
40  // PHP has serious issues with timezone handling.
41  // As a workaround, we use format(), specifying a UNIX timestamp
42  // as the format to use, which we then reinject in a new DateTime.
43  $date = new \DateTime('@'.$this->value->format('U'), $timezone);
44  if (strpos(static::XMLRPC_TYPE, '}') !== false) {
45  list($ns, $tagName) = explode('}', static::XMLRPC_TYPE, 2);
46  $ns = (string) substr($ns, 1);
47  return $writer->writeElementNS('ex', $tagName, $ns, $date->format(static::XMLRPC_FORMAT));
48  }
49  return $writer->writeElement(static::XMLRPC_TYPE, $date->format(static::XMLRPC_FORMAT));
50  }
51 
53  protected static function parse($value, \DateTimeZone $timezone = null)
54  {
55  if ($timezone === null) {
56  $timezone = new \DateTimeZone(@date_default_timezone_get());
57  }
58 
59  $result = \DateTime::createFromFormat(static::XMLRPC_FORMAT, $value, $timezone);
60 
61  if (!is_object($result) || strcasecmp($value, $result->format(static::XMLRPC_FORMAT))) {
62  throw new \InvalidArgumentException('Invalid date/time');
63  }
64 
65  return $result;
66  }
67 }
static parse($value,\DateTimeZone $timezone=null)
Abstract class for various "date-time" types.
$value
Current value associated with this object.
write(\XMLWriter $writer,\DateTimeZone $timezone, $stringTag)
A class representing an abstract XML-RPC type.