Files
eatvio-infra/app/Models/Plan.php
2023-12-11 11:35:07 +03:00

132 lines
3.2 KiB
PHP

<?php
namespace App\Models;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
use App\Models\PlanLike;
use App\Presenters\PlanPresenter;
use Illuminate\Database\Eloquent\Casts\Attribute;
use CyrildeWit\EloquentViewable\InteractsWithViews;
use CyrildeWit\EloquentViewable\Contracts\Viewable;
class Plan extends Model implements Viewable
{
use HasFactory;
use InteractsWithViews;
use PresentableTrait;
protected $withCount = [
'likes',
'comments'
];
protected $casts = [
'type' => 'array',
'packet1_options' => 'array',
'packet2_options' => 'array',
'packet3_options' => 'array',
];
protected $presenter = PlanPresenter::class;
public function author()
{
return $this->belongsToMany(User::class, 'plan_author', 'plan_id', 'user_id');
}
public function comments()
{
return $this->hasMany(PlanComment::class);
}
public function likes(): HasMany
{
return $this->hasMany(PlanLike::class);
}
public function isLiked(): bool
{
if (auth()->user()) {
return auth()->user()->plan_likes()->forPlan($this)->count();
}
return false;
}
public function allItems(): array
{
$result = [];
for ($i = 1; $i <= $this->packets_count; $i++) {
$key = "packet" . $i . "_options";
// $data = $this->unserializeOptionsObj($this->$key);
$data = $this->$key;
if (!is_null($data)) {
$result = array_merge($result, data_get($data, "items", []));
}
}
return array_values(array_unique($result));
}
public function types(): Attribute
{
// $data = $this->unserializeOptionsArr($this->type);
$data = $this->type;
return new Attribute(
get: fn () => array_keys($data),
);
}
public function minPrice(): Attribute
{
$result = 0;
for ($i = 1; $i <= $this->packets_count; $i++) {
$key = "packet" . $i . "_options";
// dd($this->$key);
// $data = $this->unserializeOptionsObj($this->$key);
$data = $this->$key;
if (!is_null($data)) {
$curPrice = (int)data_get($data, "price", 0);
$result = $curPrice > $result ? $curPrice : $result ;
}
}
return new Attribute(
get: fn () => $result,
);
}
public function removeLike(): bool
{
if (auth()->user()) {
return auth()->user()->plan_likes()->forPlan($this)->delete();
}
return false;
}
private function unserializeOptionsObj($str)
{
if (preg_match('/^".*"$/', $str)) {
return json_decode(stripslashes(mb_substr($str, 1, -1)));
}
return json_decode(stripslashes($str));
}
private function unserializeOptionsArr($str)
{
if (preg_match('/^".*"$/', $str)) {
return json_decode(stripslashes(mb_substr($str, 1, -1)), true);
}
return json_decode(stripslashes($str), true);
}
}