SerializesModels.php 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Illuminate\Queue;
  3. use ReflectionClass;
  4. use ReflectionProperty;
  5. trait SerializesModels
  6. {
  7. use SerializesAndRestoresModelIdentifiers;
  8. /**
  9. * Prepare the instance for serialization.
  10. *
  11. * @return array
  12. */
  13. public function __sleep()
  14. {
  15. $properties = (new ReflectionClass($this))->getProperties();
  16. foreach ($properties as $property) {
  17. $property->setValue($this, $this->getSerializedPropertyValue(
  18. $this->getPropertyValue($property)
  19. ));
  20. }
  21. return array_values(array_filter(array_map(function ($p) {
  22. return $p->isStatic() ? null : $p->getName();
  23. }, $properties)));
  24. }
  25. /**
  26. * Restore the model after serialization.
  27. *
  28. * @return void
  29. */
  30. public function __wakeup()
  31. {
  32. foreach ((new ReflectionClass($this))->getProperties() as $property) {
  33. if ($property->isStatic()) {
  34. continue;
  35. }
  36. $property->setValue($this, $this->getRestoredPropertyValue(
  37. $this->getPropertyValue($property)
  38. ));
  39. }
  40. }
  41. /**
  42. * Get the property value for the given property.
  43. *
  44. * @param \ReflectionProperty $property
  45. * @return mixed
  46. */
  47. protected function getPropertyValue(ReflectionProperty $property)
  48. {
  49. $property->setAccessible(true);
  50. return $property->getValue($this);
  51. }
  52. }