Skip to content

Commit

Permalink
Add support for using a custom Date class (#532)
Browse files Browse the repository at this point in the history
If your project uses a date library that doesn't extend \DateTime (e.g. Zend_Date), then you
currently have to convert to and from ActiveRecord\DateTime when interacting with models, which is a
pain and error prone. We've had to fix quite a number of bugs due to missing conversions. This
commit removes the need for that by adding support for using a custom date class.

The custom class is set in ActiveRecord\Config, which uses similar logic to the logger methods for
the getter and setter. The ActiveRecord\Config->set_date_class() method checks if the provided class
has "format" and "createFromFormat" methods, which are all that are required.

I changed everything that created new date objects to use "createFromFormat()" instead of the
constructor, because many date libraries don't accept a date string in the constructor. Besides, I
think createFromFormat() is better in general because it's more explicit.

For the "attribute_of" method, I made that an optional feature by introducing an interface that
defines it, which ActiveRecord\Model->assign_attribute() checks for. The reason I made this optional
is because if you use an immutable date class (e.g. PHP's DateTimeImmutable), you don't need to
worry about the dirty flagging, so there's no need to have that method.
  • Loading branch information
MasonM authored and koenpunt committed Apr 23, 2016
1 parent 2ecd1d8 commit d4b980f
Show file tree
Hide file tree
Showing 13 changed files with 180 additions and 15 deletions.
1 change: 1 addition & 0 deletions ActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
require __DIR__.'/lib/Singleton.php';
require __DIR__.'/lib/Config.php';
require __DIR__.'/lib/Utils.php';
require __DIR__.'/lib/DateTimeInterface.php';
require __DIR__.'/lib/DateTime.php';
require __DIR__.'/lib/Model.php';
require __DIR__.'/lib/Table.php';
Expand Down
6 changes: 4 additions & 2 deletions lib/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,13 @@ public function cast($value, $connection)
if (!$value)
return null;

if ($value instanceof DateTime)
$date_class = Config::instance()->get_date_class();

if ($value instanceof $date_class)
return $value;

if ($value instanceof \DateTime)
return new DateTime($value->format('Y-m-d H:i:s'), $value->getTimezone());
return $date_class::createFromFormat('Y-m-d H:i:s T', $value->format('Y-m-d H:i:s T'), $value->getTimezone());

return $connection->string_to_datetime($value);
}
Expand Down
30 changes: 30 additions & 0 deletions lib/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ class Config extends Singleton
*/
private $logger;

/**
* Contains the class name for the Date class to use. Must have a public format() method and a
* public static createFromFormat($format, $time) method
*
* @var string
*/
private $date_class = 'ActiveRecord\\DateTime';

/**
* The format to serialize DateTime values into.
*
Expand Down Expand Up @@ -262,6 +270,28 @@ public function get_logger()
return $this->logger;
}

public function set_date_class($date_class)
{
try {
$klass = Reflections::instance()->add($date_class)->get($date_class);
} catch (\ReflectionException $e) {
throw new ConfigException("Cannot find date class");
}

if (!$klass->hasMethod('format') || !$klass->getMethod('format')->isPublic())
throw new ConfigException('Given date class must have a "public format($format = null)" method');

if (!$klass->hasMethod('createFromFormat') || !$klass->getMethod('createFromFormat')->isPublic())
throw new ConfigException('Given date class must have a "public static createFromFormat($format, $time)" method');

$this->date_class = $date_class;
}

public function get_date_class()
{
return $this->date_class;
}

/**
* @deprecated
*/
Expand Down
7 changes: 4 additions & 3 deletions lib/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ public function datetime_to_string($datetime)
* Converts a string representation of a datetime into a DateTime object.
*
* @param string $string A datetime in the form accepted by date_create()
* @return DateTime
* @return object The date_class set in Config
*/
public function string_to_datetime($string)
{
Expand All @@ -479,7 +479,8 @@ public function string_to_datetime($string)
if ($errors['warning_count'] > 0 || $errors['error_count'] > 0)
return null;

return new DateTime($date->format(static::$datetime_format));
$date_class = Config::instance()->get_date_class();
return $date_class::createFromFormat(static::$datetime_format, $date->format(static::$datetime_format));
}

/**
Expand Down Expand Up @@ -530,4 +531,4 @@ public function accepts_limit_and_order_for_update_and_delete()
return false;
}

}
}
17 changes: 16 additions & 1 deletion lib/DateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
* @package ActiveRecord
* @see http://php.net/manual/en/class.datetime.php
*/
class DateTime extends \DateTime
class DateTime extends \DateTime implements DateTimeInterface
{
/**
* Default format used for format() and __toString()
Expand Down Expand Up @@ -113,6 +113,21 @@ public static function get_format($format=null)
return $format;
}

/**
* This needs to be overriden so it returns an instance of this class instead of PHP's \DateTime.
* See http://php.net/manual/en/datetime.createfromformat.php
*/
public static function createFromFormat($format, $time, $tz = null)
{
$phpDate = $tz ? parent::createFromFormat($format, $time, $tz) : parent::createFromFormat($format, $time);
if (!$phpDate)
return false;
// convert to this class using the timestamp
$ourDate = new static;
$ourDate->setTimestamp($phpDate->getTimestamp());
return $ourDate;
}

public function __toString()
{
return $this->format();
Expand Down
35 changes: 35 additions & 0 deletions lib/DateTimeInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;

/**
* Interface for the ActiveRecord\DateTime class so that ActiveRecord\Model->assign_attribute() will
* know to call attribute_of() on passed values. This is so the DateTime object can flag the model
* as dirty via $model->flag_dirty() when one of its setters is called.
*
* @package ActiveRecord
* @see http://php.net/manual/en/class.datetime.php
*/
interface DateTimeInterface
{
/**
* Indicates this object is an attribute of the specified model, with the given attribute name.
*
* @param Model $model The model this object is an attribute of
* @param string $attribute_name The attribute name
* @return void
*/
public function attribute_of($model, $attribute_name);

/**
* Formats the DateTime to the specified format.
*/
public function format($format=null);

/**
* See http://php.net/manual/en/datetime.createfromformat.php
*/
public static function createFromFormat($format, $time, $tz = null);
}
13 changes: 8 additions & 5 deletions lib/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -460,12 +460,15 @@ public function assign_attribute($name, $value)
}

// convert php's \DateTime to ours
if (!($value instanceof DateTime) && $value instanceof \DateTime)
$value = new DateTime($value->format('Y-m-d H:i:s'), $value->getTimezone());
if ($value instanceof \DateTime) {
$date_class = Config::instance()->get_date_class();
if (!($value instanceof $date_class))
$value = $date_class::createFromFormat('Y-m-d H:i:s T', $value->format('Y-m-d H:i:s T'), $value->getTimezone());
}

// make sure DateTime values know what model they belong to so
// dirty stuff works when calling set methods on the DateTime object
if ($value instanceof DateTime)
if ($value instanceof DateTimeInterface)
// Tell the Date object that it's associated with this model and attribute. This is so it
// has the ability to flag this model as dirty if a field in the Date object changes.
$value->attribute_of($this,$name);

$this->attributes[$name] = $value;
Expand Down
3 changes: 2 additions & 1 deletion lib/Serialization.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,10 @@ final protected function options_to_a($key)
*/
final public function to_a()
{
$date_class = Config::instance()->get_date_class();
foreach ($this->attributes as &$value)
{
if ($value instanceof \DateTime)
if ($value instanceof $date_class)
$value = $value->format(self::$DATETIME_FORMAT);
}
return $this->attributes;
Expand Down
3 changes: 2 additions & 1 deletion lib/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -428,9 +428,10 @@ private function &process_data($hash)
if (!$hash)
return $hash;

$date_class = Config::instance()->get_date_class();
foreach ($hash as $name => &$value)
{
if ($value instanceof \DateTime)
if ($value instanceof $date_class || $value instanceof \DateTime)
{
if (isset($this->columns[$name]) && $this->columns[$name]->type == Column::DATE)
$hash[$name] = $this->conn->date_to_string($value);
Expand Down
13 changes: 11 additions & 2 deletions test/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -526,11 +526,20 @@ public function test_gh245_dirty_attribute_should_not_raise_php_notice_if_not_di
$this->assert_true($event->attribute_is_dirty('title'));
}

public function test_assigning_php_datetime_gets_converted_to_ar_datetime()
public function test_assigning_php_datetime_gets_converted_to_date_class_with_defaults()
{
$author = new Author();
$author->created_at = $now = new \DateTime();
$this->assert_is_a("ActiveRecord\\DateTime",$author->created_at);
$this->assert_is_a("ActiveRecord\\DateTime", $author->created_at);
$this->assert_datetime_equals($now,$author->created_at);
}

public function test_assigning_php_datetime_gets_converted_to_date_class_with_custom_date_class()
{
ActiveRecord\Config::instance()->set_date_class('\\DateTime'); // use PHP built-in DateTime
$author = new Author();
$author->created_at = $now = new \DateTime();
$this->assert_is_a("DateTime", $author->created_at);
$this->assert_datetime_equals($now,$author->created_at);
}

Expand Down
46 changes: 46 additions & 0 deletions test/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ class TestLogger
private function log() {}
}

class TestDateTimeWithoutCreateFromFormat
{
public function format($format=null) {}
}

class TestDateTime
{
public function format($format=null) {}
public static function createFromFormat($format, $time) {}
}

class ConfigTest extends SnakeCase_PHPUnit_Framework_TestCase
{
public function set_up()
Expand Down Expand Up @@ -71,6 +82,41 @@ public function test_set_connections_with_default()
$this->assert_equals('test',$this->config->get_default_connection());
}

public function test_get_date_class_with_default()
{
$this->assert_equals('ActiveRecord\\DateTime', $this->config->get_date_class());
}

/**
* @expectedException ActiveRecord\ConfigException
*/
public function test_set_date_class_when_class_doesnt_exist()
{
$this->config->set_date_class('doesntexist');
}

/**
* @expectedException ActiveRecord\ConfigException
*/
public function test_set_date_class_when_class_doesnt_have_format_or_createfromformat()
{
$this->config->set_date_class('TestLogger');
}

/**
* @expectedException ActiveRecord\ConfigException
*/
public function test_set_date_class_when_class_doesnt_have_createfromformat()
{
$this->config->set_date_class('TestDateTimeWithoutCreateFromFormat');
}

public function test_set_date_class_with_valid_class()
{
$this->config->set_date_class('TestDateTime');
$this->assert_equals('TestDateTime', $this->config->get_date_class());
}

public function test_initialize_closure()
{
$test = $this;
Expand Down
18 changes: 18 additions & 0 deletions test/DateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,5 +129,23 @@ public function test_to_string()
{
$this->assert_equals(date(DateTime::get_format()), "" . $this->date);
}

public function test_create_from_format_error_handling()
{
$d = DateTime::createFromFormat('H:i:s Y-d-m', '!!!');
$this->assert_false($d);
}

public function test_create_from_format_without_tz()
{
$d = DateTime::createFromFormat('H:i:s Y-d-m', '03:04:05 2000-02-01');
$this->assert_equals(new DateTime('2000-01-02 03:04:05'), $d);
}

public function test_create_from_format_with_tz()
{
$d = DateTime::createFromFormat('Y-m-d H:i:s', '2000-02-01 03:04:05', new \DateTimeZone('Etc/GMT-10'));
$this->assert_equals(new DateTime('2000-01-31 17:04:05'), $d);
}
}
?>
3 changes: 3 additions & 0 deletions test/helpers/DatabaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public function set_up($connection_name=null)
$config = ActiveRecord\Config::instance();
$this->original_default_connection = $config->get_default_connection();

$this->original_date_class = $config->get_date_class();

if ($connection_name)
$config->set_default_connection($connection_name);

Expand Down Expand Up @@ -42,6 +44,7 @@ public function set_up($connection_name=null)

public function tear_down()
{
ActiveRecord\Config::instance()->set_date_class($this->original_date_class);
if ($this->original_default_connection)
ActiveRecord\Config::instance()->set_default_connection($this->original_default_connection);
}
Expand Down

0 comments on commit d4b980f

Please sign in to comment.