forked from illuminate/queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerializesAndRestoresModelIdentifiers.php
99 lines (88 loc) · 2.82 KB
/
SerializesAndRestoresModelIdentifiers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Illuminate\Queue;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Contracts\Database\ModelIdentifier;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
trait SerializesAndRestoresModelIdentifiers
{
/**
* Get the property value prepared for serialization.
*
* @param mixed $value
* @return mixed
*/
protected function getSerializedPropertyValue($value)
{
if ($value instanceof QueueableCollection) {
return new ModelIdentifier(
$value->getQueueableClass(),
$value->getQueueableIds(),
$value->getQueueableRelations(),
$value->getQueueableConnection()
);
}
if ($value instanceof QueueableEntity) {
return new ModelIdentifier(
get_class($value),
$value->getQueueableId(),
$value->getQueueableRelations(),
$value->getQueueableConnection()
);
}
return $value;
}
/**
* Get the restored property value after deserialization.
*
* @param mixed $value
* @return mixed
*/
protected function getRestoredPropertyValue($value)
{
if (! $value instanceof ModelIdentifier) {
return $value;
}
return is_array($value->id)
? $this->restoreCollection($value)
: $this->restoreModel($value);
}
/**
* Restore a queueable collection instance.
*
* @param \Illuminate\Contracts\Database\ModelIdentifier $value
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function restoreCollection($value)
{
if (! $value->class || count($value->id) === 0) {
return new EloquentCollection;
}
return $this->getQueryForModelRestoration(
(new $value->class)->setConnection($value->connection), $value->id
)->useWritePdo()->get();
}
/**
* Restore the model from the model identifier instance.
*
* @param \Illuminate\Contracts\Database\ModelIdentifier $value
* @return \Illuminate\Database\Eloquent\Model
*/
public function restoreModel($value)
{
return $this->getQueryForModelRestoration(
(new $value->class)->setConnection($value->connection), $value->id
)->useWritePdo()->firstOrFail()->load($value->relations ?? []);
}
/**
* Get the query for model restoration.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param array|int $ids
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function getQueryForModelRestoration($model, $ids)
{
return $model->newQueryForRestoration($ids);
}
}