getProperties(); foreach ($properties as $property) { $name = LuStringUtils::stringSnakeToCamelCase($property->getName(), true); $property->setAccessible(true); $value = $property->getValue($this); if (is_array($value)) { $array = []; foreach ($value as $key => $v) { if ($v instanceof LuDbo) { $array[$key] = $v->jsonSerialize(); } else { $array[$key] = $v; } } $json[$name] = $array; } else { $value = $property->getValue($this); if ($value instanceof LuDbo) { $json[$name] = $value->jsonSerialize(); } else { $json[$name] = $value; } } } return $json; } /** * @param $newClass LuDbo * @return LuDbo */ public function castAs($newClass) { $obj = new $newClass; foreach (get_object_vars($this) as $key => $name) { $obj->$key = $name; } return $obj; } public static function deserializeValue($value, $type) { if (is_null($value)) { return null; } if (is_null($type) || $type == "") { $type = "mixed"; } else if ($type == "array") { $type = "mixed[]"; } if ($type == "string") { $dbo = LuStringDbo::jsonDeserialize($value); return $dbo->getString(); } else if ($type == "int") { $dbo = LuIntDbo::jsonDeserialize($value); return $dbo->getInt(); } else if ($type == "float") { $dbo = LuFloatDbo::jsonDeserialize($value); return $dbo->getFloat(); } else if ($type == "bool") { $dbo = LuBoolDbo::jsonDeserialize($value); return $dbo->getBool(); } else if ($type == "mixed") { return $value; } else if (LuStringUtils::endsWith($type, "[]")) { if (!is_array($value)) { throw new LuDboDeserializeException("Invalid array value"); } $type = substr($type, 0, strlen($type) - 2); $data = []; foreach ($value as $v) { $data[] = self::deserializeValue($v, $type); } return $data; } else { return call_user_func_array(array($type, "jsonDeserialize"), array($value)); } } /** * Deserialize from a JSON object * @param $json mixed The JSON data to deserialize * @return LuDbo * @throws LuDboConstraintException * @throws LuDboDeserializeException */ public static function jsonDeserialize($json) { if (is_null($json)) { return null; } $dbo = new static(); $reflect = new \ReflectionClass(static::class); $properties = $reflect->getProperties(); foreach ($properties as $property) { $parser = new LuPropertyDocParser($property->getDocComment()); $name = LuStringUtils::stringSnakeToCamelCase($property->getName(), true); $doc = $parser->parse(); $type = is_null($doc) ? null : $doc->getType(); $value = null; if (isset($json[$name])) { $value = static::deserializeValue($json[$name], $type); } if ($doc->isNotNull() && is_null($value)) { throw new LuDboConstraintException("Field '" . $name . "' can not be null"); } if (!is_null($doc) && !is_null($value)) { foreach ($doc->getConstraints() as $constraint) { call_user_func_array([$value, $constraint->getMethod()], $constraint->getArguments()); } } $property->setAccessible(true); $property->setValue($dbo, $value); } return $dbo; } /** * Generate a sample JSON object for the DBO * @return array */ public static function generateSample() { return null; } }