75 lines
2.2 KiB
PHP
75 lines
2.2 KiB
PHP
<?php
|
|
namespace App\CMS\Pipeline\SavePipeline\Process;
|
|
|
|
use App\CMS\Contracts\Content\SavePipeline\Process;
|
|
use App\Models\Content\Content;
|
|
use App\Models\Content\ContentHasFile;
|
|
use App\Models\FileManager\Directory;
|
|
use App\Models\FileManager\File;
|
|
|
|
class UploadRelatedFiles implements Process
|
|
{
|
|
/**
|
|
* Process and modify given page
|
|
*
|
|
* @param Content $page
|
|
* @param array $input
|
|
*
|
|
* @return void
|
|
*/
|
|
function handle(Content & $page, array & $input)
|
|
{
|
|
$files = $input['files'];
|
|
$assignedFiles = isset($input['keepAssigned']) ? $input['keepAssigned'] : [];
|
|
|
|
// check if any file was removed
|
|
$this->removeRelatedFiles($page, $assignedFiles);
|
|
|
|
// allow uploading only on created pages
|
|
if (!$page->id || !$files[0]) {
|
|
return;
|
|
}
|
|
|
|
// find or create new directory for files assigned to content
|
|
$directory = Directory::firstOrCreate([
|
|
'name' => '.content_files',
|
|
'hidden' => true
|
|
]);
|
|
$data = new \stdClass();
|
|
$data->directoryId = $directory->id;
|
|
|
|
$fileModel = app(File::class);
|
|
|
|
foreach ($files as $file) {
|
|
if (!$file) {
|
|
continue;
|
|
}
|
|
$uploaded = $fileModel->upload($file, $data);
|
|
|
|
// add assignement
|
|
ContentHasFile::create([
|
|
'file_id' => $uploaded['id'],
|
|
'content_id' => $page->id
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete files from association
|
|
*
|
|
* @param Content $page
|
|
* @param $assignedFiles
|
|
*/
|
|
private function removeRelatedFiles(Content $page, $assignedFiles)
|
|
{
|
|
$allFiles = $page->files()
|
|
->whereNotIn('id', array_keys($assignedFiles))
|
|
->get();
|
|
|
|
foreach ($allFiles as $file) {
|
|
ContentHasFile::where('content_id', $page->id)
|
|
->where('file_id', $file->id)
|
|
->delete();
|
|
}
|
|
}
|
|
} |