Bläddra i källkod

introduce VariableHelper::cast

alexlcdee 8 år sedan
förälder
incheckning
8bf00bce9f
2 ändrade filer med 28 tillägg och 8 borttagningar
  1. 7 8
      src/components/ActiveRecord.php
  2. 21 0
      src/helpers/VariableHelper.php

+ 7 - 8
src/components/ActiveRecord.php

@@ -2,6 +2,8 @@
 
 namespace yiins\components;
 
+use yiins\helpers\VariableHelper;
+
 /**
  * Class ActiveRecord
  * @package base\components
@@ -19,6 +21,7 @@ class ActiveRecord extends \CActiveRecord
         if (!$className) {
             $className = static::class;
         }
+
         return parent::model($className);
     }
 
@@ -160,15 +163,9 @@ class ActiveRecord extends \CActiveRecord
      */
     public function castAs($destination)
     {
-        if (get_class($this) === $destination) {
-            return $this;
-        }
-        if (!is_subclass_of($destination, get_class($this)) && !is_subclass_of(get_class($this), $destination)) {
-            return false;
-        }
-        $result = unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($destination) . ':"' . $destination . '"',
-            serialize($this)));
+        $result = VariableHelper::cast($this, $destination);
         $result->refresh();
+
         return $result;
     }
 
@@ -193,6 +190,7 @@ class ActiveRecord extends \CActiveRecord
                 }
             }
         }
+
         return $attributes;
     }
 
@@ -201,6 +199,7 @@ class ActiveRecord extends \CActiveRecord
         if (($tableName = static::getTableName()) === null) {
             return parent::tableName();
         }
+
         return $tableName;
     }
 

+ 21 - 0
src/helpers/VariableHelper.php

@@ -35,4 +35,25 @@ class VariableHelper
             throw new InvalidConfigException($message ?? 'Required param not found.');
         }
     }
+
+    public static function cast($object, $class)
+    {
+        $objectClass = get_class($object);
+        if ($objectClass === $class) {
+            return $object;
+        }
+        if (!is_subclass_of($class, $objectClass) && !is_subclass_of($objectClass, $class)) {
+            throw new \InvalidArgumentException(sprintf('Object of class %s is incompatible with class %s',
+                $objectClass, $class));
+        }
+        $result = unserialize(
+            preg_replace(
+                '/^O:\d+:"[^"]++"/',
+                'O:' . strlen($class) . ':"' . $class . '"',
+                serialize($object)
+            )
+        );
+
+        return $result;
+    }
 }