Skip to content
Permalink
Browse files

Improving perfomance when hydrating date or datetime objects.

Carbon's constructor is quite heavy, using the clone keyword reduces
considerably the amount of time needed to hydrate in big number of
Time objects.
  • Loading branch information...
lorenzo committed Mar 29, 2015
1 parent 448f54f commit 1daa3d589b617b12cb4b4919cf668141d2ce3c50
@@ -53,6 +53,14 @@ class DateTimeType extends \Cake\Database\Type
*/
protected $_localeFormat;
/**
* An instance of the configured dateTimeClass, used to quickly generate
* new instances without calling the constructor.
*
* @var \DateTime
*/
protected $_datetimeInstance;
/**
* {@inheritDoc}
*/
@@ -63,6 +71,8 @@ public function __construct($name = null)
if (!class_exists(static::$dateTimeClass)) {
static::$dateTimeClass = 'DateTime';
}
$this->_datetimeInstance = new static::$dateTimeClass;
}
/**
@@ -88,23 +98,27 @@ public function toDatabase($value, Driver $driver)
*
* @param string $value The value to convert.
* @param Driver $driver The driver instance to convert with.
* @return \Carbon\Carbon
* @return \Cake\I18n\Time|DateTime
*/
public function toPHP($value, Driver $driver)
{
if ($value === null) {
return null;
}
list($value) = explode('.', $value);
$class = static::$dateTimeClass;
return $class::createFromFormat($this->_format, $value);
if (strpos($value, '.') !== false) {
list($value) = explode('.', $value);
}
$instance = clone $this->_datetimeInstance;
return $instance->modify($value);
}
/**
* Convert request data into a datetime object.
*
* @param mixed $value Request data
* @return \Carbon\Carbon
* @return \Cake\I18n\Time|DateTime
*/
public function marshal($value)
{
@@ -53,17 +53,6 @@ public function testToPHP()
$this->assertEquals('04', $result->format('d'));
}
/**
* Tests that passing invalid data will throw an exception
*
* @expectedException \InvalidArgumentException
* @return void
*/
public function testToPHPError()
{
$this->type->toPHP('2001-01-04 10:11:12', $this->driver);
}
/**
* Test converting to database format
*
@@ -53,17 +53,6 @@ public function testToPHP()
$this->assertEquals('15', $result->format('s'));
}
/**
* Tests that passing invalid data will throw an exception
*
* @expectedException \InvalidArgumentException
* @return void
*/
public function testToPHPError()
{
$this->type->toPHP('2001-01-04 10:11:12', $this->driver);
}
/**
* Test converting to database format
*

0 comments on commit 1daa3d5

Please sign in to comment.
You can’t perform that action at this time.