<?php
namespace Koselig\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Koselig\Exceptions\UnsatisfiedDependencyException;
use Koselig\Support\Action;
class Post extends Model
{
public $table = DB_PREFIX . 'posts';
public $primaryKey = 'ID';
public $timestamps = false;
public $dates = ['post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt'];
public function scopePostType($query, $name)
{
return $query->where('post_type', $name);
}
public function scopePublished($query)
{
return $query->where('post_status', 'publish');
}
public function meta()
{
return $this->hasMany(Meta::class);
}
public function getMeta($key = null)
{
$meta = $this->meta;
if (is_array($key)) {
$meta = $meta->whereIn('meta_key', $key);
} elseif (is_string($key)) {
$meta = $meta->where('meta_key', $key)->first();
return $meta ? $meta->meta_value : null;
}
return $meta->mapWithKeys(function ($item) {
return [$item->meta_key => $item->meta_value];
})->all();
}
public function getACF($key = null, $format = true)
{
if (!function_exists('acf_format_value')) {
throw new UnsatisfiedDependencyException('Advanced Custom Fields must be installed to use field');
}
$meta = $this->getMeta($key);
if (!is_array($meta)) {
$meta = [$key => $meta];
$wantsArray = false;
} else {
$wantsArray = true;
}
foreach ($meta as $k => $value)
{
$field = $this->getMeta('_' . $k);
if (!acf_is_field_key($field)) {
unset($meta[$k]);
continue;
}
if (is_serialized($value)) {
$value = @unserialize($value);
}
$field = get_field_object($field, $k, false, false);
if (((is_array($key) && !in_array($k, $key)) && $k !== $key || $key === null) && acf_is_sub_field($field)) {
unset($meta[$k]);
continue;
}
$value = Action::filter('acf/load_value', $value, $k, $field);
$value = Action::filter('acf/load_value/type=' . $field['type'], $value, $this->ID, $field);
$value = Action::filter('acf/load_value/name=' . $field['_name'], $value, $this->ID, $field);
$value = Action::filter('acf/load_value/key=' . $field['key'], $value, $this->ID, $field);
if ($format) {
$value = acf_format_value($value, $this->ID, $field);
}
$meta[$k] = $value;
}
return $wantsArray ? $meta : collect($meta)->first();
}
public function author()
{
return $this->belongsTo(User::class, 'post_author');
}
}