PopBaseJsonEntity.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. namespace Com\Pdd\Pop\Sdk;
  3. use \JsonSerializable;
  4. use \ReflectionClass;
  5. use Com\Pdd\Pop\Sdk\Common\JsonUtil;
  6. /**
  7. * 序列化基础类
  8. */
  9. class PopBaseJsonEntity implements JsonSerializable
  10. {
  11. /**
  12. * @param $doc属性字段的注解
  13. * @return 然后数组,$arr[0]是类型, $arr[1]是映射的名称
  14. */
  15. protected function parseDoc($doc)
  16. {
  17. return JsonUtil::parseDoc($doc);
  18. }
  19. public function jsonSerialize() {
  20. $data = [];
  21. $class = new ReflectionClass($this);
  22. $properties = $class->getProperties();
  23. foreach ($properties as $prop){
  24. $doc = $this->parseDoc($prop->getDocComment());
  25. $prop->setAccessible(true);
  26. if ($doc != null && count($doc) == 2){
  27. $value = $prop->getValue($this);
  28. if(is_object($value)){
  29. $value = json_decode(json_encode($value),true);
  30. }
  31. if(!is_null($value)){
  32. $data[$doc[1]] = $value;
  33. }
  34. }
  35. }
  36. return empty($data)?null:$data;
  37. }
  38. }