Skip to content

Instantly share code, notes, and snippets.

@sebsel
Created January 1, 2018 17:11
Show Gist options
  • Select an option

  • Save sebsel/38debda9164c78a81a546f0315c7d9c7 to your computer and use it in GitHub Desktop.

Select an option

Save sebsel/38debda9164c78a81a546f0315c7d9c7 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use App\Services\KirbyDataReader;
use Illuminate\Database\Eloquent\Model;
use League\Flysystem\FileNotFoundException;
abstract class HybridModel extends Model
{
const CREATED_AT = 'indexed_at';
protected $file_attributes = [];
protected $original_file_attributes = [];
protected $disk = 'local';
protected $mapDatabaseFieldsToFile = [];
/**
* Registers hooks for Events on this model
*/
static function boot()
{
parent::boot();
static::retrieved(function (self $model) {
$model->initWithFileContents();
});
static::creating(function (self $model) {
$model->saveFile();
$model->resetForDatabaseSave();
});
static::created(function (self $model) {
$model->initWithFileContents();
});
static::updating(function (self $model) {
$model->saveFile();
$model->resetForDatabaseSave();
});
}
/**
* @return array
*/
public function getDatabaseAttributes()
{
return array_only($this->attributes, array_keys($this->mapDatabaseFieldsToFile));
}
/**
* @return array
*/
public function getFileAttributes()
{
$fileAttributes = [];
foreach ($this->attributes as $key => $value) {
if (!array_key_exists($key, $this->mapDatabaseFieldsToFile)) {
$fileAttributes[$key] = $value;
continue;
}
$newKey = $this->mapDatabaseFieldsToFile[$key];
if ($newKey) $fileAttributes[$newKey] = $value;
}
return $fileAttributes;
}
/**
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function initWithFileContents()
{
$file = \Storage::disk($this->disk)->get($this->filename);
$file_data = resolve('App\Services\KirbyDataReader')->decode($file);
$this->original_file_attributes = $file_data;
$this->file_attributes = $file_data;
$this->forceFill($file_data);
}
/**
* Resets for database save
*/
public function resetForDatabaseSave()
{
$this->attributes = $this->getDatabaseAttributes();
}
/**
* Saves the file contents
*/
public function saveFile()
{
$fileContents = resolve(KirbyDataReader::class)
->encode($this->getFileAttributes());
\Storage::disk($this->disk)
->put($this->filename, $fileContents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment