forked from eatvio/eatvio-infra
111 lines
2.8 KiB
PHP
111 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use App\Models\PlanLike;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use CyrildeWit\EloquentViewable\InteractsWithViews;
|
|
use CyrildeWit\EloquentViewable\Contracts\Viewable;
|
|
|
|
class Plan extends Model implements Viewable
|
|
{
|
|
use HasFactory, InteractsWithViews;
|
|
|
|
protected $withCount = [
|
|
'likes',
|
|
'comments'
|
|
];
|
|
|
|
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);
|
|
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);
|
|
|
|
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";
|
|
$data = $this->unserializeOptionsObj($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);
|
|
}
|
|
}
|