Files
citrus-cms/app/Functions/resolve-module-from-table.php
2026-04-28 21:14:25 +03:00

78 lines
3.0 KiB
PHP

<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
if (!function_exists('resolveModuleFromTable')) {
/**
* Attempts to find the original module slug from a given table name.
* Uses type configuration, naming conventions, and parses blade files as a fallback.
*
* @param string $tableName
* @return string
*/
function resolveModuleFromTable($tableName)
{
if (empty($tableName)) {
return $tableName;
}
// Cache the result to avoid reading files repeatedly
$cacheKey = "module_slug_for_table_" . md5($tableName);
return Cache::remember($cacheKey, 3600, function () use ($tableName) {
// Priority 1: Check types.slug explicitly
$typeBySlug = DB::table('types')->where('slug', $tableName)->first();
if ($typeBySlug) {
return $typeBySlug->slug;
}
// Priority 2: Check types.table_name explicitly (best match for API table params)
if (Schema::hasColumn('types', 'table_name')) {
$typeByTableName = DB::table('types')
->where('table_name', $tableName)
->first();
if ($typeByTableName) {
return $typeByTableName->slug;
}
}
// Priority 3: Read blade files to find $tableName definition (like in MobileTypeController)
$types = DB::table('types')->get();
foreach ($types as $type) {
$bladePath = resource_path("views/admin/type/{$type->slug}.blade.php");
if (File::exists($bladePath)) {
$content = File::get($bladePath);
if (preg_match('/\$tableName\s*=\s*["\']([^"\']+)["\']\s*;/', $content, $matches)) {
$foundTable = $matches[1];
if ($foundTable === $tableName) {
return $type->slug;
}
}
}
}
// Priority 4: Try some simple naming conventions
if (\Illuminate\Support\Str::contains($tableName, '_')) {
$guessedSlug = str_replace('_', '-', $tableName);
$typeByGuessedSlug = DB::table('types')->where('slug', $guessedSlug)->first();
if ($typeByGuessedSlug) {
return $typeByGuessedSlug->slug;
}
$guessedSlugSingular = \Illuminate\Support\Str::slug(\Illuminate\Support\Str::singular($tableName));
$typeByGuessedSingular = DB::table('types')->where('slug', $guessedSlugSingular)->first();
if ($typeByGuessedSingular) {
return $typeByGuessedSingular->slug;
}
}
// Fallback: return the original string
return $tableName;
});
}
}