ldc-showroom-bo/app/Jobs/ShowroomExport.php
2024-01-08 15:54:37 +01:00

300 lines
9.7 KiB
PHP

<?php
namespace App\Jobs;
use App\Lib\Helpers\ToolboxHelper;
use App\Models\Brand;
use App\Models\Product;
use App\Models\Range;
use App\Models\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use sixlive\Laravel\JsonSchemaAssertions\SchemaAssertion;
class ShowroomExport implements ShouldQueue, ShouldBeUnique
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Export dir
*
* @var string
*/
private string $exportFolder = 'app/export';
/**
* Working dir
*
* @var string
*/
private string $tempFolder = 'app/temp/export';
/**
* The number of seconds after which the job's unique lock will be released.
*
* @var integer
*/
public int $uniqueFor = 3600;
/**
* Create a new job instance.
*/
public function __construct()
{
$this->exportFolder = \storage_path($this->exportFolder);
$this->tempFolder = \storage_path($this->tempFolder);
}
/**
* Get the unique ID for the job.
*
* @return string
*/
public function uniqueId(): string
{
return "9999999";
}
/**
* Execute the job.
*
* @return void
* @throws \RuntimeException If a schema could not be found or data could not be validated against schema.
*/
public function handle(): void
{
$data = $this->getData();
$associatedFileList = $this->getAssociatedFileList($data);
$fileContent = $this->getFile($data);
$schemaContent = ToolboxHelper::getJsonSchema('app.schema.json');
if ($schemaContent === false) {
throw new \RuntimeException("The schema could not be found 'app'");
}
$this->assertSchemaIsValid($schemaContent, json_encode($fileContent));
$filesToZip = $this->preparePicturesForZip($associatedFileList);
$dataFilePath = "{$this->tempFolder}/data.json";
// * Make json File add add to files to zip.
File::put($dataFilePath, json_encode($fileContent), true);
if (!File::exists($this->exportFolder)) {
File::makeDirectory($this->exportFolder, 0700, true);
}
// * Empty too old files
collect(File::allFiles($this->exportFolder))->each(function (\SplFileInfo $file) {
if (now()->subDays(7)->gt(Carbon::parse($file->getCTime() ?: $file->getMTime() ?: $file->getATime()))) {
Log::info('Removed exported file ' . $file->getRealPath());
File::delete($file->getRealPath());
}
});
$zipFile = $this->makeZipFile($filesToZip, $dataFilePath);
$successMessage = "File exported in {$zipFile}.";
if (app()->runningInConsole()) {
$output = new \Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln($successMessage);
}
Log::info($successMessage);
}
/**
* Make zip file and get its path.
*
* @param array $filesToZip
* @param string $dataFilePath
* @return string
* @throws \RuntimeException In case of failure.
*/
protected function makeZipFile(array $filesToZip, string $dataFilePath): string
{
$zip = new \ZipArchive();
$zipFileName = Str::of('showroom-bo-export')->append('_')
->append(now()->isoFormat('DD-MM-YYYY_HH-mm-ss'))->append('.zip');
$zipFilePath = Str::of($this->exportFolder)->append("/{$zipFileName}");
if ($zip->open($zipFilePath, \ZipArchive::CREATE) !== true) {
throw new \RuntimeException("Failed to open zip file {$zipFilePath}");
}
foreach ($filesToZip as $file) {
if (!$zip->addFile($file, Str::of($file)->explode('/')->take(-2)->implode('/'))) {
throw new \RuntimeException("Failed to add file {$file} into zip");
}
}
if (!$zip->addFile($dataFilePath, \pathinfo($dataFilePath, \PATHINFO_BASENAME))) {
throw new \RuntimeException("Failed to add file {$dataFilePath} into zip");
}
$zip->close();
return $zipFilePath;
}
/**
* Assert schema is valid
*
* @param array $schema
* @param string $fileContent
* @return void
* @throws \PHPUnit\Framework\AssertionFailedError I case of failure.
*/
protected function assertSchemaIsValid(array $schema, string $fileContent): void
{
$assertion = new SchemaAssertion($schema);
$assertion->assert($fileContent);
}
/**
* Get associated files list to export
*
* @param \Illuminate\Database\Eloquent\Collection $data
* @return array
*/
protected function getAssociatedFileList(Collection $data): array
{
$groupBy = fn (array $path) => Str::of(Arr::get($path, 0))->explode('/')->get(2);
$items = collect($data)->map(fn (Brand $brand) => [
$brand->picture,
$brand->ranges->map(fn (Range $range) => [
$range->picture,
$range->products->map(fn (Product $product) => [
$product->picture
])->collect()->groupBy($groupBy)
])->collect()->groupBy($groupBy)
])->collect();
$brandList = $items->pluck(0);
$rangeList = $items->pluck(1)->map(fn (SupportCollection $ranges) => $ranges
->map(fn (SupportCollection $range) => $range->pluck(0)))->flatten();
$productList = $items->pluck(1)->map(fn (SupportCollection $ranges) => $ranges
->map(fn (SupportCollection $range) => $range->pluck(1)->map(fn ($products) => $products
->map(fn (SupportCollection $product) => $product))))->flatten();
return [
'settings' => collect(Arr::get($this->getSettings(), 'logo')),
'brands' => $brandList,
'ranges' => $rangeList,
'products' => $productList,
];
}
/**
* Get export file content
*
* @param \Illuminate\Database\Eloquent\Collection $data
* @return array
*/
protected function getFile(Collection $data): array
{
return [
'version' => $this->getVersion(),
'settings' => $this->getSettings(),
'items' => $data->map(function (Brand $brand) {
$this->setPictureExportPath($brand);
$brand->setRelation('ranges', $brand->ranges->map(function (Range $range) {
$this->setPictureExportPath($range);
$range->setRelation('products', $range->products->map(function (Product $product) {
$this->setPictureExportPath($product);
return $product;
}));
return $range;
}));
return $brand;
})->toArray()
];
}
// * Private Methods
/**
* Get the files that should be zipped
*
* @param array<\Illuminate\Support\Collection<string>> $filesToZip
* @return array<string>
* @throws \RuntimeException If temp folder caanot be cleared in order to work.
*/
private function preparePicturesForZip(array $filesToZip): array
{
$newPaths = [];
if (!File::exists($this->tempFolder)) {
File::makeDirectory($this->tempFolder, 0700, true);
}
File::deleteDirectory($this->tempFolder, true);
if (!File::isEmptyDirectory($this->tempFolder)) {
throw new \RuntimeException("{$this->tempFolder} is not empty, refuse to prepare export");
}
$copyPath = fn (string $targetPath) => function (string $path) use ($targetPath): string {
$targetFilePath = Str::of($targetPath)->append('/')->append(\pathinfo($path, \PATHINFO_BASENAME));
File::copy(\public_path($path), $targetFilePath);
return $targetFilePath;
};
$toCopy = ['settings', 'brands', 'ranges', 'products'];
foreach ($toCopy as $element) {
$targetPath = Str::of($this->tempFolder)->append("/{$element}");
File::makeDirectory($targetPath);
$newPaths[$element] = $filesToZip[$element]->map($copyPath($targetPath));
}
return collect($newPaths)->flatten()->all();
}
/**
* Set picture export path, where it will be stored in zip file.
*
* @param \App\Models\Brand|\App\Models\Range|\App\Models\Product $model
* @return void
*/
private function setPictureExportPath(Brand|Range|Product &$model): void
{
$tableName = $model->getTable();
$model->picture = Str::start(
\pathinfo($model->picture, \PATHINFO_BASENAME),
"pictures/{$tableName}/"
);
}
/**
* Get app version
*
* @return string
*/
private function getVersion(): string
{
return Cache::get('composer')->version;
}
/**
* Get app settings
*
* @return array
*/
private function getSettings(): array
{
return Settings::getCached()->first()->toArray();
}
/**
* Get app data
*
* @return \Illuminate\Database\Eloquent\Collection<\App\Models\Brand>
*/
private function getData(): Collection
{
return Brand::query()->with('ranges.products')->get();
}
}