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

52 lines
1.2 KiB
PHP
Raw Normal View History

2021-10-08 20:44:34 +09:00
<?php
namespace App\Data;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class ItemsCollection
{
protected Collection $data;
public function __construct()
{
if (!Cache::has('items')) {
$file = storage_path('items.json');
$this->data = collect(json_decode(file_get_contents($file), true)['data']);
Cache::put('items', $this->data);
} else {
$this->data = Cache::get('items');
}
}
/**
* @param string $query
* @return array
*/
2021-10-10 13:08:50 +09:00
public function findItem(string $query): array
2021-10-08 20:44:34 +09:00
{
return $this->data->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'],
];
})->all();
}
/**
* @param string $id
* @return array
*/
public function getItemById(string $id)
{
return $this->data[$id];
}
}