diff --git a/app/Casts/HtmlColor.php b/app/Casts/HtmlColor.php index 291bb36..39a36f6 100644 --- a/app/Casts/HtmlColor.php +++ b/app/Casts/HtmlColor.php @@ -15,10 +15,10 @@ class HtmlColor implements CastsAttributes /** * Cast the given value. * - * @param Model $model - * @param string $key - * @param mixed $value - * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes * @return string * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing @@ -32,10 +32,10 @@ class HtmlColor implements CastsAttributes /** * Prepare the given value for storage. * - * @param Model $model - * @param string $key - * @param mixed $value - * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes * @return integer * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing diff --git a/app/Casts/RgbaColor.php b/app/Casts/RgbaColor.php index eaaebac..8f41586 100644 --- a/app/Casts/RgbaColor.php +++ b/app/Casts/RgbaColor.php @@ -11,10 +11,10 @@ class RgbaColor extends HtmlColor /** * Cast the given value. * - * @param Model $model - * @param string $key - * @param mixed $value - * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes * @return string * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing @@ -24,6 +24,7 @@ class RgbaColor extends HtmlColor public function get($model, $key, $value, $attributes) { // phpcs:enable + /** @var \Illuminate\Support\Collection */ $intValues = collect(\str_split($this->zeropad(\dechex(\intval($value)), 8), 2))->map(function ($hex) { return intval(\hexdec($hex)); }); @@ -35,10 +36,10 @@ class RgbaColor extends HtmlColor /** * Prepare the given value for storage. * - * @param Model $model - * @param string $key - * @param mixed $value - * @param array $attributes + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes * @return integer * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing diff --git a/app/Console/Commands/TestMail.php b/app/Console/Commands/TestMail.php index 3b5bfee..176f35a 100644 --- a/app/Console/Commands/TestMail.php +++ b/app/Console/Commands/TestMail.php @@ -12,7 +12,7 @@ class TestMail extends Command * * @var string */ - protected $signature = 'mail:test'; + protected $signature = 'uwil:mail:test'; /** * The console command description. diff --git a/app/Console/Commands/UserCreate.php b/app/Console/Commands/UserCreate.php index 9d39b03..4af399c 100644 --- a/app/Console/Commands/UserCreate.php +++ b/app/Console/Commands/UserCreate.php @@ -15,7 +15,7 @@ class UserCreate extends Command * * @var string */ - protected $signature = 'user:create'; + protected $signature = 'uwil:user:create'; /** * The console command description. @@ -25,30 +25,30 @@ class UserCreate extends Command protected $description = 'Create a backend admin user'; /** - * The firstname of the new user. + * The first name of the new user. * - * @var string + * @var string|null */ protected $firstname; /** - * The lastname of the new user. + * The last name of the new user. * - * @var string + * @var string|null */ protected $lastname; /** * The email of the new user. * - * @var string + * @var string|null */ protected $email; /** * The password of the new user. * - * @var string + * @var string|null */ protected $password; @@ -60,10 +60,10 @@ class UserCreate extends Command public function handle(): int { $this->firstname = null; - $this->addFirstname(); + $this->addFirstName(); $this->lastname = null; - $this->addLastname(); + $this->addLastName(); $this->email = null; $this->addEmail(); @@ -72,11 +72,12 @@ class UserCreate extends Command $this->addPassword(); $user = new User([ - 'firstname' => $this->firstname, - 'lastname' => $this->lastname, - 'email' => $this->email, - 'password' => $this->password, - 'last_connection' => Carbon::now(), + 'firstname' => $this->firstname, + 'lastname' => $this->lastname, + 'email' => $this->email, + 'password' => $this->password, + 'published' => true, + 'published_at' => Carbon::now(), ]); $user->saveOrFail(); @@ -86,15 +87,15 @@ class UserCreate extends Command } /** - * Add a firstname to the user. + * Add a first name to the user. * * @return void */ - private function addFirstname(): void + private function addFirstName(): void { while (is_null($this->firstname)) { try { - $tmp = $this->ask('Type the wanted user firstname', 'Admin'); + $tmp = $this->ask('Type the wanted user first name', 'Admin'); $validator = Validator::make(['firstname' => $tmp], [ 'firstname' => 'required|min:3|max:255' ]); @@ -102,7 +103,7 @@ class UserCreate extends Command $this->firstname = $tmp; } catch (ValidationException $e) { $this->error(sprintf( - 'Please provide a valid firstname %s', + 'Please provide a valid first name %s', \implode(',', collect($e->errors())->flatten()->all()) )); continue; @@ -111,15 +112,15 @@ class UserCreate extends Command } /** - * Add a lastname to the user. + * Add a last name to the user. * * @return void */ - private function addLastname(): void + private function addLastName(): void { while (is_null($this->lastname)) { try { - $tmp = $this->ask('Type the wanted user lastname', 'Saïtama'); + $tmp = $this->ask('Type the wanted user last name', 'Saïtama'); $validator = Validator::make(['lastname' => $tmp], [ 'lastname' => 'required|min:3|max:255' ]); diff --git a/app/Enums/Advices/AdviceDifficultyEnum.php b/app/Enums/Advices/AdviceDifficultyEnum.php index e906eb4..5c64453 100644 --- a/app/Enums/Advices/AdviceDifficultyEnum.php +++ b/app/Enums/Advices/AdviceDifficultyEnum.php @@ -14,6 +14,8 @@ enum AdviceDifficultyEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::easy->name => 'Facile', diff --git a/app/Enums/Advices/AdviceTimeEnum.php b/app/Enums/Advices/AdviceTimeEnum.php index 3805811..735660d 100644 --- a/app/Enums/Advices/AdviceTimeEnum.php +++ b/app/Enums/Advices/AdviceTimeEnum.php @@ -15,6 +15,8 @@ enum AdviceTimeEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::first->name => '0 - 30min', diff --git a/app/Enums/Advices/AdviceTypeEnum.php b/app/Enums/Advices/AdviceTypeEnum.php index 43dfcf2..3457805 100644 --- a/app/Enums/Advices/AdviceTypeEnum.php +++ b/app/Enums/Advices/AdviceTypeEnum.php @@ -14,6 +14,8 @@ enum AdviceTypeEnum: int /** * Optionnal labels definition + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::all->name => 'Recettes / Astuces', diff --git a/app/Enums/Contact/ContactActivityEnum.php b/app/Enums/Contact/ContactActivityEnum.php index 95d970c..9abcc3e 100644 --- a/app/Enums/Contact/ContactActivityEnum.php +++ b/app/Enums/Contact/ContactActivityEnum.php @@ -17,6 +17,8 @@ enum ContactActivityEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::distributeur->name => 'Distributeur', diff --git a/app/Enums/Contact/ContactTimeEnum.php b/app/Enums/Contact/ContactTimeEnum.php index f10a314..f07d1e0 100644 --- a/app/Enums/Contact/ContactTimeEnum.php +++ b/app/Enums/Contact/ContactTimeEnum.php @@ -14,6 +14,8 @@ enum ContactTimeEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::morning->name => 'Le matin', diff --git a/app/Enums/ExpertiseProducts/ExpertiseProductPageEnum.php b/app/Enums/ExpertiseProducts/ExpertiseProductPageEnum.php index 4fcfd71..109134b 100644 --- a/app/Enums/ExpertiseProducts/ExpertiseProductPageEnum.php +++ b/app/Enums/ExpertiseProducts/ExpertiseProductPageEnum.php @@ -16,6 +16,8 @@ enum ExpertiseProductPageEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::duck->name => 'Canard', diff --git a/app/Enums/NutriscoreEnum.php b/app/Enums/NutriscoreEnum.php index 66b1327..8000bec 100644 --- a/app/Enums/NutriscoreEnum.php +++ b/app/Enums/NutriscoreEnum.php @@ -17,6 +17,8 @@ enum NutriscoreEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::noLetter->name => 'Ø', diff --git a/app/Enums/Products/ProductSpeciesEnum.php b/app/Enums/Products/ProductSpeciesEnum.php index 32e0d8e..07ad177 100644 --- a/app/Enums/Products/ProductSpeciesEnum.php +++ b/app/Enums/Products/ProductSpeciesEnum.php @@ -22,6 +22,8 @@ enum ProductSpeciesEnum: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::caille->name => 'Caille', diff --git a/app/Enums/StaticPageType.php b/app/Enums/StaticPageType.php index 75af980..2e6d760 100644 --- a/app/Enums/StaticPageType.php +++ b/app/Enums/StaticPageType.php @@ -19,6 +19,8 @@ enum StaticPageType: int /** * Optionnal labels definition. + * + * @phpstan-ignore-next-line */ private const LABELS = [ self::contact->name => 'Contact', diff --git a/app/Http/Controllers/Bo/AdviceController.php b/app/Http/Controllers/Bo/AdviceController.php index f4bd877..03d4ea0 100644 --- a/app/Http/Controllers/Bo/AdviceController.php +++ b/app/Http/Controllers/Bo/AdviceController.php @@ -9,14 +9,15 @@ use App\Http\Requests\Bo\Advice\UpdateAdviceRequest; use App\Models\Advice; use App\Models\Product; use App\Models\Tag; -use App\Traits\Controllers\UpdateModelStatus; +use App\Traits\Controllers\UpdateModelPublished; use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class AdviceController extends Controller { - use UpdateModelStatus; + use UpdateModelPublished; /** * Display a listing of the resource. @@ -26,7 +27,7 @@ class AdviceController extends Controller */ public function index(Request $request): \Illuminate\Contracts\View\View { - /** @var \Illuminate\Database\Eloquent\Builder $advice */ + /** @var \Illuminate\Database\Eloquent\Builder $adviceModels */ $adviceModels = Advice::query(); $type = $request->input('type'); @@ -74,27 +75,21 @@ class AdviceController extends Controller $currentType = AdviceTypeEnum::make(\intval($type)); $adviceTags = Tag::query()->select(['id', 'label', 'slug'])->get(); $adviceProducts = Product::all(); - $recipeList = Advice::where('type', '=', AdviceTypeEnum::recipes)->get(); - $tipList = Advice::where('type', '=', AdviceTypeEnum::tips)->get(); + $recipeList = Advice::query()->where('type', '=', AdviceTypeEnum::recipes)->get(); + $tipList = Advice::query()->where('type', '=', AdviceTypeEnum::tips)->get(); - $recipeList = collect($recipeList)->each(function (Advice &$value) { - $value->label = $value->title; - }); - $tipList = collect($tipList)->each(function (Advice &$value) { - $value->label = $value->title; - }); - $recipesSelected = collect([]); - $tipsSelected = collect([]); - collect($advice->advices)->each(function ($eltAdvice) use (&$recipesSelected, &$tipsSelected) { - if ($eltAdvice->type->value == AdviceTypeEnum::recipes->value()) { - $eltAdvice->label = $eltAdvice->title; - $recipesSelected = $recipesSelected->concat([$eltAdvice]); - } elseif ($eltAdvice->type->value == AdviceTypeEnum::tips->value()) { - $eltAdvice->label = $eltAdvice->title; - $tipsSelected = $tipsSelected->concat([$eltAdvice]); - } - }); + $recipesSelected = collect(); + $tipsSelected = collect(); + collect($advice->advices) + // @phpstan-ignore-next-line + ->each(function (Advice $eltAdvice) use (&$recipesSelected, &$tipsSelected) { + if ($eltAdvice->type->equals(AdviceTypeEnum::recipes)) { + $recipesSelected = $recipesSelected->concat([$eltAdvice]); + } elseif ($eltAdvice->type->equals(AdviceTypeEnum::tips)) { + $tipsSelected = $tipsSelected->concat([$eltAdvice]); + } + }); return view('bo.pages.advice.create', [ 'adviceModel' => $advice, @@ -118,14 +113,19 @@ class AdviceController extends Controller { return DB::transaction(function () use ($request) { $advice = new Advice(); - $advice->fill($request->validated()); + $advice->fill(Arr::except($request->validated(), [ + 'tags', + 'products', + 'associated_tips_list', + 'associated_recipes_list', + ])); $currentType = AdviceTypeEnum::make(\intval($request->type)); if ($advice->saveOrFail()) { - $advice->tags()->sync(collect($request->tags)->pluck('id')); - $advice->products()->sync($request->products_list); - $advice->advices()->sync(array_merge($request->recipes_list, $request->tips_list)); + $advice->tags()->sync(collect($request->input('tags'))->pluck('id')); + $advice->products()->sync($request->input('products_list')); + $advice->advices()->sync(array_merge($request->input('recipes_list'), $request->input('tips_list'))); return redirect() ->route('bo.advice.edit', $advice) @@ -152,37 +152,18 @@ class AdviceController extends Controller public function edit(Advice $advice): \Illuminate\Contracts\View\View { $currentType = $advice->type; - $adviceTags = Tag::whereNotIn('id', $advice->tags()->pluck('id')) + $adviceTags = Tag::query()->whereNotIn('id', $advice->tags()->pluck('id')) ->select(['id', 'label', 'slug'])->get(); $adviceProducts = Product::all(); - $recipeList = Advice::where([ + $recipeList = Advice::query()->where([ ['type', '=', AdviceTypeEnum::recipes], ['id', '!=', $advice->id], ])->get(); - $tipList = Advice::where([ + $tipList = Advice::query()->where([ ['type', '=', AdviceTypeEnum::tips], ['id', '!=', $advice->id], ])->get(); - $recipeList = collect($recipeList)->each(function (Advice &$value) { - $value->label = $value->title; - }); - $tipList = collect($tipList)->each(function (Advice &$value) { - $value->label = $value->title; - }); - - $recipesSelected = collect([]); - $tipsSelected = collect([]); - - /** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> */ - $recipesSelected = $advice->recipes()->each(function (Advice &$recipe) { - $recipe->label = $recipe->title; - }); - /** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> */ - $tipsSelected = $advice->tips()->each(function (Advice &$tip) { - $tip->label = $tip->title; - }); - return view('bo.pages.advice.edit', [ 'adviceModel' => $advice, 'currentType' => $currentType, @@ -190,8 +171,8 @@ class AdviceController extends Controller 'adviceProducts' => $adviceProducts, 'recipeList' => $recipeList, 'tipList' => $tipList, - 'recipesSelected' => $recipesSelected, - 'tipsSelected' => $tipsSelected, + 'recipesSelected' => $advice->recipes, + 'tipsSelected' => $advice->tips, ]); } @@ -205,11 +186,16 @@ class AdviceController extends Controller public function update(UpdateAdviceRequest $request, Advice $advice): \Illuminate\Http\RedirectResponse { return DB::transaction(function () use ($request, $advice) { - $advice->tags()->sync(collect($request->tags)->pluck('id')); - $advice->products()->sync($request->products_list); - $advice->advices()->sync(array_merge($request->recipes_list, $request->tips_list)); + $advice->tags()->sync(collect($request->input('tags'))->pluck('id')); + $advice->products()->sync($request->input('products_list')); + $advice->advices()->sync(array_merge($request->input('recipes_list'), $request->input('tips_list'))); - $advice->fill($request->validated()); + $advice->fill(Arr::except($request->validated(), [ + 'tags', + 'products', + 'associated_tips_list', + 'associated_recipes_list', + ])); $currentType = AdviceTypeEnum::make(\intval($request->type)); diff --git a/app/Http/Controllers/Bo/ExpertiseProductController.php b/app/Http/Controllers/Bo/ExpertiseProductController.php index b886cd9..30f68e0 100644 --- a/app/Http/Controllers/Bo/ExpertiseProductController.php +++ b/app/Http/Controllers/Bo/ExpertiseProductController.php @@ -48,7 +48,7 @@ class ExpertiseProductController extends Controller /** * Show the form for creating a new resource. * - * @param App\Models\ExpertiseProduct $vip + * @param \App\Models\ExpertiseProduct $vip * @return \Illuminate\Contracts\View\View */ public function create(ExpertiseProduct $vip): \Illuminate\Contracts\View\View @@ -95,8 +95,8 @@ class ExpertiseProductController extends Controller /** * Update the specified resource in storage. * - * @param \App\Http\Requests\Bo\ExpertiseProduct\UpdateExpertiseProductRequest $request - * @param \App\Models\ExpertiseProduct $vip + * @param \App\Http\Requests\Bo\ExpertiseProducts\UpdateExpertiseProductRequest $request + * @param \App\Models\ExpertiseProduct $vip * @return \Illuminate\Http\RedirectResponse */ public function update( diff --git a/app/Http/Controllers/Bo/NewsController.php b/app/Http/Controllers/Bo/NewsController.php index b4de532..52d61f7 100644 --- a/app/Http/Controllers/Bo/NewsController.php +++ b/app/Http/Controllers/Bo/NewsController.php @@ -8,14 +8,14 @@ use App\Http\Requests\Bo\News\UpdateNewsRequest; use App\Models\News; use App\Models\NewsCategory; use App\Models\Product; -use App\Traits\Controllers\UpdateModelStatus; +use App\Traits\Controllers\UpdateModelPublished; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class NewsController extends Controller { - use UpdateModelStatus; + use UpdateModelPublished; /** * Display a listing of the resource. @@ -60,18 +60,18 @@ class NewsController extends Controller */ public function create(News $news): \Illuminate\Contracts\View\View { - $news = $news ?? new News(); + $news = $news->exists() ? $news : new News(); $newsCategories = NewsCategory::all(); $newsProducts = Product::all(); $newsList = News::all(); - $newsList = collect($newsList)->each(function (News &$value) { - $value->label = $value->title; + $newsList = collect($newsList)->each(function (News $value) { + $value->setAttribute('label', $value->title); }); $newsSelected = collect([]); - collect($news->news ?? [])->each(function (News &$value) use (&$newsSelected) { - $value->label = $value->title; + collect($news->news ?? [])->each(function (News $value) use (&$newsSelected) { + $value->setAttribute('label', $value->title); $newsSelected = $newsSelected->concat([$value]); }); @@ -124,13 +124,13 @@ class NewsController extends Controller $newsProducts = Product::all(); $newsList = News::where('id', '!=', $news->id)->get(); - $newsList = collect($newsList)->each(function (\App\Models\News &$value) { - $value->label = $value->title; + $newsList = collect($newsList)->each(function (News $value) { + $value->setAttribute('label', $value->title); }); $newsSelected = collect([]); - collect($news->news ?? [])->each(function (\App\Models\News &$value) use (&$newsSelected) { - $value->label = $value->title; + collect($news->news ?? [])->each(function (News $value) use (&$newsSelected) { + $value->setAttribute('label', $value->title); $newsSelected = $newsSelected->concat([$value]); }); @@ -161,12 +161,12 @@ class NewsController extends Controller if ($news->saveOrFail()) { return redirect()->route('bo.news.edit', $news->id) ->with('success', __('crud.messages.has_been_updated', [ - 'model' => Str::singular(__('models.classes.news')) + 'model' => Str::singular(__('models.classes.news')) ])); } return redirect()->route('bo.news.edit', $news->id) ->with('error', __('crud.messages.cannot_be_updated', [ - 'model' => Str::singular(__('models.classes.news')) + 'model' => Str::singular(__('models.classes.news')) ])); }); } diff --git a/app/Http/Controllers/Bo/ProductController.php b/app/Http/Controllers/Bo/ProductController.php index df83701..20af2e2 100644 --- a/app/Http/Controllers/Bo/ProductController.php +++ b/app/Http/Controllers/Bo/ProductController.php @@ -5,10 +5,10 @@ namespace App\Http\Controllers\Bo; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Products\StoreProductRequest; use App\Http\Requests\Bo\Products\UpdateProductRequest; +use App\Lib\Helpers\FileStorageHelper; use App\Models\Product; use App\Models\Subrange; -use App\Traits\Controllers\HasPicture; -use App\Traits\Controllers\UpdateModelStatus; +use App\Traits\Controllers\UpdateModelPublished; use App\Traits\Controllers\ChangesModelOrder; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; @@ -17,8 +17,7 @@ use Illuminate\Support\Str; class ProductController extends Controller { use ChangesModelOrder; - use UpdateModelStatus; - use HasPicture; + use UpdateModelPublished; /** * Display a listing of the resource. @@ -160,4 +159,22 @@ class ProductController extends Controller 'model' => Str::singular(__('models.classes.products')) ])); } + + /** + * Save Model Images + * + * @param \Illuminate\Http\Request $request + * @param \App\Models\Product $product + * @return void + */ + private function storePictures(Request $request, Product $product) + { + if (is_array($request->input('slider_pictures'))) { + $product->slider_pictures = []; + $product->slider_pictures = collect($request->input('slider_pictures')) + ->map(function ($picture) use ($product) { + return FileStorageHelper::storeFile($product, $picture, true); + })->all(); + } + } } diff --git a/app/Http/Controllers/Bo/SlideController.php b/app/Http/Controllers/Bo/SlideController.php index 603816f..cb346ca 100644 --- a/app/Http/Controllers/Bo/SlideController.php +++ b/app/Http/Controllers/Bo/SlideController.php @@ -51,7 +51,7 @@ class SlideController extends Controller /** * Show the form for creating a new resource. * - * @param App\Models\Slide $slide + * @param \App\Models\Slide $slide * @return \Illuminate\Contracts\View\View */ public function create(Slide $slide): \Illuminate\Contracts\View\View diff --git a/app/Http/Controllers/Bo/StaticPageController.php b/app/Http/Controllers/Bo/StaticPageController.php index 989aa3c..9b92073 100644 --- a/app/Http/Controllers/Bo/StaticPageController.php +++ b/app/Http/Controllers/Bo/StaticPageController.php @@ -11,6 +11,14 @@ use Illuminate\Support\Str; class StaticPageController extends Controller { + /** + * Create the controller instance. + */ + public function __construct() + { + $this->authorizeResource(StaticPage::class); + } + /** * Display a listing of the resource. * @@ -48,7 +56,7 @@ class StaticPageController extends Controller /** * Show the form for editing the specified resource. * - * @param App\Models\StaticPage $static_page + * @param \App\Models\StaticPage $static_page * @return \Illuminate\Contracts\View\View */ public function edit(StaticPage $static_page): \Illuminate\Contracts\View\View diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 4d7a184..1e14b3b 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -9,7 +9,6 @@ use App\Lib\Helpers\ToolboxHelper; use App\Models\Advice; use App\Models\News; use App\Models\Product; -use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Validation\ValidatesRequests; @@ -41,7 +40,7 @@ class Controller extends BaseController string $search, callable $searchQuery = null, string ...$fields - ): Builder { + ): \Illuminate\Database\Eloquent\Builder { if (count($fields)) { // Search using words. $words = explode(' ', $search); @@ -70,45 +69,97 @@ class Controller extends BaseController * @param array $fields * @return \Illuminate\Database\Eloquent\Builder */ - private function searchOnFields(Builder $query, string $search, array $fields): Builder - { + private function searchOnFields( + Builder $query, + string $search, + array $fields + ): \Illuminate\Database\Eloquent\Builder { $table = $query->getModel()->getTable(); - foreach ($fields as $f) { - $f = str_replace('?', '\?', $f); - if (is_array($f)) { + foreach ($fields as $field) { + $field = str_replace('?', '\?', $field); + if (is_array($field)) { $query->orWhereRaw( - sprintf("UPPER(CONCAT(%s)) LIKE UPPER(?)", collect($f)->map(function ($q) use ($table) { + sprintf("UPPER(CONCAT(%s)) LIKE UPPER(?)", collect($field)->map(function ($q) use ($table) { return "`$table`.`$q`"; })->implode(', \' \', ')), - ['%' . filter_var($search, FILTER_SANITIZE_STRING) . '%'] - ); - } else { - $query->orWhereRaw( - "UPPER(`$table`.`$f`) LIKE UPPER(?)", - ['%' . filter_var($search, FILTER_SANITIZE_STRING) . '%'] + ['%' . htmlspecialchars($search) . '%'] ); + return $query; } - } + // Get models woth enum's label. + if (is_array($this->getSearchValue($query, $search, $field))) { + foreach ($this->getSearchValue($query, $search, $field) as $array) { + $query->orWhereRaw( + "UPPER(`$table`.`$field`) LIKE UPPER(?)", + ['%' . htmlspecialchars($array->value) . '%'] + ); + } + return $query; + } + // Get models with relation's name/label. + if (Str::endsWith($field, '_id')) { + $query->orWhereHas(Str::remove('_id', $field), function ($queryRelation) use ($field, $search) { + if (Schema::hasColumn(Str::remove('_id', $field) . 's', 'name')) { + $queryRelation->where('name', 'like', '%' . $search . '%'); + } elseif (Schema::hasColumn(Str::remove('_id', $field) . 's', 'label')) { + $queryRelation->where('label', 'like', '%' . $search . '%'); + } + }); + return $query; + } + $query->orWhereRaw( + "UPPER(`$table`.`$field`) LIKE UPPER(?)", + ['%' . htmlspecialchars($this->getSearchValue($query, $search, $field)) . '%'] + ); + } //end foreach return $query; } /** - * Sort columns with a query + * Get the search value (on string or Enum). + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string $search + * @param string $field + * @return string|array + */ + protected function getSearchValue(Builder $query, string $search, string $field): string|array + { + $cast = $query->getModel()->getCasts()[$field] ?? null; + if ( + count($query->getModel()->getCasts()) and // Check if the model has casts. + $cast and // Check if there is cast about specific field. + enum_exists($cast) // Check if the cast is an enum. + ) { + /** @var \App\Traits\Enums $cast */ + // @phpstan-ignore-next-line + $cases = collect($cast::toArray()); + $enum = $cases->filter(function ($item) use ($search) { + return preg_match('/' . Str::lower($search) . '/', Str::lower($item->label)); + }); + return $enum->toArray(); + } else { + return $search; + } + } + + /** + * Sort columns with a query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array $ignore * @return \Illuminate\Database\Eloquent\Builder */ - protected function sortQuery(Builder $query, array $ignore = []): Builder + protected function sortQuery(Builder $query, array $ignore = []): \Illuminate\Database\Eloquent\Builder { $rName = request()->route()->getName(); $table = $query->getModel()->getTable(); - if (request()->sort_col) { - Session::put("$rName.sort_col", request()->sort_col); + if (request()->input('sort_col')) { + Session::put("$rName.sort_col", request()->input('sort_col')); Session::put("$rName.sorted", true); } - if (request()->sort_way) { - Session::put("$rName.sort_way", request()->sort_way); + if (request()->input('sort_way')) { + Session::put("$rName.sort_way", request()->input('sort_way')); Session::put("$rName.sorted", true); } if (request()->rst) { @@ -116,17 +167,29 @@ class Controller extends BaseController Session::remove("$rName.sort_col"); Session::remove("$rName.sort_way"); } - if (request()->sort_col and request()->sort_way and Schema::hasColumn($table, request()->sort_col)) { - if ( - !isset($ignore) or - (isset($ignore) and !in_array(request()->sort_col, $ignore)) - ) { - $query = $query->orderBy(\sprintf("$table.%s", request()->sort_col), request()->sort_way); + if ( + request()->input('sort_col') and + request()->input('sort_way') and + Schema::hasColumn($table, request()->input('sort_col')) + ) { + if (!in_array(request()->input('sort_col'), $ignore)) { + $query = $query->orderBy( + \sprintf("$table.%s", request()->input('sort_col')), + request()->input('sort_way') + ); } } elseif (Schema::hasColumn($table, 'order')) { $query = $query->orderBy('order', 'ASC'); Session::put("$rName.sort_col", 'order'); Session::put("$rName.sort_way", 'asc'); + } elseif (Schema::hasColumn($table, 'updated_at')) { + $query = $query->orderBy('updated_at', 'DESC'); + Session::put("$rName.sort_col", 'updated_at'); + Session::put("$rName.sort_way", 'desc'); + } elseif (Schema::hasColumn($table, 'created_at')) { + $query = $query->orderBy('created_at', 'DESC'); + Session::put("$rName.sort_col", 'created_at'); + Session::put("$rName.sort_way", 'desc'); } return $query; } @@ -138,13 +201,17 @@ class Controller extends BaseController * @param \App\Enums\Pagination\ItemsPerPaginationEnum|null $pagination * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ - protected function paginate(Builder $query, ItemsPerPaginationEnum $pagination = null): LengthAwarePaginator - { + protected function paginate( + Builder $query, + ItemsPerPaginationEnum $pagination = null + ): \Illuminate\Contracts\Pagination\LengthAwarePaginator { $currentRoutePath = Str::slug(request()->route()->getName()); $cacheKey = "pagination.{$currentRoutePath}"; $pagination = $pagination ?? ItemsPerPaginationEnum::twelve; - $pagination = ToolboxHelper::getValidatedPaginate( - Cache::get($cacheKey, $pagination->value) + $pagination = ToolboxHelper::getValidatedEnum( + Cache::get($cacheKey, $pagination->value()), + 'pagination', + '\App\Enums\Pagination\ItemsPerPaginationEnum', ); if (Cache::get($cacheKey) !== $pagination) { Cache::put($cacheKey, $pagination); diff --git a/app/Http/Controllers/Fo/ExpertiseController.php b/app/Http/Controllers/Fo/ExpertiseController.php index 33aa1b8..140ee81 100644 --- a/app/Http/Controllers/Fo/ExpertiseController.php +++ b/app/Http/Controllers/Fo/ExpertiseController.php @@ -11,6 +11,7 @@ use App\Models\Advice; use App\Models\ExpertiseProduct; use App\Models\Product; use App\Models\StaticPage; +use Illuminate\Contracts\Database\Eloquent\Builder; class ExpertiseController extends Controller { @@ -113,10 +114,10 @@ class ExpertiseController extends Controller ->with('subrange.range') ->get(); - /** @var \App\Models\Recipe $recipeModels */ - $recipeModels = Advice::query()->whereHas('products', function ($query) use ($enumProductSpecies) { - return $query->where('species', $enumProductSpecies->value()); - })->where('type', AdviceTypeEnum::recipes)->limit(3)->get(); + $recipeModels = Advice::query() + ->whereHas('products', function (Builder $q) use ($enumProductSpecies) { + return $q->where('species', $enumProductSpecies->value()); + })->where('type', AdviceTypeEnum::recipes)->limit(3)->get(); return [ 'staticPageModel' => $staticPageModel, diff --git a/app/Http/Controllers/Fo/HomeController.php b/app/Http/Controllers/Fo/HomeController.php index 88b7f9e..d96f457 100644 --- a/app/Http/Controllers/Fo/HomeController.php +++ b/app/Http/Controllers/Fo/HomeController.php @@ -7,8 +7,6 @@ use App\Models\News; use App\Models\Product; use App\Models\Range; use App\Models\Slide; -use Carbon\Carbon; -use Spatie\CalendarLinks\Link; class HomeController extends Controller { @@ -19,7 +17,6 @@ class HomeController extends Controller */ public function index(): \Illuminate\Contracts\View\View { - // Get Slides. /** @var \Illuminate\Database\Eloquent\Builder $slides */ @@ -40,22 +37,21 @@ class HomeController extends Controller // Get Agenda. // Events starting in the future. - $events = News::where('status', true) - ->where('event_start', '>', Carbon::now()) + $events = News::query()->where('status', true) + ->where('event_start', '>', now()) ->orderBy('event_start', 'desc') - ->take(2)->get(); - - $events = $events->reverse(); - - foreach ($events as $event) { - $event->cal_link = Link::create($event->title, $event->event_start, $event->event_end) - ->description($event->event_text) - ->ics(); - } + ->take(2)->get()->reverse(); // Get last 3 News. - $news = News::latest()->where('status', true)->take(3)->with('categories')->get(); + $news = News::query()->latest()->where('status', true) + ->take(3)->with('categories')->get(); - return view('fo.pages.home', compact('slides', 'ranges', 'threeproducts', 'events', 'news')); + return view('fo.pages.home', compact( + 'slides', + 'ranges', + 'threeproducts', + 'events', + 'news' + )); } } diff --git a/app/Http/Controllers/Fo/NewsController.php b/app/Http/Controllers/Fo/NewsController.php index 2addbd9..74e7af7 100644 --- a/app/Http/Controllers/Fo/NewsController.php +++ b/app/Http/Controllers/Fo/NewsController.php @@ -18,25 +18,24 @@ class NewsController extends Controller public function index(Request $request): \Illuminate\Contracts\View\View { // Get NewsCategories. - $categories = NewsCategory::orderBy('label', 'ASC')->get(); + $categories = NewsCategory::query()->orderBy('label', 'ASC')->get(); // Get News. - $filters_activated = $request->filtered_categorie; + $filters_activated = collect($request->input('filtered_categorie')); - $news = News::when( - isset($filters_activated) and $filters_activated[0] != 'all', + $news = News::query()->when( + $filters_activated->first() != 'all', function ($query) use ($filters_activated) { $query->with('categories') ->whereRelation('categories', function ($query) use ($filters_activated) { foreach ($filters_activated as $value) { - $query->orWhere('id', 'like', $value); + if (is_string($value)) { + $query->orWhere('id', 'like', $value); + } } }); } - ) - ->where('status', true) - ->orderBy('created_at') - ->paginate(6); + )->where('status', true)->orderBy('created_at')->paginate(6); return view('fo.pages.news.index', compact('categories', 'news', 'filters_activated')); } diff --git a/app/Http/Controllers/Fo/ProductsController.php b/app/Http/Controllers/Fo/ProductsController.php index ec25699..b366c90 100644 --- a/app/Http/Controllers/Fo/ProductsController.php +++ b/app/Http/Controllers/Fo/ProductsController.php @@ -230,7 +230,7 @@ class ProductsController extends Controller */ private function generateProductCommercialPdf(Product $product, string $title): \Mccarlosen\LaravelMpdf\LaravelMpdf { - /** @var \Mccarlosen\LaravelMpdf\LaravelMpdf */ + /** @var \Mccarlosen\LaravelMpdf\LaravelMpdfWrapper */ $mpdf = app('laravel-mpdf'); /** @var \Mccarlosen\LaravelMpdf\LaravelMpdf */ $pdf = $mpdf->loadView( @@ -256,7 +256,6 @@ class ProductsController extends Controller 'margin_bottom' => 0, 'margin_header' => 0, 'margin_footer' => 0, - 'margin_top' => 0, 'orientation' => 'P', 'title' => $title, 'author' => \config('app.name', 'Le Gaulois Pro'), diff --git a/app/Http/Controllers/Fo/SearchController.php b/app/Http/Controllers/Fo/SearchController.php index 955a76c..0288f02 100644 --- a/app/Http/Controllers/Fo/SearchController.php +++ b/app/Http/Controllers/Fo/SearchController.php @@ -12,7 +12,7 @@ class SearchController extends Controller * Search input txt in products, news and recipes * * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\Response + * @return \Illuminate\Contracts\View\View */ public function search(Request $request): \Illuminate\Contracts\View\View { @@ -25,11 +25,8 @@ class SearchController extends Controller $recipes = []; $recipesTotal = 0; - if (is_array($search)) { - abort(400); - } if (is_string($model)) { - return $this->callAction('searchModel', [$model, $search]); + return $this->searchModel($model, $search); } if (!empty($search)) { @@ -63,7 +60,7 @@ class SearchController extends Controller * * @param string $modelName * @param string $search - * @return \Illuminate\Http\Response + * @return \Illuminate\Contracts\View\View */ public function searchModel(string $modelName, string $search): \Illuminate\Contracts\View\View { diff --git a/app/Http/Controllers/Fo/StaticPageController.php b/app/Http/Controllers/Fo/StaticPageController.php index 0e5874c..9b92073 100644 --- a/app/Http/Controllers/Fo/StaticPageController.php +++ b/app/Http/Controllers/Fo/StaticPageController.php @@ -1,34 +1,91 @@ where('type', StaticPageType::legals)->firstOrFail(); - return view('fo.pages.legals', compact('staticPageModel')); + $this->authorizeResource(StaticPage::class); } /** - * Display policies page + * Display a listing of the resource. * - * @return \Illuminate\Http\Response + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Contracts\View\View */ - public function policies(): \Illuminate\Contracts\View\View + public function index(Request $request): \Illuminate\Contracts\View\View { - /** @var \App\Models\StaticPage */ - $staticPageModel = StaticPage::query()->where('type', StaticPageType::confidentiality)->firstOrFail(); - return view('fo.pages.policies', compact('staticPageModel')); + /** @var \Illuminate\Database\Eloquent\Builder $query */ + $query = StaticPage::query(); + + /** @var string $search Search field */ + $search = $request->search; + if ($search) { + $this->searchQuery( + $query, + $search, + null, + 'title', + ); + } + $searchFields = \implode(', ', [ + trans('validation.attributes.title'), + ]); + + /** Sort columns with a query */ + $this->sortQuery($query); + + /** Custom pagination */ + $staticPageModelList = $this->paginate($query); + + return view('bo.pages.static_pages.index', compact('staticPageModelList', 'search', 'searchFields')); + } + + /** + * Show the form for editing the specified resource. + * + * @param \App\Models\StaticPage $static_page + * @return \Illuminate\Contracts\View\View + */ + public function edit(StaticPage $static_page): \Illuminate\Contracts\View\View + { + return view('bo.pages.static_pages.edit', ['staticPageModel' => $static_page]); + } + + /** + * Update the specified resource in storage. + * + * @param \App\Http\Requests\Bo\StaticPages\UpdateStaticPageRequest $request + * @param \App\Models\StaticPage $static_page + * @return \Illuminate\Http\RedirectResponse + */ + public function update(UpdateStaticPageRequest $request, StaticPage $static_page): \Illuminate\Http\RedirectResponse + { + return DB::transaction(function () use ($request, $static_page) { + $static_page->fill($request->validated()); + + if ($static_page->saveOrFail()) { + return redirect()->route('bo.static_pages.edit', $static_page) + ->with('success', __('crud.messages.has_been_updated', [ + 'model' => Str::ucfirst(\trans_choice('models.classes.static_page', 1)) + ])); + } + return redirect()->route('bo.static_pages.edit', $static_page) + ->with('error', __('crud.messages.cannot_be_updated', [ + 'model' => Str::ucfirst(\trans_choice('models.classes.static_page', 1)) + ])); + }); } } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index cc5ba2f..a9aa087 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -33,7 +33,6 @@ class Authenticate extends Middleware } return route('login'); } - abort(401); return null; } diff --git a/app/Http/Requests/Bo/Advice/StoreAdviceRequest.php b/app/Http/Requests/Bo/Advice/StoreAdviceRequest.php index d894637..f56ce0d 100644 --- a/app/Http/Requests/Bo/Advice/StoreAdviceRequest.php +++ b/app/Http/Requests/Bo/Advice/StoreAdviceRequest.php @@ -34,23 +34,23 @@ class StoreAdviceRequest extends FormRequest { //phpcs:enable $this->merge([ - 'slug' => Str::slug(strip_tags($this->title)), - 'status' => $this->status ? true : false, - 'tags' => $this->tags ?? [], - 'products' => $this->products ?? [], - 'associated_tips_list' => $this->associated_tips_list ?? [], - 'associated_recipes_list' => $this->associated_recipes_list ?? [], + 'slug' => Str::slug(strip_tags($this->input('title'))), + 'status' => $this->boolean('status'), + 'tags' => $this->input('tags', []), + 'products' => $this->input('products', []), + 'associated_tips_list' => $this->input('associated_tips_list', []), + 'associated_recipes_list' => $this->input('associated_recipes_list', []), // * For sync relations - 'tags_list' => \collect($this->tags)->map(function ($value) { + 'tags_list' => \collect($this->input('tags'))->map(function ($value) { return \is_array($value) ? ($value['value'] ?? null) : null; })->filter()->all(), - 'products_list' => \collect($this->products)->map(function ($value) { + 'products_list' => \collect($this->input('products'))->map(function ($value) { return \is_array($value) ? ($value['value'] ?? null) : null; })->filter()->all(), - 'tips_list' => \collect($this->associated_tips_list)->map(function ($value) { + 'tips_list' => \collect($this->input('tips'))->map(function ($value) { return \is_array($value) ? ($value['value'] ?? null) : null; })->filter()->all(), - 'recipes_list' => \collect($this->associated_recipes_list)->map(function ($value) { + 'recipes_list' => \collect($this->input('recipes'))->map(function ($value) { return \is_array($value) ? ($value['value'] ?? null) : null; })->filter()->all(), ]); @@ -189,9 +189,9 @@ class StoreAdviceRequest extends FormRequest ]; return \array_merge( $rules, - $this->pictureRules('picture', true, 650, 690, 650, 690), - $this->pictureRules('sticker', true, 370, 300, 370, 300), - $this->pictureRules('sticker_sm', true, 270, 145, 270, 145), + $this->pictureRules('picture', 650, 690, 650, 690, true), + $this->pictureRules('sticker', 370, 300, 370, 300, true), + $this->pictureRules('sticker_sm', 270, 145, 270, 145, true), ); } diff --git a/app/Http/Requests/Bo/News/StoreNewsRequest.php b/app/Http/Requests/Bo/News/StoreNewsRequest.php index d0d1f1a..35dfabc 100644 --- a/app/Http/Requests/Bo/News/StoreNewsRequest.php +++ b/app/Http/Requests/Bo/News/StoreNewsRequest.php @@ -118,8 +118,8 @@ class StoreNewsRequest extends FormRequest ]; return \array_merge( $rules, - $this->pictureRules('picture', true, 920, 1025, 920, 1025), - $this->pictureRules('picture2', false, 920, 1025, 920, 1025) + $this->pictureRules('picture', 920, 1025, 920, 1025, true), + $this->pictureRules('picture2', 920, 1025, 920, 1025, false) ); } diff --git a/app/Http/Requests/Bo/Products/StoreProductRequest.php b/app/Http/Requests/Bo/Products/StoreProductRequest.php index 6a6028d..53903a4 100644 --- a/app/Http/Requests/Bo/Products/StoreProductRequest.php +++ b/app/Http/Requests/Bo/Products/StoreProductRequest.php @@ -79,7 +79,6 @@ class StoreProductRequest extends FormRequest ], 'caliber.*' => 'required|array', 'caliber.*.value' => 'required|string|min:1|max:255', - 'nutritionnal_values' => 'required|array', 'nutritionnal_values' => [ // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed 'present', 'array', function ($attribute, array $value, $fail) { @@ -98,8 +97,8 @@ class StoreProductRequest extends FormRequest ]; return \array_merge( $rules, - $this->pictureRules('sticker_sm', true, 206, 159, 206, 159), - $this->picturesRules('slider_pictures', true, 396, 286, 396, 286, 1, 5), + $this->pictureRules('sticker_sm', 206, 159, 206, 159, true), + $this->picturesRules('slider_pictures', 396, 286, 396, 286, 1, 5, true), ); } diff --git a/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php b/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php index 7c803ff..d057e83 100644 --- a/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php +++ b/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php @@ -53,8 +53,8 @@ class UpdateRangeRequest extends FormRequest ]; return \array_merge( $rules, - $this->pictureRules('picture', true, 290, 232, 290, 232), - $this->pictureRules('picture_banner', true, 1440, 300, 1440, 300), + $this->pictureRules('picture', 290, 232, 290, 232, true), + $this->pictureRules('picture_banner', 1440, 300, 1440, 300, true), ); } diff --git a/app/Http/Requests/Bo/Slides/StoreSlideRequest.php b/app/Http/Requests/Bo/Slides/StoreSlideRequest.php index d161e86..4c7164f 100644 --- a/app/Http/Requests/Bo/Slides/StoreSlideRequest.php +++ b/app/Http/Requests/Bo/Slides/StoreSlideRequest.php @@ -55,8 +55,8 @@ class StoreSlideRequest extends FormRequest ]; return \array_merge( $rules, - $this->pictureRules('picture', true, 950, 700, 950, 700), - $this->pictureRules('picture_thumbnail', true, 167, 70, 167, 70) + $this->pictureRules('picture', 950, 700, 950, 700, true), + $this->pictureRules('picture_thumbnail', 167, 70, 167, 70, true) ); } diff --git a/app/Http/Requests/Fo/Products/AjaxAddProductBasket.php b/app/Http/Requests/Fo/Products/AjaxAddProductBasket.php index 0f9bef0..3115b36 100644 --- a/app/Http/Requests/Fo/Products/AjaxAddProductBasket.php +++ b/app/Http/Requests/Fo/Products/AjaxAddProductBasket.php @@ -56,7 +56,7 @@ class AjaxAddProductBasket extends FormRequest /** * Get custom attributes for validator errors. * - * @return array + * @return array */ public function attributes(): array { diff --git a/app/Http/Requests/Fo/Products/AjaxFilterProductsRequest.php b/app/Http/Requests/Fo/Products/AjaxFilterProductsRequest.php index 6b648ab..e8d9a82 100644 --- a/app/Http/Requests/Fo/Products/AjaxFilterProductsRequest.php +++ b/app/Http/Requests/Fo/Products/AjaxFilterProductsRequest.php @@ -28,8 +28,7 @@ class AjaxFilterProductsRequest extends FormRequest { $this->merge([ 'vip' => $this->vip ? true : false, - 'subranges' => isset($this->subranges) ? explode(',', $this->subranges) : - (\is_array($this->subranges) ? $this->subranges : []) + 'subranges' => isset($this->subranges) ? explode(',', $this->subranges) : (\is_array($this->subranges) ? $this->subranges : []) ]); } @@ -47,7 +46,7 @@ class AjaxFilterProductsRequest extends FormRequest $rules['subranges'] = 'present|array'; $rules['subranges.*'] = [ // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed - 'exists:subranges,id', function ($attribute, $value, $fail) { + 'exists:subranges,id', function (string $attribute, $value, callable $fail) { if (empty($this->range) or !\is_object($this->range) or \get_class($this->range) !== Range::class) { $fail(trans('La gamme est obligatoire', ['attribute' => $attribute])); return; @@ -59,7 +58,7 @@ class AjaxFilterProductsRequest extends FormRequest $hasSubrange = Range::query()->whereHas('subranges', function (Builder $q) use ($subrange) { $q->where('id', $subrange->id); })->where('id', $this->range->id)->exists(); - if (empty($value) or !$hasSubrange) { + if (!$hasSubrange) { $fail(trans(':attribute doit appartenir à la bonne gamme', ['attribute' => $attribute])); return; } diff --git a/app/Lib/Helpers/ExceptionsHelper.php b/app/Lib/Helpers/ExceptionsHelper.php index 4813275..30deb54 100644 --- a/app/Lib/Helpers/ExceptionsHelper.php +++ b/app/Lib/Helpers/ExceptionsHelper.php @@ -145,7 +145,7 @@ class ExceptionsHelper $traceStr .= self::handleArgs($stack); } $traceStr .= ")\n"; - } elseif (isset($stack['function'])) { + } else { $traceStr .= "{$stack['function']}("; if (isset($stack['args'])) { $traceStr .= self::handleArgs($stack); diff --git a/app/Lib/Helpers/FileStorageHelper.php b/app/Lib/Helpers/FileStorageHelper.php index eaa0b9c..1254ec3 100644 --- a/app/Lib/Helpers/FileStorageHelper.php +++ b/app/Lib/Helpers/FileStorageHelper.php @@ -30,6 +30,20 @@ use Illuminate\Support\Str; */ class FileStorageHelper { + /** + * Remove all files from string attribute html that are stored in public + * + * @param string $publicStorageFilePath The file path from public directory. + * @return string The local storage path. + */ + public static function getFileFullPath(string $publicStorageFilePath): string + { + /** @var \Illuminate\Filesystem\FilesystemAdapter */ + $disk = Storage::disk('uploads'); + $path = ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/')); + return $disk->path($path); + } + /** * Destroy the file associate with the attribute. * @@ -308,8 +322,7 @@ class FileStorageHelper $folderPath = self::getStoragePath( $private ? 'app/private/modelfiles' : 'app/public/modelfiles', $tableName, - $filename, - $private + $filename ); $filename = self::getFileUniqueName($folderPath, $filename); return "{$folderPath}/{$filename}"; @@ -404,7 +417,7 @@ class FileStorageHelper $filename = Str::of($filename)->ltrim('.-'); // * Optional beautification if ($beautify) { - $filename = static::beautifyFilename($filename); + $filename = self::beautifyFilename($filename); } // * Maximize filename length to 255 bytes http://serverfault.com/a/9548/44086 /** @var string */ diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index 6283174..26c8a03 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -22,6 +22,36 @@ use Symfony\Component\Finder\SplFileInfo; class ToolboxHelper { + /** + * Run a terminal command and gives the output + * + * @param array|string $command The command to execute on terminal. + * @param boolean $throw Wether to throw en esception on failure or not. + * @return string|false Return false on failure only if $throw is false. + * @phpcs:disable Squiz.Commenting.FunctionComment.EmptyThrows + * @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber + * @throws \Illuminate\Process\Exceptions\ProcessTimedOutException + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \LogicException + * @throws \RuntimeException If the command fails. + */ + public static function runConsoleCommand(array|string $command, bool $throw = true): string | false + { + // phpcs:enable + $process = \Illuminate\Support\Facades\Process::command($command)->run(); + if ($process->failed()) { + $code = $process->exitCode(); + $ouput = $process->errorOutput(); + if ($throw) { + throw new \RuntimeException("Failed to run command exit code {$code} with output \n{$ouput}"); + } + return false; + } + return $process->output(); + } + /** * @param array $array1 * @param array $array2 @@ -76,7 +106,7 @@ class ToolboxHelper throw new \RuntimeException(); } if (\floatval($response->json('score')) < 0.8) { - $fail("Vous n'avez pas obtenu un score assez élevé lors de la validation du recaptcha"); + $fail(trans('recaptcha.not_enough_score')); } return; } @@ -89,7 +119,7 @@ class ToolboxHelper throw new \RuntimeException(); } } catch (\Exception $e) { - $fail('Erreur lors de la validation du formulaire veuillez réssayer'); + $fail(trans('recaptcha.error')); } //end try } ] @@ -176,11 +206,10 @@ class ToolboxHelper $url = $match; try { $request = Request::create($url); - // If a route is match then it do not throws exception. - if ( - \parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) && - $routes->match($request) - ) { + // Assert route matches existing routes. + $routes->match($request); + // ? Is url internal ? + if (\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST)) { // Removes the matched url. throw ValidationException::withMessages([ $field => trans( @@ -206,14 +235,14 @@ class ToolboxHelper * @param array|string $replace * @param array|string $subject * @param integer $count - * @return array|string + * @return array|string|false */ public static function mbReplace( array|string $search, array|string $replace, array|string $subject, int &$count = 0 - ): array|string { + ): array|string|false { if (!is_array($search) && is_array($replace)) { return false; } @@ -289,10 +318,17 @@ class ToolboxHelper */ public static function getOriginal(Model $model, string $attribute): mixed { - if (\in_array('Spatie\Translatable\HasTranslations', \class_uses_recursive($model))) { + if ( + \in_array('Spatie\Translatable\HasTranslations', \class_uses_recursive($model)) and + // @phpstan-ignore-next-line + $model->isTranslatableAttribute($attribute) + ) { + // @phpstan-ignore-next-line return $model->getTranslation( $attribute, + // @phpstan-ignore-next-line $model->getLocale(), + // @phpstan-ignore-next-line $model->useFallbackLocale() ); } @@ -362,47 +398,45 @@ class ToolboxHelper /** * Convert deeply an object to array * - * @param array|object $input + * @param mixed $input * @return array * @throws \RuntimeException If $input var is a scalar value. */ - public static function objectToArray($input): array + public static function objectToArray(mixed $input): array { // Only process if it's an object or array being passed to the function. - if (is_object($input) or is_array($input)) { - $ret = (array)$input; - foreach ($ret as &$item) { - // Recursively process EACH element only if not scalar. - $item = (is_object($item) or is_array($item)) ? - self::objectToArray($item) : $item; - } - return $ret; - } else { + if (!(is_object($input) or is_array($input))) { throw new \RuntimeException('Cannot handle $input of type ' . \gettype($input)); } + $ret = (array)$input; + foreach ($ret as &$item) { + // Recursively process EACH element only if not scalar. + $item = (is_object($item) or is_array($item)) ? + self::objectToArray($item) : $item; + } + return $ret; } /** * Convert deeply an array to object * - * @param array|object $input + * @param mixed $input * @return object * @throws \RuntimeException If $input var is a scalar value. */ - public static function arrayToObject($input): object + public static function arrayToObject(mixed $input): object { // Only process if it's an object or array being passed to the function. - if (is_object($input) or is_array($input)) { - $ret = (object)$input; - foreach ($ret as &$item) { - // Recursively process EACH element only if not scalar. - $item = (is_object($item) or is_array($item)) ? - self::arrayToObject($item) : $item; - } - return $ret; - } else { + if (!(is_object($input) or is_array($input))) { throw new \RuntimeException('Cannot handle $input of type ' . \gettype($input)); } + $ret = (object)$input; + foreach ($ret as &$item) { + // Recursively process EACH element only if not scalar. + $item = (is_object($item) or is_array($item)) ? + self::arrayToObject($item) : $item; + } + return $ret; } /** @@ -410,11 +444,11 @@ class ToolboxHelper * * @param string $attribute * @param string|null $value - * @param callback $fail + * @param callable $fail * @param object $sizes * @return void */ - public static function validatePicture(string $attribute, string|null $value, callable $fail, object $sizes) + public static function validatePicture(string $attribute, string|null $value, callable $fail, object $sizes): void { if (!($useStorage = Storage::exists($value)) and !File::exists($value)) { $fail(trans(':attribute n\'existe pas dans le système de fichier', [ @@ -422,7 +456,6 @@ class ToolboxHelper ])); return; } - /** @var string */ $fileFullPath = self::getUploadedFileFullPath($value, $useStorage); if ( !\in_array(self::getUploadedFileMimeType($value, $useStorage), [ @@ -433,7 +466,7 @@ class ToolboxHelper 'attribute' => $attribute ])); } - if (!($dimensions = \getimagesize($fileFullPath)) or !isset($dimensions[0]) or !isset($dimensions[1])) { + if (!($dimensions = \getimagesize($fileFullPath))) { $fail(trans(':attribute impossible de valider les dimensions', [ 'attribute' => $attribute ])); @@ -442,19 +475,19 @@ class ToolboxHelper $height = intval($dimensions[1]); $xMessage = trans( - ":attribute la largeur doit être comprise entre {$sizes->minWith}px et {$sizes->maxWith}px" + ":attribute la largeur doit être comprise entre {$sizes->minWidth}px et {$sizes->maxWidth}px" ); - if ($sizes->minWith === $sizes->maxWith) { - $xMessage = trans(":attribute la largeur doit être de {$sizes->minWith}px"); + if ($sizes->minWidth === $sizes->maxWidth) { + $xMessage = trans(":attribute la largeur doit être de {$sizes->minWidth}px"); } $yMessage = trans( - ":attribute la hauteur doit être comprise entre {$sizes->minWith}px et {$sizes->maxWith}px" + ":attribute la hauteur doit être comprise entre {$sizes->minWidth}px et {$sizes->maxWidth}px" ); if ($sizes->minHeight === $sizes->maxHeight) { - $yMessage = trans(":attribute la hauteur doit être de {$sizes->minWith}px"); + $yMessage = trans(":attribute la hauteur doit être de {$sizes->minHeight}px"); } - if (($width < $sizes->minWith) or ($width > $sizes->maxWith)) { + if (($width < $sizes->minWidth) or ($width > $sizes->maxWidth)) { $fail($xMessage); } if (($height < $sizes->minHeight) or ($height > $sizes->maxHeight)) { @@ -519,6 +552,26 @@ class ToolboxHelper ); } + /** + * Get validated pagination from request. + * + * @param integer $default + * @param string $field + * @param string $enumPath + * @return integer + */ + public static function getValidatedEnum(int $default, string $field, string $enumPath): int + { + try { + return \intval(Validator::make( + [$field => \request()->get($field)], + [$field => new Enum($enumPath)] + )->validated()[$field]); + } catch (ValidationException $e) { + return $default; + } + } + /** * Get validated pagination from request. * diff --git a/app/Models/Advice.php b/app/Models/Advice.php index ddd5828..bee27e9 100644 --- a/app/Models/Advice.php +++ b/app/Models/Advice.php @@ -6,8 +6,8 @@ use App\Enums\Advices\AdviceTypeEnum; use App\Enums\Advices\AdviceDifficultyEnum; use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; +use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; @@ -16,34 +16,38 @@ use Uwil\Seo\Laravel\Traits\SeoTrait; use Uwil\Seo\Laravel\Objects\SeoItem; /** - * @property integer $id Id. - * @property string $title Title. - * @property string $slug Slug of the title. - * @property string $seo_title SEO Title. - * @property string $seo_description SEO description. - * @property \App\Enums\Advices\AdviceTypeEnum $type Type of the advice. - * @property string $picture Path of a picture. - * @property string $picture_alt Picture's attribute alt. - * @property string $picture_title Picture's attribute title. - * @property string $sticker Path of a sticker. - * @property string $sticker_alt Sticker's attribute alt. - * @property string $sticker_title Sticker's attribute title. - * @property string $sticker_sm Path of a small sticker. - * @property string $sticker_sm_alt small sticker's attribute alt. - * @property string $sticker_sm_title Small sticker's attribute title. - * @property string $preparation Preparation tips. - * @property string $advice Advice. - * @property \Illuminate\Support\Carbon $ingredients Ingredients. - * @property \Illuminate\Support\Carbon $guests_nb Number of guests. - * @property \Illuminate\Support\Carbon $youtube_title Youtube title. - * @property \Illuminate\Support\Carbon $youtube_video_id Youtube video id. - * @property \Illuminate\Support\Carbon $cooking_time Time of cooking. - * @property \Illuminate\Support\Carbon $preparation_time Time of preparation. - * @property \App\Enums\Advices\AdviceDifficultyEnum $difficulty Difficulty. - * @property boolean $status Status. - * @property-read \Illuminate\Support\Carbon $created_at Created date. - * @property-read \Illuminate\Support\Carbon $updated_at Updated date. + * @property integer $id Id. + * @property string $title Title. + * @property string $slug Slug of the title. + * @property string $seo_title SEO Title. + * @property string $seo_description SEO description. + * @property \App\Enums\Advices\AdviceTypeEnum $type Type of the advice. + * @property string $picture Path of a picture. + * @property string $picture_alt Picture's attribute alt. + * @property string $picture_title Picture's attribute title. + * @property string $sticker Path of a sticker. + * @property string $sticker_alt Sticker's attribute alt. + * @property string $sticker_title Sticker's attribute title. + * @property string $sticker_sm Path of a small sticker. + * @property string $sticker_sm_alt small sticker's attribute alt. + * @property string $sticker_sm_title Small sticker's attribute title. + * @property string $preparation Preparation tips. + * @property string|null $advice Advice. + * @property array> $ingredients Ingredients. + * @property integer|null $guests_nb Number of guests. + * @property string|null $youtube_title Youtube title. + * @property string|null $youtube_video_id Youtube video id. + * @property integer|null $cooking_time Time of cooking. + * @property integer|null $preparation_time Time of preparation. + * @property \App\Enums\Advices\AdviceDifficultyEnum|null $difficulty Difficulty. + * @property boolean $status Status. + * @property-read \Illuminate\Support\Carbon $created_at Created date. + * @property-read \Illuminate\Support\Carbon $updated_at Updated date. * + * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> $recipes + * HasMany Recipes. + * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> $tips + * HasMany Tips. * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> $advices * Advices Belongs-To-Many relationship. * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Product> $products @@ -91,7 +95,7 @@ class Advice extends Authenticatable implements SeoInterface /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'ingredients' => 'array', @@ -131,10 +135,10 @@ class Advice extends Authenticatable implements SeoInterface /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { self::assertTitleIsUnique($model->title, $model->id); $model->slug = Str::slug($model->title); @@ -196,11 +200,11 @@ class Advice extends Authenticatable implements SeoInterface /** * Limit products associated. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void * @throws \Illuminate\Validation\ValidationException Error exception. */ - private static function assertLimitProducts(Model $model): void + private static function assertLimitProducts(self $model): void { $nbProductsInBdd = $model->products()->count(); if ($model->type->value == AdviceTypeEnum::recipes->value()) { @@ -221,10 +225,10 @@ class Advice extends Authenticatable implements SeoInterface /** * Asserts using validation that the title is unique. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function setCookingtimePreparationtimeValues(Model $model): void + private static function setCookingtimePreparationtimeValues(self $model): void { if ($model->type->value != AdviceTypeEnum::recipes->value()) { $model->cooking_time = null; @@ -251,21 +255,45 @@ class Advice extends Authenticatable implements SeoInterface * * @return \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> */ - public function recipes(): \Illuminate\Database\Eloquent\Collection + public function recipesQuery(): \Illuminate\Database\Eloquent\Collection { return $this->advices()->where('type', AdviceTypeEnum::recipes)->get(); } + /** + * Get the advice recipes + * + * @return \Illuminate\Database\Eloquent\Casts\Attribute + */ + protected function recipes(): Attribute + { + return Attribute::make( + get: fn () => $this->recipesQuery(), + ); + } + /** * Get associated tips * * @return \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> */ - public function tips(): \Illuminate\Database\Eloquent\Collection + public function tipsQuery(): \Illuminate\Database\Eloquent\Collection { return $this->advices()->where('type', AdviceTypeEnum::tips)->get(); } + /** + * Get the advice tips + * + * @return \Illuminate\Database\Eloquent\Casts\Attribute + */ + protected function tips(): Attribute + { + return Attribute::make( + get: fn () => $this->tipsQuery(), + ); + } + // * RELATIONSHIPS /** @@ -301,7 +329,7 @@ class Advice extends Authenticatable implements SeoInterface /** * Transfotrm to seoModel * - * @return \App\Objects\SeoItem + * @return \Uwil\Seo\Laravel\Objects\SeoItem */ public function toSeoItem(): SeoItem { diff --git a/app/Models/ExpertiseProduct.php b/app/Models/ExpertiseProduct.php index 4017587..74cdc52 100644 --- a/app/Models/ExpertiseProduct.php +++ b/app/Models/ExpertiseProduct.php @@ -30,7 +30,7 @@ class ExpertiseProduct extends Model /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'page', @@ -46,7 +46,7 @@ class ExpertiseProduct extends Model /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'points' => 'array', @@ -84,10 +84,10 @@ class ExpertiseProduct extends Model /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { self::assertFieldIsUnique('label', $model->label, $model->id); self::assertFieldIsUnique('title', $model->title, $model->id); diff --git a/app/Models/News.php b/app/Models/News.php index ff85cca..de9bde7 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -4,11 +4,12 @@ namespace App\Models; use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; +use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; +use Spatie\CalendarLinks\Link; use Uwil\Seo\Laravel\Interfaces\SeoInterface; use Uwil\Seo\Laravel\Traits\SeoTrait; @@ -24,19 +25,21 @@ use Uwil\Seo\Laravel\Traits\SeoTrait; * @property string $picture Path of a picture. * @property string $picture_alt Picture's attribute alt. * @property string $picture_title Picture's attribute title. - * @property string $picture2 Path of a second picture. - * @property string $picture2_alt Second picture's attribute alt. - * @property string $picture2_title Second picture's attribute title. + * @property string|null $picture2 Path of a second picture. + * @property string|null $picture2_alt Second picture's attribute alt. + * @property string|null $picture2_title Second picture's attribute title. * @property string $content First WYSWYG content. - * @property string $content2 Second WYSWYG content. - * @property \Illuminate\Support\Carbon $event_start Start of the event. - * @property \Illuminate\Support\Carbon $event_end End of the event. - * @property string $event_text Text of the event. + * @property string|null $content2 Second WYSWYG content. + * @property \Illuminate\Support\Carbon|null $event_start Start of the event. + * @property \Illuminate\Support\Carbon|null $event_end End of the event. + * @property string|null $event_text Text of the event. * @property boolean $status Status. * @property-read string $reading_time Time reading of a news' page * @property-read \Illuminate\Support\Carbon $created_at Created date. * @property-read \Illuminate\Support\Carbon $updated_at Updated date. * + * @property-read \Spatie\CalendarLinks\Link|null $cal_link + * * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\News> $news * News Belongs-To-Many relationship. * @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Product> $products @@ -52,7 +55,7 @@ class News extends Authenticatable implements SeoInterface /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'title', @@ -77,7 +80,7 @@ class News extends Authenticatable implements SeoInterface /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'event_start' => 'datetime', @@ -111,15 +114,36 @@ class News extends Authenticatable implements SeoInterface }); } + // * ATTRIBUTES + + /** + * Get cal_link attribute + * + * @return \Illuminate\Database\Eloquent\Casts\Attribute + */ + public function calLink(): Attribute + { + return Attribute::make( + get: fn () => ( + $this->exists() and + ($this->event_start && $this->event_end && $this->event_text) + ) ? Link::create( + $this->title, + $this->event_start, + $this->event_end + )->description($this->event_text)->ics() : null + ); + } + // * METHODS /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { self::assertTitleIsUnique($model->title, $model->id); $model->slug = Str::slug($model->title); diff --git a/app/Models/NewsCategory.php b/app/Models/NewsCategory.php index b8425cf..f552fc2 100644 --- a/app/Models/NewsCategory.php +++ b/app/Models/NewsCategory.php @@ -24,7 +24,7 @@ class NewsCategory extends Authenticatable /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'label', diff --git a/app/Models/Product.php b/app/Models/Product.php index d9d48e1..a8ae9ac 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -25,17 +25,18 @@ use Uwil\Seo\Laravel\Traits\SeoTrait; * @property string $sticker_sm Path of a small sticker. * @property string $sticker_sm_alt small sticker's attribute alt. * @property string $sticker_sm_title Small sticker's attribute title. - * @property string $slider_pictures Array of paths of pictures. - * @property string $packaging Packaging. - * @property \Illuminate\Support\Carbon $caliber Caliber. - * @property \Illuminate\Support\Carbon $nutritionnal_values Nutritionnal values. - * @property \Illuminate\Support\Carbon $ingredients Ingredients. - * @property \Illuminate\Support\Carbon $advantage Advantage. - * @property \Illuminate\Support\Carbon $preparation Preparation. - * @property \Illuminate\Support\Carbon $is_frenchpoultry Is frenchpoultry or not. - * @property \App\Enums\Advices\AdviceDifficultyEnum $is_vip Is vip or not. - * @property \App\Enums\Advices\AdviceDifficultyEnum $is_egalim Is egalim or not. + * @property array $slider_pictures Array of paths of pictures. + * @property array> $packaging Packaging. + * @property array> $caliber Caliber. + * @property array> $nutritionnal_values Nutritionnal values. + * @property string $ingredients Ingredients. + * @property string $advantage Advantage. + * @property string $preparation Preparation. + * @property boolean $is_frenchpoultry Is frenchpoultry or not. + * @property boolean $is_vip Is vip or not. + * @property boolean $is_egalim Is egalim or not. * @property boolean $status Status. + * @property integer $order Order. * @property-read \Illuminate\Support\Carbon $created_at Created date. * @property-read \Illuminate\Support\Carbon $updated_at Updated date. * @@ -53,7 +54,7 @@ class Product extends Model implements SeoInterface /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'label', @@ -82,7 +83,7 @@ class Product extends Model implements SeoInterface /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'slider_pictures' => 'array', @@ -125,13 +126,13 @@ class Product extends Model implements SeoInterface /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { // * ASSERTIONS - static::assertLabelIsUnique($model->label, $model->id); + self::assertLabelIsUnique($model->label, $model->id); ToolboxHelper::assertNoInternalBoUrls('ingredients', $model->ingredients); ToolboxHelper::assertNoInternalBoUrls('advantage', $model->advantage); ToolboxHelper::assertNoInternalBoUrls('preparation', $model->preparation); @@ -142,7 +143,7 @@ class Product extends Model implements SeoInterface ToolboxHelper::assertNoInternalBoUrls('caliber', $calib['value']); } foreach ($model->nutritionnal_values as $nutritionnal_value) { - if ($model->nutritionnal_value) { + if (!empty($nutritionnal_value['value'])) { ToolboxHelper::assertNoInternalBoUrls('nutritionnal_values', $nutritionnal_value['value']); } } @@ -196,20 +197,22 @@ class Product extends Model implements SeoInterface /** * Get associated tips. * - * @return \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> + * @return \Illuminate\Database\Eloquent\Collection */ public function tips(): \Illuminate\Database\Eloquent\Collection { + // @phpstan-ignore-next-line return $this->tipsQuery()->get(); } /** * Get associated recipes. * - * @return \Illuminate\Database\Eloquent\Collection<\App\Models\Advice> + * @return \Illuminate\Database\Eloquent\Collection */ public function recipes(): \Illuminate\Database\Eloquent\Collection { + // @phpstan-ignore-next-line return $this->recipesQuery()->get(); } @@ -218,9 +221,9 @@ class Product extends Model implements SeoInterface /** * Subrange Has-One relation. * - * @return \Illuminate\Database\Eloquent\Relations\belongsTo + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ - public function subrange(): \Illuminate\Database\Eloquent\Relations\belongsTo + public function subrange(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Subrange::class); } diff --git a/app/Models/Range.php b/app/Models/Range.php index 926eef5..765f840 100644 --- a/app/Models/Range.php +++ b/app/Models/Range.php @@ -40,7 +40,7 @@ class Range extends Model implements SeoInterface /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'label', @@ -60,7 +60,7 @@ class Range extends Model implements SeoInterface /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'color' => RgbaColor::class, @@ -77,14 +77,14 @@ class Range extends Model implements SeoInterface throw new \RuntimeException('Impossible de créer un range'); }); static::updating(function (self $model) { - static::assertLabelIsUnique($model->label, $model->id); + self::assertLabelIsUnique($model->label, $model->id); $model->slug = Str::slug($model->label); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); $model->picture_banner = FileStorageHelper::storeFile($model, $model->picture_banner, true); }); static::updated(function (self $model) { - $model->picture = FileStorageHelper::removeOldFile($model, 'picture'); - $model->picture_banner = FileStorageHelper::removeOldFile($model, 'picture_banner'); + FileStorageHelper::removeOldFile($model, 'picture'); + FileStorageHelper::removeOldFile($model, 'picture_banner'); }); static::deleting(function () { throw new \RuntimeException('Impossible de supprimer un range'); @@ -113,9 +113,9 @@ class Range extends Model implements SeoInterface /** * Subranges Has-Many relationship. * - * @return \Illuminate\Database\Eloquent\Relations\hasMany + * @return \Illuminate\Database\Eloquent\Relations\HasMany */ - public function subranges(): \Illuminate\Database\Eloquent\Relations\hasMany + public function subranges(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Subrange::class); } @@ -123,9 +123,9 @@ class Range extends Model implements SeoInterface // * SEO /** - * Transfotrm to seoModel + * Transform to seoModel * - * @return \App\Objects\SeoItem + * @return \Uwil\Seo\Laravel\Objects\SeoItem */ public function toSeoItem(): SeoItem { diff --git a/app/Models/Slide.php b/app/Models/Slide.php index 4607a7a..d71a9d1 100644 --- a/app/Models/Slide.php +++ b/app/Models/Slide.php @@ -11,11 +11,11 @@ use Illuminate\Validation\ValidationException; /** * @property integer $id Id. * @property string $title Title. - * @property integer $content WYSWYG content. + * @property string $content WYSWYG content. * @property boolean $button_display Display the button. - * @property string $button_text Title of the button. - * @property string $button_url Link of the button. - * @property boolean $button_targetblank Open in new window. + * @property string|null $button_text Title of the button. + * @property string|null $button_url Link of the button. + * @property boolean|null $button_targetblank Open in new window. * @property string $picture Path of a picture. * @property string $picture_alt Picture's attribute alt. * @property string $picture_title Picture's attribute title. @@ -33,7 +33,7 @@ class Slide extends Model /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'title', @@ -54,7 +54,7 @@ class Slide extends Model /** * The attributes that should be cast. * - * @var array + * @var array */ protected $casts = [ 'button_display' => 'bool', @@ -98,10 +98,10 @@ class Slide extends Model /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { self::assertTitleIsUnique($model->title, $model->id); ToolboxHelper::assertNoInternalBoUrls($model->content, 'content'); diff --git a/app/Models/StaticPage.php b/app/Models/StaticPage.php index 26abffe..1b97440 100644 --- a/app/Models/StaticPage.php +++ b/app/Models/StaticPage.php @@ -52,14 +52,14 @@ class StaticPage extends Model { static::creating(function (self $model) { // * ASSERTIONS - static::assertTitleIsUnique($model->title); + self::assertTitleIsUnique($model->title); // * CHANGES $model->slug = Str::slug($model->title); }); static::updating(function (self $model) { // * ASSERTIONS - static::assertTitleIsUnique($model->title, $model->id); + self::assertTitleIsUnique($model->title, $model->id); // * CHANGES $model->slug = Str::slug($model->title); diff --git a/app/Models/Subrange.php b/app/Models/Subrange.php index 6eeedce..e8e76dc 100644 --- a/app/Models/Subrange.php +++ b/app/Models/Subrange.php @@ -26,7 +26,7 @@ class Subrange extends Model /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'label', @@ -55,12 +55,12 @@ class Subrange extends Model /** * Common methods function. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param self $model * @return void */ - private static function manageFields(Model $model): void + private static function manageFields(self $model): void { - static::assertLabelIsUnique($model->label, $model->id); + self::assertLabelIsUnique($model->label, $model->id); $model->slug = Str::slug($model->label); } @@ -83,9 +83,9 @@ class Subrange extends Model /** * Products Belongs-To-Many relationship. * - * @return \Illuminate\Database\Eloquent\Relations\hasMany + * @return \Illuminate\Database\Eloquent\Relations\HasMany */ - public function products() + public function products(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Product::class); } @@ -93,9 +93,9 @@ class Subrange extends Model /** * Range Belongs-To relationship. * - * @return \Illuminate\Database\Eloquent\Relations\belongsTo + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ - public function range() + public function range(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Range::class); } diff --git a/app/Models/Tag.php b/app/Models/Tag.php index d00ea90..75590bc 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -9,30 +9,8 @@ use Illuminate\Support\Str; /** * @property integer $id Id. - * @property string $title Title. - * @property string $slug Slug of the title. - * @property string $seo_title SEO Title. - * @property string $seo_description SEO description. - * @property \App\Enums\Advices\AdviceTypeEnum $type Type of the advice. - * @property string $picture Path of a picture. - * @property string $picture_alt Picture's attribute alt. - * @property string $picture_title Picture's attribute title. - * @property string $sticker Path of a sticker. - * @property string $sticker_alt Sticker's attribute alt. - * @property string $sticker_title Sticker's attribute title. - * @property string $sticker_sm Path of a small sticker. - * @property string $sticker_sm_alt small sticker's attribute alt. - * @property string $sticker_sm_title Small sticker's attribute title. - * @property string $preparation Preparation tips. - * @property string $advice Advice. - * @property \Illuminate\Support\Carbon $ingredients Ingredients. - * @property \Illuminate\Support\Carbon $guests_nb Number of guests. - * @property \Illuminate\Support\Carbon $youtube_title Youtube title. - * @property \Illuminate\Support\Carbon $youtube_video_id Youtube video id. - * @property \Illuminate\Support\Carbon $cooking_time Time of cooking. - * @property \Illuminate\Support\Carbon $preparation_time Time of preparation. - * @property \App\Enums\Advices\AdviceDifficultyEnum $difficulty Difficulty. - * @property boolean $status Status. + * @property string $slug Slug. + * @property string $label Label. * @property-read \Illuminate\Support\Carbon $created_at Created date. * @property-read \Illuminate\Support\Carbon $updated_at Updated date. * @@ -46,7 +24,7 @@ class Tag extends Model /** * The attributes that are mass assignable. * - * @var array + * @var array */ protected $fillable = [ 'label' @@ -59,16 +37,16 @@ class Tag extends Model */ protected static function booted(): void { - static::creating(function (Tag $tag) { - static::assertLabelIsUnique($tag->label); - $tag->slug = Str::slug($tag->label); + static::creating(function (self $model) { + static::assertLabelIsUnique($model->label); + $model->slug = Str::slug($model->label); }); - static::updating(function (Tag $tag) { - static::assertLabelIsUnique($tag->label, $tag->id); - $tag->slug = Str::slug($tag->label); + static::updating(function (self $model) { + static::assertLabelIsUnique($model->label, $model->id); + $model->slug = Str::slug($model->label); }); - static::deleting(function (Tag $tag) { - $tag->advice()->detach(); + static::deleting(function (self $model) { + $model->advice()->detach(); }); } @@ -82,7 +60,7 @@ class Tag extends Model * @return void * @throws \Illuminate\Validation\ValidationException If a tag label already exists. */ - private static function assertLabelIsUnique(string $label, ?int $id = null): void + public static function assertLabelIsUnique(string $label, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id); diff --git a/app/Models/User.php b/app/Models/User.php index 6dc9e13..34bf9ce 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -14,7 +14,7 @@ use Illuminate\Support\Str; * @property string $firstname Firstname. * @property string $lastname Lastname. * @property string $email Email. - * @property \Illuminate\Support\Carbon $email_verified_at Email_verified_at. + * @property \Illuminate\Support\Carbon|null $email_verified_at Email_verified_at. * @property string $password Password. * @property string $remember_token Remember_token. * @property \Carbon\Carbon $last_connection Last_connection. @@ -67,14 +67,14 @@ class User extends Authenticatable { // * EVENT CLOSURES. static::creating(function (self $user) { - static::assertEmailIsUnique($user->email); + self::assertEmailIsUnique($user->email); if (Hash::needsRehash($user->password)) { $user->password = Hash::make($user->password); } $user->remember_token = Str::random(10); }); static::updating(function (self $user) { - static::assertEmailIsUnique($user->email, $user->id); + self::assertEmailIsUnique($user->email, $user->id); if (Hash::needsRehash($user->password)) { $user->password = Hash::make($user->password); } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index b4b23c2..2c115e8 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,7 @@ namespace App\Providers; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\URL; @@ -16,6 +17,8 @@ class AppServiceProvider extends ServiceProvider */ public function boot() { + Model::shouldBeStrict(!$this->app->environment('production')); + // * HTTPS FIX URL::forceScheme('https'); diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index afb0cf8..e56df5c 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -18,7 +18,7 @@ class AuthServiceProvider extends ServiceProvider * * @return void */ - public function boot() + public function boot(): void { $this->registerPolicies(); } diff --git a/app/Providers/TranslationServiceProvider.php b/app/Providers/TranslationServiceProvider.php index b3e3f4b..9b3029f 100644 --- a/app/Providers/TranslationServiceProvider.php +++ b/app/Providers/TranslationServiceProvider.php @@ -2,6 +2,7 @@ namespace App\Providers; +use App\Lib\Helpers\ToolboxHelper; use Illuminate\Support\Collection; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Cache; @@ -20,9 +21,19 @@ class TranslationServiceProvider extends ServiceProvider foreach ($this->collectLocalesStrings() as $locale) { // * Suported locales Cache::rememberForever(sprintf('translations.%s', $locale), function () use ($locale) { - $translations = [ - 'php' => $this->phpTranslations($locale), - 'json' => $this->jsonTranslations($locale), + $phpTransFallback = $this->phpTranslations(config('app.fallback_locale')); + $phpTransLocale = $this->phpTranslations($locale); + $jsonTransFallback = $this->jsonTranslations(config('app.fallback_locale')); + $jsonTransLocale = $this->jsonTranslations($locale); + $translations = [ + 'php' => ToolboxHelper::arrayMergeRecursiveDistinct( + $phpTransLocale, + $phpTransFallback, + ), + 'json' => ToolboxHelper::arrayMergeRecursiveDistinct( + $jsonTransLocale, + $jsonTransFallback, + ), ]; return $translations; }); @@ -36,11 +47,13 @@ class TranslationServiceProvider extends ServiceProvider */ private function collectLocalesStrings(): Collection { + // * En dur dans ->keys array. + // @phpstan-ignore-next-line return collect(File::allFiles(resource_path('lang/')))->flatMap(function (SplFileInfo $file) { if ($file->getRelativePath() and \strpos($file->getRelativePath(), 'vendor') !== 0) { return [$file->getRelativePath() => '']; } - })->keys(); + })->keys()->merge(config('app.locales', [])); } /** @@ -53,6 +66,10 @@ class TranslationServiceProvider extends ServiceProvider { $path = resource_path("lang/$locale"); + if (!File::exists($path) or !File::isReadable($path)) { + return []; + } + return collect(File::allFiles($path))->flatMap(function ($file) use ($locale) { $translation = $file->getBasename('.php'); return [$translation => trans($translation, [], $locale)]; @@ -69,10 +86,10 @@ class TranslationServiceProvider extends ServiceProvider { $path = resource_path("lang/$locale.json"); - if (is_string($path) && is_readable($path)) { - return json_decode(file_get_contents($path), true) ?? []; + if (!File::exists($path) or !File::isReadable($path)) { + return []; } - return []; + return json_decode(File::get($path), true) ?? []; } } diff --git a/app/Providers/ViewServiceProvider.php b/app/Providers/ViewServiceProvider.php index 9f4f598..8b35765 100644 --- a/app/Providers/ViewServiceProvider.php +++ b/app/Providers/ViewServiceProvider.php @@ -32,7 +32,7 @@ class ViewServiceProvider extends ServiceProvider if (collect(explode('/', \request()->getPathInfo()))->get(1) === 'bo') { Paginator::defaultView('bo.modules.pagination'); } else { - Paginator::useBootstrap(); + Paginator::useBootstrapFive(); } } } diff --git a/app/Traits/Controllers/ChangesModelOrder.php b/app/Traits/Controllers/ChangesModelOrder.php index ed0be43..1797d90 100644 --- a/app/Traits/Controllers/ChangesModelOrder.php +++ b/app/Traits/Controllers/ChangesModelOrder.php @@ -29,29 +29,27 @@ trait ChangesModelOrder } /** @var \Illuminate\Database\Eloquent\Model|null */ - $model = $className::where('id', $model->id)->first(); + $model = $className::where($model->getRouteKeyName(), $model->getRouteKey())->first(); if (!$model) { - return redirect()->back()->with('error', trans('crud.messages.order_not_changed')); + return back()->with('error', trans('crud.messages.order_not_changed')); } return DB::transaction(function () use ($request, $className, $model) { /** @var \Illuminate\Database\Eloquent\Model|null */ - $tmp = $className::where('order', $request->direction ? '<' : '>', $model->order) + $tmp = $className::where('order', $request->direction ? '<' : '>', $model->getOriginal('order')) ->orderBy('order', $request->direction ? 'DESC' : 'ASC')->first(); if (!$tmp) { - return redirect()->back()->with('error', trans('crud.messages.order_not_changed')); + return back()->with('error', trans('crud.messages.order_not_changed')); } - $newOrder = $tmp->order; - $tmp->order = $model->order; - $model->order = $newOrder; - $tmp->saveOrFail(); - $model->saveOrFail(); + $newOrder = $tmp->getOriginal('order'); + $tmp->update(['order' => $model->getOriginal('order')]); + $model->update(['order' => $newOrder]); Session::flash('success', trans('crud.messages.order_changed')); - return redirect()->back(); + return back(); }); } } diff --git a/app/Traits/Controllers/HasPicture.php b/app/Traits/Controllers/HasPicture.php deleted file mode 100644 index 9b07f3b..0000000 --- a/app/Traits/Controllers/HasPicture.php +++ /dev/null @@ -1,31 +0,0 @@ -slider_pictures)) { - $model->slider_pictures = []; - $model->slider_pictures = collect($request->slider_pictures) - ->map(function ($picture) use ($model) { - return FileStorageHelper::storeFile($model, $picture, true); - })->all(); - } - } -} diff --git a/app/Traits/Controllers/UpdateModelStatus.php b/app/Traits/Controllers/UpdateModelPublished.php similarity index 64% rename from app/Traits/Controllers/UpdateModelStatus.php rename to app/Traits/Controllers/UpdateModelPublished.php index 657e8b4..05691b1 100644 --- a/app/Traits/Controllers/UpdateModelStatus.php +++ b/app/Traits/Controllers/UpdateModelPublished.php @@ -9,18 +9,17 @@ use Illuminate\Database\Eloquent\Model; * to resolve the model and the DB row * It does not work with binder Service */ -trait UpdateModelStatus +trait UpdateModelPublished { /** - * Change model published + * Change model published. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Http\RedirectResponse */ public function changePublished(Model $model) { - $model->status = !$model->status; - $model->saveOrFail(); - return redirect()->back(); + $model->update(['published' => !$model->getOriginal('published')]); + return redirect()->back()->with('success', trans(__('crud.messages.publish_status_saved'))); } } diff --git a/app/Traits/Enums/BaseEnum.php b/app/Traits/Enums/BaseEnum.php index 559b1ee..d6016cb 100644 --- a/app/Traits/Enums/BaseEnum.php +++ b/app/Traits/Enums/BaseEnum.php @@ -118,9 +118,9 @@ trait BaseEnum /** * Fetch enum using value. * - * @param \App\Traits\Enums\BaseEnum|integer|string $value - * @param string $field - * @return \App\Traits\Enums\BaseEnum|null + * @param self|integer|string $value + * @param string $field + * @return self|null */ public static function make(self|int|string $value, string $field = 'value'): self|null { diff --git a/app/Traits/Requests/HasPicture.php b/app/Traits/Requests/HasPicture.php index b4fc8c0..7f83cfa 100644 --- a/app/Traits/Requests/HasPicture.php +++ b/app/Traits/Requests/HasPicture.php @@ -2,8 +2,11 @@ namespace App\Traits\Requests; -use Illuminate\Support\Facades\File; +use App\Lib\Helpers\ToolboxHelper; +/** + * ! This assumes file system is using local storage + */ trait HasPicture { /** @@ -11,14 +14,14 @@ trait HasPicture * * @var integer */ - private $minWith = 400; + private $minWidth = 400; /** * Maximum width * * @var integer */ - private $maxWith = 1800; + private $maxWidth = 1800; /** * Minimum height @@ -38,32 +41,41 @@ trait HasPicture * Image rules * * @param string $name - * @param boolean $required - * @param integer|null $minWith + * @param integer|null $minWidth * @param integer|null $minHeight - * @param integer|null $maxWith + * @param integer|null $maxWidth * @param integer|null $maxHeight + * @param boolean $nullable + * @param integer|null $size + * @param string|null $requiredWith + * @param string|null $requiredWithout * @return array */ public function pictureRules( string $name = 'picture', - bool $required = true, - ?int $minWith = null, + ?int $minWidth = null, ?int $minHeight = null, - ?int $maxWith = null, - ?int $maxHeight = null + ?int $maxWidth = null, + ?int $maxHeight = null, + bool $nullable = false, + ?int $size = null, + ?string $requiredWith = null, + ?string $requiredWithout = null, ): array { - $sizes = (object)[ - 'minWith' => $minWith ?? $this->minWith, + $dimensions = (object)[ + 'minWidth' => $minWidth ?? $this->minWidth, 'minHeight' => $minHeight ?? $this->minHeight, - 'maxWith' => $maxWith ?? $this->maxWith, + 'maxWidth' => $maxWidth ?? $this->maxWidth, 'maxHeight' => $maxHeight ?? $this->maxHeight ]; return [ $name => [ - $required ? 'required' : 'nullable', - function (string $attribute, $value, callable $fail) use ($sizes) { - return $this->validatePicture($attribute, $value, $fail, $sizes); + !$nullable ? 'required' : 'nullable', + (strlen($requiredWith)) ? 'required_with:' . $requiredWith : '', + (strlen($requiredWithout)) ? 'required_without:' . $requiredWithout : '', + ($size) ? 'max:' . $size : '', + function (string $attribute, $value, callable $fail) use ($dimensions) { + ToolboxHelper::validatePicture($attribute, $value, $fail, $dimensions); } ] ]; @@ -73,92 +85,43 @@ trait HasPicture * Images rules * * @param string $name - * @param boolean $required - * @param integer|null $minWith + * @param integer|null $minWidth * @param integer|null $minHeight - * @param integer|null $maxWith + * @param integer|null $maxWidth * @param integer|null $maxHeight - * @param integer|null $limitMin - * @param integer|null $limitMax + * @param integer $limitMin + * @param integer $limitMax + * @param boolean $nullable * @return array */ public function picturesRules( string $name = 'pictures', - bool $required = true, - ?int $minWith = null, + ?int $minWidth = null, ?int $minHeight = null, - ?int $maxWith = null, + ?int $maxWidth = null, ?int $maxHeight = null, - ?int $limitMin = null, - ?int $limitMax = null + int $limitMin = 1, + int $limitMax = 5, + bool $nullable = false ): array { $sizes = (object)[ - 'required' => $required ?? $this->required, - 'minWith' => $minWith ?? $this->minWith, + 'minWidth' => $minWidth ?? $this->minWidth, 'minHeight' => $minHeight ?? $this->minHeight, - 'maxWith' => $maxWith ?? $this->maxWith, + 'maxWidth' => $maxWidth ?? $this->maxWidth, 'maxHeight' => $maxHeight ?? $this->maxHeight, - 'limitMin' => $limitMin ?? $this->limitMin, - 'limitMax' => $limitMax ?? $this->limitMax ]; return [ - "{$name}" => ($required ? 'required' : 'nullable') . "|array|between:$limitMin,$limitMax", - "{$name}.*" => [ + $name => [!$nullable ? 'required' : 'nullable', 'array', "between:{$limitMin},{$limitMax}"], + "{$name}Validate" => "required_with:{$name}|array", + "{$name}Validate.*" => [ 'required', function (string $attribute, $value, callable $fail) use ($sizes) { - return $this->validatePicture($attribute, $value, $fail, $sizes); + ToolboxHelper::validatePicture($attribute, $value, $fail, $sizes); } ] ]; } - /** - * Validate picture - * - * @param string $attribute - * @param mixed $value - * @param callback $fail - * @param object $sizes - * @return void - * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed - */ - private function validatePicture(string $attribute, mixed $value, callable $fail, object $sizes) - { - if (!File::exists($value)) { - $fail(trans(":attribute n'existe pas dans le système de fichier")); - return; - } - if (!\in_array(File::mimeType($value), ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) { - $fail(trans(":attribute doit être une image de type 'image/jpeg,image/jpg,image/png,image/gif'")); - } - if (!($dimensions = \getimagesize($value)) or !isset($dimensions[0]) or !isset($dimensions[1])) { - $fail(trans(":attribute impossible de valider les dimensions")); - } else { - $width = intval($dimensions[0]); - $height = intval($dimensions[1]); - - $xMessage = trans( - ":attribute la largeur doit être comprise entre {$sizes->minWith}px et {$sizes->maxWith}px" - ); - if ($sizes->minWith === $sizes->maxWith) { - $xMessage = trans(":attribute la largeur doit être de {$sizes->minWith}px"); - } - $yMessage = trans( - ":attribute la hauteur doit être comprise entre {$sizes->minWith}px et {$sizes->maxWith}px" - ); - if ($sizes->minHeight === $sizes->maxHeight) { - $yMessage = trans(":attribute la hauteur doit être de {$sizes->minWith}px"); - } - - if (($width < $sizes->minWith) or ($width > $sizes->maxWith)) { - $fail($xMessage); - } - if (($height < $sizes->minHeight) or ($height > $sizes->maxHeight)) { - $fail($yMessage); - } - } //end if - } - /** * Merges products pictures fields with request data * @@ -189,4 +152,38 @@ trait HasPicture ]); } //end if } + + /** + * Merges products pictures fields with request data + * + * @param string $name + * @return void + */ + protected function mergePictures(string $name = 'pictures'): void + { + $pictures = $this->{$name}; + if (is_array($pictures)) { + $this->merge(["{$name}Validate" => []]); + foreach ($pictures as $key => $picturePath) { + // ! Empty picture. + if ($picturePath === 'false') { + // * Empty picture and exit + $this->merge([$name => []]); + return; + } + $decodedPath = \urldecode($picturePath); + $this->merge([ + "{$name}Validate" => array_merge( + $this->{"{$name}Validate"}, + [\public_path(ltrim($decodedPath, '/'))] + ) + ]); + $changedPicture = $this->{$name}; + $changedPicture[$key] = ltrim($decodedPath, '/'); + $this->merge([ + $name => $changedPicture + ]); + } + } //end if + } } diff --git a/composer.json b/composer.json index d87488c..394a5c4 100644 --- a/composer.json +++ b/composer.json @@ -34,6 +34,7 @@ "require-dev": { "doctrine/dbal": "^3.3", "fakerphp/faker": "^1.9.1", + "larastan/larastan": "^2.8", "laravel-lang/lang": "10.0", "laravel/pint": "^1.0", "laravel/sail": "^1.18", diff --git a/composer.lock b/composer.lock index 8d2be82..d5ea94f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6f32bca1570707ed0515b4b0d1ab2cde", + "content-hash": "176385e79104d9157757632c5e4b0f9a", "packages": [ { "name": "axlon/laravel-postal-code-validation", @@ -10128,6 +10128,107 @@ }, "time": "2020-07-09T08:09:16+00:00" }, + { + "name": "larastan/larastan", + "version": "v2.8.1", + "source": { + "type": "git", + "url": "https://github.com/larastan/larastan.git", + "reference": "b7cc6a29c457a7d4f3de90466392ae9ad3e17022" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/larastan/larastan/zipball/b7cc6a29c457a7d4f3de90466392ae9ad3e17022", + "reference": "b7cc6a29c457a7d4f3de90466392ae9ad3e17022", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/console": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/container": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/contracts": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/database": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/http": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/pipeline": "^9.52.16 || ^10.28.0 || ^11.0", + "illuminate/support": "^9.52.16 || ^10.28.0 || ^11.0", + "php": "^8.0.2", + "phpmyadmin/sql-parser": "^5.8.2", + "phpstan/phpstan": "^1.10.50" + }, + "require-dev": { + "nikic/php-parser": "^4.17.1", + "orchestra/canvas": "^7.11.1 || ^8.11.0 || ^9.0.0", + "orchestra/testbench": "^7.33.0 || ^8.13.0 || ^9.0.0", + "phpunit/phpunit": "^9.6.13 || ^10.5" + }, + "suggest": { + "orchestra/testbench": "Using Larastan for analysing a package needs Testbench" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "psr-4": { + "Larastan\\Larastan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Can Vural", + "email": "can9119@gmail.com" + }, + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "Larastan - Discover bugs in your code without running it. A phpstan/phpstan wrapper for Laravel", + "keywords": [ + "PHPStan", + "code analyse", + "code analysis", + "larastan", + "laravel", + "package", + "php", + "static analysis" + ], + "support": { + "issues": "https://github.com/larastan/larastan/issues", + "source": "https://github.com/larastan/larastan/tree/v2.8.1" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/canvural", + "type": "github" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://www.patreon.com/nunomaduro", + "type": "patreon" + } + ], + "time": "2024-01-08T09:11:17+00:00" + }, { "name": "laravel-lang/lang", "version": "10.0.0", @@ -10607,6 +10708,94 @@ }, "time": "2022-02-21T01:04:05+00:00" }, + { + "name": "phpmyadmin/sql-parser", + "version": "5.9.0", + "source": { + "type": "git", + "url": "https://github.com/phpmyadmin/sql-parser.git", + "reference": "011fa18a4e55591fac6545a821921dd1d61c6984" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpmyadmin/sql-parser/zipball/011fa18a4e55591fac6545a821921dd1d61c6984", + "reference": "011fa18a4e55591fac6545a821921dd1d61c6984", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0", + "symfony/polyfill-mbstring": "^1.3", + "symfony/polyfill-php80": "^1.16" + }, + "conflict": { + "phpmyadmin/motranslator": "<3.0" + }, + "require-dev": { + "phpbench/phpbench": "^1.1", + "phpmyadmin/coding-standard": "^3.0", + "phpmyadmin/motranslator": "^4.0 || ^5.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.9.12", + "phpstan/phpstan-phpunit": "^1.3.3", + "phpunit/php-code-coverage": "*", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", + "psalm/plugin-phpunit": "^0.16.1", + "vimeo/psalm": "^4.11", + "zumba/json-serializer": "~3.0.2" + }, + "suggest": { + "ext-mbstring": "For best performance", + "phpmyadmin/motranslator": "Translate messages to your favorite locale" + }, + "bin": [ + "bin/highlight-query", + "bin/lint-query", + "bin/sql-parser", + "bin/tokenize-query" + ], + "type": "library", + "autoload": { + "psr-4": { + "PhpMyAdmin\\SqlParser\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0-or-later" + ], + "authors": [ + { + "name": "The phpMyAdmin Team", + "email": "developers@phpmyadmin.net", + "homepage": "https://www.phpmyadmin.net/team/" + } + ], + "description": "A validating SQL lexer and parser with a focus on MySQL dialect.", + "homepage": "https://github.com/phpmyadmin/sql-parser", + "keywords": [ + "analysis", + "lexer", + "parser", + "query linter", + "sql", + "sql lexer", + "sql linter", + "sql parser", + "sql syntax highlighter", + "sql tokenizer" + ], + "support": { + "issues": "https://github.com/phpmyadmin/sql-parser/issues", + "source": "https://github.com/phpmyadmin/sql-parser" + }, + "funding": [ + { + "url": "https://www.phpmyadmin.net/donate/", + "type": "other" + } + ], + "time": "2024-01-20T20:34:02+00:00" + }, { "name": "phpstan/phpdoc-parser", "version": "1.24.5", @@ -10654,6 +10843,68 @@ }, "time": "2023-12-16T09:33:33+00:00" }, + { + "name": "phpstan/phpstan", + "version": "1.10.57", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "1627b1d03446904aaa77593f370c5201d2ecc34e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/1627b1d03446904aaa77593f370c5201d2ecc34e", + "reference": "1627b1d03446904aaa77593f370c5201d2ecc34e", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", + "type": "tidelift" + } + ], + "time": "2024-01-24T11:51:34+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "10.1.10", diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..df74d87 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,10 @@ +includes: + - vendor/larastan/larastan/extension.neon + +parameters: + + paths: + - app/ + + # Level 9 is the highest level + level: 5 diff --git a/resources/ts/bo/components/BelongsToManyDropdownComponent.vue b/resources/ts/bo/components/BelongsToManyDropdownComponent.vue index 8c1ad9f..3d2f3bb 100644 --- a/resources/ts/bo/components/BelongsToManyDropdownComponent.vue +++ b/resources/ts/bo/components/BelongsToManyDropdownComponent.vue @@ -39,13 +39,13 @@