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

#37 crop images #58

Merged
merged 3 commits into from
Nov 7, 2023
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
35 changes: 0 additions & 35 deletions .github/workflows/laravel.yml

This file was deleted.

35 changes: 11 additions & 24 deletions app/Http/Controllers/Recipe/ImportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
use App\Http\Requests\Import\ImportRequest;
use App\Http\Requests\Recipe\RecipeRequest;
use App\Http\Resources\Recipe\ImportResource;
use App\Http\Traits\UploadImageTrait;
use App\Http\Traits\FillableAttributes;
use App\Models\Recipe;
use App\Support\FileHelper;
use App\Support\OpenAIRecipeParser;
use App\Support\StructuredDataRecipeParser;
use Brick\StructuredData\HTMLReader;
Expand All @@ -17,12 +16,11 @@
use Brick\StructuredData\Reader\RdfaLiteReader;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Inertia\Inertia;

class ImportController extends Controller
{
use UploadImageTrait;
use FillableAttributes;

public function index()
{
Expand Down Expand Up @@ -67,35 +65,24 @@ public function create(ImportRequest $request)
*/
public function store(RecipeRequest $request)
{
$return_to_import_page = $request->get('return_to_import_page');

$attributes = $request->validated();
$attributes['user_id'] = $request->user()->id;
// TODO Make a mutator for this.
// Convert tags to lowercase and trim whitespace.
$attributes['tags'] = !empty($attributes['tags']) ? array_filter(array_map('strtolower', array_map('trim', explode(',', $attributes['tags'])))) : [];

$recipe = (new Recipe)->create($this->fillableAttributes(new Recipe, $attributes));

if ($external_image = $request->get('external_image')) {
$extension = substr($external_image, strrpos($external_image, '.') + 1);
if ($externalImage = $request->get('external_image')) {
try {
$attributes['image'] = FileHelper::uploadExternalImage(
$external_image,
Str::slug($attributes['title']) . '-' . time() . '.' . $extension
);
$recipe->addMediaFromUrl($externalImage)
->toMediaCollection('recipe_image');
} catch (\Exception $e) {
// @TODO handle exception
}
}

if ($image = $this->saveImage($request)) {
$attributes['image'] = $image;
}

$attributes['tags'] = !empty($attributes['tags']) ? array_filter(array_map('strtolower', array_map('trim', explode(',', $attributes['tags'])))) : [];

// Always unset external_image, because it's not saved to the database.
unset($attributes['external_image']);

$recipe = Recipe::create($attributes);

if ($return_to_import_page) {
if ($request->get('return_to_import_page')) {
return redirect()->route('import.index')->with('success', 'Het recept “<a href="' . route('recipes.show', $recipe->slug) . '"><i>' . $recipe->title . '</i></a>” is succesvol geïmporteerd!');
}
return redirect()->route('recipes.show', $recipe->slug)->with('success', "Het recept “<i>{$recipe->title}</i>” is succesvol geïmporteerd!");
Expand Down
88 changes: 48 additions & 40 deletions app/Http/Controllers/Recipe/RecipeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,18 @@
use App\Http\Resources\Recipe\IngredientsResource;
use App\Http\Resources\StructuredData\Recipe\IngredientsResource as StructuredDataIngredientsResource;
use App\Http\Resources\StructuredData\Recipe\InstructionsResource;
use App\Http\Traits\UploadImageTrait;
use App\Http\Traits\FillableAttributes;
use App\Models\Recipe;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Inertia\Inertia;
use ProtoneMedia\LaravelCrossEloquentSearch\Search;

class RecipeController extends Controller
{
use UploadImageTrait;
use FillableAttributes;

/**
* Display a listing of the resource.
Expand All @@ -35,7 +34,7 @@ public function index()
'id' => $recipe->id,
'title' => $recipe->title,
'slug' => $recipe->slug,
'image' => $recipe->image ? Storage::disk('public')->url($recipe->image) : null,
'image' => $recipe->getFirstMediaUrl('recipe_image', 'overview'),
]),
]);
}
Expand All @@ -60,15 +59,12 @@ public function store(RecipeRequest $request)
{
$attributes = $request->validated();
$attributes['user_id'] = $request->user()->id;

if ($image = $this->saveImage($request)) {
$attributes['image'] = $image;
}

// TODO Make a mutator for this. Also for the update method.
$attributes['tags'] = !empty($attributes['tags']) ? array_filter(array_map('strtolower', array_map('trim', explode(',', $attributes['tags'])))) : [];

$recipe = (new Recipe)->create($this->fillableAttributes(new Recipe, $attributes));

$recipe = Recipe::create($attributes);
$this->saveMedia($request, $recipe);

return redirect()->route('recipes.show', $recipe->slug)->with('success', "Het recept “<i>{$recipe->title}</i>” is succesvol toegevoegd!");
}
Expand All @@ -93,7 +89,7 @@ public function show(Request $request, string $slug)
'id' => $recipe->id,
'title' => $recipe->title,
'slug' => $recipe->slug,
'image' => $recipe->image ? Storage::disk('public')->url($recipe->image) : null,
'image' => $recipe->getFirstMediaUrl('recipe_image', 'show'),
'summary' => $recipe->summary,
'tags' => $recipe->tags->pluck('name'),
'servings' => $recipe->servings,
Expand All @@ -115,7 +111,7 @@ public function show(Request $request, string $slug)
])->withViewData([
'open_graph' => [
'title' => $recipe->title,
'image' => $recipe->image ? Storage::disk('public')->url($recipe->image) : null,
'image' => $recipe->getFirstMediaUrl('recipe_image', 'show'),
'url' => URL::current(),
],
]);
Expand All @@ -129,16 +125,12 @@ public function show(Request $request, string $slug)
*/
public function edit(Recipe $recipe)
{
if ($recipe->image) {
$recipe->image = Storage::disk('public')->url($recipe->image);
}

return Inertia::render('Recipes/Form', [
'recipe' => [
'id' => $recipe->id,
'title' => $recipe->title,
'slug' => $recipe->slug,
'image' => $recipe->image,
'media' => $recipe->getFirstMedia('recipe_image'),
'summary' => $recipe->summary,
'tags' => $recipe->tags->pluck('name')->implode(', '),
'servings' => $recipe->servings,
Expand All @@ -162,32 +154,16 @@ public function edit(Recipe $recipe)
*/
public function update(RecipeRequest $request, Recipe $recipe)
{
$attributes = $request->validated();
$destroyImage = $request->get('destroy_image', false);

// If the image field is empty, remove it from the attributes array, because there is no image to update or delete.
if (empty($attributes['image'])) {
unset($attributes['image']);
}

if ($image = $this->saveImage($request)) {
$attributes['image'] = $image;
$attributes = $request->validated();
$attributes['tags'] = !empty($attributes['tags']) ? array_filter(array_map('strtolower', array_map('trim', explode(',', $attributes['tags'])))) : [];

// Delete the old image if there is one.
if ($recipe->image) {
$this->destroyImage($recipe);
}
}
$recipe->update($this->fillableAttributes($recipe, $attributes));

// If the user wants to remove the image, set the image field to null and delete the image.
if ($destroyImage) {
$attributes['image'] = null;
$this->destroyImage($recipe);
if ($request->get('destroy_media', false)) {
$recipe->clearMediaCollection('recipe_image');
}

$attributes['tags'] = !empty($attributes['tags']) ? array_filter(array_map('strtolower', array_map('trim', explode(',', $attributes['tags'])))) : [];

$recipe->update($attributes);
$this->saveMedia($request, $recipe);

return redirect()->route('recipes.show', $recipe->slug)->with('success', "Het recept “<i>{$recipe->title}</i>” is succesvol gewijzigd!");
}
Expand Down Expand Up @@ -217,7 +193,7 @@ private function notFound(Request $request, $slug): \Illuminate\Http\JsonRespons
'id' => $recipe->id,
'title' => $recipe->title,
'slug' => $recipe->slug,
'image' => $recipe->image ? Storage::url($recipe->image) : null,
'image' => $recipe->getFirstMedia('recipe_image', 'overview'),
]);

return Inertia::render('Recipes/NotFound', [
Expand All @@ -227,4 +203,36 @@ private function notFound(Request $request, $slug): \Illuminate\Http\JsonRespons
->toResponse($request)
->setStatusCode(404);
}

private function saveMedia(Request $request, Recipe $recipe): void
{
$mediaDimensions = $request->get('media_dimensions', []);

if (!empty($mediaDimensions['card'])) {
$cardDimensions = $mediaDimensions['card'];
$manipulationsCard = ['manualCrop' => "${cardDimensions['width']},${cardDimensions['height']},${cardDimensions['left']},${cardDimensions['top']}"];
}

if (!empty($mediaDimensions['show'])) {
$showDimensions = $mediaDimensions['show'];
$manipulationsShow = ['manualCrop' => "${showDimensions['width']},${showDimensions['height']},${showDimensions['left']},${showDimensions['top']}"];
}

if ($request->hasFile('media')) {
$recipe->addMediaFromRequest('media')
->withManipulations([
'card' => $manipulationsCard ?? [],
'show' => $manipulationsShow ?? [],
])
->toMediaCollection('recipe_image');
}

if ($media = $recipe->getFirstMedia('recipe_image')) {
$media->manipulations = [
'card' => $manipulationsCard ?? [],
'show' => $manipulationsShow ?? [],
];
$media->save();
}
}
}
2 changes: 1 addition & 1 deletion app/Http/Requests/Recipe/RecipeRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function rules()
{
return [
'title' => 'required',
'image' => ['nullable', 'file', 'image', 'mimes:jpg,jpeg,png'],
'media' => ['nullable', 'image', 'mimes:jpg,png', 'max:' . (config('media-library.max_file_size', 1024 * 1024 * 10) / 1024)],
'external_image' => ['nullable', 'url', new ExternalImage],
'tags' => ['nullable', 'string'],
'servings' => ['required', 'integer', 'min:1'],
Expand Down
18 changes: 18 additions & 0 deletions app/Http/Traits/FillableAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Http\Traits;

use App\Models\Recipe;

trait FillableAttributes
{
// TODO See if this can be refactored to a model trait.
private function fillableAttributes(Recipe $recipe, array $attributes): array
{
return array_filter(
$attributes,
static fn($key) => in_array($key, $recipe->getFillable(), true),
ARRAY_FILTER_USE_KEY
);
}
}
44 changes: 0 additions & 44 deletions app/Http/Traits/UploadImageTrait.php

This file was deleted.

Loading