Repository navigation
fix(profile): corrige upload de capa e avatar (#458) #523
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
133 changes: 133 additions & 0 deletions
133
app-modules/identity/src/User/Concerns/HasProfileImages.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\Identity\User\Concerns; | ||
|
|
||
| use He4rt\Identity\User\Enums\ProfileImage; | ||
| use Illuminate\Http\UploadedFile; | ||
| use Illuminate\Support\Str; | ||
| use Spatie\Image\Enums\Fit; | ||
| use Spatie\MediaLibrary\MediaCollections\Models\Media; | ||
|
|
||
| /** | ||
| * Avatar e capa do perfil: como são guardados, convertidos e enquadrados. | ||
| * | ||
| * As dimensões e limites moram no enum ProfileImage; aqui fica só o que | ||
| * acontece com o arquivo. | ||
| */ | ||
| trait HasProfileImages | ||
| { | ||
| /** | ||
| * Chamado pelo `registerMediaCollections()` do model: o media library | ||
| * também define esse método, e dois traits com o mesmo nome colidem. | ||
| */ | ||
| public function registerProfileImageCollections(): void | ||
| { | ||
| foreach (ProfileImage::cases() as $image) { | ||
| $this->addMediaCollection($image->value) | ||
| ->singleFile() | ||
| ->useDisk('public') | ||
| ->acceptsMimeTypes(ProfileImage::mimeTypes()) | ||
| ->registerMediaConversions(function (?Media $media = null) use ($image): void { | ||
| // O que é servido inteiro não passa por aqui: converter | ||
| // acharia o primeiro quadro de um GIF e mataria a animação. | ||
| // O enquadramento desses fica por conta do object-cover. | ||
| if (in_array($media?->mime_type, ProfileImage::unconvertedMimeTypes(), strict: true)) { | ||
| return; | ||
| } | ||
|
|
||
| // Para o resto, o front recebe sempre a mesma dimensão e o | ||
| // mesmo formato, independente do arquivo enviado. Aqui | ||
| // também é onde o upscale acontece, quando necessário. | ||
| $this->addMediaConversion($image->value) | ||
| ->nonQueued() | ||
| ->fit(Fit::Crop, $image->width(), $image->height()) | ||
| ->format('webp'); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| public function putImage(ProfileImage $image, UploadedFile $file): void | ||
| { | ||
| $this->refreshMediaRelation(); | ||
|
|
||
| // A collection é singleFile: o media library troca a imagem anterior. | ||
| $this->addMedia($file) | ||
| ->usingFileName(Str::uuid()->toString().'.'.$this->extensionOf($file)) | ||
| ->toMediaCollection($image->value); | ||
| } | ||
|
|
||
| public function removeImage(ProfileImage $image): void | ||
| { | ||
| $this->refreshMediaRelation(); | ||
|
|
||
| $this->clearMediaCollection($image->value); | ||
| } | ||
|
|
||
| /** | ||
| * URL da conversão normalizada, caindo no original quando não existe | ||
| * conversão: mídia antiga, ou formato que é servido como chega. | ||
| */ | ||
| public function imageUrl(ProfileImage $image): ?string | ||
| { | ||
| $media = $this->getFirstMedia($image->value); | ||
|
|
||
| if (!$media instanceof Media) { | ||
| return null; | ||
| } | ||
|
|
||
| return $media->hasGeneratedConversion($image->value) | ||
| ? $media->getUrl($image->value) | ||
| : $media->getUrl(); | ||
| } | ||
|
|
||
| /** | ||
| * Imagem servida inteira, sem conversão, depende do enquadramento para | ||
| * decidir o que aparece no recorte da tela. | ||
| */ | ||
| public function imageNeedsFraming(ProfileImage $image): bool | ||
| { | ||
| $media = $this->getFirstMedia($image->value); | ||
|
|
||
| return $media instanceof Media && !$media->hasGeneratedConversion($image->value); | ||
| } | ||
|
|
||
| /** | ||
| * Faixa vertical da imagem que aparece no recorte da tela, em porcentagem. | ||
| */ | ||
| public function imageFocalY(ProfileImage $image): int | ||
| { | ||
| $focalY = $this->getFirstMedia($image->value)?->getCustomProperty('focal_y'); | ||
|
|
||
| return is_numeric($focalY) ? (int) $focalY : ProfileImage::DEFAULT_FOCAL_Y; | ||
| } | ||
|
|
||
| public function setImageFocalY(ProfileImage $image, int $focalY): void | ||
| { | ||
| $media = $this->getFirstMedia($image->value); | ||
|
|
||
| if (!$media instanceof Media) { | ||
| return; | ||
| } | ||
|
|
||
| $media->setCustomProperty('focal_y', max(0, min(100, $focalY))); | ||
| $media->save(); | ||
| } | ||
|
|
||
| /** | ||
| * O media library resolve `singleFile` lendo a relação já carregada. Numa | ||
| * requisição Livewire ela foi carregada na renderização, antes do upload, | ||
| * então sem descartar o cache a imagem anterior não é encontrada e fica | ||
| * órfã no disco. | ||
| */ | ||
| private function refreshMediaRelation(): void | ||
| { | ||
| $this->unsetRelation('media'); | ||
| } | ||
|
|
||
| private function extensionOf(UploadedFile $file): string | ||
| { | ||
| return $file->getClientOriginalExtension() ?: $file->guessExtension() ?: 'jpg'; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\Identity\User\Enums; | ||
|
|
||
| /** | ||
| * Fonte única de configuração das imagens de perfil: nome da collection no | ||
| * media library, dimensão servida ao front, piso aceito no upload, proporção | ||
| * e limite de tamanho. | ||
| * | ||
| * Variação de imagem aqui é dado, não subclasse: uma imagem nova entra como | ||
| * mais um case e já nasce com upload, recorte, validação e conversão. | ||
| * | ||
| * Altura é sempre derivada da proporção, nunca armazenada, senão largura e | ||
| * altura divergem e o recorte deixa de ser previsível. | ||
| */ | ||
| enum ProfileImage: string | ||
| { | ||
| case Avatar = 'avatar'; | ||
| case Cover = 'cover'; | ||
|
|
||
| /** Centro da imagem: o recorte pega a faixa do meio. */ | ||
| public const int DEFAULT_FOCAL_Y = 50; | ||
|
|
||
| /** | ||
| * @return list<string> | ||
| */ | ||
| public static function mimeTypes(): array | ||
| { | ||
| return ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; | ||
| } | ||
|
|
||
| /** | ||
| * Formatos servidos exatamente como chegam, sem conversão. | ||
| * | ||
| * @return list<string> | ||
| */ | ||
| public static function unconvertedMimeTypes(): array | ||
| { | ||
| return ['image/gif']; | ||
| } | ||
|
|
||
| /** | ||
| * Teto menor para o que é servido sem conversão: nesses formatos o peso do | ||
| * upload é o peso que cada visita ao perfil baixa. | ||
| */ | ||
| public static function unconvertedMaxKilobytes(): int | ||
| { | ||
| return 2_048; | ||
| } | ||
|
|
||
| /** | ||
| * Os mesmos formatos, como o usuário os reconhece. | ||
| * | ||
| * GIF entra e é servido como chega, com a animação intacta: converter | ||
| * leria só o primeiro quadro no GD. Quem recorta pelo editor perde a | ||
| * animação, porque o recorte acontece no canvas do browser. | ||
| */ | ||
| public static function formatLabels(): string | ||
| { | ||
| return 'JPG, PNG, GIF, WEBP'; | ||
| } | ||
|
|
||
| /** | ||
| * Largura da conversão servida ao front. | ||
| */ | ||
| public function width(): int | ||
| { | ||
| return match ($this) { | ||
| self::Avatar => 500, | ||
| self::Cover => 1_800, | ||
| }; | ||
| } | ||
|
|
||
| public function height(): int | ||
| { | ||
| return $this->heightFor($this->width()); | ||
| } | ||
|
|
||
| /** | ||
| * Menor largura aceita no upload. Abaixo disso o upscale ficaria agressivo | ||
| * demais; entre o piso e a largura ideal, quem estica é a conversão. | ||
| */ | ||
| public function minWidth(): int | ||
| { | ||
| return match ($this) { | ||
| self::Avatar => 256, | ||
| self::Cover => 1_200, | ||
| }; | ||
| } | ||
|
|
||
| public function minHeight(): int | ||
| { | ||
| return $this->heightFor($this->minWidth()); | ||
| } | ||
|
|
||
| /** | ||
| * Proporção no formato aceito pelo editor de recorte do Filament. | ||
| */ | ||
| public function aspectRatio(): string | ||
| { | ||
| [$width, $height] = $this->ratio(); | ||
|
|
||
| return sprintf('%d:%d', $width, $height); | ||
| } | ||
|
|
||
| /** | ||
| * A mesma proporção, no formato da propriedade CSS `aspect-ratio`. O blade | ||
| * não deve conhecer esses números por conta própria. | ||
| */ | ||
| public function cssAspectRatio(): string | ||
| { | ||
| [$width, $height] = $this->ratio(); | ||
|
|
||
| return sprintf('%d / %d', $width, $height); | ||
| } | ||
|
|
||
| public function maxKilobytes(): int | ||
| { | ||
| return match ($this) { | ||
| self::Avatar => 2_048, | ||
| self::Cover => 4_096, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * @return array{int, int} | ||
| */ | ||
| private function ratio(): array | ||
| { | ||
| return match ($this) { | ||
| self::Avatar => [1, 1], | ||
| self::Cover => [3, 1], | ||
| }; | ||
| } | ||
|
|
||
| private function heightFor(int $width): int | ||
| { | ||
| [$ratioWidth, $ratioHeight] = $this->ratio(); | ||
|
|
||
| return intdiv($width * $ratioHeight, $ratioWidth); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| use He4rt\Identity\User\Enums\ProfileImage; | ||
|
|
||
| test('height is always derived from the aspect ratio', function (ProfileImage $image): void { | ||
| [$ratioWidth, $ratioHeight] = explode(':', $image->aspectRatio()); | ||
|
|
||
| expect($image->height())->toBe(intdiv($image->width() * (int) $ratioHeight, (int) $ratioWidth)) | ||
| ->and($image->minHeight())->toBe(intdiv($image->minWidth() * (int) $ratioHeight, (int) $ratioWidth)); | ||
| })->with(ProfileImage::cases()); | ||
|
|
||
| test('the minimum is never bigger than the recommended size', function (ProfileImage $image): void { | ||
| expect($image->minWidth())->toBeLessThanOrEqual($image->width()) | ||
| ->and($image->minHeight())->toBeLessThanOrEqual($image->height()); | ||
| })->with(ProfileImage::cases()); | ||
|
|
||
| test('css aspect ratio mirrors the cropper aspect ratio', function (ProfileImage $image): void { | ||
| expect($image->cssAspectRatio())->toBe(str_replace(':', ' / ', $image->aspectRatio())); | ||
| })->with(ProfileImage::cases()); | ||
|
|
||
| test('cover is wide and avatar is square', function (): void { | ||
| expect(ProfileImage::Cover->aspectRatio())->toBe('3:1') | ||
| ->and(ProfileImage::Avatar->aspectRatio())->toBe('1:1'); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.