2
0

SerializerToDb.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace PhpDevCommunity\PaperORM\Serializer;
  3. use PhpDevCommunity\PaperORM\Entity\EntityInterface;
  4. use PhpDevCommunity\PaperORM\Mapper\ColumnMapper;
  5. use PhpDevCommunity\PaperORM\Mapping\Column\JoinColumn;
  6. final class SerializerToDb
  7. {
  8. /**
  9. * @var object
  10. */
  11. private object $entity;
  12. public function __construct(object $entity)
  13. {
  14. $this->entity = $entity;
  15. }
  16. public function serialize(array $columnsToSerialize = [] ): array
  17. {
  18. $entity = $this->entity;
  19. $columns = ColumnMapper::getColumns(get_class($entity));
  20. $reflection = new \ReflectionClass($entity);
  21. $dbData = [];
  22. foreach ($columns as $column) {
  23. if (!empty($columnsToSerialize) && !in_array($column->getProperty(), $columnsToSerialize)) {
  24. continue;
  25. }
  26. try {
  27. if (false !== ($reflectionParent = $reflection->getParentClass()) && $reflectionParent->hasProperty($column->getProperty())) {
  28. $property = $reflectionParent->getProperty($column->getProperty());
  29. }else {
  30. $property = $reflection->getProperty($column->getProperty());
  31. }
  32. } catch (\ReflectionException $e) {
  33. throw new \InvalidArgumentException("Property {$column->getProperty()} not found in class " . get_class($entity));
  34. }
  35. $property->setAccessible(true);
  36. $key = sprintf('`%s`', $column->getName());
  37. $value = $property->getValue($entity);
  38. if ($column instanceof JoinColumn) {
  39. if (is_object($value) && ($value instanceof EntityInterface || method_exists($value, 'getPrimaryKeyValue'))) {
  40. $value = $value->getPrimaryKeyValue();
  41. }
  42. }
  43. $dbData[$key] = $column->convertToDatabase($value) ;
  44. }
  45. return $dbData;
  46. }
  47. }