Lae/app/Events/Users.php

83 lines
1.9 KiB
PHP
Raw Normal View History

2022-09-22 04:18:35 +00:00
<?php
namespace App\Events;
use App\Models\Module;
use App\Models\User;
use Carbon\Carbon;
2022-09-22 04:18:35 +00:00
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
2023-01-11 12:19:05 +00:00
use Illuminate\Database\Eloquent\Model;
2022-11-06 11:28:22 +00:00
use Illuminate\Queue\SerializesModels;
2022-09-22 06:00:03 +00:00
use Illuminate\Support\Facades\Auth;
2023-01-11 12:19:05 +00:00
use Illuminate\Support\Facades\Log;
2022-09-22 04:18:35 +00:00
class Users extends Event implements ShouldBroadcastNow
2022-09-22 04:18:35 +00:00
{
use SerializesModels;
public User $user;
2023-01-30 16:14:07 +00:00
2023-01-11 12:19:05 +00:00
public array|Model $data;
2023-01-30 16:14:07 +00:00
2023-01-11 12:19:05 +00:00
public null|Module $module = null;
2023-01-30 16:14:07 +00:00
2023-01-13 14:12:49 +00:00
public string $event = 'notification';
2022-09-22 04:18:35 +00:00
public Carbon $sent_at;
2022-09-22 04:18:35 +00:00
/**
* Create a new event instance.
*
* @return void
*/
2023-01-13 14:21:48 +00:00
public function __construct(User|int $user, string $event, array|Model $data)
2022-09-22 04:18:35 +00:00
{
2023-01-11 12:19:05 +00:00
// init vars
$this->sent_at = Carbon::now();
// if user is int
if (is_int($user)) {
2023-01-13 14:16:48 +00:00
$user = (new User)->find($user);
2023-01-11 12:19:05 +00:00
}
$this->user = $user;
2023-01-11 12:19:05 +00:00
2023-01-13 14:12:49 +00:00
$this->event = $event;
2022-09-22 06:00:03 +00:00
2023-01-11 12:19:05 +00:00
if ($data instanceof Model) {
$this->data = $data->toArray();
} else {
$this->data = $data;
}
2022-11-06 14:57:01 +00:00
if (Auth::guard('module')->check()) {
$this->module = Auth::guard('module')->user();
2023-01-11 12:19:05 +00:00
2023-01-13 14:26:13 +00:00
// if (isset($this->data['event'])) {
// $this->event = $this->module->id . '.' . $this->data['event'];
// }
2023-01-11 12:19:05 +00:00
}
// log
if (config('app.env') != 'production') {
Log::debug('Users Event', [
'user' => $this->user->id,
'data' => $this->data,
'module' => $this->module,
'event' => $this->event,
]);
2022-09-22 06:00:03 +00:00
}
2022-09-22 04:18:35 +00:00
}
2023-01-30 16:14:07 +00:00
public function broadcastOn(): PrivateChannel
2022-09-22 04:18:35 +00:00
{
2023-02-07 09:04:11 +00:00
return new PrivateChannel('users.'.$this->user->id);
2022-09-22 04:18:35 +00:00
}
2023-01-10 15:01:25 +00:00
2023-01-30 16:14:07 +00:00
public function broadcastAs(): string
2023-01-10 15:01:25 +00:00
{
2023-01-11 12:19:05 +00:00
return 'messages';
2023-01-10 15:01:25 +00:00
}
2022-09-22 04:18:35 +00:00
}