Changes
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Dto;
|
||||
|
||||
use Carbon\Carbon;
|
||||
|
||||
class MainSliderDTO
|
||||
{
|
||||
public function __construct(
|
||||
public ?string $title,
|
||||
public ?string $content,
|
||||
public ?string $image,
|
||||
public ?string $link,
|
||||
public ?string $link_text,
|
||||
public ?string $color_theme,
|
||||
public ?bool $is_active,
|
||||
public ?Carbon $start_time,
|
||||
public ?Carbon $end_time,
|
||||
public ?int $sort,
|
||||
) {}
|
||||
|
||||
// Опционально: метод для создания DTO из массива
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
title: $data['title'] ?? null,
|
||||
content: $data['content'] ?? null,
|
||||
image: $data['image'] ?? null,
|
||||
link: $data['link'] ?? null,
|
||||
link_text: $data['link_text'] ?? null,
|
||||
color_theme: $data['color_theme'] ?? 'white',
|
||||
is_active: $data['is_active'] ?? true,
|
||||
start_time: isset($data['start_time']) ? Carbon::parse($data['start_time']) : null,
|
||||
end_time: isset($data['end_time']) ? Carbon::parse($data['end_time']) : null,
|
||||
sort: $data['sort'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
// Опционально: метод для преобразования DTO в массив
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->title,
|
||||
'content' => $this->content,
|
||||
'image' => $this->image,
|
||||
'link' => $this->link,
|
||||
'link_text' => $this->link_text,
|
||||
'color_theme' => $this->color_theme,
|
||||
'is_active' => $this->is_active,
|
||||
'start_time' => $this->start_time?->toDateTimeString(),
|
||||
'end_time' => $this->end_time?->toDateTimeString(),
|
||||
'sort' => $this->sort,
|
||||
'created_at' => $this->created_at?->toDateTimeString(),
|
||||
'updated_at' => $this->updated_at?->toDateTimeString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use App\Models\PageReferenceList;
|
||||
use App\Models\Post;
|
||||
use Filament\Forms;
|
||||
use Filament\Forms\Components\Builder;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\Grid;
|
||||
@@ -97,7 +98,7 @@ class PostForm
|
||||
]),
|
||||
Tabs\Tab::make('Содержание новости')
|
||||
->schema([
|
||||
ContentBuilderItem::getItem('content')
|
||||
ContentBuilderItem::getItem('content')->required(),
|
||||
]),
|
||||
Tabs\Tab::make('Изображения')
|
||||
->schema([
|
||||
@@ -118,6 +119,51 @@ class PostForm
|
||||
->multiple()
|
||||
->directory('images'),
|
||||
]),
|
||||
Tabs\Tab::make('Добавление новости в слайдер')
|
||||
->schema([
|
||||
Toggle::make('is_slider_enabled')
|
||||
->label('Добавить новый слайд')
|
||||
->live()
|
||||
->dehydrated(false)
|
||||
->default(false),
|
||||
Section::make()
|
||||
->schema([
|
||||
Forms\Components\TextInput::make('slide.title')
|
||||
->label('Заголовок слайда'),
|
||||
Forms\Components\Textarea::make('slide.content')
|
||||
->label('Текст слайда'),
|
||||
FileUpload::make('slide.image')
|
||||
->label('Изображение')
|
||||
->image()
|
||||
->optimize('webp')
|
||||
->resize(50)
|
||||
->disk('public')
|
||||
->directory('images')
|
||||
->imageEditor()
|
||||
->required(),
|
||||
Grid::make(2)->schema([
|
||||
Toggle::make('disable_link_text')
|
||||
->label('Отключить текст кнопки (ссылка будет открываться при нажатии на слайд)')
|
||||
->live()
|
||||
->inline(false)
|
||||
->dehydrated(false)
|
||||
->default(false),
|
||||
Forms\Components\TextInput::make('slide.link_text')
|
||||
->default('Читать')
|
||||
->label('Текст кнопки')
|
||||
->disabled(fn (Forms\Get $get) => $get('disable_link_text')),
|
||||
]),
|
||||
|
||||
DateTimePicker::make('slide.end_time')
|
||||
->label('Слайд действует до')
|
||||
->native()
|
||||
->displayFormat('d/m/Y')
|
||||
->minDate(Carbon::now())
|
||||
->maxDate(Carbon::now()->addWeek()),
|
||||
])
|
||||
->disabled(fn (Forms\Get $get) => !$get('is_slider_enabled')) // Отключаем секцию, если Toggle выключен
|
||||
->hidden(fn (Forms\Get $get) => !$get('is_slider_enabled')), // Скрываем секцию, если Toggle выключен
|
||||
])->hidden(fn (string $context): bool => $context === 'edit'),
|
||||
]),
|
||||
])
|
||||
]);
|
||||
|
||||
@@ -10,6 +10,7 @@ use Filament\Forms;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Columns\TextInputColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\SoftDeletingScope;
|
||||
@@ -29,7 +30,7 @@ class AcceptedInvitationResource extends Resource implements HasShieldPermission
|
||||
{
|
||||
return $form
|
||||
->schema([
|
||||
//
|
||||
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -37,7 +38,8 @@ class AcceptedInvitationResource extends Resource implements HasShieldPermission
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
//
|
||||
Tables\Columns\TextColumn::make('receiver.name')->label('Приглашенный пользователь'),
|
||||
TextInputColumn::make('post_limit')->label('Лимит постов')->default(0)->rules(['required', 'max:10', 'integer'])
|
||||
])
|
||||
->filters([
|
||||
//
|
||||
|
||||
@@ -104,4 +104,16 @@ class ContactWidgetResource extends Resource
|
||||
'edit' => Pages\EditContactWidget::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPermissionPrefixes(): array
|
||||
{
|
||||
return [
|
||||
'view',
|
||||
'view_any',
|
||||
'create',
|
||||
'update',
|
||||
'delete',
|
||||
'delete_any',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Enums\FormEducation;
|
||||
use App\Filament\Resources\EducationalGroupResource\Pages;
|
||||
use App\Filament\Resources\EducationalGroupResource\RelationManagers;
|
||||
use App\Models\EducationalGroup;
|
||||
@@ -33,7 +34,9 @@ class EducationalGroupResource extends Resource
|
||||
Forms\Components\Grid::make(2)->schema([
|
||||
Forms\Components\TextInput::make('title')->label('Название группы')->required(),
|
||||
Forms\Components\Select::make('faculty_id')->label('Факультет')->required()
|
||||
->options(Faculty::all()->pluck('title', 'id'))
|
||||
->options(Faculty::all()->pluck('title', 'id')),
|
||||
Forms\Components\Select::make('education_form_id')->label('Форма обучения')
|
||||
->options(FormEducation::class)
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
|
||||
@@ -10,15 +10,19 @@ use App\Models\Page;
|
||||
use App\Models\Post;
|
||||
use Filament\Forms;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Forms\Components\ToggleButtons;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\SoftDeletingScope;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Str;
|
||||
use Yepsua\Filament\Forms\Components\RangeSlider;
|
||||
|
||||
class MainSliderResource extends Resource
|
||||
{
|
||||
@@ -96,32 +100,75 @@ class MainSliderResource extends Resource
|
||||
]),
|
||||
]),
|
||||
Forms\Components\Section::make('Слайдер')->schema([
|
||||
Forms\Components\TextInput::make('title')
|
||||
->label('Заголовок слайда')
|
||||
->required(),
|
||||
Forms\Components\Textarea::make('content')
|
||||
->label('Текст слайда'),
|
||||
FileUpload::make('image')
|
||||
->label('Изображение')
|
||||
->image()
|
||||
->optimize('webp')
|
||||
->resize(50)
|
||||
->disk('public')
|
||||
->directory('images')
|
||||
->imageEditor(),
|
||||
Forms\Components\Grid::make(2)->schema([
|
||||
|
||||
Forms\Components\Section::make('Информация слайда')->schema([
|
||||
Forms\Components\TextInput::make('title')
|
||||
->label('Заголовок слайда'),
|
||||
Forms\Components\Textarea::make('content')
|
||||
->label('Текст слайда'),
|
||||
Forms\Components\Grid::make()->schema([
|
||||
ColorPicker::make('color_theme')
|
||||
->label('Цвет текста')
|
||||
->default('#ffffff')
|
||||
->required(),
|
||||
Forms\Components\ToggleButtons::make('settings.text_position')
|
||||
->options([
|
||||
'left' => 'Текст слева',
|
||||
'center' => 'Текст по середине',
|
||||
'right' => 'Текст справа'
|
||||
])
|
||||
->inline()->default('left')->grouped()
|
||||
->label('Позиция текста на слайде'),
|
||||
]),
|
||||
Forms\Components\Grid::make()->schema([
|
||||
Toggle::make('active_button')
|
||||
->label('Использовать кнопку для ссылки (Ссылка будет открываться при нажатии на слайд)')
|
||||
->inline(false)
|
||||
->default(true)
|
||||
->live()
|
||||
->dehydrated(false),
|
||||
Forms\Components\TextInput::make('settings.link_text')
|
||||
->default('Читать')
|
||||
->label('Текст кнопки')
|
||||
->disabled(fn (Forms\Get $get) => !$get('active_button'))
|
||||
]),
|
||||
]),
|
||||
Forms\Components\Section::make('Изображение')->schema([
|
||||
FileUpload::make('image.url')
|
||||
->label('Изображение')
|
||||
->image()
|
||||
->optimize('webp')
|
||||
->resize(50)
|
||||
->disk('public')
|
||||
->directory('images')
|
||||
->imageEditor()
|
||||
->required(),
|
||||
ToggleButtons::make('image.shading')->inline()->grouped()->label('Уровень затемнения изображения')->options([
|
||||
'1' => 'Без затемнения',
|
||||
'0.7' => 'Слабое затемнение',
|
||||
'0.5' => 'Среднее затемнение',
|
||||
'0.3' => 'Сильное затемнение',
|
||||
]),
|
||||
]),
|
||||
Forms\Components\Section::make('Общая часть')->schema([
|
||||
Forms\Components\Grid::make()->schema([
|
||||
DateTimePicker::make('start_time')
|
||||
->label('Слайд начинается с')
|
||||
->native()
|
||||
->displayFormat('d/m/Y')
|
||||
->minDate(Carbon::now()->subDay())
|
||||
->maxDate(Carbon::now()->addWeek()),
|
||||
DateTimePicker::make('end_time')
|
||||
->label('Слайд действует до')
|
||||
->native()
|
||||
->displayFormat('d/m/Y')
|
||||
->minDate(Carbon::now())
|
||||
->maxDate(Carbon::now()->addMonth()),
|
||||
]),
|
||||
Forms\Components\TextInput::make('link')
|
||||
->label('Ссылка кнопки')
|
||||
->required(),
|
||||
Forms\Components\TextInput::make('link_text')
|
||||
->default('Читать')
|
||||
->label('Текст кнопки')
|
||||
->required(),
|
||||
]),
|
||||
ColorPicker::make('color_theme')
|
||||
->label('Цвет текста')
|
||||
->default('#ffffff')
|
||||
->required(),
|
||||
|
||||
Toggle::make('is_active')->default(true)->label('Активный слайдер')->inline(false),
|
||||
]),
|
||||
|
||||
@@ -44,8 +44,6 @@ class PageResource extends Resource
|
||||
|
||||
protected static ?string $pluralLabel = 'Страницы';
|
||||
|
||||
public static ?string $label = 'Страница';
|
||||
|
||||
|
||||
protected static ?string $navigationGroup = 'Структура приложения';
|
||||
|
||||
|
||||
@@ -59,10 +59,12 @@ class PostResource extends Resource implements HasShieldPermissions
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('id')->sortable(),
|
||||
// Tables\Columns\TextColumn::make('id')->sortable(),
|
||||
Tables\Columns\TextColumn::make('created_at')->label('Дата создания')->sortable(),
|
||||
Tables\Columns\TextColumn::make('title')->label('Заголовок')->sortable()->searchable(),
|
||||
Tables\Columns\TextColumn::make('status')->label('Статус')->sortable()->badge(),
|
||||
Tables\Columns\TextColumn::make('publish_at')->label('Дата публикации')->sortable(),
|
||||
Tables\Columns\TextColumn::make('author.name')->label('Автор')->sortable()->searchable(),
|
||||
|
||||
])->defaultSort('publish_at', 'desc')
|
||||
->filters([
|
||||
@@ -92,6 +94,8 @@ class PostResource extends Resource implements HasShieldPermissions
|
||||
'index' => Pages\ListPosts::route('/'),
|
||||
'create' => Pages\CreatePost::route('/create'),
|
||||
'edit' => Pages\EditPost::route('/{record}/edit'),
|
||||
'view' => Pages\ViewPost::route('/{record}'),
|
||||
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,29 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\PostResource\Pages;
|
||||
|
||||
use App\Dto\MainSliderDTO;
|
||||
use App\Enums\PostStatus;
|
||||
use App\Filament\Resources\PostResource;
|
||||
use App\Jobs\CreateVkPost;
|
||||
use App\Models\Post;
|
||||
use App\Models\User;
|
||||
use App\Services\VK\VkService;
|
||||
use Carbon\Carbon;
|
||||
use Closure;
|
||||
use Filament\Actions;
|
||||
use Filament\Notifications\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use App\Services\Filament\Domain\Posts\PostDataProcessor;
|
||||
use App\Services\Filament\Domain\Posts\PostNotificationService;
|
||||
use App\Services\Filament\Domain\Posts\PostSeoGenerator;
|
||||
use App\Services\Filament\Domain\Posts\PostSliderService;
|
||||
use App\Services\Filament\Domain\Posts\VkPostPublisher;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Notifications\Messages\BroadcastMessage;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use PhpParser\Node\Expr\AssignOp\Mod;
|
||||
use VK\Client\VKApiClient;
|
||||
use VK\OAuth\Scopes\VKOAuthGroupScope;
|
||||
use VK\OAuth\Scopes\VKOAuthUserScope;
|
||||
use VK\OAuth\VKOAuth;
|
||||
use VK\OAuth\VKOAuthDisplay;
|
||||
use VK\OAuth\VKOAuthResponseType;
|
||||
|
||||
class CreatePost extends CreateRecord
|
||||
{
|
||||
@@ -33,277 +19,68 @@ class CreatePost extends CreateRecord
|
||||
protected array $seoData;
|
||||
protected array $publicationAgreements;
|
||||
|
||||
protected array $slideData;
|
||||
|
||||
protected static array|string $routeMiddleware = ['limit.post'];
|
||||
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$this->publicationAgreements = $data['publication'];
|
||||
unset($data['publication']);
|
||||
$this->seoData = $this->generateSeo($data);
|
||||
$data['preview_text'] = $this->setPreviewText($data);
|
||||
$data['publish_at'] = $this->setPublishDateTime($data['publish_setting']);
|
||||
unset($data['publish_setting']);
|
||||
$data['search_data'] = $this->generateSearchData($data['content']);
|
||||
$data['reading_time'] = $this->calculateReadingTime($data['search_data']);
|
||||
return $data;
|
||||
$this->extractAdditionalData($data);
|
||||
return $this->processPostData($data);
|
||||
}
|
||||
|
||||
protected function extractAdditionalData(array &$data): void
|
||||
{
|
||||
$this->publicationAgreements = $data['publication'] ?? [];
|
||||
$this->slideData = $data['slide'] ?? [];
|
||||
unset($data['slide'], $data['publication']);
|
||||
}
|
||||
|
||||
protected function processPostData(array $data): array
|
||||
{
|
||||
return (new PostDataProcessor())->process($data);
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$this->record->seo()->create($this->seoData);
|
||||
$this->sendNotify($this->record, auth()->user());
|
||||
$publish_date = ($this->record->publish_at > now()) ? Carbon::parse($this->record->publish_at)->timestamp : null;
|
||||
$this->postToSocialMedia($this->publicationAgreements, $this->record->content, $this->record->title, $publish_date);
|
||||
$this->handleSlides();
|
||||
$this->generateSeo();
|
||||
$this->sendNotifications();
|
||||
$this->publishToVk();
|
||||
}
|
||||
|
||||
private function generateSeo(array $data) : array
|
||||
protected function handleSlides(): void
|
||||
{
|
||||
$title = $data['title'];
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
if ($rowData !== null) {
|
||||
$description = html_entity_decode(strip_tags($rowData['data']['content']));
|
||||
} else {
|
||||
$description = null;
|
||||
} $image = ($data['preview'] !== null) ? $data['preview'] : null;
|
||||
|
||||
return [
|
||||
'title' => $title,
|
||||
'description' => Str::limit(htmlspecialchars($description, ENT_QUOTES, 'UTF-8'), 160),
|
||||
'image' => $image,
|
||||
];
|
||||
}
|
||||
|
||||
private function setPreviewText(array $data) : string
|
||||
{
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
$preview_text = html_entity_decode(strip_tags($rowData['data']['content']));
|
||||
return Str::limit($preview_text, 160);
|
||||
}
|
||||
|
||||
private function generateSearchData(array $data) : string
|
||||
{
|
||||
$result = "";
|
||||
foreach ($data as $block) {
|
||||
$result .= $this->getDataFromBlocks($block);
|
||||
}
|
||||
// Удаляем лишние пробелы и переносы строк
|
||||
$result = preg_replace('/\s+/', ' ', $result);
|
||||
$result = trim($result);
|
||||
|
||||
return strtolower($result);
|
||||
}
|
||||
private function getFirstBlockByName(string $name, array $content) : array|null
|
||||
{
|
||||
$data = null;
|
||||
foreach ($content as $block) {
|
||||
$data = ($block['type'] === $name) ? $block : null;
|
||||
break;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function getBlockBySeoActiveState(string $name, array $content) : array|null
|
||||
{
|
||||
$data = [];
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name) {
|
||||
$data[] = $block;
|
||||
}
|
||||
}
|
||||
$block = null;
|
||||
foreach ($data as $item) {
|
||||
if ($item['data']['seo_active'] === true) {
|
||||
$block = $item;
|
||||
}
|
||||
}
|
||||
return $block;
|
||||
}
|
||||
|
||||
private function sendNotify($post, $recipient) : void
|
||||
{
|
||||
Notification::make()
|
||||
->title('Новость на проверку')
|
||||
->body('Новая запись была создана!')
|
||||
->actions([
|
||||
Action::make('view')
|
||||
->label('Проверить')
|
||||
->button()
|
||||
->markAsRead()
|
||||
->url(PostResource::getUrl('edit', ['record' => $post])),
|
||||
|
||||
])->sendToDatabase($recipient);
|
||||
}
|
||||
private function setPublishDateTime(array $data) : Carbon|null
|
||||
{
|
||||
if ($data['publish_after'] === true) {
|
||||
return Carbon::parse($data['publish_at']);
|
||||
}
|
||||
return Carbon::now();
|
||||
}
|
||||
private function calculateReadingTime(string $text): int
|
||||
{
|
||||
|
||||
// Calculate the number of words in the text
|
||||
$wordCount = str_word_count($text,0,"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя");
|
||||
|
||||
|
||||
|
||||
|
||||
// Calculate the average reading speed in words per minute
|
||||
$wordsPerMinute = 120; // You can adjust this value based on your desired reading speed
|
||||
|
||||
// Calculate the reading time in minutes
|
||||
$readingTime = $wordCount / $wordsPerMinute;
|
||||
|
||||
// Round the reading time to the nearest integer
|
||||
$readingTime = round($readingTime);
|
||||
|
||||
|
||||
return $readingTime;
|
||||
}
|
||||
protected function convertDataToHtml($blocks) {
|
||||
$convertedHtml = "";
|
||||
foreach ($blocks as $block) {
|
||||
switch ($block['type']) {
|
||||
case "header":
|
||||
$convertedHtml .= "<h" . $block['data']['level'] . ">" . $block['data']['text'] . "</h" . $block['data']['level'] . ">";
|
||||
break;
|
||||
case "embded":
|
||||
$convertedHtml .= "<div><iframe width='560' height='315' src='" . $block['data']['embed'] . "' frameborder='0' allow='autoplay; encrypted-media' allowfullscreen></iframe></div>";
|
||||
break;
|
||||
case "paragraph":
|
||||
$convertedHtml .= "<p>" . $block['data']['text'] . "</p>";
|
||||
break;
|
||||
case "delimiter":
|
||||
$convertedHtml .= "<hr />";
|
||||
break;
|
||||
case "image":
|
||||
$convertedHtml .= "<img class='img-fluid' src='" . $block['data']['file']['url'] . "' title='" . $block['data']['caption'] . "' /><br /><em>" . $block['data']['caption'] . "</em>";
|
||||
break;
|
||||
case "list":
|
||||
$convertedHtml .= "<ul>";
|
||||
foreach ($block['data']['items'] as $li) {
|
||||
$convertedHtml .= "<li>" . $li . "</li>";
|
||||
}
|
||||
$convertedHtml .= "</ul>";
|
||||
break;
|
||||
case "table":
|
||||
$convertedHtml .= "<table>";
|
||||
if ($block['data']['withHeadings']) {
|
||||
$convertedHtml .= "<thead><tr>";
|
||||
foreach ($block['data']['content'][0] as $th) {
|
||||
$convertedHtml .= "<th>" . $th . "</th>";
|
||||
}
|
||||
$convertedHtml .= "</tr></thead>";
|
||||
}
|
||||
$convertedHtml .= "<tbody>";
|
||||
foreach ($block['data']['content'] as $row) {
|
||||
$convertedHtml .= "<tr>";
|
||||
foreach ($row as $td) {
|
||||
$convertedHtml .= "<td>" . $td . "</td>";
|
||||
}
|
||||
$convertedHtml .= "</tr>";
|
||||
}
|
||||
$convertedHtml .= "</tbody></table>";
|
||||
break;
|
||||
default:
|
||||
echo "Unknown block type " . $block['type'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $convertedHtml;
|
||||
}
|
||||
private function getDataFromBlocks($block) : string
|
||||
{
|
||||
$data = "";
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'heading':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'files':
|
||||
foreach ($block['data']['file'] as $file) {
|
||||
$data .= $file['title'] . " ";
|
||||
}
|
||||
break;
|
||||
case 'person':
|
||||
$data .= $block['data']['name'] . " ";
|
||||
break;
|
||||
case 'stepper':
|
||||
$data .= $block['data']['step_name'] . " ";
|
||||
foreach ($block['data']['steps'] as $step) {
|
||||
$data .= $step['title'] . " ";
|
||||
$data .= strip_tags($step['content']) . " ";
|
||||
}
|
||||
break;
|
||||
case 'tabs':
|
||||
foreach ($block['data']['tab'] as $item) {
|
||||
foreach ($item['content'] as $block) {
|
||||
$data .= $this->getDataFromBlocks($block);
|
||||
};
|
||||
};
|
||||
break;
|
||||
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function postToSocialMedia($settings, $content, $title, $publish_date) : void
|
||||
{
|
||||
if ($this->record->status === PostStatus::PUBLISHED) {
|
||||
if ($settings['vk']) {
|
||||
$text = "";
|
||||
foreach ($content as $block) {
|
||||
$text .= $this->generateContentToVK($block);
|
||||
}
|
||||
|
||||
$images = $this->generateImageLinksToVK($this->record->images);
|
||||
|
||||
$post_id = $this->record->id;
|
||||
|
||||
|
||||
|
||||
dispatch(new CreateVkPost($title, $text, $images, $post_id, $publish_date));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private function generateContentToVK($block) : string
|
||||
{
|
||||
$data = "";
|
||||
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
// Удаляем все HTML-теги и заменяем закрывающие теги p и h2 на двойной отступ
|
||||
$content = preg_replace('/<\/(p|h2)>/', "\n\n", $block['data']['content']);
|
||||
$data .= html_entity_decode(strip_tags($content));
|
||||
break;
|
||||
|
||||
case 'heading':
|
||||
// Удаляем теги заголовка и добавляем двойной отступ
|
||||
$data .= $block['data']['content'] . "\n\n";
|
||||
break;
|
||||
if (empty($this->slideData)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return $data;
|
||||
$this->slideData['is_active'] = $this->record->status === PostStatus::PUBLISHED;
|
||||
$this->slideData['start_time'] = $this->record->publish_at;
|
||||
|
||||
$sliderDTO = MainSliderDTO::fromArray($this->slideData);
|
||||
(new PostSliderService($sliderDTO, $this->record->slug))->create();
|
||||
}
|
||||
private function generateImageLinksToVK($images)
|
||||
|
||||
protected function generateSeo(): void
|
||||
{
|
||||
$seoData = (new PostSeoGenerator())->generate([
|
||||
'title' => $this->record->title,
|
||||
'content' => $this->record->content,
|
||||
'preview' => $this->record->preview,
|
||||
]);
|
||||
$this->record->seo()->create($seoData);
|
||||
}
|
||||
|
||||
$imageUrls = array_map(function ($file) {
|
||||
return url(Storage::url($file)); // Добавляем домен
|
||||
}, $images);
|
||||
protected function sendNotifications(): void
|
||||
{
|
||||
(new PostNotificationService())->send($this->record);
|
||||
}
|
||||
|
||||
|
||||
return $imageUrls; // Возвращаем массив с полными URL изображений
|
||||
protected function publishToVk(): void
|
||||
{
|
||||
(new VkPostPublisher())->publish($this->publicationAgreements, $this->record);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,14 +2,17 @@
|
||||
|
||||
namespace App\Filament\Resources\PostResource\Pages;
|
||||
|
||||
use App\Dto\MainSliderDTO;
|
||||
use App\Enums\PostStatus;
|
||||
use App\Filament\Resources\PostResource;
|
||||
use App\Jobs\UpdateVkPost;
|
||||
use App\Services\Filament\Domain\Posts\PostDataProcessor;
|
||||
use App\Services\Filament\Domain\Posts\PostNotificationService;
|
||||
use App\Services\Filament\Domain\Posts\PostSeoGenerator;
|
||||
use App\Services\Filament\Domain\Posts\PostSliderService;
|
||||
use App\Services\Filament\Domain\Posts\VkPostPublisher;
|
||||
use Carbon\Carbon;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EditPost extends EditRecord
|
||||
{
|
||||
@@ -18,224 +21,75 @@ class EditPost extends EditRecord
|
||||
protected array $seoData;
|
||||
protected array $publicationAgreements;
|
||||
|
||||
protected array $slideData;
|
||||
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$this->seoData = $this->generateSeo($data);
|
||||
$this->publicationAgreements = $data['publication'];
|
||||
unset($data['publication']);
|
||||
unset($data['publish_setting']);
|
||||
$data['preview_text'] = $this->setPreviewText($data);
|
||||
$data['publish_at'] = $this->setPublishDateTime($data['status'], $this->record->publish_at);
|
||||
$data['search_data'] = $this->generateSearchData($data['content']);
|
||||
$data['reading_time'] = $this->calculateReadingTime($data['search_data']);
|
||||
$this->extractAdditionalData($data);
|
||||
return $this->processPostData($data);
|
||||
}
|
||||
|
||||
return $data;
|
||||
protected function extractAdditionalData(array &$data): void
|
||||
{
|
||||
$this->publicationAgreements = $data['publication'] ?? [];
|
||||
$this->slideData = $data['slide'] ?? [];
|
||||
unset($data['slide'], $data['publication']);
|
||||
}
|
||||
|
||||
protected function processPostData(array $data): array
|
||||
{
|
||||
return (new PostDataProcessor())->process($data);
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$this->record->seo()->update($this->seoData);
|
||||
$publish_date = ($this->record->publish_at > now()) ? Carbon::parse($this->record->publish_at)->timestamp : null;
|
||||
$this->postToSocialMedia($this->publicationAgreements, $this->record->content, $this->record->title, $publish_date);
|
||||
$this->handleSlides();
|
||||
$this->generateSeo();
|
||||
$this->sendNotifications();
|
||||
$this->publishToVk();
|
||||
}
|
||||
|
||||
private function setPreviewText(array $data) : string|null
|
||||
|
||||
protected function handleSlides(): void
|
||||
{
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
if ($rowData !== null) {
|
||||
$preview_text = html_entity_decode(strip_tags($rowData['data']['content']));
|
||||
return Str::limit($preview_text, 160);
|
||||
} else {
|
||||
$preview_text = null;
|
||||
return $preview_text;
|
||||
if (empty($this->slideData)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->slideData['is_active'] = $this->record->status === PostStatus::PUBLISHED;
|
||||
$this->slideData['start_time'] = $this->record->publish_at;
|
||||
|
||||
$sliderDTO = MainSliderDTO::fromArray($this->slideData);
|
||||
(new PostSliderService($sliderDTO, $this->record->slug))->update();
|
||||
}
|
||||
|
||||
private function getBlockBySeoActiveState(string $name, array $content) : array|null
|
||||
protected function generateSeo(): void
|
||||
{
|
||||
$data = [];
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name) {
|
||||
$data[] = $block;
|
||||
}
|
||||
}
|
||||
$block = null;
|
||||
foreach ($data as $item) {
|
||||
if ($item['data']['seo_active'] === true) {
|
||||
$block = $item;
|
||||
}
|
||||
}
|
||||
return $block;
|
||||
$seoData = (new PostSeoGenerator())->generate([
|
||||
'title' => $this->record->title,
|
||||
'content' => $this->record->content,
|
||||
'preview' => $this->record->preview,
|
||||
]);
|
||||
$this->record->seo()->update($seoData);
|
||||
}
|
||||
|
||||
private function generateSeo(array $data) : array
|
||||
{
|
||||
$title = $data['title'];
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
if ($rowData !== null) {
|
||||
$description = html_entity_decode(strip_tags($rowData['data']['content']));
|
||||
} else {
|
||||
$description = null;
|
||||
}
|
||||
$image = ($this->record->preview !== null) ? $this->record->preview : null;
|
||||
|
||||
return [
|
||||
'title' => $title,
|
||||
'description' => Str::limit(htmlspecialchars($description, ENT_QUOTES, 'UTF-8'), 160),
|
||||
'image' => $image,
|
||||
];
|
||||
}
|
||||
|
||||
private function setPublishDateTime($status, $publish_at)
|
||||
{
|
||||
if ($publish_at !== null) {
|
||||
return $publish_at;
|
||||
}
|
||||
return PostStatus::tryFrom($status) === PostStatus::PUBLISHED ? Carbon::now() : null;
|
||||
}
|
||||
private function getDataFromBlocks($block) : string
|
||||
{
|
||||
$data = "";
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'heading':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'files':
|
||||
foreach ($block['data']['file'] as $file) {
|
||||
$data .= $file['title'] . " ";
|
||||
}
|
||||
break;
|
||||
case 'person':
|
||||
$data .= $block['data']['name'] . " ";
|
||||
break;
|
||||
case 'stepper':
|
||||
$data .= $block['data']['step_name'] . " ";
|
||||
foreach ($block['data']['steps'] as $step) {
|
||||
$data .= $step['title'] . " ";
|
||||
$data .= strip_tags($step['content']) . " ";
|
||||
}
|
||||
break;
|
||||
case 'tabs':
|
||||
foreach ($block['data']['tab'] as $item) {
|
||||
foreach ($item['content'] as $block) {
|
||||
$data .= $this->getDataFromBlocks($block);
|
||||
};
|
||||
};
|
||||
break;
|
||||
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function calculateReadingTime(string $text): int
|
||||
{
|
||||
|
||||
// Calculate the number of words in the text
|
||||
$wordCount = str_word_count($text,0,"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя");
|
||||
|
||||
|
||||
|
||||
|
||||
// Calculate the average reading speed in words per minute
|
||||
$wordsPerMinute = 120; // You can adjust this value based on your desired reading speed
|
||||
|
||||
// Calculate the reading time in minutes
|
||||
$readingTime = $wordCount / $wordsPerMinute;
|
||||
|
||||
// Round the reading time to the nearest integer
|
||||
$readingTime = round($readingTime);
|
||||
|
||||
|
||||
return $readingTime;
|
||||
}
|
||||
|
||||
private function generateSearchData(array $data) : string
|
||||
{
|
||||
$result = "";
|
||||
foreach ($data as $block) {
|
||||
$result .= $this->getDataFromBlocks($block);
|
||||
}
|
||||
// Удаляем лишние пробелы и переносы строк
|
||||
$result = preg_replace('/\s+/', ' ', $result);
|
||||
$result = htmlspecialchars(trim($result));
|
||||
|
||||
return strtolower($result);
|
||||
}
|
||||
private function getFirstBlockByName(string $name, array $content) : array|null
|
||||
{
|
||||
$data = null;
|
||||
foreach ($content as $block) {
|
||||
$data = ($block['type'] === $name) ? $block : null;
|
||||
break;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function generateContentToVK($block) : string
|
||||
{
|
||||
$data = "";
|
||||
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
// Удаляем все HTML-теги и заменяем закрывающие теги p и h2 на двойной отступ
|
||||
$content = preg_replace('/<\/(p|h2)>/', "\n\n", $block['data']['content']);
|
||||
$data .= html_entity_decode(strip_tags($content));
|
||||
break;
|
||||
|
||||
case 'heading':
|
||||
// Удаляем теги заголовка и добавляем двойной отступ
|
||||
$data .= $block['data']['content'] . "\n\n";
|
||||
break;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function postToSocialMedia($settings, $content, $title, $publish_date) : void
|
||||
protected function sendNotifications(): void
|
||||
{
|
||||
// Отправляем уведомления
|
||||
$notificationService = new PostNotificationService();
|
||||
if ($this->record->status === PostStatus::PUBLISHED) {
|
||||
if ($settings['vk']) {
|
||||
$text = "";
|
||||
foreach ($content as $block) {
|
||||
$text .= $this->generateContentToVK($block);
|
||||
}
|
||||
|
||||
$images = $this->generateImageLinksToVK($this->record->images);
|
||||
|
||||
$post_id = $this->record->id;
|
||||
|
||||
|
||||
dispatch(new UpdateVkPost($title, $text, $images, $post_id, $publish_date));
|
||||
}
|
||||
$notificationService->sendSuccessNotification($this->record);
|
||||
} elseif ($this->record->status === PostStatus::REJECTED) {
|
||||
$notificationService->sendDeniedNotification($this->record);
|
||||
}
|
||||
}
|
||||
|
||||
private function generateImageLinksToVK($images)
|
||||
protected function publishToVk(): void
|
||||
{
|
||||
|
||||
$imageUrls = array_map(function ($file) {
|
||||
return url(Storage::url($file)); // Добавляем домен
|
||||
}, $images);
|
||||
|
||||
|
||||
return $imageUrls; // Возвращаем массив с полными URL изображений
|
||||
(new VkPostPublisher())->publish($this->publicationAgreements, $this->record);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -50,7 +50,6 @@ class UserResource extends Resource implements HasShieldPermissions
|
||||
Forms\Components\TextInput::make('password')
|
||||
->label('Пароль')
|
||||
->password()
|
||||
->default(Str::password(15))
|
||||
->required(fn (string $context): bool => $context === 'create')
|
||||
->dehydrated(fn ($state) => filled($state))
|
||||
->maxLength(255),
|
||||
|
||||
@@ -22,11 +22,10 @@ class ClientAcademicJournalController extends Controller
|
||||
public function show(string $slug)
|
||||
{
|
||||
$journal = new ClientAcademicJournalListResource(AcademicJournal::query()->where('slug', '=', $slug)->firstOrFail());
|
||||
$journalIssues = JournalIssue::all()
|
||||
->groupBy('year_publication');
|
||||
$journalIssues = JournalIssue::where('academic_journal_id', $journal->id)
|
||||
->groupBy('year_publication')->get();
|
||||
|
||||
$journals = [];
|
||||
$years = JournalIssue::select('year_publication')->distinct()->get();
|
||||
|
||||
foreach ($journalIssues as $year => $journalGroup) {
|
||||
$journals[] = [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\FormEducation;
|
||||
use App\Http\Resources\ClientEducationalGroupResource;
|
||||
use App\Http\Resources\ScheduleResource;
|
||||
use App\Models\EducationalGroup;
|
||||
@@ -14,22 +15,71 @@ class ClientScheduleController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$educationalGroups = collect();
|
||||
$educationalGroups = ClientEducationalGroupResource::collection(EducationalGroup::query()
|
||||
->has('schedules')
|
||||
->when(request()->input('search'), function ($query, $search) {
|
||||
$query->whereRaw('LOWER(title) like ?', ["%".strtolower($search)."%"]);
|
||||
})
|
||||
->when(request()->input('favorite'), function ($query, $favorite) {
|
||||
$query->whereHas('schedules', function ($query) use ($favorite) {
|
||||
$query->whereIn('id', $favorite);
|
||||
});
|
||||
})
|
||||
->when(request()->input('form'), function ($query, $form) {
|
||||
$query->where('education_form_id', FormEducation::fromName($form)->value);
|
||||
|
||||
if (request()->filled('search')) {
|
||||
$educationalGroups = ClientEducationalGroupResource::collection(EducationalGroup::query()
|
||||
->has('schedules')
|
||||
->when(request()->input('search'), function ($query, $search) {
|
||||
$query->whereRaw('LOWER(title) like ?', ["%".strtolower($search)."%"]);
|
||||
})
|
||||
->with('schedules')
|
||||
->with('faculty')
|
||||
->orderBy('title')
|
||||
->get());
|
||||
})
|
||||
|
||||
->with('schedules')
|
||||
->with('faculty')
|
||||
->orderBy('title')
|
||||
->get());
|
||||
|
||||
$schedulesByFaculty = $educationalGroups->groupBy(function ($group) {
|
||||
return $group->faculty->title; // Предполагаем, что у факультета есть поле 'name'
|
||||
});
|
||||
|
||||
$schedulesByFaculty = $schedulesByFaculty->toArray();
|
||||
|
||||
if ($request->has('favorite') && empty($request->input('favorite'))) {
|
||||
$schedulesByFaculty = [];
|
||||
}
|
||||
$searchRequest = request()->input('search');
|
||||
|
||||
return Inertia::render('Client/Schedules/Index', compact('educationalGroups', 'searchRequest'));
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$forms_education = [];
|
||||
foreach (FormEducation::cases() as $case) {
|
||||
$forms_education[$case->name] = $case->getLabel();
|
||||
}
|
||||
|
||||
$filters = [
|
||||
'direction_filter' => [
|
||||
'type' => 'direction',
|
||||
'value' => request()->input('direction'),
|
||||
'param' => 'direction'
|
||||
],
|
||||
'form_education_filter' => [
|
||||
'type' => 'form',
|
||||
'value' => request()->input('form'),
|
||||
'param' => 'form'
|
||||
],
|
||||
'search_filter' => [
|
||||
'type' => 'search',
|
||||
'value' => $request->input('search'),
|
||||
'param' => 'search'
|
||||
],
|
||||
'favorite_filter' => [
|
||||
'type' => 'favorite',
|
||||
'value' => $request->input('favorite'),
|
||||
'param' => 'favorite'
|
||||
]
|
||||
];
|
||||
|
||||
// Возвращаем данные в представление
|
||||
return Inertia::render('Client/Schedules/Index', compact('educationalGroups', 'filters', 'forms_education', 'schedulesByFaculty'));
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
|
||||
@@ -27,6 +27,7 @@ use App\Services\Vicon\EducationalProgram\EducationalProgramService;
|
||||
use Carbon\Carbon;
|
||||
use DateTime;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
@@ -37,14 +38,32 @@ class MainController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$admissionCampaign = $this->getAdmissionCampaign();
|
||||
$educations = $this->getEducationsData();
|
||||
$sliders = $this->getActiveSliders();
|
||||
$posts = $this->getRecentPosts();
|
||||
$events = $this->getUpcomingEvents();
|
||||
// Кешируем данные на 60 минут (можно изменить время по необходимости)
|
||||
// $admissionCampaign = Cache::remember('admission_campaign', now()->addHour(), function () {
|
||||
// return $this->getAdmissionCampaign();
|
||||
// });
|
||||
|
||||
$educations = Cache::remember('educations_data', now()->addHour(), function () {
|
||||
return $this->getEducationsData();
|
||||
});
|
||||
|
||||
$sliders = Cache::remember('active_sliders', now()->addHour(), function () {
|
||||
return $this->getActiveSliders();
|
||||
});
|
||||
|
||||
$posts = Cache::remember('recent_posts', now()->addHour(), function () {
|
||||
return $this->getRecentPosts();
|
||||
});
|
||||
|
||||
$events = Cache::remember('upcoming_events', now()->addHour(), function () {
|
||||
return $this->getUpcomingEvents();
|
||||
});
|
||||
|
||||
$path = route('index', null, false);
|
||||
$page = Page::where('path', $path)->first();
|
||||
$page = Cache::remember('page_' . $path, now()->addHour(), function () use ($path) {
|
||||
return Page::where('path', $path)->first();
|
||||
});
|
||||
|
||||
$seo = $page->seo ?? null;
|
||||
|
||||
return Inertia::render('Main', compact('posts', 'events', 'sliders', 'educations', 'seo'));
|
||||
@@ -82,11 +101,10 @@ class MainController extends Controller
|
||||
|
||||
private function getActiveSliders()
|
||||
{
|
||||
return ClientMainSliderResource::collection(
|
||||
return (ClientMainSliderResource::collection(
|
||||
MainSlider::where('is_active', true)
|
||||
->orderBy('sort', 'asc')
|
||||
->get()
|
||||
);
|
||||
->get()));
|
||||
}
|
||||
|
||||
private function getRecentPosts()
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http;
|
||||
|
||||
use App\Http\Middleware\AccessCheck;
|
||||
use App\Http\Middleware\InternalRequestOnly;
|
||||
use App\Http\Middleware\LimitPost;
|
||||
use App\Http\Middleware\RateLimitCheckMiddleware;
|
||||
use App\Http\Middleware\RateLimitCounterMiddleware;
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
@@ -84,6 +85,7 @@ class Kernel extends HttpKernel
|
||||
'rate.limited.check' => RateLimitCheckMiddleware::class,
|
||||
'ensure.browser' => InternalRequestOnly::class,
|
||||
'superadmin' => \App\Http\Middleware\EnsureUserIsSuperadmin::class,
|
||||
'limit.post' => LimitPost::class,
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -12,6 +13,6 @@ class Authenticate extends Middleware
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
return $request->expectsJson() ? null : throw new AuthorizationException('Forbidden', 403);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
class LimitPost
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (auth()->user()->receivedInvitation === null) {
|
||||
return $next($request);
|
||||
}
|
||||
if (auth()->user()->receivedInvitation->post_limit > 0) {
|
||||
return $next($request);
|
||||
} else {
|
||||
throw new HttpException(403, 'Лимит постов исчерпан');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,10 @@ class MainSlider extends Model
|
||||
use HasFactory;
|
||||
|
||||
protected $guarded = false;
|
||||
|
||||
|
||||
protected $casts = [
|
||||
'settings' => 'array',
|
||||
'image' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -34,6 +34,11 @@ class Post extends Model
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
public function author() : BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
|
||||
public function seo()
|
||||
{
|
||||
|
||||
@@ -94,6 +94,7 @@ class User extends Authenticatable implements FilamentUser
|
||||
{
|
||||
if (config('filament-shield.dashboard_user.enabled', false)) {
|
||||
FilamentShield::createRole(name: config('filament-shield.dashboard_user.name', 'dashboard_user'));
|
||||
FilamentShield::createRole(name: config('', 'editor'));
|
||||
static::created(function (User $user) {
|
||||
$user->assignRole(config('filament-shield.dashboard_user.name', 'dashboard_user'));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Models\MainSlider;
|
||||
use App\Services\App\Cache\MainSliderCacheService;
|
||||
|
||||
class MainSliderObserver
|
||||
{
|
||||
|
||||
protected MainSliderCacheService $cacheService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->cacheService = new MainSliderCacheService();
|
||||
}
|
||||
/**
|
||||
* Handle the MainSlider "created" event.
|
||||
*/
|
||||
public function created(MainSlider $mainSlider): void
|
||||
{
|
||||
// Устанавливаем сортировку для новой записи
|
||||
$mainSlider->sort = 1;
|
||||
$mainSlider->save();
|
||||
|
||||
// Обновляем сортировку для всех остальных записей
|
||||
$this->updateSortOrder();
|
||||
|
||||
$this->cacheService->clearAllCacheByModel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the MainSlider "updated" event.
|
||||
*/
|
||||
public function updated(MainSlider $mainSlider): void
|
||||
{
|
||||
$this->cacheService->clearAllCacheByModel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the MainSlider "deleted" event.
|
||||
*/
|
||||
public function deleted(MainSlider $mainSlider): void
|
||||
{
|
||||
$this->cacheService->clearAllCacheByModel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the MainSlider "restored" event.
|
||||
*/
|
||||
public function restored(MainSlider $mainSlider): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the MainSlider "force deleted" event.
|
||||
*/
|
||||
public function forceDeleted(MainSlider $mainSlider): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
protected function updateSortOrder(): void
|
||||
{
|
||||
// Получаем все записи, отсортированные по текущему значению sort
|
||||
$slides = MainSlider::orderBy('sort', 'asc')->get();
|
||||
|
||||
// Обновляем сортировку для каждой записи
|
||||
foreach ($slides as $index => $slide) {
|
||||
$slide->sort = $index + 1; // Начинаем с 1
|
||||
$slide->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ class PostObserver
|
||||
*/
|
||||
public function updated(Post $post)
|
||||
{
|
||||
$this->postCacheService->clearCache($post);
|
||||
$this->postCacheService->clearAllCacheByModel();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\ContactWidget;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
|
||||
class ContactWidgetPolicy
|
||||
{
|
||||
use HandlesAuthorization;
|
||||
|
||||
/**
|
||||
* Determine whether the user can view any models.
|
||||
*/
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('view_any_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can view the model.
|
||||
*/
|
||||
public function view(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('view_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can create models.
|
||||
*/
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->can('create_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can update the model.
|
||||
*/
|
||||
public function update(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('update_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can delete the model.
|
||||
*/
|
||||
public function delete(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('delete_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can bulk delete.
|
||||
*/
|
||||
public function deleteAny(User $user): bool
|
||||
{
|
||||
return $user->can('delete_any_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can permanently delete.
|
||||
*/
|
||||
public function forceDelete(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('force_delete_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can permanently bulk delete.
|
||||
*/
|
||||
public function forceDeleteAny(User $user): bool
|
||||
{
|
||||
return $user->can('force_delete_any_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can restore.
|
||||
*/
|
||||
public function restore(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('restore_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can bulk restore.
|
||||
*/
|
||||
public function restoreAny(User $user): bool
|
||||
{
|
||||
return $user->can('restore_any_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can replicate.
|
||||
*/
|
||||
public function replicate(User $user, ContactWidget $contactWidget): bool
|
||||
{
|
||||
return $user->can('replicate_contact::widget');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can reorder.
|
||||
*/
|
||||
public function reorder(User $user): bool
|
||||
{
|
||||
return $user->can('reorder_contact::widget');
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,20 @@
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Models\MainSection;
|
||||
use App\Models\MainSlider;
|
||||
use App\Models\Page;
|
||||
use App\Models\Post;
|
||||
use App\Models\SubSection;
|
||||
use App\Observers\MainSectionObserver;
|
||||
use App\Observers\MainSliderObserver;
|
||||
use App\Observers\PageObserver;
|
||||
use App\Observers\PostObserver;
|
||||
use App\Observers\SubSectionObserver;
|
||||
use App\Services\App\Cache\MainSliderCacheService;
|
||||
use Carbon\Carbon;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Support\Facades\FilamentView;
|
||||
use Filament\Tables\View\TablesRenderHook;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\Facades\Vite;
|
||||
@@ -34,16 +39,29 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
setlocale(LC_TIME, 'ru_RU.UTF-8');
|
||||
Page::observe(PageObserver::class);
|
||||
Post::observe(PostObserver::class);
|
||||
MainSection::observe(MainSectionObserver::class);
|
||||
SubSection::observe(SubSectionObserver::class);
|
||||
Carbon::setLocale(config('app.locale'));
|
||||
self::setObserversByModel();
|
||||
self::setLocaleTime();
|
||||
Model::preventLazyLoading(!app()->isProduction());
|
||||
// URL::forceScheme('https');
|
||||
self::registerFilamentNavigationGroups();
|
||||
$this->loadViewsFrom(__DIR__.'/path/to/views', 'checkpoint');
|
||||
|
||||
FilamentView::registerRenderHook(TablesRenderHook::TOOLBAR_REORDER_TRIGGER_AFTER, function () {
|
||||
(new MainSliderCacheService())->clearAllCacheByModel();
|
||||
});
|
||||
}
|
||||
|
||||
private static function setObserversByModel() : void {
|
||||
Page::observe(PageObserver::class);
|
||||
Post::observe(PostObserver::class);
|
||||
MainSection::observe(MainSectionObserver::class);
|
||||
SubSection::observe(SubSectionObserver::class);
|
||||
MainSlider::observe(MainSliderObserver::class);
|
||||
}
|
||||
|
||||
private static function setLocaleTime() : void {
|
||||
setlocale(LC_TIME, 'ru_RU.UTF-8');
|
||||
Carbon::setLocale(config('app.locale'));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ class AdminPanelProvider extends PanelProvider
|
||||
->default()
|
||||
->id('admin')
|
||||
->path('admin')
|
||||
->registration()
|
||||
// ->registration()
|
||||
->login()
|
||||
->databaseNotifications()
|
||||
->databaseNotificationsPolling('5s')
|
||||
|
||||
@@ -29,6 +29,8 @@ class DashboardPanelProvider extends PanelProvider
|
||||
'primary' => Color::Amber,
|
||||
])
|
||||
->login()
|
||||
->databaseNotifications()
|
||||
->databaseNotificationsPolling('5s')
|
||||
->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
|
||||
->discoverPages(in: app_path('Filament/Dashboard/Pages'), for: 'App\\Filament\\Dashboard\\Pages')
|
||||
->pages([
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\App\Cache;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class MainSliderCacheService extends AbstractCacheService implements CacheInterface
|
||||
{
|
||||
/**
|
||||
* Очищает кеш, связанный с постом.
|
||||
*
|
||||
* @param mixed $entity Пост или связанная сущность
|
||||
* @return void
|
||||
*/
|
||||
public function clearCache($entity): void
|
||||
{
|
||||
}
|
||||
|
||||
public function clearAllCacheByModel(): void
|
||||
{
|
||||
$this->clearCacheByPrefix('active_sliders*');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Получает кешированные данные по ключу.
|
||||
*
|
||||
* @param string $key Ключ кеша
|
||||
* @return mixed
|
||||
*/
|
||||
public function getCachedData(string $key)
|
||||
{
|
||||
return Cache::get($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Кеширует данные по ключу.
|
||||
*
|
||||
* @param string $key Ключ кеша
|
||||
* @param mixed $data Данные для кеширования
|
||||
* @param int $ttl Время жизни кеша в секундах
|
||||
* @return void
|
||||
*/
|
||||
public function cacheData(string $key, $data, int $ttl = 3600): void
|
||||
{
|
||||
Cache::put($key, $data, $ttl);
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,18 @@ class PostCacheService extends AbstractCacheService implements CacheInterface
|
||||
$cacheKeyBySlug = md5($entity->slug);
|
||||
$cacheKeyById = md5($entity->id);
|
||||
|
||||
Cache::forget($cacheKeyBySlug);
|
||||
Cache::forget($cacheKeyById);
|
||||
Cache::forget('post_' .$cacheKeyBySlug);
|
||||
Cache::forget('post_' .$cacheKeyById);
|
||||
|
||||
$this->clearCacheByPrefix('recent_posts*');
|
||||
|
||||
}
|
||||
|
||||
public function clearAllCacheByModel(): void
|
||||
{
|
||||
$this->clearCacheByPrefix('post_*');
|
||||
$this->clearCacheByPrefix('posts_*');
|
||||
$this->clearCacheByPrefix('recent_posts*');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Filament\Domain\Posts;
|
||||
|
||||
use App\Enums\PostStatus;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class PostDataProcessor
|
||||
{
|
||||
/**
|
||||
* Обрабатывает данные перед созданием поста.
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public function process(array $data): array
|
||||
{
|
||||
// Удаляем ненужные данные
|
||||
unset($data['publication']);
|
||||
|
||||
// Устанавливаем текст для предпросмотра
|
||||
$data['preview_text'] = $this->setPreviewText($data);
|
||||
|
||||
// Устанавливаем время публикации
|
||||
$data['publish_at'] = $this->setPublishDateTime($data['publish_setting'], $data['status']);
|
||||
unset($data['publish_setting']);
|
||||
|
||||
// Генерируем данные для поиска
|
||||
$data['search_data'] = $this->generateSearchData($data['content']);
|
||||
|
||||
// Рассчитываем время чтения
|
||||
$data['reading_time'] = $this->calculateReadingTime($data['search_data']);
|
||||
|
||||
// Устанавливаем ID текущего пользователя
|
||||
$data['user_id'] = auth()->id();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает текст для предпросмотра.
|
||||
*
|
||||
* @param array $data
|
||||
* @return string
|
||||
*/
|
||||
private function setPreviewText(array $data): string
|
||||
{
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
|
||||
$previewText = $rowData ? html_entity_decode(strip_tags($rowData['data']['content'])) : '';
|
||||
return Str::limit($previewText, 160);
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает время публикации.
|
||||
*
|
||||
* @param array $publishSetting
|
||||
* @param string $status
|
||||
* @return Carbon|null
|
||||
*/
|
||||
private function setPublishDateTime(array $publishSetting, string|PostStatus $status): ?Carbon
|
||||
{
|
||||
if ($publishSetting['publish_after'] === true) {
|
||||
return Carbon::parse($publishSetting['publish_at']);
|
||||
}
|
||||
|
||||
if ($status === PostStatus::PUBLISHED) {
|
||||
return Carbon::now();
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует данные для поиска.
|
||||
*
|
||||
* @param array $content
|
||||
* @return string
|
||||
*/
|
||||
private function generateSearchData(array $content): string
|
||||
{
|
||||
$result = "";
|
||||
foreach ($content as $block) {
|
||||
$result .= $this->getDataFromBlocks($block);
|
||||
}
|
||||
|
||||
// Удаляем лишние пробелы и переносы строк
|
||||
$result = preg_replace('/\s+/', ' ', $result);
|
||||
$result = trim($result);
|
||||
|
||||
return strtolower($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает данные из блоков контента.
|
||||
*
|
||||
* @param array $block
|
||||
* @return string
|
||||
*/
|
||||
private function getDataFromBlocks(array $block): string
|
||||
{
|
||||
$data = "";
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'heading':
|
||||
$data .= strip_tags($block['data']['content']) . " ";
|
||||
break;
|
||||
case 'files':
|
||||
foreach ($block['data']['file'] as $file) {
|
||||
$data .= $file['title'] . " ";
|
||||
}
|
||||
break;
|
||||
case 'person':
|
||||
$data .= $block['data']['name'] . " ";
|
||||
break;
|
||||
case 'stepper':
|
||||
$data .= $block['data']['step_name'] . " ";
|
||||
foreach ($block['data']['steps'] as $step) {
|
||||
$data .= $step['title'] . " ";
|
||||
$data .= strip_tags($step['content']) . " ";
|
||||
}
|
||||
break;
|
||||
case 'tabs':
|
||||
foreach ($block['data']['tab'] as $item) {
|
||||
foreach ($item['content'] as $block) {
|
||||
$data .= $this->getDataFromBlocks($block);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Рассчитывает время чтения.
|
||||
*
|
||||
* @param string $text
|
||||
* @return int
|
||||
*/
|
||||
private function calculateReadingTime(string $text): int
|
||||
{
|
||||
$wordCount = str_word_count($text, 0, "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя");
|
||||
$wordsPerMinute = 120; // Средняя скорость чтения
|
||||
return max(1, round($wordCount / $wordsPerMinute));
|
||||
}
|
||||
|
||||
/**
|
||||
* Находит первый блок по имени.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $content
|
||||
* @return array|null
|
||||
*/
|
||||
private function getFirstBlockByName(string $name, array $content): ?array
|
||||
{
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Находит блок по SEO-активности.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $content
|
||||
* @return array|null
|
||||
*/
|
||||
private function getBlockBySeoActiveState(string $name, array $content): ?array
|
||||
{
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name && ($block['data']['seo_active'] ?? false)) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Filament\Domain\Posts;
|
||||
|
||||
use App\Filament\Resources\PostResource;
|
||||
use App\Models\Post;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Filament\Notifications\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
|
||||
class PostNotificationService
|
||||
{
|
||||
/**
|
||||
* Отправляет уведомления редакторам о новом посте.
|
||||
*
|
||||
* @param Post $post
|
||||
* @return void
|
||||
*/
|
||||
public function send(Post $post): void
|
||||
{
|
||||
// Находим всех пользователей с ролью "editor"
|
||||
$editors = Role::findByName('editor')->users;
|
||||
|
||||
// Отправляем уведомление каждому редактору
|
||||
foreach ($editors as $editor) {
|
||||
Notification::make()
|
||||
->title('Новость на проверку')
|
||||
->body('Новость "' . $post->title . '" нуждается в проверке')
|
||||
->actions([
|
||||
Action::make('view')
|
||||
->label('Проверить')
|
||||
->button()
|
||||
->markAsRead()
|
||||
->url(PostResource::getUrl('edit', ['record' => $post])),
|
||||
])
|
||||
->sendToDatabase($editor); // Отправляем уведомление конкретному редактору
|
||||
}
|
||||
}
|
||||
|
||||
public function sendSuccessNotification(Post $post): void
|
||||
{
|
||||
$user = User::find($post->user_id);
|
||||
|
||||
Notification::make()
|
||||
->title('Ваша новость опубликована')
|
||||
->body('Новость "' . $post->title . '" опубликована')
|
||||
->actions([
|
||||
Action::make('view')
|
||||
->label('Смотреть')
|
||||
->button()
|
||||
->markAsRead()
|
||||
->url(route('client.post.show', $post->slug)),
|
||||
])
|
||||
->sendToDatabase($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет уведомление об отклонении.
|
||||
*
|
||||
* @param Post $post
|
||||
* @return void
|
||||
*/
|
||||
public function sendDeniedNotification(Post $post): void
|
||||
{
|
||||
$user = User::find($post->user_id);
|
||||
|
||||
Notification::make()
|
||||
->title('Ваша новость отклонена :(')
|
||||
->body('Новость "' . $post->title . '" была отклонена')
|
||||
->actions([
|
||||
Action::make('view')
|
||||
->label('Смотреть')
|
||||
->button()
|
||||
->markAsRead()
|
||||
->url(PostResource::getUrl('edit', ['record' => $post])),
|
||||
])
|
||||
->sendToDatabase($user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Filament\Domain\Posts;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class PostSeoGenerator
|
||||
{
|
||||
/**
|
||||
* Генерирует SEO-данные для поста.
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public function generate(array $data): array
|
||||
{
|
||||
return [
|
||||
'title' => $this->extractSeoTitle($data),
|
||||
'description' => $this->extractSeoDescription($data['content']),
|
||||
'image' => $this->extractSeoImage($data),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает SEO-заголовок.
|
||||
*
|
||||
* @param array $data
|
||||
* @return string
|
||||
*/
|
||||
private function extractSeoTitle(array $data): string
|
||||
{
|
||||
return $data['title'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает SEO-описание.
|
||||
*
|
||||
* @param array $content
|
||||
* @return string
|
||||
*/
|
||||
private function extractSeoDescription(array $content): string
|
||||
{
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $content);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $content);
|
||||
}
|
||||
|
||||
$description = $rowData ? html_entity_decode(strip_tags($rowData['data']['content'])) : '';
|
||||
return Str::limit(htmlspecialchars($description, ENT_QUOTES, 'UTF-8'), 160);
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает SEO-изображение.
|
||||
*
|
||||
* @param array $data
|
||||
* @return string|null
|
||||
*/
|
||||
private function extractSeoImage(array $data): ?string
|
||||
{
|
||||
return $data['preview'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Находит первый блок по имени.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $content
|
||||
* @return array|null
|
||||
*/
|
||||
private function getFirstBlockByName(string $name, array $content): ?array
|
||||
{
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Находит блок по SEO-активности.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $content
|
||||
* @return array|null
|
||||
*/
|
||||
private function getBlockBySeoActiveState(string $name, array $content): ?array
|
||||
{
|
||||
foreach ($content as $block) {
|
||||
if ($block['type'] === $name && ($block['data']['seo_active'] ?? false)) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function setPreviewText(array $data): ?string
|
||||
{
|
||||
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
|
||||
if ($rowData === null) {
|
||||
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
|
||||
}
|
||||
|
||||
if ($rowData !== null) {
|
||||
$previewText = html_entity_decode(strip_tags($rowData['data']['content']));
|
||||
return Str::limit($previewText, 160);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Filament\Domain\Posts;
|
||||
|
||||
use App\Dto\MainSliderDTO;
|
||||
use App\Models\MainSlider;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class PostSliderService
|
||||
{
|
||||
public function __construct(
|
||||
readonly private MainSliderDTO $dto,
|
||||
readonly private string $postSlug,
|
||||
){}
|
||||
|
||||
public function create(): void
|
||||
{
|
||||
try {
|
||||
MainSlider::create([
|
||||
'title' => $this->dto->title,
|
||||
'content' => $this->dto->content,
|
||||
'image' => $this->dto->image,
|
||||
'link' => parse_url(route('client.post.show', $this->postSlug), PHP_URL_PATH),
|
||||
'link_text' => $this->dto->link_text,
|
||||
'is_active' => $this->dto->is_active,
|
||||
'color_theme' => $this->dto->color_theme,
|
||||
'start_time' => $this->dto->start_time,
|
||||
'end_time' => $this->dto->end_time,
|
||||
]);
|
||||
|
||||
Log::info('MainSlider created successfully', ['postSlug' => $this->postSlug]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Failed to create MainSlider', ['error' => $e->getMessage()]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function update(): void
|
||||
{
|
||||
try {
|
||||
MainSlider::update([
|
||||
'title' => $this->dto->title,
|
||||
'content' => $this->dto->content,
|
||||
'image' => $this->dto->image,
|
||||
'link' => parse_url(route('client.post.show', $this->postSlug), PHP_URL_PATH),
|
||||
'link_text' => $this->dto->link_text,
|
||||
'is_active' => $this->dto->is_active,
|
||||
'color_theme' => $this->dto->color_theme,
|
||||
'start_time' => $this->dto->start_time,
|
||||
'end_time' => $this->dto->end_time,
|
||||
]);
|
||||
|
||||
Log::info('MainSlider updated successfully', ['postSlug' => $this->postSlug]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Failed to update MainSlider', ['error' => $e->getMessage()]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Filament\Domain\Posts;
|
||||
|
||||
use App\Enums\PostStatus;
|
||||
use App\Jobs\CreateVkPost;
|
||||
use App\Models\Post;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class VkPostPublisher
|
||||
{
|
||||
/**
|
||||
* Публикует пост в социальных сетях.
|
||||
*
|
||||
* @param array $settings
|
||||
* @param Post $post
|
||||
* @return void
|
||||
*/
|
||||
public function publish(array $settings, Post $post): void
|
||||
{
|
||||
if ($post->status === PostStatus::PUBLISHED) {
|
||||
if ($settings['vk']) {
|
||||
$text = $this->generateContentForVk($post->content);
|
||||
$images = $this->generateImageLinksForVk($post->images);
|
||||
$publishDate = $post->publish_at > now() ? $post->publish_at->timestamp : null;
|
||||
|
||||
dispatch(new CreateVkPost($post->title, $text, $images, $post->id, $publishDate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует текстовый контент для ВКонтакте.
|
||||
*
|
||||
* @param array $content
|
||||
* @return string
|
||||
*/
|
||||
private function generateContentForVk(array $content): string
|
||||
{
|
||||
$text = '';
|
||||
foreach ($content as $block) {
|
||||
switch ($block['type']) {
|
||||
case 'paragraph':
|
||||
$text .= strip_tags($block['data']['content']) . "\n\n";
|
||||
break;
|
||||
case 'heading':
|
||||
$text .= strip_tags($block['data']['content']) . "\n\n";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return trim($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует ссылки на изображения для ВКонтакте.
|
||||
*
|
||||
* @param array $images
|
||||
* @return array
|
||||
*/
|
||||
private function generateImageLinksForVk(array $images): array
|
||||
{
|
||||
return array_map(function ($file) {
|
||||
return Storage::url($file); // Генерируем полный URL для изображения
|
||||
}, $images);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user