ldc-wenn-dann-mit-respekt/app/Traits/Controllers/UpdateModelStatus.php

67 lines
1.9 KiB
PHP

<?php
namespace App\Traits\Controllers;
use App\Interfaces\Models\Publishable;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Models\IsPublishable;
/**
* This trait works with Route::bind in App service provider
* to resolve the model and the DB row
* It does not work with binder Service
*/
trait UpdateModelStatus
{
/**
* Change model published boolean
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Http\RedirectResponse
*/
public function changePublished(Model $model)
{
$model->update(['status' => !$model->getOriginal('status')]);
return redirect()->back()->with('success', __('The status has been changed'));
}
/**
* Change model publication date + boolean
*
* @param Model $model
* @return \Illuminate\Http\RedirectResponse
* @throws \InvalidArgumentException Model must use IsPublishable trait.
*/
public function updatePublicationDate(Model $model)
{
if (!$this->isPublishable($model)) {
throw new \InvalidArgumentException('Model must use IsPublishable trait');
}
/** @var Publishable&Model $model */
if ($model->getStatus()) {
$model->setUnpublishAt(now());
$model->setStatus(false);
} else {
$model->setPublishAt(now());
$model->setUnpublishAt(null);
$model->setStatus(true);
}
$model->saveOrFail();
return redirect()->back()->with('success', __('The status has been changed'));
}
/**
* Check if a Model implements Publishable interface.
*
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return boolean
*/
protected function isPublishable(Model $model): bool
{
return $model instanceof Publishable &&
in_array(IsPublishable::class, class_uses_recursive($model));
}
}