File: D:/HostingSpaces/SBogers10/stielman.komma.nl/vendor/komma/kms/src/Core/AbstractTranslationModel.php
<?php
namespace Komma\KMS\Core;
use Illuminate\Support\Carbon;
use Komma\KMS\Core\Entities\DisplayNameTrait;
use Komma\KMS\Globalization\Languages\Models\Language;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Represents a translation for a AbstractTranslatableModel implementation
*
* @property string title
* @property string description
*
* @note make sure that the implementation has a name attribute and not a title attribute
* @see AbstractTranslatableModel
*/
abstract class AbstractTranslationModel extends Model
{
use DisplayNameTrait;
/**
* @return BelongsTo relation That resolves to a TranslatableModelInterface
* @see AbstractTranslatableModel
*/
abstract public function translatable(): BelongsTo;
/**
* @return belongsTo relation That resolves to a Language model
* @see Language
*/
public function language():BelongsTo {
return $this->belongsTo(Language::class);
}
/**
* Returns the 2 character length iso 2 code of the language of the model
*
* @return string
*/
public function getLanguageIso(){
return $this->language()->first()->iso_2;
}
/**
* Returns true or false depending on whether or not the translation can be considered empty
*
* @return bool
*/
public function isEmpty():bool
{
$empty = true;
foreach($this->attributes as $attributeName => $value)
{
if(substr($attributeName, -3) == '_id') continue;
if($value != "" && $value != "[]") {
$empty = false;
break;
}
}
return $empty;
}
public function setUpdatedAtAttribute($value) {
$timestamp = $this->fixInvalidDateValueIfNeeded($value);
parent::setUpdatedAt($timestamp);
}
public function setCreatedAt($value) {
$timestamp = $this->fixInvalidDateValueIfNeeded($value);
parent::setCreatedAt($timestamp);
}
public function save(array $options = []) {
if(!$this->exists || $this->wasRecentlyCreated) {
//This is needed because sometimes we don't set the updated_at attribute resulting in an invalid date being set in some cases.
//Attributes will always return string values, and in this case, because there is no updated_at date, it return a date that is not valid.
$timestamp = $this->fixInvalidDateValueIfNeeded(null);
$this->setUpdatedAt($timestamp);
$this->setCreatedAt($timestamp);
}
return parent::save($options);
}
private function fixInvalidDateValueIfNeeded($value) {
if(
$value && //Value must be set
substr((Carbon::parse($value))->toDateTimeString(), 0, 1) === '-' //Time value must not start with a dash. Example of invalid date: ) {
) {
//invalid date detected. Force it to the "now date"
return Carbon::now()->timestamp;
}
return $value;
}
}