🚚 Passe toutes les images sous MediaLibrary

Fix #14
This commit is contained in:
Clement Desmidt 2020-03-19 12:11:21 +01:00
parent 9ec28afa4a
commit 3ab7e495e9
10 changed files with 131 additions and 73 deletions

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers;
use App\Http\Requests\AddPost;
use App\Post;
use App\PostsTag;
use App\Services\ImageService;
@ -11,6 +12,9 @@ use DateTime;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\DiskDoesNotExist;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileDoesNotExist;
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileIsTooBig;
class DashboardController extends Controller
{
@ -72,39 +76,35 @@ class DashboardController extends Controller
/**
* Edit today's entry
* @param AddPost $request
* @param TagDetectorService $tag_detector
* @return
* @throws \Exception
*/
public function edit(TagDetectorService $tag_detector)
public function edit(AddPost $request, TagDetectorService $tag_detector)
{
/** @var Post $today_post */
$today_post = Post::whereDate('date_post', '=', (new DateTime())->format('Y-m-d'))
->where('user_id', Auth::user()->getAuthIdentifier())
->firstOrFail();
$data = request()->validate([
'message' => 'required'
]);
$data = $request->validated();
$today_post->deleteTags();
$tags = $tag_detector->detectFrom($data['message']);
$today_post->content = $data['message'];
$today_post->save();
$all_tags = Tag::all();
$all_tags_names = [];
foreach ($all_tags as $tag) {
$all_tags_names[$tag->id] = $tag->name;
}
foreach ($tags as $tag) {
if (in_array($tag, $all_tags_names)) {
PostsTag::create([
'post_id' => $today_post->id,
'tag_id' => array_search($tag, $all_tags_names),
]);
if (!empty($validated_data['file'])) {
try {
$today_post->addMediaFromRequest('file')->toMediaCollection('post_image');
} catch (DiskDoesNotExist $e) {
} catch (FileDoesNotExist $e) {
} catch (FileIsTooBig $e) {
}
}
$today_post->deleteTags();
$today_post->content = $data['message'];
$today_post->save();
$this->setPostsTagsForPost($today_post, $tag_detector->detectFrom($data['message']));
return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
}
@ -127,37 +127,42 @@ class DashboardController extends Controller
}
/**
* @param AddPost $request
* @param TagDetectorService $tag_detector
* @return mixed
* @throws \Exception
*/
public function store(TagDetectorService $tag_detector, ImageService $image_service)
public function store(AddPost $request, TagDetectorService $tag_detector)
{
$user_id = Auth::user()->getAuthIdentifier();
$validated_data = $request->validated();
$validated_data = request()->validate([
'message' => 'required',
'file' => 'file|mimes:jpeg,png,jpg,gif,svg',
]);
$data = [
'user_id' => $user_id,
/** @var Post $post */
$post = Post::create([
'user_id' => Auth::user()->getAuthIdentifier(),
'date_post' => new DateTime(),
'content' => $validated_data['message'],
];
]);
if (!empty($validated_data['file'])) {
/** @var UploadedFile $uploaded_document */
$uploaded_document = $validated_data['file'];
$file_name = $uploaded_document->getClientOriginalName();
$uploaded_document->storeAs(Auth::user()->getFolder(), $file_name);
$image_service->makeThumbnail($uploaded_document->getRealPath(), ['width' => 300]);
$data['image'] = $file_name;
try {
$post->addMediaFromRequest('file')->toMediaCollection('post_image');
} catch (DiskDoesNotExist $e) {
} catch (FileDoesNotExist $e) {
} catch (FileIsTooBig $e) {
}
}
$tags = $tag_detector->detectFrom($data['content']);
$this->setPostsTagsForPost($post, $tag_detector->detectFrom($validated_data['message']));
$check = Post::create($data);
return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
}
/**
* @param Post $post
* @param $tags
*/
private function setPostsTagsForPost(Post $post, $tags)
{
$all_tags = Tag::all();
$all_tags_names = [];
foreach ($all_tags as $tag) {
@ -165,14 +170,12 @@ class DashboardController extends Controller
}
foreach ($tags as $tag) {
if (in_array($tag, $all_tags_names)) {
if (in_array($tag, $all_tags_names, true)) {
PostsTag::create([
'post_id' => $check->id,
'post_id' => $post->id,
'tag_id' => array_search($tag, $all_tags_names),
]);
}
}
return Redirect::to('home')->withSuccess('Great! Form successfully submit with validation.');
}
}

View File

@ -4,10 +4,11 @@ namespace App\Http\Controllers;
use App\Post;
use App\Services\ImageService;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\File;
use Spatie\MediaLibrary\Models\Media;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
@ -15,28 +16,40 @@ class ImageController extends Controller
{
/**
* @param int $post_id
* @param string|array $options
* @param string $alias
* @param string $image
* @param ImageService $image_service
*
* @return mixed
*/
public function display($post_id, $options = 'o:full', $image, ImageService $image_service)
public function display($post_id, $alias = '')
{
/** @var Post $post */
$post = Post::find($post_id);
if (Auth::user()->getAuthIdentifier() !== (int)$post->user_id) {
throw new UnauthorizedHttpException('Cette image ne vous appartient pas.');
}
$original = sprintf('%s/%s/%s', storage_path('app'), Auth::user()->getFolder(), $image);
if ('o:full' === $options) {
$img = $image_service->makeThumbnail($original);
} else {
$img = $image_service->makeThumbnail($original, ['width' => 300]);
$first_media = $post->getFirstMedia('post_image');
if (!$first_media instanceof Media) {
throw new NotFoundHttpException('Média non trouvé en base.');
}
return $img->response(File::extension($original));
return Image::make($first_media->getPath($alias))->response($first_media->mime_type);
}
/**
* @param string $alias
* @return mixed
*/
public function avatar($alias = '')
{
/** @var User $user */
$user = User::find(Auth::user()->getAuthIdentifier());
readfile($user->getFirstMediaPath('avatars', $alias));
exit;
}
/**

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class AddPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return !Auth::guest();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'message' => 'required',
'file' => 'file|mimes:jpeg,png,jpg,gif,svg',
];
}
}

View File

@ -3,9 +3,15 @@
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Spatie\Image\Exceptions\InvalidManipulation;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\Models\Media;
class Post extends Model
class Post extends Model implements HasMedia
{
use HasMediaTrait;
/**
* The attributes that are mass assignable.
*
@ -52,4 +58,18 @@ class Post extends Model
->orderBy('date_post')
->get();
}
/**
* @param Media|null $media
*/
public function registerMediaConversions(Media $media = null)
{
try {
$this->addMediaConversion('list')
->width(300)
->optimize();
} catch (InvalidManipulation $e) {
Log::alert(sprintf('Error while manipulating Post Image for %s (%s)', $this->id, $e->getMessage()));
}
}
}

View File

@ -72,13 +72,4 @@ class User extends Authenticatable implements HasMedia
Log::alert(sprintf('Error while manipulating Avatar for %s (%s)', $this->email, $e->getMessage()));
}
}
/**
* @param string $alias
* @return string
*/
public function getAvatar($alias = 'thumb'): string
{
return $this->getFirstMediaUrl('avatars', $alias);
}
}

View File

@ -21,7 +21,7 @@
<div class="card-body">
<p>
<a href="{{ route('display_image', ['post_id' => $post->id, 'options' => 'o:full', 'image_name' => $post->image]) }}">
<img src="{{ route('display_image', ['post_id' => $post->id, 'options' => 'w:300', 'image_name' => $post->image]) }}"/>
<img src="{{ route('display_image', ['post_id' => $post->id, 'alias' => 'list']) }}"/>
</a>
</p>
</div>

View File

@ -126,8 +126,7 @@
</div>
</div>
<div class="card-body @if($today->format('Y-m-d') === \Carbon\Carbon::instance($post->date_post)->format('Y-m-d')) already @endif ">
@if($post->image != '')<p><img src="{{ route('display_image', ['post_id' => $post->id, 'options' => 'w:300', 'image_name' => $post->image]) }}"/></p>@endif
<p data-encrypt>{!! $tag_detector->linkTagFrom($post->content) !!}</p>
@if($post->hasMedia('post_image'))<p><img src="{{ route('display_image', ['post_id' => $post->id]) }}"/></p>@endif <p data-encrypt>{!! $tag_detector->linkTagFrom($post->content) !!}</p>
</div>
<div class="card-footer">
{{ \Carbon\Carbon::instance($post->date_post)->format('d F Y') }}

View File

@ -55,10 +55,10 @@
</div>
<div class="dropdown">
<a href="#" class="nav-link pr-0 leading-none" data-toggle="dropdown">
@php($avatar = Auth::user()->getAvatar('icon'))
@php($avatar = Auth::user()->hasMedia('avatars'))
@if($avatar !== '')
<span>
<img src="{{ $avatar }}"/>
<img src="{{ route('display_avatar', ['alias' => 'icon']) }}"/>
</span>
@else
<span class="avatar">

View File

@ -81,9 +81,8 @@
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="form-label">{{ __('Avatar') }}</div>
@php($avatar = Auth::user()->getAvatar())
@if($avatar !== '')
<img src="{{ $avatar}}">
@if(Auth::user()->hasMedia('avatars'))
<img src="{{ route('display_avatar', ['alias' => 'thumb'])}}">
@endif
<div class="custom-file">
<input type="file" class="custom-file-input" name="avatar">

View File

@ -32,7 +32,8 @@ Route::group(['middleware' => ['auth']], function() {
Route::get('/calendar/{type}/{year?}/{month?}', 'StatsController@calendar')->name('calendar');
// gallery
Route::get('/display/{post_id}/{options}/{image_name}', 'ImageController@display')->name('display_image');
Route::get('/avatar/{alias}', 'ImageController@avatar')->name('display_avatar');
Route::get('/display/{post_id}/{alias?}', 'ImageController@display')->name('display_image');
Route::get('/gallery', 'ImageController@gallery')->name('gallery');
// user