Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve conversions #2101

Merged
merged 21 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/Conversions/Actions/PerformConversionAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Spatie\MediaLibrary\Conversions\Actions;

use Spatie\MediaLibrary\Conversions\Conversion;
use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompleted;
use Spatie\MediaLibrary\Conversions\Events\ConversionWillStart;
use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory;
use Spatie\MediaLibrary\MediaCollections\Filesystem;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\ResponsiveImages\ResponsiveImageGenerator;

class PerformConversionAction
{
public function execute(
Conversion $conversion,
Media $media,
string $copiedOriginalFile
) {
event(new ConversionWillStart($media, $conversion, $copiedOriginalFile));

$imageGenerator = ImageGeneratorFactory::forMedia($media);

$copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion);

$manipulationResult = (new PerformManipulationsAction)->execute($media, $conversion, $copiedOriginalFile);

$newFileName = $conversion->getConversionFile($media);

$renamedFile = $this->renameInLocalDirectory($manipulationResult, $newFileName);

if ($conversion->shouldGenerateResponsiveImages()) {
/** @var ResponsiveImageGenerator $responsiveImageGenerator */
$responsiveImageGenerator = app(ResponsiveImageGenerator::class);

$responsiveImageGenerator->generateResponsiveImagesForConversion(
$media,
$conversion,
$renamedFile
);
}

app(Filesystem::class)->copyToMediaLibrary($renamedFile, $media, 'conversions');

$media->markAsConversionGenerated($conversion->getName());

event(new ConversionHasBeenCompleted($media, $conversion));
}

protected function renameInLocalDirectory(
string $fileNameWithDirectory,
string $newFileNameWithoutDirectory
): string {
$targetFile = pathinfo($fileNameWithDirectory, PATHINFO_DIRNAME).'/'.$newFileNameWithoutDirectory;

rename($fileNameWithDirectory, $targetFile);

return $targetFile;
}
}
49 changes: 49 additions & 0 deletions src/Conversions/Actions/PerformManipulationsAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Spatie\MediaLibrary\Conversions\Actions;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\Conversions\Conversion;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\ImageFactory;

class PerformManipulationsAction
{
public function execute(
Media $media,
Conversion $conversion,
string $imageFile
): string {
if ($conversion->getManipulations()->isEmpty()) {
return $imageFile;
}

$conversionTempFile = $this->getConversionTempFileName($media, $conversion, $imageFile);

File::copy($imageFile, $conversionTempFile);

$supportedFormats = ['jpg', 'pjpg', 'png', 'gif'];
if ($conversion->shouldKeepOriginalImageFormat() && in_array($media->extension, $supportedFormats)) {
$conversion->format($media->extension);
}

ImageFactory::load($conversionTempFile)
->manipulate($conversion->getManipulations())
->save();

return $conversionTempFile;
}

protected function getConversionTempFileName(
Media $media,
Conversion $conversion,
string $imageFile
): string {
$directory = pathinfo($imageFile, PATHINFO_DIRNAME);

$fileName = Str::random(32)."{$conversion->getName()}.{$media->extension}";

return "{$directory}/{$fileName}";
}
}
14 changes: 0 additions & 14 deletions src/Conversions/ConversionCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,6 @@ public function getConversions(string $collectionName = ''): self
return $this->filter(fn (Conversion $conversion) => $conversion->shouldBePerformedOn($collectionName));
}

public function getQueuedConversions(string $collectionName = ''): self
{
return $this
->getConversions($collectionName)
->filter(fn (Conversion $conversion) => $conversion->shouldBeQueued());
}

protected function addManipulationToConversion(Manipulations $manipulations, string $conversionName)
{
/** @var \Spatie\MediaLibrary\Conversions\Conversion|null $conversion */
Expand All @@ -116,13 +109,6 @@ protected function addManipulationToConversion(Manipulations $manipulations, str
}
}

public function getNonQueuedConversions(string $collectionName = ''): self
{
return $this
->getConversions($collectionName)
->reject(fn (Conversion $conversion) => $conversion->shouldBeQueued());
}

public function getConversionsFiles(string $collectionName = ''): self
{
return $this
Expand Down
155 changes: 40 additions & 115 deletions src/Conversions/FileManipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,179 +2,104 @@

namespace Spatie\MediaLibrary\Conversions;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompleted;
use Spatie\MediaLibrary\Conversions\Events\ConversionWillStart;
use Spatie\MediaLibrary\Conversions\Actions\PerformConversionAction;
use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory;
use Spatie\MediaLibrary\Conversions\Jobs\PerformConversionsJob;
use Spatie\MediaLibrary\MediaCollections\Filesystem;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\ResponsiveImages\ResponsiveImageGenerator;
use Spatie\MediaLibrary\Support\ImageFactory;
use Spatie\MediaLibrary\Support\TemporaryDirectory;

class FileManipulator
{
public function createDerivedFiles(
Media $media,
array $only = [],
array $onlyConversionNames = [],
bool $onlyMissing = false
): void {
$profileCollection = ConversionCollection::createForMedia($media);

if (! empty($only)) {
$profileCollection = $profileCollection->filter(
fn (Conversion $conversion) => in_array($conversion->getName(), $only)
);
if (!$this->canConvertMedia($media)) {
return;
}

$this->performConversions(
$profileCollection->getNonQueuedConversions($media->collection_name),
$media,
$onlyMissing
);
[$queuedConversions, $conversions] = ConversionCollection::createForMedia($media)
->filter(function (Conversion $conversion) use ($onlyConversionNames) {
if (count($onlyConversionNames) === 0) {
return true;
}

$queuedConversions = $profileCollection->getQueuedConversions($media->collection_name);
return in_array($conversion->getName(), $onlyConversionNames);
})
->filter(fn (Conversion $conversion) => $conversion->shouldBePerformedOn($media->collection_name))
->partition(fn (Conversion $conversion) => $conversion->shouldBeQueued());

if ($queuedConversions->isNotEmpty()) {
$this->dispatchQueuedConversions($media, $queuedConversions, $onlyMissing);
}
$this
->dispatchQueuedConversions($media, $queuedConversions, $onlyMissing)
->performConversions($conversions, $media, $onlyMissing);
}

public function performConversions(
ConversionCollection $conversions,
Media $media,
bool $onlyMissing = false
): void {
): self {
if ($conversions->isEmpty()) {
return;
}

$imageGenerator = ImageGeneratorFactory::forMedia($media);

if (! $imageGenerator) {
return;
return $this;
}

$temporaryDirectory = TemporaryDirectory::create();

$copiedOriginalFile = $this->filesystem()->copyFromMediaLibrary(
$copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary(
$media,
$temporaryDirectory->path(Str::random(32).'.'.$media->extension)
$temporaryDirectory->path(Str::random(32) . '.' . $media->extension)
);

$conversions
->reject(function (Conversion $conversion) use ($onlyMissing, $media) {
$relativePath = $media->getPath($conversion->getName());

$rootPath = config("filesystems.disks.{$media->disk}.root");

if ($rootPath) {
if ($rootPath = config("filesystems.disks.{$media->disk}.root")) {
$relativePath = str_replace($rootPath, '', $relativePath);
}

return $onlyMissing && Storage::disk($media->disk)->exists($relativePath);
})
->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) {
event(new ConversionWillStart($media, $conversion, $copiedOriginalFile));

$copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion);

$manipulationResult = $this->performManipulations($media, $conversion, $copiedOriginalFile);

$newFileName = $conversion->getConversionFile($media);

$renamedFile = $this->renameInLocalDirectory($manipulationResult, $newFileName);

if ($conversion->shouldGenerateResponsiveImages()) {
/** @var ResponsiveImageGenerator $responsiveImageGenerator */
$responsiveImageGenerator = app(ResponsiveImageGenerator::class);

$responsiveImageGenerator->generateResponsiveImagesForConversion(
$media,
$conversion,
$renamedFile
);
}

$this->filesystem()->copyToMediaLibrary($renamedFile, $media, 'conversions');

$media->markAsConversionGenerated($conversion->getName());

event(new ConversionHasBeenCompleted($media, $conversion));
->each(function (Conversion $conversion) use ($media, $copiedOriginalFile) {
(new PerformConversionAction)->execute($conversion, $media, $copiedOriginalFile);
});

$temporaryDirectory->delete();
}

public function performManipulations(
Media $media,
Conversion $conversion,
string $imageFile
): string {
if ($conversion->getManipulations()->isEmpty()) {
return $imageFile;
}

$conversionTempFile = $this->getConversionTempFileName($media, $conversion, $imageFile);

File::copy($imageFile, $conversionTempFile);

$supportedFormats = ['jpg', 'pjpg', 'png', 'gif'];
if ($conversion->shouldKeepOriginalImageFormat() && in_array($media->extension, $supportedFormats)) {
$conversion->format($media->extension);
}

ImageFactory::load($conversionTempFile)
->manipulate($conversion->getManipulations())
->save();

return $conversionTempFile;
return $this;
}

protected function dispatchQueuedConversions(
Media $media,
ConversionCollection $queuedConversions,
ConversionCollection $conversions,
bool $onlyMissing = false
): void {
$performConversionsJobClass = config('media-library.jobs.perform_conversions', PerformConversionsJob::class);

$job = new $performConversionsJobClass($queuedConversions, $media, $onlyMissing);

if ($customQueue = config('media-library.queue_name')) {
$job->onQueue($customQueue);
): self {
if ($conversions->isEmpty()) {
return $this;
}

dispatch($job);
}
$performConversionsJobClass = config(
'media-library.jobs.perform_conversions',
PerformConversionsJob::class
);

protected function renameInLocalDirectory(
string $fileNameWithDirectory,
string $newFileNameWithoutDirectory
): string {
$targetFile = pathinfo($fileNameWithDirectory, PATHINFO_DIRNAME).'/'.$newFileNameWithoutDirectory;
/** @var PerformConversionsJob $job */
$job = (new $performConversionsJobClass($conversions, $media, $onlyMissing))
->onQueue(config('media-library.queue_name'));

rename($fileNameWithDirectory, $targetFile);
dispatch($job);

return $targetFile;
return $this;
}

protected function filesystem(): Filesystem
protected function canConvertMedia(Media $media): bool
{
return app(Filesystem::class);
}

protected function getConversionTempFileName(
Media $media,
Conversion $conversion,
string $imageFile
): string {
$directory = pathinfo($imageFile, PATHINFO_DIRNAME);

$fileName = Str::random(32)."{$conversion->getName()}.{$media->extension}";
$imageGenerator = ImageGeneratorFactory::forMedia($media);

return "{$directory}/{$fileName}";
return $imageGenerator ? true : false;
}
}
4 changes: 2 additions & 2 deletions tests/Conversions/FileManipulatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace Spatie\MediaLibrary\Tests\Conversions;

use Spatie\MediaLibrary\Conversions\Actions\PerformManipulationsAction;
use Spatie\MediaLibrary\Conversions\Conversion;
use Spatie\MediaLibrary\Conversions\FileManipulator;
use Spatie\MediaLibrary\Tests\TestCase;

class FileManipulatorTest extends TestCase
Expand All @@ -25,7 +25,7 @@ public function it_does_not_perform_manipulations_if_not_necessary()
$imageFile = $this->getTestJpg();
$media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection();

$conversionTempFile = (new FileManipulator)->performManipulations(
$conversionTempFile = (new PerformManipulationsAction())->execute(
$media,
$this->conversion->withoutManipulations(),
$imageFile
Expand Down