ModelIdentifier.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Illuminate\Contracts\Database;
  3. use Illuminate\Database\Eloquent\Relations\Relation;
  4. class ModelIdentifier
  5. {
  6. /**
  7. * Use the Relation morphMap for a Model's name when serializing.
  8. */
  9. protected static bool $useMorphMap = false;
  10. /**
  11. * The class name of the model.
  12. *
  13. * @var class-string<\Illuminate\Database\Eloquent\Model>|string|null
  14. */
  15. public $class;
  16. /**
  17. * The unique identifier of the model.
  18. *
  19. * This may be either a single ID or an array of IDs.
  20. *
  21. * @var mixed
  22. */
  23. public $id;
  24. /**
  25. * The relationships loaded on the model.
  26. *
  27. * @var array
  28. */
  29. public $relations;
  30. /**
  31. * The connection name of the model.
  32. *
  33. * @var string|null
  34. */
  35. public $connection;
  36. /**
  37. * The class name of the model collection.
  38. *
  39. * @var class-string<\Illuminate\Database\Eloquent\Collection>|null
  40. */
  41. public $collectionClass;
  42. /**
  43. * Create a new model identifier.
  44. *
  45. * @param class-string<\Illuminate\Database\Eloquent\Model>|null $class
  46. * @param mixed $id
  47. * @param array $relations
  48. * @param mixed $connection
  49. */
  50. public function __construct($class, $id, array $relations, $connection)
  51. {
  52. if ($class !== null && self::$useMorphMap) {
  53. $class = Relation::getMorphAlias($class);
  54. }
  55. $this->class = $class;
  56. $this->id = $id;
  57. $this->relations = $relations;
  58. $this->connection = $connection;
  59. }
  60. /**
  61. * Specify the collection class that should be used when serializing / restoring collections.
  62. *
  63. * @param class-string<\Illuminate\Database\Eloquent\Collection> $collectionClass
  64. * @return $this
  65. */
  66. public function useCollectionClass(?string $collectionClass)
  67. {
  68. $this->collectionClass = $collectionClass;
  69. return $this;
  70. }
  71. /**
  72. * Get the fully-qualified class name of the Model.
  73. *
  74. * @return class-string<\Illuminate\Database\Eloquent\Model>|null
  75. */
  76. public function getClass(): ?string
  77. {
  78. if (self::$useMorphMap && $this->class !== null) {
  79. return Relation::getMorphedModel($this->class) ?? $this->class;
  80. }
  81. return $this->class;
  82. }
  83. /**
  84. * Indicate whether to use the relational morph-map when serializing Models.
  85. */
  86. public static function useMorphMap(bool $useMorphMap = true): void
  87. {
  88. static::$useMorphMap = $useMorphMap;
  89. }
  90. }