| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace app\entity;
- use app\utils\ArrayUtil;
- use ReflectionClass;
- class CommonEntity
- {
- /**
- * 将 参数 实例化到 实体
- * @param array $data
- * @return CommonEntity
- */
- public static function newInstance(array $data = []): CommonEntity
- {
- if (empty($data)) {
- return new static();
- } else {
- $instance = new static();
- $data = ArrayUtil::underline2CamelArr($data);
- foreach ($instance as $ik => $iv) {
- if (isset($data[$ik])) {
- $setFunctionName = 'set' . ucfirst($ik);
- $instance->$setFunctionName($data[$ik]);
- }
- }
- return $instance;
- }
- }
- /**
- * 声明公共方法 将实体 转成数组
- * @return array
- */
- public function toArray(): array
- {
- $data = [];
- try {
- $ref = new ReflectionClass(static::class);
- foreach ($ref->getProperties() as $property) {
- $p = $ref->getProperty($property->name);
- $p->setAccessible(true);
- $data[$property->name] = $p->getValue($this);
- }
- } catch (\Exception $e) {
- }
- return $data;
- }
- /**
- * 将实体属性(驼峰命名)转换为下划线命名的数组
- * 用于数据库写入
- * @return array
- */
- public function toUnderlineArray(): array
- {
- $result = [];
- $camelArray = $this->toArray(); // 先获取驼峰格式的数组
- foreach ($camelArray as $key => $value) {
- if (is_null($value)) {
- continue;
- }
- // 将驼峰键名转为下划线格式
- $underlineKey = $this->camelToUnderline($key);
- $result[$underlineKey] = $value;
- }
- return $result;
- }
- /**
- * 驼峰命名转下划线命名
- * @param string $camel
- * @return string
- */
- private function camelToUnderline(string $camel): string
- {
- // 处理连续大写字母(如 "userID" 转 "user_id")
- $camel = preg_replace('/([A-Z]+)([A-Z][a-z])/', '$1_$2', $camel);
- // 将大写字母前添加下划线并转为小写
- return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel));
- }
- }
|