-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathUserResourceView.php
More file actions
71 lines (58 loc) · 1.91 KB
/
UserResourceView.php
File metadata and controls
71 lines (58 loc) · 1.91 KB
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
<?php
namespace ProcessMaker\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Collection;
use ProcessMaker\Models\ProcessMakerModel;
class UserResourceView extends ProcessMakerModel
{
use HasFactory;
protected $fillable = [
'user_id',
'viewable_id',
'viewable_type',
];
public function user()
{
return $this->belongsTo(User::class);
}
public static function setViewed($user, $viewable)
{
return self::firstOrCreate([
'user_id' => $user->id,
'viewable_type' => get_class($viewable),
'viewable_id' => $viewable->id,
]);
}
public static function addToResourceCollection(Collection &$collection, User|null $user)
{
if (!$user) {
return $collection;
}
if ($collection->count() === 0) {
return $collection;
}
$class = null;
$firstItem = $collection->first();
if (property_exists($firstItem, 'resource')) {
$firstResource = $firstItem->resource;
if ($firstResource instanceof ProcessRequest) {
$class = ProcessRequest::class;
} elseif ($firstResource instanceof ProcessRequestToken) {
$class = ProcessRequestToken::class;
}
}
if (!$class) {
return $collection;
}
$result = self::where('user_id', $user->id)
->whereIn('viewable_id', $collection->pluck('id'))
->where('viewable_type', $class)
->pluck('created_at', 'viewable_id');
// Use transform instead of map to (maybe) save memory
$collection->transform(function ($item) use ($result) {
$userViewedAt = $result->get($item->id);
$item['user_viewed_at'] = $userViewedAt ? (string) $userViewedAt : null;
return $item;
});
}
}