From d52c05bf97d3fd2c2c75a4947c7866af34a365ee Mon Sep 17 00:00:00 2001 From: Dyan Galih Date: Mon, 16 Dec 2019 23:34:18 +0700 Subject: [PATCH] Support for Laravel Model Copy --- src/Tools/Lazy.php | 49 ++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/src/Tools/Lazy.php b/src/Tools/Lazy.php index f820094..535747e 100644 --- a/src/Tools/Lazy.php +++ b/src/Tools/Lazy.php @@ -52,35 +52,31 @@ public static function copy(object $fromClass, object $toClass, int $option = se { try { switch ($option) { - case self::NONE: - foreach (get_object_vars($fromClass) as $key => $value) { - $toClass->$key = $value; - } - break; case self::VALIDATE_ORIGIN: foreach (get_object_vars($fromClass) as $key => $value) { if (self::_validate($fromClass, $fromClass, $key)) { $toClass->$key = $value; } - }; + } break; case self::VALIDATE_DEST: foreach (get_object_vars($toClass) as $key => $value) { - if (property_exists($toClass, $key)) { - if (self::_validate($fromClass, $toClass, $key)) { - $toClass->$key = $fromClass->$key; - } + if (property_exists($toClass, $key) && (self::_validate($fromClass, $toClass, $key))) { + $toClass->$key = $fromClass->$key; } - }; + } break; case self::VALIDATE_BOTH: foreach (get_object_vars($fromClass) as $key => $value) { - if (property_exists($toClass, $key)) { - if (self::_validate($fromClass, $fromClass, $key) && self::_validate($fromClass, $toClass, $key)) { - $toClass->$key = $value; - } + if (property_exists($toClass, $key) && self::_validate($fromClass, $fromClass, $key) && self::_validate($fromClass, $toClass, $key)) { + $toClass->$key = $value; } - }; + } + break; + default: + foreach (get_object_vars($fromClass) as $key => $value) { + $toClass->$key = $value; + } break; } @@ -102,7 +98,6 @@ public static function copy(object $fromClass, object $toClass, int $option = se private static function _validate($fromClass, $toClass, $key) { $propertyClass = self::_getVarValue($toClass, $key); - if (gettype($fromClass->$key) == $propertyClass) { return true; } else { @@ -149,11 +144,23 @@ public static function validate(object $class) */ public static function copyFromArray(array $fromArray, object $toClass, int $option = self::NONE): object { - foreach (get_object_vars($toClass) as $key => $value) { + $model = false; + if (method_exists($toClass, 'getFillable')) { + $varList = $toClass->getFillable(); + $vars = array_flip($varList); + $model = true; + } else { + $vars = get_object_vars($toClass); + } + foreach ($vars as $key => $value) { if ($option == self::NONE) { - self::_validate((object)$fromArray, $toClass, $key); - $toClass->$key = $fromArray[$key]; - } else { + if (!$model) { + self::_validate((object)$fromArray, $toClass, $key); + } + if (isset($fromArray[$key])) { + $toClass->$key = $fromArray[$key]; + } + } elseif ($option == self::AUTOCAST) { $propertyClass = self::_getVarValue($toClass, $key); switch ($propertyClass) {