BaseBeanV1.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Tool\ShanTaoTool\Bean;
  3. class BaseBeanV1
  4. {
  5. /**
  6. * 构造函数
  7. * @param $data 数据集
  8. */
  9. public function __construct($data = [])
  10. {
  11. if (!empty($data)) {
  12. foreach ($data as $key => $val) {
  13. if (property_exists($this, $key) && !is_null($val)) {
  14. $setMethodName = $this->getSetMethodName($key);
  15. if (method_exists($this, $setMethodName)) {
  16. $this->$setMethodName($val);
  17. } else {
  18. $this->$key = $val;
  19. }
  20. }
  21. }
  22. }
  23. }
  24. /**
  25. * 获取set方法名称
  26. * @param $key
  27. * @return string
  28. */
  29. protected function getSetMethodName($key)
  30. {
  31. return "set" . ucfirst($this->conversionToTuoFeng($key));
  32. }
  33. /**
  34. * 获取get方法名称
  35. * @param $key
  36. * @return string
  37. */
  38. protected function getGetMethodName($key)
  39. {
  40. return "get" . ucfirst($this->conversionToTuoFeng($key));
  41. }
  42. public function toArray()
  43. {
  44. $data = [];
  45. //获取所有属性
  46. $reflectInstance = new \ReflectionClass(get_class($this));
  47. $properties = $reflectInstance->getProperties();
  48. foreach ($properties as $property){
  49. $key = $property->getName();
  50. $getMethodName = $this->getGetMethodName($key);
  51. $data[$key] = method_exists($this, $getMethodName) ? $this->$getMethodName() : $this->$key;
  52. if(is_null($data[$key])){
  53. unset($data[$key]);
  54. }
  55. }
  56. return $data;
  57. }
  58. /**
  59. * 下划线转驼峰
  60. * @param $key
  61. */
  62. public function conversionToTuoFeng($key)
  63. {
  64. $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
  65. return strtoupper($matches[2]);
  66. }, $key);
  67. return $str;
  68. }
  69. /**
  70. * 驼峰转下划线
  71. * @param $key
  72. * @return string
  73. */
  74. public function conversionToXiaHuaXian($key)
  75. {
  76. $str = str_replace("_", "", $key);
  77. $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
  78. return '_' . strtolower($matches[0]);
  79. }, $str);
  80. return ltrim($str, "_");
  81. }
  82. }