Rework admin panel and other

This commit is contained in:
F4ilji
2025-04-02 18:37:20 +05:00
parent 49072e50c7
commit 5cd6ff11b5
198 changed files with 9715 additions and 6664 deletions
@@ -7,34 +7,71 @@ use App\Http\Resources\ClientBreadcrumbSection;
use App\Http\Resources\ClientBreadcrumbSubSection;
use App\Models\Page;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
class BreadcrumbService
{
public function generateBreadcrumbs($routeName) : array|null
public function generateBreadcrumbs(): ?array
{
$path = $this->generatePath($routeName);
$routeName = Route::currentRouteName();
// Кешируем страницу
$page = Cache::remember('page_' . $path, now()->addHours(1), function () use ($path) {
return Page::where('path', '=', $path)->with('section.pages.section', 'section.mainSection')->first();
});
if (isset($page->section)) {
$breadcrumbs = [
'mainSection' => new ClientBreadcrumbSection($page->section->mainSection),
'subSection' => new ClientBreadcrumbSubSection($page->section),
'page' => new ClientBreadcrumbPage($page),
];
} else {
$breadcrumbs = null;
// Пытаемся найти index-версию маршрута
$indexRouteName = $this->getIndexRouteName($routeName);
if ($indexRouteName === null) {
return null;
}
return $breadcrumbs;
// Используем index-версию, если она существует
$finalRouteName = Route::has($indexRouteName) ? $indexRouteName : $routeName;
$path = $this->generatePath($finalRouteName);
$page = Cache::remember('page_' . $path, now()->addHours(1), function () use ($path) {
return Page::where('path', $path)
->with('section.pages.section', 'section.mainSection')
->first();
});
if (!$page?->section) {
return null;
}
return [
'mainSection' => new ClientBreadcrumbSection($page->section->mainSection),
'subSection' => new ClientBreadcrumbSubSection($page->section),
'page' => new ClientBreadcrumbPage($page),
];
}
private function generatePath($routeName) : string
private function generatePath(string $routeName): string
{
if ($routeName === 'page.view') {
return request()->path();
}
$routeUrl = route($routeName);
return ltrim(parse_url($routeUrl, PHP_URL_PATH), '/');
}
private function getIndexRouteName(string $routeName = null): string|null
{
if ($routeName === null) {
return null;
}
$parts = explode('.', $routeName);
// Если в маршруте нет точек или он уже заканчивается на index
if (count($parts) <= 1 || end($parts) === 'index') {
return $routeName;
}
// Заменяем последнюю часть на index
$parts[count($parts) - 1] = 'index';
return implode('.', $parts);
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\AcademicJournal;
use Illuminate\Support\Facades\Cache;
class AcademicJournalCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof AcademicJournal) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::ACADEMIC_JOURNAL_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::ACADEMIC_JOURNALS_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\AdditionalEducation;
use Illuminate\Support\Facades\Cache;
class AdditionalEducationCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof AdditionalEducation) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::ADDITIONAL_EDUCATIONAL_PROGRAM_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::ADDITIONAL_EDUCATIONAL_PROGRAMS_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -2,48 +2,30 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
class CategoryCacheService extends AbstractCacheService implements CacheInterface
{
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
*/
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$this->clearAllCacheByModel();
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix('categories*');
$this->clearCacheByPrefix('category_content_*');
$this->clearCacheByPrefix(CacheKeys::CATEGORIES_PREFIX->value.'*');
}
/**
* Получает кешированные данные по ключу.
*
* @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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\ContactWidget;
use Illuminate\Support\Facades\Cache;
class ContactWidgetCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof ContactWidget) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::CONTACT_WIDGET_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::CONTACT_WIDGETS_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\Department;
use Illuminate\Support\Facades\Cache;
class DepartmentCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof Department) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::DEPARTMENT_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::DEPARTMENTS_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Services\App\Cache;
use App\Models\Division;
use Illuminate\Support\Facades\Cache;
class DivisionCacheService extends AbstractCacheService implements CacheInterface
{
private const CACHE_PREFIX = 'division_';
private const ALL_CACHE_KEY = 'division_all';
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof Division) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(self::CACHE_PREFIX.'*');
$this->clearAllDivisionsCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
public function getCacheKey(int $id): string
{
return self::CACHE_PREFIX . $id;
}
public function getAllCacheKey(): string
{
return self::ALL_CACHE_KEY;
}
private function forgetDivisionCache(int $id): void
{
Cache::forget($this->getCacheKey($id));
}
private function clearAllDivisionsCache(): void
{
Cache::forget(self::ALL_CACHE_KEY);
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\EducationalProgram;
use Illuminate\Support\Facades\Cache;
class EducationalProgramCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof EducationalProgram) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::EDUCATION_PROGRAMS_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::EDUCATION_PROGRAM_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
public function getCacheKey(int $id): string
{
return CacheKeys::EDUCATION_PROGRAM_PREFIX->value . $id;
}
private function forgetProgramCache(int $id): void
{
Cache::forget($this->getCacheKey($id));
}
private function clearAllProgramsCache(): void
{
Cache::forget(CacheKeys::EDUCATION_PROGRAMS_PREFIX->value . '*');
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\Event;
use Illuminate\Support\Facades\Cache;
class EventCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof Event) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::EVENT_PREFIX->value.'*');
$this->clearAllEventsCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearAllEventsCache(): void
{
Cache::forget(CacheKeys::EVENTS_PREFIX->value.'*');
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\Faculty;
use Illuminate\Support\Facades\Cache;
class FacultyCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof Faculty) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::FACULTY_PREFIX->value.'*');
$this->clearAllFacultiesCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearAllFacultiesCache(): void
{
Cache::forget(CacheKeys::FACULTIES_PREFIX->value.'*');
}
}
@@ -2,43 +2,36 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
class MainSectionCacheService extends AbstractCacheService implements CacheInterface
{
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
*/
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$this->clearCacheByPrefix('posts_');
$this->clearNavigationCache();
}
public function clearAllCacheByModel(): void
{
$this->clearNavigationCache();
}
/**
* Получает кешированные данные по ключу.
*
* @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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearNavigationCache(): void
{
Cache::forget(CacheKeys::NAVIGATION_PREFIX->value);
}
}
@@ -1,48 +0,0 @@
<?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 -38
View File
@@ -2,62 +2,42 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\Page;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
class PageCacheService extends AbstractCacheService implements CacheInterface
{
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
*/
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$cacheKeyByPath = md5($entity->path);
$cacheKeyById = md5($entity->id);
Cache::forget('page_' . $cacheKeyByPath);
Cache::forget('page_' . $cacheKeyById);
Cache::forget('navigation');
if ($entity instanceof Page) {
$this->clearAllCacheByModel();
$this->clearNavigationCache();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix('page_*');
$this->clearCacheByPrefix('page_data_*');
Cache::forget('navigation');
$this->clearCacheByPrefix(CacheKeys::PAGE_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::PAGE_DATA_PREFIX->value.'*');
$this->clearNavigationCache();
}
/**
* Получает кешированные данные по ключу.
*
* @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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearNavigationCache(): void
{
Cache::forget(CacheKeys::NAVIGATION_PREFIX->value);
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\PageReferenceList;
use Illuminate\Support\Facades\Cache;
class PageReferenceListCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof PageReferenceList) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::PAGE_REFERENCE_LIST_PREFIX->value.'*');
$this->clearAllReferencesCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearAllReferencesCache(): void
{
Cache::forget(CacheKeys::PAGE_REFERENCE_LISTS_PREFIX->value.'*');
}
}
+31 -34
View File
@@ -2,59 +2,56 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
class PostCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
* Clear cache for specific post
*/
public function clearCache($entity): void
{
$cacheKeyBySlug = md5($entity->slug);
$cacheKeyById = md5($entity->id);
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*');
$this->forgetPostCache($entity->slug, $entity->id);
$this->clearRecentPostsCache();
}
/**
* Получает кешированные данные по ключу.
*
* @param string $key Ключ кеша
* @return mixed
* Clear all cache related to posts
*/
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::POST_PREFIX->value.'*');
$this->clearCacheByPrefix(CacheKeys::POSTS_PREFIX->value.'*');
$this->clearRecentPostsCache();
}
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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
/**
* Forget cache for specific post by slug and id
*/
private function forgetPostCache(string $slug, int $id): void
{
Cache::forget(CacheKeys::POST_PREFIX->value.md5($slug));
Cache::forget(CacheKeys::POST_PREFIX->value.md5($id));
}
/**
* Clear recent posts cache
*/
private function clearRecentPostsCache(): void
{
$this->clearCacheByPrefix(CacheKeys::RECENT_POSTS_PREFIX->value.'*');
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\Schedule;
use Illuminate\Support\Facades\Cache;
class ScheduleCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof Schedule) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::SCHEDULE_PREFIX->value.'*');
$this->clearAllSchedulesCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function forgetScheduleCache(int $id): void
{
Cache::forget($this->getCacheKey($id));
}
private function clearAllSchedulesCache(): void
{
Cache::forget(CacheKeys::SCHEDULES_PREFIX->value);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
class SliderCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$this->clearAllCacheByModel();
}
public function clearAllCacheByModel(): void
{
$this->clearSliderCache();
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearSliderCache(): void
{
$this->clearCacheByPrefix(CacheKeys::SLIDER_PREFIX->value.'*');
}
}
@@ -2,42 +2,38 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
class SubSectionCacheService extends AbstractCacheService implements CacheInterface
{
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
*/
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$this->clearCacheByPrefix('posts_');
$this->clearAllCacheByModel();
}
public function clearAllCacheByModel(): void
{
$this->clearNavigationCache();
}
/**
* Получает кешированные данные по ключу.
*
* @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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearNavigationCache(): void
{
Cache::forget(CacheKeys::NAVIGATION_PREFIX->value);
}
}
+24 -26
View File
@@ -2,49 +2,47 @@
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use Illuminate\Support\Facades\Cache;
class TagCacheService extends AbstractCacheService implements CacheInterface
{
/**
* Очищает кеш, связанный с постом.
*
* @param mixed $entity Пост или связанная сущность
* @return void
*/
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
$this->clearAllCacheByModel();
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix('tag_ids*');
$this->clearCacheByPrefix('tags*');
$this->clearCacheByPrefix('tag_content_*');
$this->clearTagIdsCache();
$this->clearTagsCache();
$this->clearTagContentCache();
}
/**
* Получает кешированные данные по ключу.
*
* @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
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl);
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
private function clearTagIdsCache(): void
{
$this->clearCacheByPrefix(CacheKeys::TAG_IDS_PREFIX->value.'*');
}
private function clearTagsCache(): void
{
$this->clearCacheByPrefix(CacheKeys::TAGS_PREFIX->value.'*');
}
private function clearTagContentCache(): void
{
$this->clearCacheByPrefix(CacheKeys::TAG_CONTENT_PREFIX->value.'*');
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Services\App\Cache;
use App\Enums\CacheKeys;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
class UserCacheService extends AbstractCacheService implements CacheInterface
{
private const DEFAULT_TTL = 3600;
public function clearCache($entity): void
{
if ($entity instanceof User) {
$this->clearAllCacheByModel();
}
}
public function clearAllCacheByModel(): void
{
$this->clearCacheByPrefix(CacheKeys::USER_PREFIX->value.'*');
}
public function getCachedData(string $key)
{
return Cache::get($key);
}
public function cacheData(string $key, $data, int $ttl = null): void
{
Cache::put($key, $data, $ttl ?? self::DEFAULT_TTL);
}
}
@@ -0,0 +1,8 @@
<?php
namespace App\Services\App\Seo;
interface SeoDescriptionInterface
{
public function getSeoDescription(): array;
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Services\App\Seo;
use App\Enums\CacheKeys;
use App\Models\Page;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
class SeoPageProvider
{
public function getSeoForModel(Model $model): ?array
{
return $model->seo?->toArray();
}
public function getSeoForCurrentPage(): ?array
{
$path = $this->getCurrentPath();
$page = Cache::remember(
CacheKeys::PAGE_PREFIX->value . $path,
now()->addHours(1),
fn() => Page::where('path', $path)->first()
);
return $page->seo?->toArray(); // Предполагается, что у модели Page есть поле `seo` (JSON или массив)
}
private function getCurrentPath(): string
{
if (Route::currentRouteName() === 'page.view') {
return request()->path();
}
$routeUrl = route(Route::currentRouteName());
return ltrim(parse_url($routeUrl, PHP_URL_PATH), '/');
}
}
@@ -5,6 +5,7 @@ namespace App\Services\Filament\Domain\Posts;
use App\Dto\MainSliderDTO;
use App\Models\MainSlider;
use App\Models\Post;
use App\Models\Slide;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
@@ -23,7 +24,8 @@ class PostSliderService
public function create(): void
{
try {
$this->post->mainSlider()->create([
$post = Post::find($this->post->id);
$slide = new Slide([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
@@ -33,11 +35,13 @@ class PostSliderService
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
'slider_id' => $this->dto->slider_id,
]);
$post->slide()->save($slide);
Log::info('MainSlider created successfully', ['postTitle' => $this->post->title]);
Log::info('Slide created successfully', ['postTitle' => $this->post->title]);
} catch (\Exception $e) {
Log::error('Failed to create MainSlider', [
Log::error('Failed to create slide', [
'postTitle' => $this->post->title,
'error' => $e->getMessage(),
]);
@@ -53,31 +57,20 @@ class PostSliderService
public function update(): void
{
try {
// Retrieve the MainSlider instance
$mainSlider = $this->post->mainSlider;
$post = Post::find($this->post->id);
$post->slide()->update([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
'link' => $this->generatePostLink(),
'settings' => $this->dto->settings,
'color_theme' => $this->dto->color_theme,
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
'slider_id' => $this->dto->slider_id,
]);
if ($mainSlider) {
// Update properties and save to trigger model events
$mainSlider->fill([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
'link' => $this->generatePostLink(),
'settings' => $this->dto->settings,
'color_theme' => $this->dto->color_theme,
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
]);
$mainSlider->save(); // This will trigger updating and updated observer events
Log::info('MainSlider updated successfully', ['postTitle' => $this->post->title]);
} else {
Log::warning('MainSlider not found for update', ['postTitle' => $this->post->title]);
}
} catch (\Exception $e) {
Log::error('Failed to update MainSlider', [
'postTitle' => $this->post->title,
@@ -0,0 +1,95 @@
<?php
namespace App\Services\Filament\Domain\Seo;
use Illuminate\Support\Str;
class SeoGeneratorService
{
/**
*
* @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;
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Services\Filament\Services;
use DiDom\Document;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class BreadcrumbFinderService
{
const FILES_DIR = 'sveden';
public function isSameCategory($html)
{
return $this->getBreadcrumb($html);
}
private function getBreadcrumb(string $html): ?string
{
$document = new Document($html);
$breadcrumbs = $document->first('ol.breadcrumb')?->find('li') ?? [];
foreach ($breadcrumbs as $index => $breadcrumb) {
if ($index === 2) { // Индексация с 0 → третий элемент = 2
return $breadcrumb->text();
}
}
return null;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Services\Filament\Services;
use DiDom\Document;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class CategoryFinderService
{
const FILES_DIR = 'sveden';
public function getCategories()
{
$file = public_path(self::FILES_DIR . '/' . 'index.html');
$html = file_get_contents($file);
$document = new Document($html);
$dropdownMenu = $document->first('ul.dropdown-menu');
$links = $dropdownMenu->find('a');
$categories = [];
foreach ($links as $link) {
$category = trim($link->text());
$categories[] = $category;
}
return $categories;
}
}
@@ -0,0 +1,198 @@
<?php
namespace App\Services\Filament\Services;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class StaticFileSearch
{
const CACHE_KEY = 'static_html_index_v2';
const FILES_DIR = 'sveden';
const CACHE_TTL = 86400; // 24 часа
const PER_PAGE = 10; // Количество результатов на страницу
public function search(string $query): array
{
if ($query === null) {
return [
'data' => null
];
}
$page = request()->input('page', 1);
try {
$index = $this->getIndex();
$results = [];
$normalizedQuery = $this->normalizeText(Str::lower($query));
foreach ($index as $filePath => $content) {
if (stripos($content['content'], $normalizedQuery) !== false) {
$relativePath = str_replace(public_path() . '/', '', $filePath);
$results[] = [
'file' => $relativePath,
'content' => $content['title'],
'category' => trim($content['category']),
];
}
}
return $this->paginateResults($results, $page);
} catch (\Exception $e) {
Log::error('Search error: ' . $e->getMessage());
return [
'data' => [],
'meta' => [
'current_page' => 1,
'total' => 0,
'per_page' => self::PER_PAGE,
'last_page' => 1
]
];
}
}
protected function paginateResults(array $results, int $page): array
{
$total = count($results);
$lastPage = max(1, ceil($total / self::PER_PAGE));
$page = max(1, min($page, $lastPage));
$offset = ($page - 1) * self::PER_PAGE;
$paginatedResults = array_slice($results, $offset, self::PER_PAGE);
return [
'data' => $paginatedResults,
'meta' => [
'current_page' => $page,
'total' => $total,
'per_page' => self::PER_PAGE,
'last_page' => $lastPage
]
];
}
protected function getIndex(): array
{
return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function() {
try {
$index = [];
$directory = public_path(self::FILES_DIR);
if (!is_dir($directory)) {
Log::error("Directory not found: {$directory}");
return [];
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $this->isHtmlFile($file)) {
$content = file_get_contents($file->getPathname());
if ($content !== false) {
$breadcrumb = app(BreadcrumbFinderService::class)->isSameCategory($content);
$text = $this->normalizeText(strip_tags($content));
$index[$file->getPathname()] = [
'title' => $this->getFirstH1Content($content),
'content' => $text,
'category' => $breadcrumb ?? null,
];
}
}
}
return $index;
} catch (\Exception $e) {
Log::error('Index creation error: ' . $e->getMessage());
return [];
}
});
}
protected function isHtmlFile(\SplFileInfo $file): bool
{
$extension = strtolower($file->getExtension());
return in_array($extension, ['html', 'htm']);
}
protected function normalizeText(string $text): string
{
$text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = preg_replace('/\s+/u', ' ', $text);
$text = trim($text);
return Str::lower($text);
}
protected function findMatches(string $content, string $query): array
{
$matches = [];
$offset = 0;
$query = Str::lower($query);
$content = Str::lower($content);
$queryLength = mb_strlen($query, 'UTF-8');
while (($offset = mb_strpos($content, $query, $offset, 'UTF-8')) !== false) {
$start = max(0, $offset - 50);
$length = min(150, mb_strlen($content) - $start);
$excerpt = mb_substr($content, $start, $length, 'UTF-8');
$matches[] = str_replace(
$query,
'[[HIGHLIGHT]]'.$query.'[[/HIGHLIGHT]]',
$excerpt
);
$offset += $queryLength;
}
return $matches;
}
public function clearCache(): bool
{
try {
Cache::forget(self::CACHE_KEY);
return true;
} catch (\Exception $e) {
Log::error('Cache clear error: ' . $e->getMessage());
return false;
}
}
public function rebuildIndex(): array
{
$this->clearCache();
return $this->getIndex();
}
public function getCacheStatus(): array
{
return [
'exists' => Cache::has(self::CACHE_KEY),
'ttl' => Cache::get(self::CACHE_KEY.'_ttl', null),
'driver' => config('cache.default'),
'path' => public_path(self::FILES_DIR),
'directory_exists' => is_dir(public_path(self::FILES_DIR))
];
}
public function getFirstH1Content(string $content): ?string
{
try {
if (preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $content, $matches)) {
return $this->normalizeText($matches[1]);
}
return null;
} catch (\Exception $e) {
Log::error('Failed to get H1: ' . $e->getMessage());
return null;
}
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Services\Filament\Traits;
use App\Services\App\Seo\SeoDescriptionInterface;
use App\Services\Filament\Domain\Seo\SeoGeneratorService;
trait SeoGenerate
{
public function createSeo($record): void
{
$record->seo()->create($this->generateSeo($record));
}
public function updateSeo($record): void
{
if ($record->seo()->exists()) {
$record->seo()->update($this->generateSeo($record));
} else {
$this->createSeo($record);
}
}
private function generateSeo($record) {
return app(SeoGeneratorService::class)->generate([
'title' => $record->title,
'content' => $record instanceof SeoDescriptionInterface
? $record->getSeoDescription()
: $record->content,
'preview' => $record->preview,
]);
}
}