Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for using a custom Date class #532

Merged
merged 6 commits into from
Apr 23, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion 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/DateTimeLinkedModelInterface.php';
require __DIR__.'/lib/DateTime.php';
require __DIR__.'/lib/Model.php';
require __DIR__.'/lib/Table.php';
Expand Down Expand Up @@ -46,4 +47,4 @@ function activerecord_autoload($class_name)

if (file_exists($file))
require_once $file;
}
}
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 T'));
return $date_class::createFromFormat('Y-m-d H:i:s T', $value->format('Y-m-d H:i:s T'));

return $connection->string_to_datetime($value);
}
Expand Down
32 changes: 31 additions & 1 deletion 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 Expand Up @@ -300,4 +330,4 @@ public function set_cache($url, $options=array())
{
Cache::initialize($url,$options);
}
}
}
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;
}

}
}
19 changes: 17 additions & 2 deletions 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 DateTimeLinkedModelInterface
{
/**
* 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 Expand Up @@ -147,4 +162,4 @@ public function setTimestamp($unixtimestamp)
$this->flag_dirty();
call_user_func_array(array($this,'parent::setTimestamp'),func_get_args());
}
}
}
25 changes: 25 additions & 0 deletions lib/DateTimeLinkedModelInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;

/**
* Interface for Date classes that can be linked to to a model attribute. This is used by
* ActiveRecord\DateTime so it 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 DateTimeLinkedModelInterface
{
/**
* 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);
}
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 T'));
if (is_object($value) && get_class($value) === 'DateTime') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The double instanceof has been introduced just recently, and according to a (not so scientific?) benchmark the instanceof was performing better than get_class with string comparison.

See that conversation here: #531 (comment)

$date_class = Config::instance()->get_date_class();
if ($date_class !== 'DateTime')
$value = $date_class::createFromFormat('Y-m-d H:i:s T', $value->format('Y-m-d H:i:s T'));
}

// 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 DateTimeLinkedModelInterface)
// 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
5 changes: 3 additions & 2 deletions 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 Expand Up @@ -372,4 +373,4 @@ private function to_csv($arr)
fclose($outstream);
return $buffer;
}
}
}
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 @@ -123,5 +123,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
2 changes: 1 addition & 1 deletion test/helpers/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,4 @@
});

error_reporting(E_ALL | E_STRICT);
?>
?>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is unrelated

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, that's been fixed. Let me know when/if you'd like me to squash these commits into one.

Have you considered adding a .editorconfig file? That would prevent these sorts of issues. I can enter another PR with one if that sounds like something you'd like to see.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case editorconfig is unrelated, because this wouldn't have been edited anyway :) Even though if we would add a editorconfig, it would be set to insert a newline, which then will gradually roll out through. So yeah I'm pro-editorconfig.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #534