From 551e4a740988522cbf007197b1099da1a59d34ae Mon Sep 17 00:00:00 2001 From: Ronan Chilvers Date: Thu, 10 Oct 2019 21:34:08 +0100 Subject: [PATCH] Add clone handling --- src/Features/HasTimestamps.php | 11 +++++++++++ src/Model.php | 30 +++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/Features/HasTimestamps.php b/src/Features/HasTimestamps.php index 5b46a69..9c05a5a 100644 --- a/src/Features/HasTimestamps.php +++ b/src/Features/HasTimestamps.php @@ -64,4 +64,15 @@ protected function updateTimestamps() $this->setAttribute(static::$updated, $now); } } + + /** + * Clear the timestamps on this model + * + * @author Ronan Chilvers + */ + protected function clearTimestamps() + { + $this->setAttribute(static::$created, null); + $this->setAttribute(static::$updated, null); + } } diff --git a/src/Model.php b/src/Model.php index 650e797..5e55798 100644 --- a/src/Model.php +++ b/src/Model.php @@ -150,10 +150,38 @@ public static function qualify($string) */ public function __construct() { - $this->bootHasTimestamps(); + if ($this->useTimestamps()) { + $this->bootHasTimestamps(); + } $this->boot(); } + /** + * Magic clone method to ensure that cloned models are new + * + * @author Ronan Chilvers + */ + public function __clone() + { + $primaryKey = static::primaryKey(); + if (isset($this->data[$primaryKey])) { + unset($this->data[$primaryKey]); + } + if ($this->useTimestamps()) { + $this->clearTimestamps(); + } + $this->clone(); + } + + /** + * Clone function designed to be overriden by subclasses + * + * + * @author Ronan Chilvers + */ + protected function clone() + {} + /** * Boot the model *