Files
eatvio-infra/app/Livewire/Diet/DayEdit.php
2024-01-15 17:11:55 +03:00

98 lines
2.7 KiB
PHP

<?php
namespace App\Livewire\Diet;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Contracts\View\View;
use Livewire\Component;
class DayEdit extends Component
{
public string $day;
public array $eatingTypes = ['breakfast', 'dinner', 'supper', 'lunch', 'snacks'];
public string $activeType = 'breakfast';
public array $portions = [];
public string $name = '';
public int $quantity = 0;
public string $portion = 'gram';
protected array $rules = [
'name' => 'required|min:3',
'quantity' => 'required|numeric|min:1',
'portion' => 'required|min:3',
];
public function render(): View|ViewFactory
{
return view('livewire.diet.day-edit');
}
public function addPortion(string $type): void
{
$this->validate();
$newData = [
'name' => $this->name,
'quantity' => $this->quantity,
'portion' => $this->portion,
'uniq' => $this->name.'-'.time(),
];
$this->portions[$type][] = $newData;
$this->reset(['name', 'quantity', 'portion']);
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
public function delete(string $uniq, string $type): void
{
$newPortions = collect($this->portions[$type])
->filter(
function ($item) use ($uniq) {
return $item['uniq'] !== $uniq;
}
);
$this->portions[$type] = $newPortions->toArray();
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
public function edit(string $uniq, string $type): void
{
$elemKey = collect($this->portions[$type])
->search(function ($item) use ($uniq) {
return $item['uniq'] === $uniq;
});
if ($elemKey !== false) {
$item = $this->portions[$type][$elemKey];
$this->fill([
'name' => $item['name'],
'quantity' => $item['quantity'],
'portion' => $item['portion'],
]);
$this->delete($item['uniq'], $type);
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
}
public function takePaste(string $day, array $data): void
{
if (intval($day) === intval($this->day)) {
foreach ($data as $type => $props) {
$this->portions[$type] = $props;
}
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
}
protected function getListeners(): array
{
return ['takePaste'];
}
}