Файл: app/Models/Message.php
Строк: 87
<?php
declare(strict_types=1);
namespace AppModels;
use AppCastsHtmlCast;
use AppTraitsConvertVideoTrait;
use AppTraitsFileableTrait;
use AppTraitsUploadTrait;
use CarbonCarbonImmutable;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsTo;
use IlluminateDatabaseEloquentRelationsHasMany;
use IlluminateSupportCollection;
use IlluminateSupportFacadesDB;
use IlluminateSupportHtmlString;
/**
* Class Message
*
* @property int $id
* @property int $user_id
* @property int $author_id
* @property string $text
* @property CarbonImmutable $created_at
* @property-read User $user
* @property-read User $author
* @property-read Collection<File> $files
* @property-read Collection<Dialogue> $dialogues
*/
class Message extends Model
{
use FileableTrait;
use ConvertVideoTrait;
use UploadTrait;
public const string IN = 'in'; // Принятые
public const string OUT = 'out'; // Отправленные
/**
* The name of the "updated at" column.
*/
public const ?string UPDATED_AT = null;
/**
* The attributes that aren't mass assignable.
*/
protected $guarded = [];
/**
* Morph name
*/
public static string $morphName = 'messages';
/**
* Директория загрузки файлов
*/
public string $uploadPath = '/uploads/messages';
/**
* Get the attributes that should be cast.
*/
protected function casts(): array
{
return [
'user_id' => 'int',
'text' => HtmlCast::class,
];
}
/**
* Get text
*/
public function getText(): HtmlString
{
return renderHtml($this->text, 'message-' . $this->id);
}
/**
* Возвращает связь пользователя
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id')->withDefault();
}
/**
* Возвращает связь владельца
*/
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id')->withDefault();
}
/**
* Возвращает связь с диалогами
*/
public function dialogues(): HasMany
{
return $this->hasMany(Dialogue::class);
}
/**
* Create dialogue
*/
public function createDialogue(User $user, ?User $author, string $text, bool $withAuthor): self
{
$authorId = $author->id ?? 0;
$message = self::query()->create([
'user_id' => $user->id,
'author_id' => $authorId,
'text' => $text,
]);
Dialogue::query()->create([
'message_id' => $message->id,
'user_id' => $user->id,
'author_id' => $authorId,
'type' => self::IN,
]);
if ($authorId && $withAuthor) {
Dialogue::query()->create([
'message_id' => $message->id,
'user_id' => $authorId,
'author_id' => $user->id,
'type' => self::OUT,
'reading' => 1,
]);
}
$user->increment('newprivat');
return $message;
}
/**
* Удаление сообщения и загруженных файлов
*/
public function delete(): ?bool
{
return DB::transaction(function () {
$this->files->each(static function (File $file) {
$file->delete();
});
return parent::delete();
});
}
}