QR_code_generator/app/Models/Publications/Publication.php

108 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Models\Publications;
use App\Models\Asset;
use App\Models\Pages\Page;
use App\Models\User;
use App\Support\HasObjectsTrait;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
class Publication extends Model {
use UuidScopeTrait, SoftDeletes, HasObjectsTrait, RelationValuesTrait;
protected $dates = [
'published_at'
];
protected $fillable = [
'uuid',
'page_id',
'author_id',
'slug',
'type',
'name',
'excerpt',
'content',
'is_published',
'is_blank',
'published_at'
];
protected $hidden = [
'id'
];
public function page(): BelongsTo {
return $this->belongsTo(Page::class);
}
public function poster(): BelongsTo {
return $this->belongsTo(Asset::class);
}
public function author(): BelongsTo {
return $this->belongsTo(User::class);
}
public function sections(): MorphToMany {
return $this->objectsByGroup('sections');
}
public function sidebars(): MorphToMany {
return $this->objectsByGroup('sidebars');
}
public function scopeBySlug($query, $slug) {
$query->where(['slug' => $slug]);
}
public function getLinkAttribute(): string {
return ($this->page->link ?? '') . "/{$this->slug}";
}
public function getParentsAttribute(): Collection {
$page = $this->page;
$result = collect([$page]);
while ($page = $page->parent) $result->push($page);
return $result;
}
public function getPublishDateRusAttribute(): string {
return $this->published_at ? $this->published_at->format('d') . ' ' . $this->published_at->getTranslatedMonthName('Do MMMM') . ' ' . $this->published_at->format('Y') . ' г.' : 'Дата не указана';
}
public function addSection($typeName, $ord = null): ?Model {
return $this->createObject($typeName, $ord, 'sections');
}
public function addSidebar($typeName = 'page-sidebar', $ord = null): ?Model {
return $this->createObject($typeName, $ord, 'sidebars');
}
public static function byUrl($url) {
if ($url = trim($url, '/ ')) {
$slugs = explode('/', $url);
$publicationSlug = array_pop($slugs);
$pageUrl = implode('/', $slugs);
if ($pageUrl) {
return ($page = Page::byUrl($pageUrl)) ? $page->publications()->bySlug($publicationSlug)->first() : null;
} else return self::bySlug($publicationSlug)->first();
}
return null;
}
}