Skip to content

Commit

Permalink
Support for Laravel Model Copy
Browse files Browse the repository at this point in the history
  • Loading branch information
DyanGalih committed Dec 16, 2019
1 parent 81a1b63 commit d52c05b
Showing 1 changed file with 28 additions and 21 deletions.
49 changes: 28 additions & 21 deletions src/Tools/Lazy.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

}
Expand All @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit d52c05b

Please sign in to comment.