1
0
cms11/app/Classes/AttachmentsManager.php

109 lines
2.4 KiB
PHP

<?php
namespace App\Classes;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Str;
class AttachmentsManager
{
/**
* Original metadata content
*/
private array $originalContent = [];
/**
* Current metadata content
*/
private array $content = [];
public function __construct(protected string $root, protected FilesystemAdapter $disk)
{
}
/**
* Add a file to a named history and return attachment's reference
*/
public function addToHistory(string $name, array $data): string
{
$reference = $this->add($data);
$this->content['history'][$name][] = [
'reference' => $reference,
'date' => now(),
];
return $reference;
}
/**
* Add a single file to the bundle
*/
public function add(array $data): string
{
$reference = $this->generateNewReference();
$filename = $data['filename'];
$contents = $data['contents'];
unset($data['contents']);
$fullPath = sprintf('%s/%s', $this->root, $filename);
$relativePath = Str::remove(dirname($this->root), $fullPath);
$data['filename'] = $relativePath;
$this->disk->put($fullPath, $contents);
$this->content['files'][$reference] = $data;
return $reference;
}
/**
* Return a boolean value indicating if the file actually exists on disk
*/
public function exists()
{
return $this->disk->exists($this->root . '.json');
}
/**
* 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->root . '.json', $json);
$this->originalContent = $this->content;
return true;
}
/**
* Generate new, random reference for a file
*/
private function generateNewReference(): string
{
return Str::random(6);
}
}