This commit is contained in:
f4ilji
2025-01-30 00:31:40 +05:00
parent bad611eb84
commit 3385dc5807
60 changed files with 1811 additions and 825 deletions
+47 -1
View File
@@ -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)
]),
]),
]);
+69 -22
View File
@@ -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),
]),
-2
View File
@@ -44,8 +44,6 @@ class PageResource extends Resource
protected static ?string $pluralLabel = 'Страницы';
public static ?string $label = 'Страница';
protected static ?string $navigationGroup = 'Структура приложения';
+5 -1
View File
@@ -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 [
-1
View File
@@ -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),