1
0
cms11/app/Classes/MetadataManager.php
2024-04-17 16:18:27 +02:00

98 lines
2.1 KiB
PHP

<?php
namespace App\Classes;
use ArrayAccess;
use Illuminate\Filesystem\FilesystemAdapter;
class MetadataManager implements ArrayAccess
{
/**
* Original metadata content
*/
private array $originalContent = [];
/**
* Current metadata content
*/
private array $content = [];
public function __construct(protected string $filename, protected FilesystemAdapter $disk)
{
}
/**
* Return a boolean value indicating if the file actually exists on disk
*/
public function exists()
{
return $this->disk->exists($this->filename);
}
/**
* Set a new array of values
*/
public function set(array $content): void
{
$this->content = $content;
}
/**
* Return a boolean indicating if the file has changed since it was loaded
*/
public function isDirty(): bool
{
$original = collect($this->originalContent);
$current = collect($this->content);
return !$original->diffAssoc($current)->isEmpty() || !$current->diffAssoc($original)->isEmpty();
}
/**
* Store file on disk
*/
public function save(): bool
{
if (!$this->isDirty()) {
return false;
}
$json = json_encode($this->content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$this->disk->put($this->filename, $json);
$this->originalContent = $this->content;
return true;
}
public function offsetExists(mixed $offset): bool
{
return isset($this->content[$offset]);
}
public function &offsetGet(mixed $offset): mixed
{
if (!isset($this->content[$offset])) {
$this->content[$offset] = null;
}
return $this->content[$offset];
}
public function offsetSet(mixed $offset, mixed $value): void
{
if (is_null($offset)) {
$this->content[] = $value;
} else {
$this->content[$offset] = $value;
}
}
public function offsetUnset(mixed $offset): void
{
unset($this->content[$offset]);
}
}