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

66 lines
1.8 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) use ($query) {
$query = Str::lower($query);
return Str::contains($val['_id'], $query)
|| Str::contains($val['_name'], $query)
|| Str::contains($val['_parent'], $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,
];
}
}