refactor sitemap generation and navigation handling; remove old GenerateSitemap command, update to use tasks for better organization, and enhance navigation data retrieval

This commit is contained in:
F4ilji
2025-07-18 13:07:51 +05:00
parent 1257cd552c
commit 0874d3e6b5
28 changed files with 461 additions and 475 deletions
@@ -0,0 +1,44 @@
<?php
namespace App\Containers\AppStructure\Actions;
use App\Containers\AppStructure\Models\Page;
use App\Containers\AppStructure\Tasks\FindPageByPathTask;
use App\Containers\AppStructure\UI\WEB\Transformers\PageResource;
use App\Ship\Contracts\SeoServiceInterface;
use Inertia\Response;
class RenderPageAction
{
public function __construct(readonly SeoServiceInterface $seoPageProvider, readonly FindPageByPathTask $findPageByPathTask){}
public function run(string $path): Response
{
$page = $this->findPageByPathTask->run($path);
$this->handleCheckNotFoundStatusCode($page);
$subSectionPages = $page->section ? PageResource::collection($page->section->pages) : null;
$seo = $this->seoPageProvider->getSeoForModel($page);
$pageResource = new PageResource($page);
$this->handlePageStatusCode($pageResource);
return inertia()->render('Page', [
'page' => $pageResource,
'subSectionPages' => $subSectionPages,
'seo' => $seo,
]);
}
private function handlePageStatusCode(PageResource $pageResource): void
{
if ($pageResource->code != 200) {
abort($pageResource->code);
}
}
private function handleCheckNotFoundStatusCode($page): void
{
if ($page === null) {
abort(404);
}
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
class AddUrlsToSitemapTask
{
public function run(Sitemap $sitemap, $items, callable $callback)
{
foreach ($items as $item) {
$urlData = $callback($item);
$url = route($urlData['route'], $urlData['params']);
$sitemap->add(Url::create($url)
->setLastModificationDate($urlData['lastModificationDate'])
->setPriority($urlData['priority']));
}
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\Page;
use Illuminate\Support\Facades\Cache;
class FindPageByPathTask
{
public function run(string $path): ?Page
{
$cacheKey = 'page_' . md5($path);
return Cache::remember($cacheKey, now()->addHours(48), function () use ($path) {
return Page::where('path', '=', $path)
->with('section.pages.section', 'section.mainSection')
->first();
});
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\Page;
use App\Containers\AppStructure\Tasks\FindPageByPathTask;
use App\Containers\AppStructure\Tasks\GeneratePathTask;
use App\Containers\AppStructure\Tasks\GetIndexRouteNameTask;
use App\Ship\Resources\Breadcrumb\ClientBreadcrumbPage;
use App\Ship\Resources\Breadcrumb\ClientBreadcrumbSection;
use App\Ship\Resources\Breadcrumb\ClientBreadcrumbSubSection;
use Illuminate\Support\Facades\Route;
class GenerateBreadcrumbsTask
{
public function __construct(
private readonly GeneratePathTask $generatePathTask,
private readonly GetIndexRouteNameTask $getIndexRouteNameTask,
private readonly FindPageByPathTask $findPageByPathTask
){}
public function run(?string $routeN = null): ?array
{
$routeName = $routeN ?? Route::currentRouteName();
$indexRouteName = $this->getIndexRouteNameTask->run($routeName);
$finalRouteName = Route::has($indexRouteName) ? $indexRouteName : $routeName;
$path = $this->generatePathTask->run($finalRouteName);
if ($path === null) {
return null;
}
$page = $this->findPageByPathTask->run($path);
if (!$page?->section) {
return null;
}
return [
'mainSection' => new ClientBreadcrumbSection($page->section->mainSection),
'subSection' => new ClientBreadcrumbSubSection($page->section),
'page' => new ClientBreadcrumbPage($page),
];
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use Illuminate\Support\Facades\Route;
class GeneratePathTask
{
public function run(?string $routeName): string|null
{
if ($routeName === 'page.view') {
return request()->path();
}
try {
$route = Route::getRoutes()->getByName($routeName);
// Если у маршрута есть обязательные параметры без значений по умолчанию, возвращаем null
if ($route && count($route->parameterNames()) > 0) {
return null;
}
$routeUrl = route($routeName);
return ltrim(parse_url($routeUrl, PHP_URL_PATH), '/');
} catch (\Exception $e) {
return null;
}
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AdditionalEducation\Models\AdditionalEducation;
class GetAdditionalEducationsForSitemapTask
{
public function run()
{
return AdditionalEducation::query()
->where('is_active', true)
->get();
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\MainSection;
use App\Containers\AppStructure\UI\API\Transformers\NavigationResource;
use Illuminate\Support\Facades\Cache;
class GetCachedNavigationDataTask
{
public function run()
{
return Cache::remember('navigation', now()->addHours(1), function () {
return NavigationResource::collection(
MainSection::with('subSections.pages.section')
->orderBy('sort', 'asc')
->get()
);
});
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\InstituteStructure\Models\Department;
class GetDepartmentsForSitemapTask
{
public function run()
{
return Department::query()
->where('is_active', true)
->with('faculty')
->get();
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\InstituteStructure\Models\Division;
class GetDivisionsForSitemapTask
{
public function run()
{
return Division::query()
->where('is_active', true)
->get();
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\Education\Models\EducationalProgram;
use App\Ship\Enums\Education\EducationalProgramStatus;
class GetEducationalProgramsForSitemapTask
{
public function run()
{
return EducationalProgram::query()
->where('status', EducationalProgramStatus::PUBLISHED)
->get();
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\Event\Models\Event;
class GetEventsForSitemapTask
{
public function run()
{
$now = now()->toDateString();
return Event::query()
->where('event_date_end', '>=', $now)
->get();
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\InstituteStructure\Models\Faculty;
class GetFacultiesForSitemapTask
{
public function run()
{
return Faculty::query()
->where('is_active', true)
->get();
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Containers\AppStructure\Tasks;
class GetIndexRouteNameTask
{
public function run(string $routeName = null): ?string
{
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,15 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\MainSection;
class GetNavigationDataTask
{
public function run()
{
return MainSection::with('subSections.pages')
->orderBy('sort', 'asc')
->get();
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\Page;
class GetPagesForSitemapTask
{
public function run()
{
return Page::query()
->where('is_visible', true)
->where('code', 200)
->where('path', '!=', null)
->where('is_url', false)
->where('title', '!=', null)
->where('searchable', true)
->get();
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\Article\Enums\PostStatus;
use App\Containers\Article\Models\Post;
class GetPostsForSitemapTask
{
public function run()
{
return Post::query()
->where('status', PostStatus::PUBLISHED)
->get();
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\User\Models\User;
class GetUsersForSitemapTask
{
public function run()
{
return User::query()
->whereHas('userDetail', function ($q) {
$q->where('is_only_worker', false);
})
->get();
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Containers\AppStructure\Tasks;
use App\Containers\AppStructure\Models\Page;
use Illuminate\Support\Facades\Route;
class RegisterApplicationRoutesTask
{
public function run(): void
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
if (!Page::where('path', '=', $route->uri)->where('is_registered', '=', true)->exists()) {
Page::create([
'path' => $route->uri,
'is_registered' => true,
'is_url' => false,
'searchable' => false,
'code' => 200,
]);
}
}
}
}
@@ -2,14 +2,16 @@
namespace App\Containers\AppStructure\UI\API\Controllers;
use App\Containers\AppStructure\Models\MainSection;
use App\Containers\AppStructure\Tasks\GetNavigationDataTask;
use App\Containers\AppStructure\UI\API\Transformers\NavigationResource;
use App\Ship\Controllers\Controller;
class NavigateController extends Controller
{
public function __construct(private readonly GetNavigationDataTask $getNavigationDataTask){}
public function index()
{
return NavigationResource::collection(MainSection::with('subSections.pages')->orderBy('sort', 'asc')->get());
return NavigationResource::collection($this->getNavigationDataTask->run());
}
}
@@ -3,72 +3,42 @@
namespace App\Containers\AppStructure\UI\CLI\Commands;
use App\Ship\Abstracts\Commands\ConsoleCommand as AbstractConsoleCommand;
use App\Containers\AdditionalEducation\Models\AdditionalEducation;
use App\Containers\AppStructure\Models\Page;
use App\Containers\Article\Enums\PostStatus;
use App\Containers\Article\Models\Post;
use App\Containers\Education\Models\EducationalProgram;
use App\Containers\Event\Models\Event;
use App\Containers\InstituteStructure\Models\Department;
use App\Containers\InstituteStructure\Models\Division;
use App\Containers\InstituteStructure\Models\Faculty;
use App\Containers\User\Models\User;
use App\Ship\Enums\Education\EducationalProgramStatus;
use App\Containers\AppStructure\Tasks\GetPagesForSitemapTask;
use App\Containers\AppStructure\Tasks\GetPostsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetDivisionsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetEducationalProgramsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetEventsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetAdditionalEducationsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetFacultiesForSitemapTask;
use App\Containers\AppStructure\Tasks\GetDepartmentsForSitemapTask;
use App\Containers\AppStructure\Tasks\GetUsersForSitemapTask;
use App\Containers\AppStructure\Tasks\AddUrlsToSitemapTask;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
class GenerateSitemap extends AbstractConsoleCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Генерирует карту сайта';
/**
* Execute the console command.
*
* @return int
*/
public function __construct(
private readonly GetPagesForSitemapTask $getPagesForSitemapTask,
private readonly GetPostsForSitemapTask $getPostsForSitemapTask,
private readonly GetDivisionsForSitemapTask $getDivisionsForSitemapTask,
private readonly GetEducationalProgramsForSitemapTask $getEducationalProgramsForSitemapTask,
private readonly GetEventsForSitemapTask $getEventsForSitemapTask,
private readonly GetAdditionalEducationsForSitemapTask $getAdditionalEducationsForSitemapTask,
private readonly GetFacultiesForSitemapTask $getFacultiesForSitemapTask,
private readonly GetDepartmentsForSitemapTask $getDepartmentsForSitemapTask,
private readonly GetUsersForSitemapTask $getUsersForSitemapTask,
private readonly AddUrlsToSitemapTask $addUrlsToSitemapTask
) {parent::__construct();}
public function handle()
{
$sitemap = Sitemap::create();
// Генерация карты сайта для всех моделей
$this->generatePages($sitemap);
$this->generatePosts($sitemap);
$this->generateDivisions($sitemap);
$this->generateEducationPrograms($sitemap); // Добавляем генерацию для EducationProgram
$this->generateEvents($sitemap); // Добавляем генерацию для Event
$this->generateAdditionalEducations($sitemap); // Добавляем генерацию для AdditionalEducation
$this->generateFaculties($sitemap); // Добавляем генерацию для Faculty
$this->generateDepartments($sitemap); // Добавляем генерацию для Department
$this->generateUsers($sitemap); // Добавляем генерацию для User
// Сохраняем карту сайта в файл
$sitemap->writeToFile(public_path('sitemap.xml'));
}
protected function generatePages(Sitemap $sitemap)
{
$pages = Page::query()
->where('is_visible', true)
->where('code', 200)
->where('path', '!=', null)
->where('is_url', false)
->where('title', '!=', null)
->where('searchable', true)
->get();
$this->addUrlsToSitemap($sitemap, $pages, function($page) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getPagesForSitemapTask->run(), function($page) {
return [
'route' => 'page.view',
'params' => ['path' => $page->path],
@@ -76,15 +46,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generatePosts(Sitemap $sitemap)
{
$posts = Post::query()
->where('status', PostStatus::PUBLISHED)
->get();
$this->addUrlsToSitemap($sitemap, $posts, function($post) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getPostsForSitemapTask->run(), function($post) {
return [
'route' => 'client.post.show',
'params' => ['slug' => $post->slug],
@@ -92,15 +55,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateDivisions(Sitemap $sitemap)
{
$divisions = Division::query()
->where('is_active', true)
->get();
$this->addUrlsToSitemap($sitemap, $divisions, function($division) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getDivisionsForSitemapTask->run(), function($division) {
return [
'route' => 'client.division.show',
'params' => ['slug' => $division->slug],
@@ -108,15 +64,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateEducationPrograms(Sitemap $sitemap)
{
$programs = EducationalProgram::query()
->where('status', EducationalProgramStatus::PUBLISHED) // Пример условия для активных программ
->get();
$this->addUrlsToSitemap($sitemap, $programs, function($program) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getEducationalProgramsForSitemapTask->run(), function($program) {
return [
'route' => 'client.program.show',
'params' => ['slug' => $program->slug],
@@ -124,17 +73,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateEvents(Sitemap $sitemap)
{
$now = now()->toDateString(); // Текущая дата
$events = Event::query()
->where('event_date_end', '>=', $now) // Только актуальные события
->get();
$this->addUrlsToSitemap($sitemap, $events, function($event) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getEventsForSitemapTask->run(), function($event) {
return [
'route' => 'client.event.show',
'params' => ['slug' => $event->slug],
@@ -142,15 +82,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateAdditionalEducations(Sitemap $sitemap)
{
$educations = AdditionalEducation::query()
->where('is_active', true) // Пример условия для активных программ
->get();
$this->addUrlsToSitemap($sitemap, $educations, function($education) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getAdditionalEducationsForSitemapTask->run(), function($education) {
return [
'route' => 'client.additionalEducation.show',
'params' => ['slug' => $education->slug],
@@ -158,15 +91,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateFaculties(Sitemap $sitemap)
{
$faculties = Faculty::query()
->where('is_active', true) // Пример условия для активных факультетов
->get();
$this->addUrlsToSitemap($sitemap, $faculties, function($faculty) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getFacultiesForSitemapTask->run(), function($faculty) {
return [
'route' => 'client.faculty.show',
'params' => ['slug' => $faculty->slug],
@@ -174,15 +100,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateDepartments(Sitemap $sitemap)
{
$departments = Department::query()
->where('is_active', true) // Пример условия для активных кафедр
->get();
$this->addUrlsToSitemap($sitemap, $departments, function($department) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getDepartmentsForSitemapTask->run(), function($department) {
return [
'route' => 'client.department.show',
'params' => ['facultySlug' => $department->faculty->slug, 'departmentSlug' => $department->slug],
@@ -190,17 +109,8 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function generateUsers(Sitemap $sitemap)
{
$users = User::query()
->whereHas('userDetail', function ($q) {
$q->where('is_only_worker', false);
})
->get();
$this->addUrlsToSitemap($sitemap, $users, function($user) {
$this->addUrlsToSitemapTask->run($sitemap, $this->getUsersForSitemapTask->run(), function($user) {
return [
'route' => 'client.person.show',
'params' => ['slug' => $user->slug],
@@ -208,16 +118,7 @@ class GenerateSitemap extends AbstractConsoleCommand
'priority' => 0.5,
];
});
}
protected function addUrlsToSitemap(Sitemap $sitemap, $items, callable $callback)
{
foreach ($items as $item) {
$urlData = $callback($item);
$url = route($urlData['route'], $urlData['params']);
$sitemap->add(Url::create($url)
->setLastModificationDate($urlData['lastModificationDate'])
->setPriority($urlData['priority']));
}
$sitemap->writeToFile(public_path('sitemap.xml'));
}
}
@@ -3,51 +3,19 @@
namespace App\Containers\AppStructure\UI\CLI\Commands;
use App\Ship\Abstracts\Commands\ConsoleCommand as AbstractConsoleCommand;
use App\Containers\AppStructure\Models\Page;
use Illuminate\Support\Facades\Route;
use App\Containers\AppStructure\Tasks\RegisterApplicationRoutesTask;
class RegisterRoutes extends AbstractConsoleCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'routes:register';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Register application routes in the database';
/**
* Execute the console command.
*
* @return int
*/
public function __construct(private readonly RegisterApplicationRoutesTask $registerApplicationRoutesTask)
{parent::__construct();}
public function handle()
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
// Проверяем, существует ли маршрут в базе данных
if (!Page::where('path', '=', $route->uri)->where('is_registered', '=', true)->exists()) {
// Если не существует, создаем новую запись
Page::create([
'path' => $route->uri,
'is_registered' => true,
'is_url' => false,
'searchable' => false,
'code' => 200,
]);
$this->info("Маршрут зарегистрирован: " . $route->uri);
} else {
$this->info("Маршрут уже существует: " . $route->uri);
}
}
$this->registerApplicationRoutesTask->run();
$this->info('Все маршруты успешно проверены.');
}
}
@@ -2,55 +2,16 @@
namespace App\Containers\AppStructure\UI\WEB\Controllers;
use App\Containers\AppStructure\Models\Page;
use App\Containers\AppStructure\UI\WEB\Transformers\PageResource;
use App\Ship\Contracts\SeoServiceInterface;
use App\Containers\AppStructure\Actions\RenderPageAction;
use App\Ship\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Inertia\Response;
class PageController extends Controller
{
public function __construct(readonly SeoServiceInterface $seoPageProvider){}
public function __construct(private readonly RenderPageAction $renderPageAction){}
public function render(string $path): Response
{
$page = $this->getPageByPath($path);
$this->handleCheckNotFoundStatusCode($page);
$subSectionPages = $page->section ? PageResource::collection($page->section->pages) : null;
$seo = $this->seoPageProvider->getSeoForModel($page);
$pageResource = new PageResource($page);
$this->handlePageStatusCode($pageResource);
return inertia()->render('Page', [
'page' => $pageResource,
'subSectionPages' => $subSectionPages,
'seo' => $seo,
]);
}
private function handlePageStatusCode(PageResource $pageResource): void
{
if ($pageResource->code != 200) {
abort($pageResource->code);
}
}
private function handleCheckNotFoundStatusCode($page): void
{
if ($page === null) {
abort(404);
}
}
public function getPageByPath(string $path): ?Page
{
$cacheKey = 'page_' . md5($path);
return Cache::remember($cacheKey, now()->addHours(48), function () use ($path) {
return Page::where('path', '=', $path)
->with('section.pages.section', 'section.mainSection')
->first();
});
return $this->renderPageAction->run($path);
}
}