1
0
cms11/app/Classes/AttachmentsManager.php

104 lines
2.3 KiB
PHP

<?php
namespace App\Classes;
use App\Classes\Traits\ManagesMetadata;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Str;
class AttachmentsManager
{
use ManagesMetadata;
/**
* Manages images
*/
const Images = 'images';
/**
* Manages sounds
*/
const Sounds = 'sounds';
/**
* Manages videos
*/
const Videos = 'videos';
private string $targetForFiles;
private string $metadataFilePath;
private MetadataManager $manager;
public function __construct(protected string $kind, protected string $root, protected FilesystemAdapter $disk)
{
$this->metadataFilePath = sprintf('%s%s.json', $root, $kind);
$this->targetForFiles = sprintf('%s%s', $root, $kind);
$this->manager = new MetadataManager($this->metadataFilePath, $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->manager['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->targetForFiles, $filename);
$relativePath = sprintf('%s/%s', $this->kind, $filename);
$data['filename'] = $relativePath;
$this->disk->put($fullPath, $contents);
$this->manager['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->metadataFilePath);
}
/**
* Store file on disk
*/
public function save(): bool
{
return $this->manager->save();
}
/**
* Generate new, random reference for a file
*/
private function generateNewReference(): string
{
return Str::random(6);
}
}