1
0
cms11/app/Classes/AttachmentsManager.php

131 lines
2.9 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;
private string $attachmentsDir = 'attachments';
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/%s', $root, $this->attachmentsDir, $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;
}
/**
* Provides direct access to underlying manager for better control
*/
public function manager(): MetadataManager
{
return $this->manager;
}
/**
* Add or replace attachment with specified reference. Will replace existing
* data
*/
public function upsert(string $reference, array $data)
{
$this->manager['files'][$reference] = $data;
}
/**
* 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/%s', $this->attachmentsDir, $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);
}
/**
* Load data from disk
*/
public function load()
{
$this->manager->load();
}
/**
* 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);
}
}