spt-items-api/app/Data/ItemsCollection.php

70 lines
2.1 KiB
PHP

<?php
namespace App\Data;
use App\Exceptions\ItemNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class ItemsCollection
{
protected Collection $items;
protected Collection $locale;
public function __construct()
{
if (!Cache::has('items')) {
$file = storage_path('items.json');
$this->items = collect(json_decode(file_get_contents($file), true)['data']);
Cache::put('items', $this->items);
} else {
$this->items = Cache::get('items');
}
if (!Cache::has('locale')) {
$file = storage_path('locale.json');
$this->locale = collect(json_decode(file_get_contents($file), true)['templates']);
Cache::put('locale', $this->locale);
} else {
$this->locale = Cache::get('locale');
}
}
/**
* @param string $query
* @return Collection
*/
public function findItem(string $query): Collection
{
return $this->items->filter(function ($val, $key) use ($query) {
$query = Str::lower($query);
return Str::contains($val['_id'], $query)
|| Str::contains($val['_name'], $query)
|| Str::contains($val['_parent'], $query)
|| (($this->locale[$key] ?? false)
&& $this->locale[$key]['Name']
&& Str::contains(Str::lower($this->locale[$key]['Name']), $query)
&& Str::contains(Str::lower($this->locale[$key]['ShortName']), $query));
})->map(function ($item) {
return [
'_id' => $item['_id'],
'_name' => $item['_name'],
'locale' => $this->locale[$item['_id']] ?? ''
];
})->values();
}
/**
* @param string $id
* @return array
* @throws ItemNotFoundException
*/
public function getItemById(string $id): array
{
$item = $this->items[$id] ?? throw new ItemNotFoundException('Item not found');
return [
'item' => $item,
];
}
}