Migrate backend to Porto architecture and fix minor bugs

- Fully transitioned the backend to the Porto architectural pattern
- Improved code organization and maintainability
- Fixed minor bugs and inconsistencies
This commit is contained in:
F4ilji
2025-05-12 08:47:43 +05:00
parent 76deaf75f3
commit c01016a154
620 changed files with 16218 additions and 6073 deletions
@@ -0,0 +1,15 @@
<?php
namespace App\Containers\AppStructure\UI\API\Controllers;
use App\Containers\AppStructure\Models\MainSection;
use App\Containers\AppStructure\UI\API\Transformers\NavigationResource;
use App\Ship\Controllers\Controller;
class NavigateController extends Controller
{
public function index()
{
return NavigationResource::collection(MainSection::with('subSections.pages')->orderBy('sort', 'asc')->get());
}
}
@@ -0,0 +1,11 @@
<?php
use App\Containers\AppStructure\UI\API\Controllers\NavigateController;
use Illuminate\Support\Facades\Route;
Route::middleware('ensure.browser')->group(function () {
Route::get('/getNavigation', [NavigateController::class, 'index'])->name('client.main.navigate');
});
@@ -0,0 +1,23 @@
<?php
namespace App\Containers\AppStructure\UI\API\Transformers;
use App\Ship\Resources\JsonResource;
class NavigationResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'subSections' => SubSectionNavigateResource::collection($this->whenLoaded('subSections')->sortBy('sort')),
];
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Containers\AppStructure\UI\API\Transformers;
use App\Ship\Resources\JsonResource;
class PageNavigateResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'path' => $this->path,
'is_url' => $this->is_url,
'icon' => $this->icon
];
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Containers\AppStructure\UI\API\Transformers;
use App\Ship\Resources\JsonResource;
class SubSectionNavigateResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'pages' => PageNavigateResource::collection($this->whenLoaded('pages')),
];
}
}
@@ -0,0 +1,223 @@
<?php
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 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 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) {
return [
'route' => 'page.view',
'params' => ['path' => $page->path],
'lastModificationDate' => $page->updated_at,
'priority' => 0.5,
];
});
}
protected function generatePosts(Sitemap $sitemap)
{
$posts = Post::query()
->where('status', PostStatus::PUBLISHED)
->get();
$this->addUrlsToSitemap($sitemap, $posts, function($post) {
return [
'route' => 'client.post.show',
'params' => ['slug' => $post->slug],
'lastModificationDate' => $post->updated_at,
'priority' => 0.5,
];
});
}
protected function generateDivisions(Sitemap $sitemap)
{
$divisions = Division::query()
->where('is_active', true)
->get();
$this->addUrlsToSitemap($sitemap, $divisions, function($division) {
return [
'route' => 'client.division.show',
'params' => ['slug' => $division->slug],
'lastModificationDate' => $division->updated_at,
'priority' => 0.5,
];
});
}
protected function generateEducationPrograms(Sitemap $sitemap)
{
$programs = EducationalProgram::query()
->where('status', EducationalProgramStatus::PUBLISHED) // Пример условия для активных программ
->get();
$this->addUrlsToSitemap($sitemap, $programs, function($program) {
return [
'route' => 'client.program.show',
'params' => ['slug' => $program->slug],
'lastModificationDate' => $program->updated_at,
'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) {
return [
'route' => 'client.event.show',
'params' => ['slug' => $event->slug],
'lastModificationDate' => $event->updated_at,
'priority' => 0.5,
];
});
}
protected function generateAdditionalEducations(Sitemap $sitemap)
{
$educations = AdditionalEducation::query()
->where('is_active', true) // Пример условия для активных программ
->get();
$this->addUrlsToSitemap($sitemap, $educations, function($education) {
return [
'route' => 'client.additionalEducation.show',
'params' => ['slug' => $education->slug],
'lastModificationDate' => $education->updated_at,
'priority' => 0.5,
];
});
}
protected function generateFaculties(Sitemap $sitemap)
{
$faculties = Faculty::query()
->where('is_active', true) // Пример условия для активных факультетов
->get();
$this->addUrlsToSitemap($sitemap, $faculties, function($faculty) {
return [
'route' => 'client.faculty.show',
'params' => ['slug' => $faculty->slug],
'lastModificationDate' => $faculty->updated_at,
'priority' => 0.5,
];
});
}
protected function generateDepartments(Sitemap $sitemap)
{
$departments = Department::query()
->where('is_active', true) // Пример условия для активных кафедр
->get();
$this->addUrlsToSitemap($sitemap, $departments, function($department) {
return [
'route' => 'client.department.show',
'params' => ['facultySlug' => $department->faculty->slug, 'departmentSlug' => $department->slug],
'lastModificationDate' => $department->updated_at,
'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) {
return [
'route' => 'client.person.show',
'params' => ['slug' => $user->slug],
'lastModificationDate' => $user->updated_at,
'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']));
}
}
}
@@ -0,0 +1,53 @@
<?php
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;
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 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->info('Все маршруты успешно проверены.');
}
}
@@ -0,0 +1,49 @@
<?php
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\Ship\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
class PageController extends Controller
{
public function __construct(readonly SeoServiceInterface $seoPageProvider){}
public function render(string $path): \Inertia\Response
{
// Генерируем уникальный ключ для кеширования
$cacheKey = 'page_' . md5($path);
// Пытаемся получить данные из кеша
$page = Cache::remember($cacheKey, now()->addHours(48), function () use ($path) {
return Page::where('path', '=', $path)
->with('section.pages.section', 'section.mainSection')
->first();
});
if ($page === null) {
abort(404);
}
$subSectionPages = $page->section ? PageResource::collection($page->section->pages) : null;
$seo = $this->seoPageProvider->getSeoForModel($page);
$page = new PageResource($page);
if ($page->code != 200) {
abort($page->code);
}
return inertia()->render('Page', [
'page' => $page,
'subSectionPages' => $subSectionPages,
'seo' => $seo,
]);
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Containers\AppStructure\UI\WEB\Transformers;
use App\Ship\Resources\JsonResource;
class PageResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \App\Ship\Requests\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'slug' => $this->slug,
'code' => $this->code,
'path' => $this->path,
'is_url' => $this->is_url,
'settings' => $this->settings,
'icon' => $this->icon,
'section' => $this->section ? $this->section->title : null,
'created_at' => $this->created_at->diffforhumans()
];
}
}