Files
citrus-cms/app/Services/JointTypeService.php
T
2026-04-28 21:14:25 +03:00

127 lines
3.3 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class JointTypeService
{
private const CACHE_KEY = 'joint_types.normalized';
private const CACHE_TTL = 3600;
public function mechanicalTypes(): array
{
return $this->all()
->where('is_mechanical', true)
->pluck('short_name_en')
->values()
->all();
}
public function weldedTypes(): array
{
return $this->all()
->where('is_welded', true)
->pluck('short_name_en')
->values()
->all();
}
public function hasNdtTypes(): array
{
return $this->all()
->where('has_ndt', true)
->pluck('short_name_en')
->values()
->all();
}
public function requiresNdt(?string $code): bool
{
if (!$code) {
return false;
}
return in_array($code, $this->hasNdtTypes(), true);
}
public function isMechanical(?string $code): bool
{
if (!$code) {
return false;
}
return in_array($code, $this->mechanicalTypes(), true);
}
public function isWelded(?string $code): bool
{
if (!$code) {
return false;
}
return in_array($code, $this->weldedTypes(), true);
}
/**
* @param EloquentBuilder|QueryBuilder $query
* @return EloquentBuilder|QueryBuilder
*/
public function filterWelded($query, string $column = 'type_of_welds')
{
return $this->applyFilter($query, $this->weldedTypes(), $column);
}
/**
* @param EloquentBuilder|QueryBuilder $query
* @return EloquentBuilder|QueryBuilder
*/
public function filterMechanical($query, string $column = 'type_of_welds')
{
return $this->applyFilter($query, $this->mechanicalTypes(), $column);
}
public function clearCache(): void
{
Cache::forget(self::CACHE_KEY);
}
private function all(): Collection
{
return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function () {
return DB::table('joint_types')
->select([
'short_name_en',
DB::raw('COALESCE(is_mechanical, 0) as is_mechanical'),
DB::raw('COALESCE(is_welded, 0) as is_welded'),
DB::raw('COALESCE(has_ndt, 0) as has_ndt'),
])
->get()
->map(function ($row) {
$row->is_mechanical = (bool) $row->is_mechanical;
$row->is_welded = (bool) $row->is_welded;
$row->has_ndt = (bool) $row->has_ndt;
return $row;
});
});
}
/**
* @param EloquentBuilder|QueryBuilder $query
* @return EloquentBuilder|QueryBuilder
*/
private function applyFilter($query, array $values, string $column)
{
if ($query instanceof EloquentBuilder || $query instanceof QueryBuilder) {
return $query->whereIn($column, $values);
}
throw new \InvalidArgumentException('Unsupported query type for joint type filtering.');
}
}