2021-10-08 20:44:34 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Data;
|
|
|
|
|
2021-10-10 13:09:11 +09:00
|
|
|
use App\Exceptions\ItemNotFoundException;
|
2021-10-08 20:44:34 +09:00
|
|
|
use Illuminate\Support\Collection;
|
|
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
|
|
class ItemsCollection
|
|
|
|
{
|
2021-10-11 17:26:19 +09:00
|
|
|
protected Collection $items;
|
|
|
|
protected Collection $locale;
|
2021-10-08 20:44:34 +09:00
|
|
|
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
if (!Cache::has('items')) {
|
|
|
|
$file = storage_path('items.json');
|
2021-10-11 17:26:19 +09:00
|
|
|
$this->items = collect(json_decode(file_get_contents($file), true)['data']);
|
|
|
|
Cache::put('items', $this->items);
|
2021-10-08 20:44:34 +09:00
|
|
|
} else {
|
2021-10-11 17:26:19 +09:00
|
|
|
$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');
|
2021-10-08 20:44:34 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $query
|
2021-10-11 16:00:25 +09:00
|
|
|
* @return Collection
|
2021-10-08 20:44:34 +09:00
|
|
|
*/
|
2021-10-11 16:00:25 +09:00
|
|
|
public function findItem(string $query): Collection
|
2021-10-08 20:44:34 +09:00
|
|
|
{
|
2021-10-11 17:26:19 +09:00
|
|
|
return $this->items->filter(function ($val) use ($query) {
|
2021-10-10 13:08:50 +09:00
|
|
|
$query = Str::lower($query);
|
2021-10-08 20:44:34 +09:00
|
|
|
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'],
|
|
|
|
];
|
2021-10-11 16:00:25 +09:00
|
|
|
})->values();
|
2021-10-08 20:44:34 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $id
|
|
|
|
* @return array
|
2021-10-10 13:09:11 +09:00
|
|
|
* @throws ItemNotFoundException
|
2021-10-08 20:44:34 +09:00
|
|
|
*/
|
2021-10-10 13:09:11 +09:00
|
|
|
public function getItemById(string $id): array
|
2021-10-08 20:44:34 +09:00
|
|
|
{
|
2021-10-11 17:26:19 +09:00
|
|
|
$item = $this->items[$id] ?? throw new ItemNotFoundException('Item not found');
|
|
|
|
return [
|
|
|
|
'item' => $item,
|
|
|
|
'locale' => $this->locale[$id] ?? ''
|
|
|
|
];
|
2021-10-08 20:44:34 +09:00
|
|
|
}
|
|
|
|
}
|