fix: 🚨 resolve phpstan errors with strict level 7

This commit is contained in:
Alexis Gousseau 2026-04-24 15:04:18 +02:00
parent 93e4ed4cae
commit 0c9d7da807
No known key found for this signature in database
GPG key ID: 7F3C786EE12DBB72
82 changed files with 687 additions and 697 deletions

View file

@ -0,0 +1,117 @@
<?php
namespace App\Console\Commands;
use App\Enums\Users\RoleEnum;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
/**
* Artisan command to create a backend admin user.
*/
class MakeUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'uwil:make:user';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new backend admin user.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->components->info("Creating a new <comment>backend user</comment>...");
$firstName = $this->askValid(
'first_name',
'First name',
'Admin',
['required', 'min:3', 'max:255']
);
$lastName = $this->askValid(
'last_name',
'Last name',
'Saïtama',
['required', 'min:3', 'max:255']
);
$email = $this->askValid(
'email',
'Email',
'equipe.web@ldc.fr',
['required', 'unique:users,email', 'email:rfc,strict,dns,spoof,filter']
);
$role = $this->askRole();
$user = new User([
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'role' => $role,
'published' => true,
'published_at' => Carbon::now(),
]);
$user->saveOrFail();
$this->components->success("User <comment>{$firstName} {$lastName}</comment> created successfully.");
}
/**
* Ask for a value and validate it, re-prompting on failure.
*
* @param string $field
* @param string $label
* @param string $default
* @param array<int, string> $rules
* @return string
*/
private function askValid(string $field, string $label, string $default, array $rules): string
{
try {
$value = $this->ask(sprintf("Type the wanted user %s", $label), $default);
$validator = Validator::make([$field => $value], [$field => $rules]);
$validator->validate();
return $value;
} catch (ValidationException $e) {
$this->components->error(
collect($e->errors())->flatten()->first()
);
return $this->askValid($field, $label, $default, $rules);
}
}
/**
* Ask for a role and return the corresponding RoleEnum.
*
* @return \App\Enums\Users\RoleEnum
*/
private function askRole(): \App\Enums\Users\RoleEnum
{
$options = collect([
RoleEnum::conceptor,
RoleEnum::admin,
RoleEnum::visitor,
])->mapWithKeys(fn(RoleEnum $role) => [
Str::ucFirst($role->label()) => $role
]);
/** @var string $choice */
$choice = $this->choice('Role', $options->keys()->all(), Str::ucFirst(RoleEnum::visitor->label()));
return $options->get($choice);
}
}

View file

@ -1,207 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Enums\Users\RoleEnum;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
class UserCreate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'uwil:user:create';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a backend admin user';
/**
* The first name of the new user.
*
* @var string|null
*/
protected $first_name;
/**
* The last name of the new user.
*
* @var string|null
*/
protected $last_name;
/**
* The email of the new user.
*
* @var string|null
*/
protected $email;
/**
* The role of the new user.
*
* @var string|null
*/
protected $role;
/**
* Execute the console command.
*
* @return integer
*/
public function handle(): int
{
$this->first_name = null;
$this->addFirstName();
$this->last_name = null;
$this->addLastName();
$this->email = null;
$this->addEmail();
$this->role = null;
$this->addRole();
$user = new User([
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'role' => $this->role,
'published' => true,
'published_at' => Carbon::now(),
]);
$user->saveOrFail();
$this->info('User created 👌');
return 0;
}
/**
* Add a first name to the user.
*
* @return void
*/
private function addFirstName(): void
{
while (is_null($this->first_name)) {
try {
$tmp = $this->ask('Type the wanted user first name', 'Admin');
$validator = Validator::make(['first_name' => $tmp], [
'first_name' => 'required|min:3|max:255'
]);
$validator->validate();
$this->first_name = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid first name %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
/**
* Add a last name to the user.
*
* @return void
*/
private function addLastName(): void
{
while (is_null($this->last_name)) {
try {
$tmp = $this->ask('Type the wanted user last name', 'Saïtama');
$validator = Validator::make(['last_name' => $tmp], [
'last_name' => 'required|min:3|max:255'
]);
$validator->validate();
$this->last_name = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid last_name %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
/**
* Add an email to the user.
*
* @return void
*/
private function addEmail(): void
{
while (is_null($this->email)) {
try {
$tmp = $this->ask('Type the wanted user email', 'equipe.web@ldc.fr');
$validator = Validator::make(['email' => $tmp], [
'email' => 'required|unique:users,email|email:rfc,dns'
]);
$validator->validate();
$this->email = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid email %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
/**
* Add a role to the user.
*
* @return void
*/
private function addRole(): void
{
while (is_null($this->role)) {
try {
$tmp = $this->choice(
'Select his role',
[
Str::ucFirst(RoleEnum::conceptor->label()),
Str::ucFirst(RoleEnum::admin->label()),
Str::ucFirst(RoleEnum::visitor->label())
],
Str::ucFirst(RoleEnum::visitor->label()),
);
if ($tmp === Str::ucFirst(RoleEnum::conceptor->label())) {
$tmp = RoleEnum::conceptor;
}
if ($tmp === Str::ucFirst(RoleEnum::admin->label())) {
$tmp = RoleEnum::admin;
}
if ($tmp === Str::ucFirst(RoleEnum::visitor->label())) {
$tmp = RoleEnum::visitor;
}
$validator = Validator::make(['role' => $tmp], [
'role' => 'required'
]);
$validator->validate();
$this->role = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please choose from the selection %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
}

View file

@ -14,7 +14,7 @@ enum ActivityLogsEventEnum: int
case deleted = 4;
/**
* Optionnal labels definition
* Optionnal labels definition.
*
* @phpstan-ignore-next-line
*/
@ -27,7 +27,7 @@ enum ActivityLogsEventEnum: int
/**
* Custom added classes definition
* Custom added classes definition.
*/
private const BOOTSTRAPCLASS = [
self::created->name => 'success',
@ -37,7 +37,7 @@ enum ActivityLogsEventEnum: int
];
/**
* Get Class
* Get Class.
*
* @return string
*/

View file

@ -518,7 +518,7 @@ enum Country: int
/**
* Get Valid Shipping Countries
*
* @return array
* @return array<int, self>
*/
public static function validShippingCountries(): array
{
@ -544,7 +544,7 @@ enum Country: int
/**
* Get Valid Shipping Countries
*
* @return array
* @return array<int, self>
*/
public static function validBillingCountries(): array
{
@ -568,7 +568,7 @@ enum Country: int
/**
* Get Alpha 2 ISO code of valid shipping countries
*
* @return array
* @return array<int, string>
*/
public static function getValidShippingCountriesIsoAplha2Codes(): array
{
@ -578,7 +578,7 @@ enum Country: int
/**
* Get Alpha 2 ISO code of valid billing countries
*
* @return array
* @return array<int, string>
*/
public static function getValidBillingCountriesIsoAplha2Codes(): array
{
@ -586,7 +586,7 @@ enum Country: int
}
/**
* Custom added ISOCODES definition
* Custom added ISOCODES definition.
*/
private const ISOCODES = [
self::afghanistan->name => 'AFG',

View file

@ -68,7 +68,7 @@ enum SpeciesEnum: int
];
/**
* Get picture alt attribute
* Get picture alt attribute.
*
* @return string
*/
@ -77,7 +77,6 @@ enum SpeciesEnum: int
return self::ALTS[$this->name];
}
/**
* Alt attributes for pictures.
*/
@ -92,7 +91,7 @@ enum SpeciesEnum: int
];
/**
* Get picture alt attribute
* Get picture alt attribute.
*
* @return string
*/

View file

@ -40,7 +40,7 @@ enum StaticPageType: int
/**
* Get the enums for the page which contains sections.
*
* @return array
* @return array<int, self>
*/
public static function containsSection(): array
{

View file

@ -42,7 +42,7 @@ enum PictoEnum: int
];
/**
* Get picture path
* Get picture path.
*
* @return string
*/
@ -64,7 +64,7 @@ enum PictoEnum: int
];
/**
* Get picture alt attribute
* Get picture alt attribute.
*
* @return string
*/
@ -87,7 +87,7 @@ enum PictoEnum: int
];
/**
* Get picture alt attribute
* Get picture alt attribute.
*
* @return string
*/

View file

@ -29,6 +29,9 @@ enum TypeEnum: int
self::hire->name => 'On Embauche',
];
/**
* Optionnal labels definition.
*/
private const COLORS = [
self::breeding->name => 'tertiary',
self::better_life->name => 'quad',
@ -39,7 +42,7 @@ enum TypeEnum: int
];
/**
* Get color name
* Get color name.
*
* @return string
*/

View file

@ -21,7 +21,7 @@ class ActivityLogController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $query */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\ActivityLog> $query */
$query = ActivityLog::query()->with('user');
/** @var string $search Search field */
@ -55,6 +55,7 @@ class ActivityLogController extends Controller
*/
public function show(ActivityLog $activity_log): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Model $targetModelClass */
$targetModelClass = $activity_log->model_class;
$targetModel = $activity_log->model_class::where(
(new $targetModelClass())->getRouteKeyName(),

View file

@ -34,8 +34,9 @@ class AisleController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $aisleModels */
$aisleModels = Aisle::query()->with('network');
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Aisle> $aisleModels */
$aisleModels = Aisle::query()->with('network');
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Network> $networkModels */
$networkModels = Network::query()->where('published', true)->get();
$selectedNetwork = intval($request->network);

View file

@ -32,7 +32,7 @@ class BrandController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $brandModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Brand> $brandModels */
$brandModels = Brand::query()->with('aisle');
/** @var string $search Search field */

View file

@ -36,9 +36,10 @@ class CarouselController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $carouselModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Carousel> $carouselModels */
$carouselModels = Carousel::query()->with('section');
$sectionModels = Section::query()->whereHas('carousels')->get();
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Section> $sectionModels */
$sectionModels = Section::query()->whereHas('carousels')->get();
$selectedSection = intval($request->section);

View file

@ -7,7 +7,7 @@ use App\Http\Controllers\Controller;
class DashboardController extends Controller
{
/**
* Dashboard Page
* Dashboard Page.
*
* @return \Illuminate\Contracts\View\View
*/

View file

@ -28,7 +28,7 @@ class HistoricalMilestoneController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $historicalMilestoneModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\HistoricalMilestone> $historicalMilestoneModels */
$historicalMilestoneModels = HistoricalMilestone::query();
/** @var string $search Search field */

View file

@ -28,7 +28,7 @@ class JobVideoController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $jobVideoModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\JobVideo> $jobVideoModels */
$jobVideoModels = JobVideo::query();
/** @var string $search Search field */

View file

@ -28,7 +28,7 @@ class LogoController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $logoModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Logo> $logoModels */
$logoModels = Logo::query();
/** @var string $search Search field */

View file

@ -33,7 +33,7 @@ class NetworkController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $networkModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Network> $networkModels */
$networkModels = Network::query();
/** @var string $search Search field */

View file

@ -33,7 +33,7 @@ class NewsController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $newsModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $newsModels */
$newsModels = News::query();
/** @var string $search Search field */

View file

@ -30,7 +30,7 @@ class SectionController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $query */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Section> $query */
$query = Section::query()->with('page');
// Filter by related page if requested.
@ -92,11 +92,15 @@ class SectionController extends Controller
public function update(UpdateSectionRequest $request, Section $section): RedirectResponse
{
return DB::transaction(function () use ($request, $section) {
$section->fill(array_replace_recursive(
\json_decode(\json_encode($section->toArray()), true),
$request->validated()
));
$encoded = json_encode($section->toArray());
if ($encoded === false) {
return redirect()->back()->with('error', trans('crud.messages.cannot_be_updated', [
'model' => Str::ucfirst(trans('models.classes.section'))
]));
}
/** @var array<string, mixed> $data */
$data = json_decode($encoded, true);
$section->fill(array_replace_recursive($data, $request->validated()));
if ($section->saveOrFail()) {
return redirect()->route('bo.sections.edit', $section)

View file

@ -32,7 +32,7 @@ class SiteController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $siteModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Site> $siteModels */
$siteModels = Site::query();
/** @var string $search Search field */
@ -90,7 +90,9 @@ class SiteController extends Controller
$site->fill($request->safe()->except(['logos']));
if ($site->saveOrFail()) {
$site->logos()->attach(collect($request->validated('logos'))->pluck('id'));
/** @var array<int, array<string, mixed>> $logos */
$logos = $request->validated('logos') ?? [];
$site->logos()->attach(collect($logos)->pluck('id'));
return redirect()->route('bo.sites.edit', $site)
->with('success', trans('crud.messages.has_been_created', [
'model' => Str::ucfirst(trans('models.classes.site'))
@ -129,8 +131,10 @@ class SiteController extends Controller
public function update(UpdateSiteRequest $request, Site $site): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request, $site) {
/** @var array<int, array<string, mixed>> $logos */
$logos = $request->validated('logos') ?? [];
$site->logos()->sync(collect($logos)->pluck('id'));
$site->fill($request->safe()->except(['logos']));
$site->logos()->sync(collect($request->validated('logos'))->pluck('id'));
if ($site->saveOrFail()) {
return redirect()->route('bo.sites.edit', $site)

View file

@ -28,7 +28,7 @@ class SlideController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $slideModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Slide> $slideModels */
$slideModels = Slide::query();
/** @var string $search Search field */

View file

@ -27,7 +27,7 @@ class StaticPageController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $query */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\StaticPage> $query */
$query = StaticPage::query();
/** @var string $search Search field */

View file

@ -28,7 +28,7 @@ class StickyController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $stickyModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Sticky> $stickyModels */
$stickyModels = Sticky::query();
/** @var string $search Search field */

View file

@ -33,7 +33,7 @@ class StripController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $stripModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Strip> $stripModels */
$stripModels = Strip::query()->with('news');
/** @var string $search Search field */

View file

@ -28,7 +28,7 @@ class TestimonialController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $testimonialModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Testimonial> $testimonialModels */
$testimonialModels = Testimonial::query();
/** @var string $search Search field */

View file

@ -5,6 +5,7 @@ namespace App\Http\Controllers\Bo;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\UploadFileRequest;
use App\Lib\Helpers\FileStorageHelper;
use Illuminate\Database\Eloquent\Model;
class UploadController extends Controller
{
@ -19,9 +20,11 @@ class UploadController extends Controller
{
$modelClass = "App\\Models\\$request->folder";
if (!class_exists($modelClass)) {
if (!class_exists($modelClass) && !is_subclass_of($modelClass, Model::class)) {
return response()->json(['error' => 'Invalid model class'], 404);
}
/** @var \Illuminate\Database\Eloquent\Model $model */
$model = new $modelClass();
/** @var \Illuminate\Http\UploadedFile $image */

View file

@ -31,7 +31,7 @@ class UserController extends Controller
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $userModels */
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\User> $userModels */
$userModels = User::query();
/** @var string $search Search field */
@ -145,7 +145,7 @@ class UserController extends Controller
{
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
\parse_str((string) \parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($user->deleteOrFail()) {
return redirect()->route('bo.users.index', $previousQueries)
->with('success', trans('crud.messages.has_been_deleted', [

View file

@ -24,13 +24,14 @@ class Controller extends BaseController
* Build Search query on specified fields
* splitting search into words or using whole sentence
*
* @param \Illuminate\Database\Eloquent\Builder $query The eloquent query builder.
* @param string $search The query string.
* @param callable|null $searchQuery The query string.
* @param string ...$fields Either a simple array or a string
* in case of a string the two fields
* would be concatenate to make the search.
* @return \Illuminate\Database\Eloquent\Builder
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Database\Eloquent\Builder<TModel> $query The eloquent query builder.
* @param string $search The searched string.
* @param callable|null $searchQuery The query string.
* @param string ...$fields Either a simple array or a string
* in case of a string the two fields
* would be concatenate to make the search.
* @return \Illuminate\Database\Eloquent\Builder<TModel>
*/
protected function searchQuery(
Builder $query,
@ -61,15 +62,16 @@ class Controller extends BaseController
/**
* Build query search on all fields
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $search
* @param array $fields
* @return \Illuminate\Database\Eloquent\Builder
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Database\Eloquent\Builder<TModel> $query
* @param string $search
* @param array<int|string, string|array<int, string>> $fields
* @return \Illuminate\Database\Eloquent\Builder<TModel>
*/
private function searchOnFields(
Builder $query,
string $search,
array $fields
array $fields,
): \Illuminate\Database\Eloquent\Builder {
$table = $query->getModel()->getTable();
foreach ($fields as $field) {
@ -115,13 +117,17 @@ class Controller extends BaseController
/**
* Get the search value (on string or Enum).
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $search
* @param string $field
* @return string|array
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Database\Eloquent\Builder<TModel> $query
* @param string $search
* @param string $field
* @return string|array<int, mixed>
*/
protected function getSearchValue(Builder $query, string $search, string $field): 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.
@ -131,8 +137,8 @@ class Controller extends BaseController
/** @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));
$enum = $cases->filter(function ($item) use ($search): bool {
return preg_match('/' . Str::lower($search) . '/', Str::lower($item->label)) === 1;
});
return $enum->toArray();
} else {
@ -143,12 +149,15 @@ class Controller extends BaseController
/**
* Sort columns with a query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $ignore
* @return \Illuminate\Database\Eloquent\Builder
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Database\Eloquent\Builder<TModel> $query
* @param array<int, string> $ignore
* @return \Illuminate\Database\Eloquent\Builder<TModel>
*/
protected function sortQuery(Builder $query, array $ignore = []): \Illuminate\Database\Eloquent\Builder
{
protected function sortQuery(
Builder $query,
array $ignore = [],
): \Illuminate\Database\Eloquent\Builder {
$rName = request()->route()->getName();
$table = $query->getModel()->getTable();
if (request()->input('sort_col')) {
@ -194,9 +203,10 @@ class Controller extends BaseController
/**
* Customize pagination with cache or config (default).
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Database\Eloquent\Builder<TModel> $query
* @param \App\Enums\Pagination\ItemsPerPaginationEnum|null $pagination
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator<TModel>
*/
protected function paginate(
Builder $query,
@ -208,7 +218,7 @@ class Controller extends BaseController
$pagination = ToolboxHelper::getValidatedEnum(
Cache::get($cacheKey, $pagination->value()),
'pagination',
'\App\Enums\Pagination\ItemsPerPaginationEnum',
ItemsPerPaginationEnum::class,
);
if (Cache::get($cacheKey) !== $pagination) {
Cache::put($cacheKey, $pagination);
@ -228,7 +238,7 @@ class Controller extends BaseController
$theme = ToolboxHelper::getValidatedEnum(
$request->theme ?: Cache::get('theme', BootstrapThemeEnum::light->value()),
'theme',
'\App\Http\Controllers\BootstrapThemeEnum',
BootstrapThemeEnum::class,
);
if (Cache::get("theme") !== $theme) {
Cache::put("theme", $theme);

View file

@ -83,7 +83,7 @@ class StaticPageController extends Controller
$staticPageModel = StaticPage::query()->where('type', StaticPageType::unveil)->first();
$sectionModels = Section::query()->where('page_id', $staticPageModel->id)->get();
$historicalMilestoneModels = HistoricalMilestone::query()->orderBy('year', 'ASC')->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Site> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\Site> */
$siteModelList = Site::query()->orderBy('order')->get();
$keySection = $sectionModels->where('section', PageSectionEnum::unveil_pole)->first();
$missionsSection = $sectionModels->where('section', PageSectionEnum::unveil_missions)->first();
@ -98,10 +98,9 @@ class StaticPageController extends Controller
// * Calcul Viewbox leaflet map ().
// Carte page “on se dévoile” : Point central = Laval + rayon = 100 km
/** @var \App\Models\Site|null $lavalSite */
// @phpstan-ignore-next-line
$lavalSite = $siteModelList->first(fn(Site $site) => Str::contains($site->name, 'Laval'));
if ($lavalSite) {
$viewBox = (object)[
$viewBox = (object) [
'lat' => $lavalSite->latitude,
'lng' => $lavalSite->longitude
];
@ -252,8 +251,8 @@ class StaticPageController extends Controller
public function listenForm(ListenFormRequest $request): \Illuminate\Http\RedirectResponse
{
Mail::to(config('mail.contact.' . ObjectEnum::make(intval($request->validated()['object']))->name()))
->send(new SendContactMail((object)$request->validated()));
Mail::to($request->validated()['email'])->send(new SendConfirmationMail((object)$request->validated()));
->send(new SendContactMail((object) $request->validated()));
Mail::to($request->validated()['email'])->send(new SendConfirmationMail((object) $request->validated()));
return redirect()->route('fo.listen.show')
->with('success', trans(
@ -308,7 +307,7 @@ class StaticPageController extends Controller
*/
public function site(Site $site): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Site> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\Site> */
$siteModels = Site::query()->orderBy('order')->get();
$siteModelList = $siteModels->keyBy('order');
@ -321,7 +320,7 @@ class StaticPageController extends Controller
$nextSiteModel = $siteModelList->first();
}
$viewBox = (object)[
$viewBox = (object) [
'lat' => $site->latitude,
'lng' => $site->longitude
];

View file

@ -12,7 +12,7 @@ class HtmlSanitizer
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|array ...$params
* @param string|array<int, mixed> ...$params
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle(

View file

@ -15,7 +15,7 @@ class SecureHeaders
* Great starting point would be to go check out @Scott_Helme's:
* https://securityheaders.com/
*
* @var array
* @var list<string>
*/
private $unwantedHeaderList = [
'X-Powered-By',
@ -112,9 +112,9 @@ class SecureHeaders
}
/**
* Remove unwanted headers
* Remove unwanted headers.
*
* @param array $headerList
* @param list<string> $headerList
* @return void
*/
private function removeUnwantedHeaders(array $headerList): void

View file

@ -45,7 +45,7 @@ class StoreCarouselRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -91,7 +91,7 @@ class StoreCarouselRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -36,7 +36,7 @@ class StoreHistoricalMilestoneRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -61,7 +61,7 @@ class StoreHistoricalMilestoneRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -22,7 +22,7 @@ class StoreJobVideoRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -36,7 +36,7 @@ class StoreJobVideoRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -32,7 +32,7 @@ class StoreLogoRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -51,7 +51,7 @@ class StoreLogoRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -36,7 +36,7 @@ class StoreNewsRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -67,7 +67,7 @@ class StoreNewsRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -56,7 +56,7 @@ class UpdateSectionRequest extends UpdateMiniCrudRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -27,10 +27,12 @@ class StoreSiteRequest extends FormRequest
*/
protected function prepareForValidation(): void
{
/** @var array<int, mixed> $pictos */
$pictos = $this->input('pictos') ?? [];
$this->merge([
'published' => $this->boolean('published'),
'invert_director_block' => $this->boolean('invert_director_block'),
'pictos' => \collect($this->input('pictos'))->all(),
'pictos' => \collect($pictos)->all(),
]);
$this->mergePicture('logo');
$this->mergePicture('picture_1');
@ -41,7 +43,7 @@ class StoreSiteRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -93,7 +95,7 @@ class StoreSiteRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -39,7 +39,7 @@ class StoreSlideRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -92,7 +92,7 @@ class StoreSlideRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{
@ -114,7 +114,7 @@ class StoreSlideRequest extends FormRequest
/**
* Custom validaton messages.
*
* @return array
* @return array<string, string>
*/
public function messages(): array
{

View file

@ -68,7 +68,7 @@ class UpdateStaticPageRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -22,7 +22,7 @@ class StoreStickyRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -43,7 +43,7 @@ class StoreStickyRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -39,7 +39,7 @@ class StoreStripRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -59,8 +59,8 @@ class StoreStripRequest extends FormRequest
$rules = array_merge(
$rules,
[
'picture_alt' => 'required_with|string|between:3,255',
'picture_title' => 'required_with|string|between:3,255',
'picture_alt' => 'required_with|string|between:3,255',
'picture_title' => 'required_with|string|between:3,255',
],
$this->pictureRules('picture', 100, 65, 100, 65, true),
);
@ -82,7 +82,7 @@ class StoreStripRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -33,7 +33,7 @@ class StoreTestimonialRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -57,7 +57,7 @@ class StoreTestimonialRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -31,7 +31,7 @@ class UpdateChangeOrderRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{

View file

@ -29,8 +29,8 @@ abstract class UpdateMiniCrudRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.MaxExceeded
* @phpcs:disable Generic.Metrics.NestingLevel.TooHigh
*/
public function rules(): array
@ -38,7 +38,8 @@ abstract class UpdateMiniCrudRequest extends FormRequest
// phpcs:enable
$rules = [];
foreach ($this->{$this->modelName}->data as $iptName => $input) {
$input = \json_decode(\json_encode($input), true);
$encoded = \json_encode($input);
$input = \json_decode($encoded !== false ? $encoded : '[]', true);
switch ($input['inputType']) {
case InputType::number->value:
$rules = array_merge($rules, [
@ -71,7 +72,7 @@ abstract class UpdateMiniCrudRequest extends FormRequest
$mergeRules = $this->compileValidate('required|string|min:15', $input);
$mergeRules = collect($mergeRules)
->map(function ($rule) {
if (\strpos($rule, 'max:') !== false) {
if (\is_string($rule) && \strpos($rule, 'max:') !== false) {
$max = \intval(str_replace('max:', '', $rule));
return function ($attribute, $value, $fail) use ($max) {
if (\strlen(\strip_tags($value)) > $max) {
@ -80,7 +81,7 @@ abstract class UpdateMiniCrudRequest extends FormRequest
};
}
return $rule;
});
})->all();
$rules = array_merge($rules, [
"data.$iptName.value" => $mergeRules
]);
@ -99,11 +100,11 @@ abstract class UpdateMiniCrudRequest extends FormRequest
}) : $input['dimensions'];
// * Adapt dimensions
$sizes = (object)[
$sizes = [
'minHeight' => $dim['height'],
'maxHeight' => $dim['height'],
'minWidth' => $dim['width'],
'maxWidth' => $dim['width'],
'minWidth' => $dim['width'],
'maxWidth' => $dim['width'],
];
$rules = array_merge($rules, [
"data.$iptName.value" => [
@ -155,22 +156,23 @@ abstract class UpdateMiniCrudRequest extends FormRequest
break;
} //end switch
} //end foreach
// @phpstan-ignore-next-line
return $rules;
}
/**
* Undocumented function
* Undocumented function.
*
* @param string|array $inputTypeValidate
* @param array $input
* @return array
* @param string|array<int, string> $inputTypeValidate
* @param array<string, mixed> $input
* @return array<int, mixed>
*/
public function compileValidate(string|array $inputTypeValidate, array $input): array
{
if (\is_string($inputTypeValidate)) {
$inputTypeValidate = explode('|', $inputTypeValidate);
}
/** @var array|string */
/** @var array<int|string, mixed>|string $inputValidate */
$inputValidate = \collect($input)->get('validate', $input);
$inputValidate = \is_string($inputValidate) ? explode('|', $inputValidate) : $inputValidate;
foreach ($inputValidate as $validate) {

View file

@ -38,7 +38,7 @@ class UpdateOrderRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{

View file

@ -19,7 +19,7 @@ class UploadFileRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{

View file

@ -35,7 +35,7 @@ class StoreUserRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -51,7 +51,7 @@ class StoreUserRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -32,7 +32,7 @@ class UpdateUserRequest extends StoreUserRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{

View file

@ -30,7 +30,7 @@ class ListenFormRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
@ -101,7 +101,7 @@ class ListenFormRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string>
*/
public function attributes(): array
{

View file

@ -10,26 +10,27 @@ use Illuminate\Support\Collection;
class CollectionHelper
{
/**
* Paginate a collection
* Paginate a collection.
*
* @param \Illuminate\Support\Collection $results
* @param integer $pageSize
* @return \Illuminate\Pagination\LengthAwarePaginator
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $results
* @param integer $pageSize
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
public static function paginate(Collection $results, int $pageSize): \Illuminate\Pagination\LengthAwarePaginator
{
$page = Paginator::resolveCurrentPage('page');
return self::paginateManually($results, $pageSize, $page);
}
/**
* Paginate a collection
* Paginate a collection.
*
* @param \Illuminate\Support\Collection $results
* @param integer $pageSize
* @param integer $page
* @return \Illuminate\Pagination\LengthAwarePaginator
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $results
* @param integer $pageSize
* @param integer $page
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
public static function paginateManually(
Collection $results,
@ -39,7 +40,7 @@ class CollectionHelper
$total = $results->count();
return self::paginator($results->forPage($page, $pageSize), $total, $pageSize, $page, [
'path' => Paginator::resolveCurrentPath(),
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
@ -47,12 +48,13 @@ class CollectionHelper
/**
* Create a new length-aware paginator instance.
*
* @param \Illuminate\Support\Collection $items
* @param integer $total
* @param integer $perPage
* @param integer $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $items
* @param integer $total
* @param integer $perPage
* @param integer $currentPage
* @param array<mixed> $options
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
protected static function paginator(
Collection $items,
@ -62,11 +64,11 @@ class CollectionHelper
array $options
): \Illuminate\Pagination\LengthAwarePaginator {
return Container::getInstance()->makeWith(LengthAwarePaginator::class, [
'items' => $items,
'total' => $total,
'perPage' => $perPage,
'items' => $items,
'total' => $total,
'perPage' => $perPage,
'currentPage' => $currentPage,
'options' => $options
'options' => $options
]);
}
}

View file

@ -5,7 +5,7 @@ namespace App\Lib\Helpers;
class ExceptionsHelper
{
/**
* Handle sentry event
* Handle sentry event.
*
* @param \Sentry\Event $event
* @return null|\Sentry\Event
@ -26,7 +26,7 @@ class ExceptionsHelper
}
/**
* Anonimize Sentry Exception bag
* Anonimize Sentry Exception bag.
*
* @param \Sentry\ExceptionDataBag $exceptionDataBag
* @return \Sentry\ExceptionDataBag
@ -42,7 +42,7 @@ class ExceptionsHelper
}
/**
* Anonymise sentry stacktrace
* Anonymise sentry stacktrace.
*
* @param \Sentry\Stacktrace $stackTrace
* @return \Sentry\Stacktrace
@ -70,7 +70,7 @@ class ExceptionsHelper
}
/**
* Get anonymized sentry params
* Get anonymized sentry params.
*
* @param mixed[] $params
* @return string[]
@ -80,7 +80,7 @@ class ExceptionsHelper
foreach ($params as &$param) {
$type = \strtolower(\gettype($param));
if (\is_string($param)) {
$type = \explode(' ', \trim(strtolower($param)))[0] ?? null;
$type = \explode(' ', \trim(strtolower($param)))[0];
}
switch (true) {
case $type === 'lambda':
@ -104,7 +104,7 @@ class ExceptionsHelper
}
/**
* Anonymize at least Sql queries
* Anonymize at least Sql queries.
*
* @param string $message
* @return string
@ -119,14 +119,14 @@ class ExceptionsHelper
}
/**
* Anonymize stack trace
* Anonymize stack trace.
*
* @param \Throwable $e
* @return string
*/
public static function getAnonymizedStackTrace(\Throwable $e): string
{
$projectPath = \realpath(\sprintf('%s/../', \app_path()));
$projectPath = \realpath(\sprintf('%s/../', \app_path())) ?: '';
$traceStack = $e->getTrace();
$traceStr = '';
$maxStackStage = 0;
@ -158,9 +158,9 @@ class ExceptionsHelper
}
/**
* Handle Args
* Handle Args.
*
* @param array $stack
* @param array<string, mixed> $stack
* @return string
*/
public static function handleArgs(array $stack): string

View file

@ -25,8 +25,6 @@ use Illuminate\Support\Str;
* The final path will be storage/modelfiles/posts/10/04/19/5f/black-cat-under-red-car-286071690833400.png
*
* ! No limits of file per folder will be handled.
*
* @author Munsch Jérémy <jeremy.munsch@ldc.fr>
*/
class FileStorageHelper
{
@ -40,7 +38,7 @@ class FileStorageHelper
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$disk = Storage::disk('uploads');
$path = ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
$path = ToolboxHelper::mbReplaceString('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
return $disk->path($path);
}
@ -57,7 +55,7 @@ class FileStorageHelper
if (\strpos($path, 'storage') !== 0) {
return;
}
$path = ToolboxHelper::mbReplace('storage/', '', $path);
$path = ToolboxHelper::mbReplaceString('storage/', '', $path);
if (Storage::disk('public')->exists($path)) {
Storage::disk('public')->delete($path);
}
@ -81,7 +79,7 @@ class FileStorageHelper
if (\strpos($originalPath, 'storage') !== 0) {
return;
}
$originalPath = ToolboxHelper::mbReplace('storage/', '', $originalPath);
$originalPath = ToolboxHelper::mbReplaceString('storage/', '', $originalPath);
if (Storage::disk('public')->exists($originalPath)) {
Storage::disk('public')->delete($originalPath);
}
@ -106,7 +104,7 @@ class FileStorageHelper
$file,
bool $slugify = false,
string|null $filename = null,
bool $private = false
bool $private = false,
): string {
// phpcs:enable
$tableName = $model->getTable();
@ -173,9 +171,9 @@ class FileStorageHelper
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$disk = Storage::disk('uploads');
$fileInfo = new \SplFileInfo($disk->path(
ToolboxHelper::mbReplace('/uploads/', '', \urldecode($path))
ToolboxHelper::mbReplaceString('/uploads/', '', \urldecode($path))
));
$htmlString = ToolboxHelper::mbReplace(
$htmlString = ToolboxHelper::mbReplaceString(
$path,
'/' . self::storeFile($model, $fileInfo, true),
$htmlString
@ -216,7 +214,7 @@ class FileStorageHelper
$filesToKeep = \collect(self::onlyUploadedFilesWithFileStorageHelper($newFiles));
$filesToRemove = $oldFiles->diff($filesToKeep);
$filesToRemove->each(function (string $publicStorageFilePath) {
$path = ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
$path = ToolboxHelper::mbReplaceString('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
if (Storage::disk('public')->exists($path)) {
Storage::disk('public')->delete($path);
}
@ -233,7 +231,7 @@ class FileStorageHelper
{
$filesToRemove = \collect(self::onlyUploadedFilesWithFileStorageHelper(self::findFilesInHtml($htmlString)));
$filesToRemove->each(function (string $publicStorageFilePath) {
$path = ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
$path = ToolboxHelper::mbReplaceString('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
if (Storage::disk('public')->exists($path)) {
Storage::disk('public')->delete($path);
}
@ -244,7 +242,7 @@ class FileStorageHelper
* Find all occurence of files in html
*
* @param string $html
* @return array
* @return array<mixed>
*/
public static function findFilesInHtml(string $html): array
{
@ -259,20 +257,20 @@ class FileStorageHelper
* Filter array to get only uploaded files that exists
* on disk 'public' (using helper storage strategy)
*
* @param array $urls
* @return array
* @param array<int, string> $urls
* @return array<mixed>
*/
public static function onlyUploadedFilesWithFileStorageHelper(array $urls): array
{
return \collect($urls)->unique()
// * Filter to get only /uploads and using app url or empty
->filter(function (string $url) {
$path = \parse_url($url, \PHP_URL_PATH);
$path = (string) \parse_url($url, \PHP_URL_PATH);
return \strpos(\ltrim($path, '/'), 'storage/modelfiles') === 0;
})->filter(function (string $url) {
$path = \parse_url($url, \PHP_URL_PATH);
$path = (string) \parse_url($url, \PHP_URL_PATH);
return Storage::disk('public')
->exists(ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($path), '/')));
->exists(ToolboxHelper::mbReplaceString('storage/', '', \ltrim(\urldecode($path), '/')));
})->all();
}
@ -280,22 +278,22 @@ class FileStorageHelper
* Filter array to get only uploaded files that exists
* on disk 'uploads'
*
* @param array $urls
* @return array
* @param array<int, string> $urls
* @return array<mixed>
*/
private static function onlyUploadedFilesWithFileManager(array $urls): array
{
return \collect($urls)->unique()
// * Filter to get only /uploads and using app url or empty
->filter(function (string $url) {
$host = \parse_url($url, \PHP_URL_HOST);
$path = \parse_url($url, \PHP_URL_PATH);
return ($host === \parse_url(config('app.url'), PHP_URL_HOST) or \is_null($host)) and
$host = (string) \parse_url($url, \PHP_URL_HOST);
$path = (string) \parse_url($url, \PHP_URL_PATH);
return ($host === (string) \parse_url(config('app.url'), PHP_URL_HOST) or $host === '') and
\strpos(\ltrim($path, '/'), 'uploads') === 0;
})->filter(function (string $url) {
$path = \parse_url($url, \PHP_URL_PATH);
$path = (string) \parse_url($url, \PHP_URL_PATH);
return Storage::disk('uploads')
->exists(ToolboxHelper::mbReplace('uploads/', '', \ltrim(\urldecode($path), '/')));
->exists(ToolboxHelper::mbReplaceString('uploads/', '', \ltrim(\urldecode($path), '/')));
})->all();
}
@ -459,7 +457,7 @@ class FileStorageHelper
'/\.{2,}/'
], '.', $filename);
// Lowercase for windows/unix interoperability http://support.microsoft.com/kb/100625 .
$filename = mb_strtolower($filename, mb_detect_encoding($filename));
$filename = mb_strtolower($filename, mb_detect_encoding($filename) ?: null);
// * ".file-name.-" becomes "file-name"
$filename = trim($filename, '.-');
return $filename;
@ -468,7 +466,7 @@ class FileStorageHelper
/**
* Remove all model files for the given Model.
*
* @param Model $model
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public static function removeModelFiles(Model $model): void

View file

@ -3,7 +3,7 @@
namespace App\Lib\Helpers;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
@ -24,8 +24,8 @@ 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.
* @param array<string>|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
@ -36,7 +36,7 @@ class ToolboxHelper
* @throws \LogicException
* @throws \RuntimeException If the command fails.
*/
public static function runConsoleCommand(array|string $command, bool $throw = true): string | false
public static function runConsoleCommand(array|string $command, bool $throw = true): string|false
{
// phpcs:enable
$process = \Illuminate\Support\Facades\Process::command($command)->run();
@ -54,7 +54,6 @@ class ToolboxHelper
/**
* @param array<int|string, mixed> $array1
* @param array<int|string, mixed> $array2
*
* @return array<int|string, mixed>
*/
public static function arrayMergeRecursiveDistinct(array &$array1, array &$array2): array
@ -67,7 +66,6 @@ class ToolboxHelper
$merged[$key] = $value;
}
}
return $merged;
}
@ -230,11 +228,12 @@ class ToolboxHelper
/**
* Mutltibyte string replace.
*
* @param array|string $search
* @param array|string $replace
* @param array|string $subject
* @param integer $count
* @return array|string|false
* @param array<string>|string $search
* @param array<string>|string $replace
* @param array<string>|string $subject
* @param integer $count
* @return array<string>|string|false
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
public static function mbReplace(
array|string $search,
@ -248,37 +247,58 @@ class ToolboxHelper
if (is_array($subject)) {
// Call mb_replace for each single string in $subject .
foreach ($subject as &$string) {
$string = &self::mbReplace($search, $replace, $string, $count);
$string = &self::mbReplace($search, $replace, $string, $count) ?: '';
}
return $subject;
} elseif (is_array($search)) {
if (!is_array($replace)) {
foreach ($search as &$string) {
$subject = self::mbReplace($string, $replace, $subject, $count);
$subject = self::mbReplace($string, $replace, $subject, $count) ?: '';
}
} else {
$n = max(count($search), count($replace));
while ($n--) {
$subject = self::mbReplace(current($search), current($replace), $subject, $count);
$currentSearch = current($search);
$currentReplace = current($replace);
if ($currentSearch === false || $currentReplace === false) {
break;
}
$result = self::mbReplace($currentSearch, $currentReplace, $subject, $count);
$subject = is_string($result) ? $result : '';
next($search);
next($replace);
}
}
} else {
$parts = mb_split(preg_quote($search), $subject);
$count = count($parts) - 1;
$subject = implode($replace, $parts);
$parts = mb_split(preg_quote($search), $subject) ?: [];
$count = (int) count($parts) - 1;
$subject = implode(is_array($replace) ? '' : $replace, $parts);
} //end if
return $subject;
}
/**
* Asserts that the field is unique.
* Multibyte string replace (string only version).
*
* @param string $table
* @param string $field
* @param string|integer|float|boolean|null|array $value
* @param integer|null $id
* @param callable|null $query
* @param string $search
* @param string $replace
* @param string $subject
* @return string
*/
public static function mbReplaceString(string $search, string $replace, string $subject): string
{
$parts = mb_split(preg_quote($search), $subject) ?: [];
return implode($replace, $parts);
}
/**
* Asserts that the field is unique
*
* @param string $table
* @param string $field
* @param string|integer|float|boolean|null|array<mixed> $value
* @param integer|null $id
* @param callable|null $query
* @return void
* @throws \Illuminate\Validation\ValidationException If the field is not unique.
*/
@ -291,20 +311,24 @@ class ToolboxHelper
): void {
if (!$query) {
Validator::make([$field => $value], [
/** @phpstan-ignore-next-line */
self::mbReplace('.', '\.', $field) => Rule::unique($table, $field)->ignore($id),
], [
self::mbReplace('.', '\.', "{$field}.unique")
=> trans('crud.libs.toolbox.assertFieldIsUnique', ['attribute' => $field, 'value' => $value])
/** @phpstan-ignore-next-line */
self::mbReplace('.', '\.', "{$field}.unique") => trans('crud.libs.toolbox.assertFieldIsUnique', [
'attribute' => $field,
'value' => is_array($value) ? implode(', ', array_map('strval', $value)) : (string) $value,
])
])->validate();
return;
}
Validator::make([$field => $value], [
$field => Rule::unique($table)->where($query)->ignore($id),
$field => Rule::unique($table)->where(\Closure::fromCallable($query))->ignore($id),
], [
$field . '.unique' => trans(
'crud.libs.toolbox.assertFieldIsUnique',
['attribute' => $field, 'value' => $value]
)
$field . '.unique' => trans('crud.libs.toolbox.assertFieldIsUnique', [
'attribute' => $field,
'value' => is_array($value) ? implode(', ', array_map('strval', $value)) : (string) $value,
])
])->validate();
}
@ -337,20 +361,20 @@ class ToolboxHelper
/**
* Dynamic model query.
*
* @param string $defaultLocale
* @param \Illuminate\Database\Eloquent\Builder $q
* @param string $column
* @param string $value
* @return \Illuminate\Database\Eloquent\Builder
* @param string $defaultLocale
* @param \Illuminate\Contracts\Database\Eloquent\Builder $q
* @param string $column
* @param string $value
* @return \Illuminate\Contracts\Database\Eloquent\Builder
*/
public static function queryColumnWithLocales(
string $defaultLocale,
Builder $q,
string $column,
string $value
): \Illuminate\Database\Eloquent\Builder {
): \Illuminate\Contracts\Database\Eloquent\Builder {
$currentLocale = app()->currentLocale();
$locales = collect(config('app.locales'))
$locales = collect((array) config('app.locales', []))
->mapWithKeys(fn (string $locale) => [$locale => $locale]);
if (!$locales->has($defaultLocale)) {
// * Remove default locale.
@ -378,15 +402,16 @@ class ToolboxHelper
/**
* Generates an array from a dot separated string.
*
* @param string $path
* @param mixed $value
* @param string $separator
* @return array
* @param string $path
* @param mixed $value
* @param string|null $separator
* @return array<mixed>
*/
public static function dotStringToNestedArray(string $path, mixed $value, string $separator = '.'): array
public static function dotStringToNestedArray(string $path, mixed $value, string|null $separator = null): array
{
$arr = $value;
$keys = array_reverse(explode($separator, $path));
$arr = $value;
$separator = $separator ?: '.';
$keys = array_reverse(explode($separator, $path));
foreach ($keys as $key) {
$arr = [$key => $arr];
@ -398,7 +423,7 @@ class ToolboxHelper
* Convert deeply an object to array.
*
* @param mixed $input
* @return array
* @return array<mixed>
* @throws \RuntimeException If $input var is a scalar value.
*/
public static function objectToArray(mixed $input): array
@ -407,7 +432,7 @@ class ToolboxHelper
if (!(is_object($input) or is_array($input))) {
throw new \RuntimeException('Cannot handle $input of type ' . \gettype($input));
}
$ret = (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)) ?
@ -429,25 +454,25 @@ class ToolboxHelper
if (!(is_object($input) or is_array($input))) {
throw new \RuntimeException('Cannot handle $input of type ' . \gettype($input));
}
$ret = (object)$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::arrayToObject($item) : $item;
}
return $ret;
return (object) $ret;
}
/**
* Validate picture.
*
* @param string $attribute
* @param string|null $value
* @param callable $fail
* @param object $sizes
* @param string $attribute
* @param string|null $value
* @param callable $fail
* @param array{minWidth: int, maxWidth: int, minHeight: int, maxHeight: int} $sizes
* @return void
*/
public static function validatePicture(string $attribute, string|null $value, callable $fail, object $sizes): void
public static function validatePicture(string $attribute, string|null $value, callable $fail, array $sizes): void
{
if (!($useStorage = Storage::exists($value)) and !File::exists($value)) {
$fail(trans(':attribute n\'existe pas dans le système de fichier', [
@ -474,22 +499,22 @@ class ToolboxHelper
$height = intval($dimensions[1]);
$xMessage = trans(
":attribute la largeur doit être comprise entre {$sizes->minWidth}px et {$sizes->maxWidth}px"
":attribute la largeur doit être comprise entre {$sizes['minWidth']}px et {$sizes['maxWidth']}px"
);
if ($sizes->minWidth === $sizes->maxWidth) {
$xMessage = trans(":attribute la largeur doit être de {$sizes->minWidth}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->minHeight}px et {$sizes->maxHeight}px"
":attribute la hauteur doit être comprise entre {$sizes['minHeight']}px et {$sizes['maxHeight']}px"
);
if ($sizes->minHeight === $sizes->maxHeight) {
$yMessage = trans(":attribute la hauteur doit être de {$sizes->minHeight}px");
if ($sizes['minHeight'] === $sizes['maxHeight']) {
$yMessage = trans(":attribute la hauteur doit être de {$sizes['minHeight']}px");
}
if (($width < $sizes->minWidth) or ($width > $sizes->maxWidth)) {
if (($width < $sizes['minWidth']) or ($width > $sizes['maxWidth'])) {
$fail($xMessage);
}
if (($height < $sizes->minHeight) or ($height > $sizes->maxHeight)) {
if (($height < $sizes['minHeight']) or ($height > $sizes['maxHeight'])) {
$fail($yMessage);
}
} //end if
@ -546,7 +571,7 @@ class ToolboxHelper
{
return Arr::where(
static::getClassesUsingNamespace($namespace),
fn (string $class_namespace) => \collect(class_implements($class_namespace, true))->filter()
fn (string $class_namespace) => \collect(class_implements($class_namespace, true) ?: [])->filter()
->contains(fn (string $class_interface) => $class_interface === $interface)
);
}
@ -554,9 +579,9 @@ class ToolboxHelper
/**
* Get validated pagination from request.
*
* @param integer $default
* @param string $field
* @param string $enumPath
* @param integer $default
* @param string $field
* @param class-string<\UnitEnum> $enumPath
* @return integer
*/
public static function getValidatedEnum(int $default, string $field, string $enumPath): int

View file

@ -46,10 +46,10 @@ class SendConfirmationMail extends Mailable
*/
private function sanitizeStringInputs(): void
{
$this->data = (object)Arr::map((array)$this->data, function ($el) {
$this->data = (object) Arr::map((array) $this->data, function ($el) {
if (is_string($el)) {
$el = \htmlspecialchars(\strip_tags(Blade::render(
(string)Markdown::parse($el)
(string) Markdown::parse($el)
)));
$el = Str::of($el)->replaceMatches(
'/[^\p{L}0-9\n\s\@\.\:\-\_\?\!\;\(\)\+\-\/\\\=]+/us',

View file

@ -49,10 +49,10 @@ class SendContactMail extends Mailable
*/
private function sanitizeStringInputs(): void
{
$this->data = (object)Arr::map((array)$this->data, function ($el) {
$this->data = (object) Arr::map((array) $this->data, function ($el) {
if (is_string($el)) {
$el = \htmlspecialchars(\strip_tags(Blade::render(
(string)Markdown::parse($el)
(string) Markdown::parse($el)
)));
$el = Str::of($el)->replaceMatches(
'/[^\p{L}0-9\n\s\@\.\:\-\_\?\!\;\(\)\+\-\/\\\=]+/us',

View file

@ -3,25 +3,20 @@
namespace App\Models;
use App\Enums\ActivityLogs\ActivityLogsEventEnum;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
/**
* @property string $model Target model.
* @property string $model_id Id of the target model.
* @property \App\Enums\ActivityLogs\ActivityLogsEventEnum $event Event of this activity (ActivityLogsEventEnum).
* @property array $data Changes.
* @property \Illuminate\Support\Carbon $created_at Created date.
* @property array<string, mixed> $data Changes.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
*
* @property-read \App\Models\User $user User BelongsTo relation.
*/
class ActivityLog extends Model
{
use HasFactory;
use Notifiable;
/**
* Indicates if the model should be timestamped.
*
@ -32,7 +27,7 @@ class ActivityLog extends Model
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'is_anonymous',
@ -81,7 +76,8 @@ class ActivityLog extends Model
$activity->model_id = $model->getKey();
$activity->event = $eventEnum;
$activity->data = static::getChangedColumns($activity, $model, $eventEnum);
$activity->created_at = now();
// @phpstan-ignore-next-line
$activity->created_at = now();
$activity->saveOrFail();
}
@ -91,17 +87,19 @@ class ActivityLog extends Model
* @param self $activity
* @param \Illuminate\Database\Eloquent\Model $model
* @param \App\Enums\ActivityLogs\ActivityLogsEventEnum $eventEnum
* @return array
* @return array<string, string>
*/
public static function getChangedColumns(self $activity, Model $model, ActivityLogsEventEnum $eventEnum): array
{
$modelClassName = $activity->model_class;
$modelTarget = new $modelClassName();
/** Get type of each fields of the target model */
/** @var \Illuminate\Database\Eloquent\Model|null $targetModel */
$targetModel = $activity->model_class::where(
(new $modelClassName())->getRouteKeyName(),
$targetModel = ($modelTarget instanceof \Illuminate\Database\Eloquent\Model) ? $activity->model_class::where(
$modelTarget->getRouteKeyName(),
$activity->model_id
)->first();
)->first() : null;
if (\is_null($targetModel)) {
return [];
@ -133,6 +131,7 @@ class ActivityLog extends Model
// phpcs:enable
$type = \gettype($value);
switch ($type) {
// phpcs:ignore PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
case 'string':
return match (true) {
Str::length(\strip_tags($value)) !== Str::length($value) => 'html',
@ -163,12 +162,12 @@ class ActivityLog extends Model
} //end switch
}
// * RELATIONS
// * RELATIONS.
/**
* User BelongsTo relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\User,$this>
*/
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{

View file

@ -5,20 +5,18 @@ namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\ActivityLog;
use App\Traits\Models\Orderable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class Aisle extends Model
{
use ActivityLog;
use HasFactory;
use Orderable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'name',
@ -67,7 +65,7 @@ class Aisle extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -120,12 +118,12 @@ class Aisle extends Model
return 'network_id';
}
// * RELATIONS
// * RELATIONS.
/**
* The network that belongs to the logo.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Network,$this>
*/
public function network(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
@ -135,7 +133,7 @@ class Aisle extends Model
/**
* Associated brands.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Brand,$this>
*/
public function brands(): \Illuminate\Database\Eloquent\Relations\HasMany
{

View file

@ -4,19 +4,17 @@ namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class Brand extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'name',
@ -62,7 +60,7 @@ class Brand extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -72,10 +70,10 @@ class Brand extends Model
*/
private static function manageFields(self $model): void
{
// * ASSERTIONS
// * ASSERTIONS.
self::assertLimitPublishedModels($model);
// * TRANSFORMATIONS
// * TRANSFORMATIONS.
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
@ -107,12 +105,12 @@ class Brand extends Model
}
}
// * RELATIONS
// * RELATIONS.
/**
* Associated aisle.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Aisle,$this>
*/
public function aisle(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{

View file

@ -6,28 +6,26 @@ use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use App\Traits\Models\Orderable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property-read int $id Id.
* @property string $title Title.
* @property array $media Medias of the carousel.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
* @property-read int $id Id.
* @property string $title Title.
* @property array $media Medias of the carousel.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
*
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/
class Carousel extends Model
{
use ActivityLog;
use HasFactory;
use Orderable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'section_id',
@ -43,7 +41,7 @@ class Carousel extends Model
* @var array<string, string>
*/
protected $casts = [
'media' => 'array',
'media' => 'array',
'published' => 'boolean',
];
@ -78,7 +76,7 @@ class Carousel extends Model
});
}
// * METHODS
// * METHODS.
/**
* Group ordering by section_id.
@ -90,13 +88,12 @@ class Carousel extends Model
return 'section_id';
}
// * RELATIONSHIPS
// * RELATIONSHIPS.
/**
* Get the sections that owns the Carousel
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Section,$this>
*/
public function section(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{

View file

@ -26,12 +26,13 @@ use Illuminate\Database\Eloquent\Model;
class HistoricalMilestone extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\HistoricalMilestoneFactory> */
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'title',
@ -78,7 +79,7 @@ class HistoricalMilestone extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.

View file

@ -18,12 +18,13 @@ use Illuminate\Database\Eloquent\Model;
class JobVideo extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\JobVideoFactory> */
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'title',

View file

@ -21,12 +21,13 @@ use Illuminate\Database\Eloquent\Model;
class Logo extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\LogoFactory> */
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'label',
@ -57,7 +58,7 @@ class Logo extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -70,12 +71,12 @@ class Logo extends Model
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
// * RELATIONS
// * RELATIONS.
/**
* The sites that belong to the logo.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Site,$this>
*/
public function sites(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{

View file

@ -5,7 +5,6 @@ namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@ -13,12 +12,11 @@ use Illuminate\Validation\ValidationException;
class Network extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'seo_title',
@ -69,7 +67,7 @@ class Network extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -79,12 +77,12 @@ class Network extends Model
*/
private static function manageFields(self $model): void
{
// * ASSERTIONS
// * ASSERTIONS.
self::assertLimitPublishedModels($model);
self::assertFieldIsUnique('name', $model->name, $model->id);
self::assertFieldIsUnique('slug', Str::slug($model->name), $model->id);
// * TRANSFORMATIONS
// * TRANSFORMATIONS.
self::setSlug($model, $model->name);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
@ -151,12 +149,12 @@ class Network extends Model
}
}
// * RELATIONS
// * RELATIONS.
/**
* The aisles that belong to the logo.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Aisle,$this>
*/
public function aisles(): \Illuminate\Database\Eloquent\Relations\HasMany
{

View file

@ -6,11 +6,9 @@ use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use App\Traits\Models\PlanificatedStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;
use Uwil\SitemapGenerator\Lib\SitemapHelper;
/**
@ -41,13 +39,12 @@ use Uwil\SitemapGenerator\Lib\SitemapHelper;
class News extends Model implements Sitemapable
{
use ActivityLog;
use HasFactory;
use PlanificatedStatus;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'seo_title',
@ -105,7 +102,7 @@ class News extends Model implements Sitemapable
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -172,11 +169,11 @@ class News extends Model implements Sitemapable
}
/**
* toSitemapTag method
* To sitemap tag method.
*
* @return Url|string|array
* @return \Spatie\Sitemap\Tags\Url|string|array<int|string, mixed>
*/
public function toSitemapTag(): Url | string | array
public function toSitemapTag(): \Spatie\Sitemap\Tags\Url | string | array
{
$model = $this;
$route = 'fo.news.show';

View file

@ -29,13 +29,14 @@ use App\Enums\StaticPageType;
class Section extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\SectionFactory> */
use HasFactory;
use MiniCrudModel;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'section',
@ -88,20 +89,19 @@ class Section extends Model
}
// * METHODS.
// * EMPTY BLOCS.
/**
* Empty bloc for picture.
*
* @param array $data
* @param string $img
* @param string $imgAlt
* @param string $imgTitle
* @param integer $width
* @param integer $height
* @param boolean $required
* @param string $name
* @return array
* @param array<string, mixed> $data
* @param string $img
* @param string $imgAlt
* @param string $imgTitle
* @param integer $width
* @param integer $height
* @param boolean $required
* @param string $name
* @return array<string, mixed>
*/
public static function emptyPictureBloc(
array $data,
@ -129,11 +129,11 @@ class Section extends Model
/**
* Empty bloc for link.
*
* @param array $data
* @param string $url
* @param boolean $required
* @param string $name
* @return array
* @param array<string, mixed> $data
* @param string $url
* @param boolean $required
* @param string $name
* @return array<string, mixed>
*/
public static function emptyLinkBloc(
array $data,
@ -154,9 +154,9 @@ class Section extends Model
/**
* Empty bloc for boolean new tab link.
*
* @param array $data
* @param string $name
* @return array
* @param array<string, mixed> $data
* @param string $name
* @return array<string, mixed>
*/
public static function emptyLinkNewTabBloc(
array $data,
@ -173,12 +173,11 @@ class Section extends Model
/**
* Empty bloc for key numbers.
*
* @param array $data
* @param string $name
* @param integer $value
* @param boolean $required
*
* @return array
* @param array<string, mixed> $data
* @param string $name
* @param integer $value
* @param boolean $required
* @return array<string, mixed>
*/
public static function emptyKeyNumberBloc(
array $data,
@ -199,10 +198,10 @@ class Section extends Model
/**
* Empty bloc for the button boolean.
*
* @param array $data
* @param string $name
* @param boolean $value
* @return array
* @param array<string, mixed> $data
* @param string $name
* @param boolean $value
* @return array<string, mixed>
*/
public static function emptyButtonBooleanBloc(
array $data,
@ -220,10 +219,10 @@ class Section extends Model
/**
* Empty bloc for a boolean.
*
* @param array $data
* @param string $name
* @param boolean $value
* @return array
* @param array<string, mixed> $data
* @param string $name
* @param boolean $value
* @return array<string, mixed>
*/
public static function emptyBooleanBloc(
array $data,
@ -241,11 +240,11 @@ class Section extends Model
/**
* Empty bloc for the h3 title.
*
* @param array $data
* @param string $name
* @param string $value
* @param boolean $required
* @return array
* @param array<string, mixed> $data
* @param string $name
* @param string $value
* @param boolean $required
* @return array<string, mixed>
*/
public static function emptyStringBloc(
array $data,
@ -266,12 +265,12 @@ class Section extends Model
/**
* Empty bloc for the WYSIWYG content.
*
* @param array $data
* @param array<string, mixed> $data
* @param string $name
* @param string $value
* @param \App\Enums\CkEditorConfigName $config
* @param boolean $required
* @return array
* @return array<string, mixed>
*/
public static function emptyWysiwygBloc(
array $data,
@ -292,7 +291,7 @@ class Section extends Model
}
/**
* Add part piece
* Add part piece.
*
* @return void
*/
@ -305,15 +304,22 @@ class Section extends Model
$this->countPartPieces() + 1
);
$linesToSkip = 1;
$data = collect($this->data);
/** @var array<string, mixed> $rawData */
$rawData = $this->data;
$data = collect($rawData);
$linesToSkip = 1;
$groupedPieces = $data->skip($linesToSkip)->splitIn($data->count() / ($pieceTemplateLinesCount ?: 1))
->concat([$pieceToAdd])
->sort(function ($aCollect, $bCollect) {
if ($this->section->equals(PageSectionEnum::produce_rhd)) {
/** @var array<string, mixed> $aFirst */
$aFirst = collect($aCollect)->first();
/** @var array<string, mixed> $bFirst */
$bFirst = collect($bCollect)->first();
return strcmp(
strrev(collect(collect($aCollect)->first())->first()),
strrev(collect(collect($bCollect)->first())->first())
strrev((string) collect($aFirst)->first()),
strrev((string) collect($bFirst)->first())
);
}
return 0;
@ -323,7 +329,7 @@ class Section extends Model
}
/**
* Remove part piece
* Remove part piece.
*
* @param integer $index
* @return integer Elements count removed.
@ -346,7 +352,7 @@ class Section extends Model
}
/**
* Count part pieces
* Count part pieces.
*
* @return integer
*/
@ -367,9 +373,9 @@ class Section extends Model
}
/**
* Get part pieces
* Get part pieces.
*
* @return array
* @return array<string, mixed>
*/
private function getPartPieces(): array
{
@ -378,28 +384,31 @@ class Section extends Model
}
/**
* Addable part piece block
* Addable part piece block.
*
* @param \App\Enums\Sections\PageSectionEnum $sectionEnum
* @param integer $index
* @return array
* @return array<string, mixed>|null
*/
public static function getAddablePartPieceBlock(PageSectionEnum $sectionEnum, int $index = 1): array|null
{
$data = null;
$pieceTemplate = self::getAddablePartPieceBlockTemplate($sectionEnum);
if (!is_null($pieceTemplate)) {
$data = json_decode(Str::of(json_encode($pieceTemplate))->replace('__index', strval($index)), true);
/** @var array $data */
$encoded = json_encode($pieceTemplate);
if ($encoded !== false) {
/** @var array<string, mixed> $data */
$data = json_decode(Str::of($encoded)->replace('__index', strval($index)), true);
}
}
return $data;
}
/**
* Addable part piece block
* Addable part piece block.
*
* @param \App\Enums\Sections\PageSectionEnum $sectionEnum
* @return array
* @return array<int, string>|null
*/
public static function getAddablePartPieceBlockIndexes(PageSectionEnum $sectionEnum): array|null
{
@ -411,8 +420,10 @@ class Section extends Model
}
/**
* Addable part piece block template.
*
* @param \App\Enums\Sections\PageSectionEnum $sectionEnum
* @return array|null
* @return array<string, mixed>|null
*/
private static function getAddablePartPieceBlockTemplate(PageSectionEnum $sectionEnum): array|null
{
@ -449,7 +460,7 @@ class Section extends Model
* Returns the list of sections for a page type.
*
* @param \App\Enums\StaticPageType $type
* @return \Illuminate\Database\Eloquent\Collection
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function getSections(StaticPageType $type): \Illuminate\Database\Eloquent\Collection
{
@ -460,7 +471,7 @@ class Section extends Model
}
/**
* Get the active section for a type page
* Get the active section for a type page.
*
* @param \App\Enums\StaticPageType $type
* @return boolean
@ -475,12 +486,12 @@ class Section extends Model
);
}
// * RELATIONS
// * RELATIONS.
/**
* Get the page that owns the section.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\StaticPage,$this>
*/
public function page(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
@ -490,7 +501,7 @@ class Section extends Model
/**
* Get the sections that own the carousel.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Carousel,$this>
*/
public function carousels(): \Illuminate\Database\Eloquent\Relations\HasMany
{

View file

@ -9,7 +9,6 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;
use Uwil\SitemapGenerator\Lib\SitemapHelper;
/**
@ -56,12 +55,13 @@ use Uwil\SitemapGenerator\Lib\SitemapHelper;
class Site extends Model implements Sitemapable
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\SiteFactory> */
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'seo_title',
@ -142,7 +142,7 @@ class Site extends Model implements Sitemapable
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -202,28 +202,28 @@ class Site extends Model implements Sitemapable
ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id);
}
// * RELATIONS
/**
* The logos that belong to the site.
* To sitemap tag method.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @return \Spatie\Sitemap\Tags\Url|string|array<int|string, mixed>
*/
public function logos(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Logo::class);
}
/**
* toSitemapTag method
*
* @return Url|string|array
*/
public function toSitemapTag(): Url | string | array
public function toSitemapTag(): \Spatie\Sitemap\Tags\Url | string | array
{
$model = $this;
$route = 'fo.sites.show';
$params = ['site' => $model];
return SitemapHelper::generateUrl($route, $params, $model);
}
// * RELATIONS.
/**
* The logos that belong to the site.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\Logo,$this>
*/
public function logos(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Logo::class);
}
}

View file

@ -29,6 +29,7 @@ use Illuminate\Validation\ValidationException;
class Slide extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\SlideFactory> */
use HasFactory;
/** @var integer Minimum number of published slides */
@ -40,7 +41,7 @@ class Slide extends Model
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'type',
@ -106,7 +107,7 @@ class Slide extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.

View file

@ -6,7 +6,6 @@ use App\Enums\StaticPageType;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
@ -29,12 +28,11 @@ use Illuminate\Support\Str;
class StaticPage extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'seo_title',
@ -73,7 +71,7 @@ class StaticPage extends Model
});
}
// * ROUTABLE
// * METHODS.
/**
* Get the value of the model's route key.
@ -99,8 +97,6 @@ class StaticPage extends Model
return 'type';
}
// * METHODS
/**
* Manage model fields.
*
@ -162,12 +158,12 @@ class StaticPage extends Model
return $query;
}
// * RELATIONS
// * RELATIONS.
/**
*
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Section,$this>
*/
public function sections(): \Illuminate\Database\Eloquent\Relations\HasMany
{

View file

@ -6,7 +6,6 @@ use App\Enums\StaticPageType;
use App\Enums\Users\RoleEnum;
use App\Traits\Models\ActivityLog;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
@ -22,12 +21,11 @@ use Illuminate\Database\Eloquent\Model;
class Sticky extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'type',

View file

@ -26,13 +26,14 @@ use Illuminate\Database\Eloquent\Model;
class Strip extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\StripFactory> */
use HasFactory;
use PlanificatedStatus;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'picto',
@ -79,7 +80,7 @@ class Strip extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.
@ -95,12 +96,12 @@ class Strip extends Model
}
}
// * RELATIONS
// * RELATIONS.
/**
* Get the news that owns the strip.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\News,$this>
*/
public function news(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{

View file

@ -24,12 +24,13 @@ use Illuminate\Database\Eloquent\Model;
class Testimonial extends Model
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\TestimonialFactory> */
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'name',
@ -71,7 +72,7 @@ class Testimonial extends Model
});
}
// * METHODS
// * METHODS.
/**
* Manage model fields.

View file

@ -24,13 +24,14 @@ use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use ActivityLog;
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
* @var list<string>
*/
protected $fillable = [
'first_name',
@ -45,7 +46,7 @@ class User extends Authenticatable
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
* @var list<string>
*/
protected $hidden = [
'remember_token',
@ -57,10 +58,10 @@ class User extends Authenticatable
* @var array<string, string>
*/
protected $casts = [
'role' => RoleEnum::class,
'last_connection' => 'date',
'published' => 'boolean',
'published_at' => 'datetime',
'role' => RoleEnum::class,
'last_connection' => 'date',
'published' => 'boolean',
'published_at' => 'datetime',
];
/**

View file

@ -3,6 +3,7 @@
namespace App\Traits\Controllers;
use App\Http\Requests\Bo\UpdateChangeOrderRequest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
@ -29,11 +30,11 @@ trait ChangesModelOrder
throw new \RuntimeException("The {$className} class doesn't exist.");
}
if (!\is_object($model)) {
if (!($model instanceof Model)) {
throw new \RuntimeException("The second last param isn't an object.");
}
if (get_class($model) !== (string)Str::of($className)->replaceStart('\\', '')) {
if (get_class($model) !== (string) Str::of($className)->replaceStart('\\', '')) {
throw new \RuntimeException("The {$className} doesn't match second last binded param.");
}

View file

@ -4,9 +4,12 @@ namespace App\Traits\Enums;
use Illuminate\Support\Str;
/**
* Provides rich functionality to PHP backed enums.
*/
trait BaseEnum
{
// * GENERIC METHODS
// * GENERIC METHODS.
/**
* Get enum value.
@ -38,12 +41,14 @@ trait BaseEnum
return $this->name;
}
// * STATIC FETCH METHODS
// * STATIC FETCH METHODS.
/**
* Get enum labels.
*
* @return array<string>
* @return array<string, string>
* @throws \Error If missing definition label.
* @phpstan-ignore missingType.iterableValue
*/
public static function toLabels(): array
{
@ -65,7 +70,8 @@ trait BaseEnum
/**
* Get enum values.
*
* @return array<integer|string>
* @return array<string, integer|string>
* @phpstan-ignore missingType.iterableValue
*/
public static function toValues(): array
{
@ -79,7 +85,8 @@ trait BaseEnum
/**
* Get enums.
*
* @return array
* @return list<static>
* @phpstan-ignore missingType.iterableValue
*/
public static function all(): array
{
@ -89,7 +96,8 @@ trait BaseEnum
/**
* Get enums.
*
* @return array<self>
* @return array<string, object>
* @phpstan-ignore missingType.iterableValue
*/
public static function toArray(): array
{
@ -98,7 +106,7 @@ trait BaseEnum
self::setCache('enums', \collect(self::cases())
->mapWithKeys(function ($enum) use ($definitions) {
$baseArray = [
'name' => $enum->name,
'name' => $enum->name,
'label' => $enum->label(),
'value' => $enum->value,
];
@ -109,7 +117,7 @@ trait BaseEnum
}
$baseArray[$index] = $elements[$enum->name];
}
return [$enum->name => (object)$baseArray];
return [$enum->name => (object) $baseArray];
})->all());
}
return self::getCache('enums');
@ -120,21 +128,30 @@ trait BaseEnum
*
* @param self|integer|string $value
* @param string $field
* @return self|null
* @return static|null
*/
public static function make(self|int|string $value, string $field = 'value'): self|null
{
if ($field === "label") {
$enumLabels = array_change_key_case(array_flip(self::toLabels()), CASE_LOWER);
$value = (isset($enumLabels[strtolower($value)])) ? $enumLabels[strtolower($value)] : false;
$field = 'name';
$enumLabels = array_change_key_case(
array_flip(array_map(fn($value): string => Str::slug($value), self::toLabels())),
CASE_LOWER
);
$searchValue = $value instanceof self ? (string) $value->value : (string) $value;
$slugged = Str::slug($searchValue);
$value = $enumLabels[$slugged] ?? false;
if ($value === false) {
return null;
}
$field = 'name';
}
return !\is_object($value) ?
\collect(self::cases())->keyBy($field)->get($value) : $value;
/** @phpstan-ignore-next-line */
return !\is_object($value) ? \collect(self::cases())->keyBy($field)->get($value) : $value;
}
/**
* Test if 2 enum are equals.
* Test if 2 enums are equals.
*
* @param object ...$others
* @return boolean
@ -144,12 +161,11 @@ trait BaseEnum
{
foreach ($others as $other) {
if (!\in_array(BaseEnum::class, \class_uses_recursive($other))) {
throw new \Error(__METHOD__ .
' requires $enum to use ' . BaseEnum::class);
throw new \Error(__METHOD__ . ' requires $enum to use ' . BaseEnum::class);
}
if (
get_class($this) === get_class($other)
&& $this->value === $other->value
&& $this->value === $other->value // @phpstan-ignore-line
) {
return true;
}
@ -167,14 +183,14 @@ trait BaseEnum
return $this->value;
}
// * CACHE
// * CACHE.
/**
* Get cache array.
*
* @param string $index
* @return array
* @return array<mixed>
* @phpstan-ignore missingType.iterableValue
*/
private static function getCache(string $index): array
{
@ -188,9 +204,10 @@ trait BaseEnum
/**
* Set cache array.
*
* @param string $index
* @param array $items
* @param string $index
* @param array<mixed> $items
* @return void
* @phpstan-ignore missingType.iterableValue
*/
private static function setCache(string $index, array $items): void
{
@ -220,12 +237,13 @@ trait BaseEnum
}
}
// * PRIVATE
// * PRIVATE.
/**
* Fetch the LABELS constant if exists.
*
* @return array|null
* @return array<string, string>|null
* @phpstan-ignore missingType.iterableValue
*/
private static function getLabelsConstant(): array|null
{
@ -241,21 +259,23 @@ trait BaseEnum
/**
* Get custom constants.
*
* @return array
* @return array<string, array<mixed>>
* @phpstan-ignore missingType.iterableValue
*/
private static function getCustomDefinitions(): array
{
// ? Has custom props in cache ?
if (!isset($GLOBALS[self::class]) or \is_null($GLOBALS[self::class]['customProps'])) {
$names = \collect(self::cases())->keyBy('name');
$GLOBALS[self::class]['customProps'] = \collect((new \ReflectionClass(self::class))->getConstants())
->filter(function (mixed $constant, string $key) use ($names) {
->filter(function (mixed $constant, string $key) use ($names): bool {
if ($key === 'LABELS' or !\is_array($constant)) {
return false;
}
return \collect($constant)->keys()
->filter(fn (string $name) => $names->has($name))->count();
$count = \collect($constant)->keys()
->filter(fn (string $name) => $names->has($name))
->count();
return $count > 0;
})->all();
}
return $GLOBALS[self::class]['customProps'];

View file

@ -2,8 +2,8 @@
namespace App\Traits\Models;
use App\Models\ActivityLog as ModelsActivityLog;
use App\Observers\ModelObserver;
use App\Models\ActivityLog as ActivityLogModel;
/**
* If there is a static function in a trait (named boot[TraitName]),
@ -27,10 +27,10 @@ trait ActivityLog
/**
* Activities logs One-to-many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\ActivityLog, covariant static>
*/
public function activityLogs(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(ModelsActivityLog::class);
return $this->hasMany(ActivityLogModel::class, 'model_id');
}
}

View file

@ -11,7 +11,7 @@ trait MiniCrudModel
/**
* Fill the model with an array of attributes.
*
* @param array $attributes
* @param array<string, mixed> $attributes
* @return $this
*
* @throws \Illuminate\Database\Eloquent\MassAssignmentException If fill prop is not allowed.
@ -34,7 +34,7 @@ trait MiniCrudModel
*/
public function minicrudCreating(): void
{
/** @var array<string,array> */
/** @var array<int, array<string, mixed>> */
$data = $this->data;
foreach ($data as &$input) {
switch ($input['inputType']) {
@ -64,8 +64,9 @@ trait MiniCrudModel
*/
public function minicrudUpdated(): void
{
/** @var array $input */
foreach ($this->data as $index => $input) {
/** @var array<int, array<string, mixed>> $data */
$data = $this->data;
foreach ($data as $index => $input) {
switch ($input['inputType']) {
case InputType::text->value:
$original = ToolboxHelper::getOriginal($this, 'data');
@ -92,8 +93,9 @@ trait MiniCrudModel
*/
public function minicrudDeleted(): void
{
/** @var array $input */
foreach ($this->data as $index => $input) {
/** @var array<int, array<string, mixed>> $data */
$data = $this->data;
foreach ($data as $index => $input) {
switch ($input['inputType']) {
case InputType::text->value:
FileStorageHelper::removeModelFilesOfHtml($input['value']);
@ -112,7 +114,7 @@ trait MiniCrudModel
/**
* Set a specific prop.
*
* @param array $data
* @param array<string, mixed> $data
* @return void
*/
private function setData(array $data): void
@ -127,7 +129,7 @@ trait MiniCrudModel
/**
* Set a specific prop.
*
* @param array $value
* @param array<int|string, mixed> $value
* @return void
*/
protected function setDataAttribute(array $value): void
@ -142,7 +144,7 @@ trait MiniCrudModel
* Set a specific prop.
*
* @param string|null $data
* @return array
* @return array<int|string, mixed>
*/
protected function getDataAttribute(string|null $data): array
{
@ -152,8 +154,8 @@ trait MiniCrudModel
/**
* Serialize properties.
*
* @param array $data
* @return array
* @param array<int|string, array<string, mixed>> $data
* @return array<int|string, array<string, mixed>>
* @throws \ErrorException If input type is no handled.
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber

View file

@ -49,7 +49,7 @@ trait HasPicture
* @param integer|null $size
* @param string|null $requiredWith
* @param string|null $requiredWithout
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function pictureRules(
string $name = 'picture',
@ -62,10 +62,10 @@ trait HasPicture
?string $requiredWith = null,
?string $requiredWithout = null,
): array {
$dimensions = (object)[
'minWidth' => $minWidth ?? $this->minWidth,
$dimensions = [
'minWidth' => $minWidth ?? $this->minWidth,
'minHeight' => $minHeight ?? $this->minHeight,
'maxWidth' => $maxWidth ?? $this->maxWidth,
'maxWidth' => $maxWidth ?? $this->maxWidth,
'maxHeight' => $maxHeight ?? $this->maxHeight
];
return [
@ -92,7 +92,7 @@ trait HasPicture
* @param integer $limitMin
* @param integer $limitMax
* @param boolean $nullable
* @return array
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function picturesRules(
string $name = 'pictures',
@ -104,10 +104,10 @@ trait HasPicture
int $limitMax = 5,
bool $nullable = false
): array {
$sizes = (object)[
'minWidth' => $minWidth ?? $this->minWidth,
$sizes = [
'minWidth' => $minWidth ?? $this->minWidth,
'minHeight' => $minHeight ?? $this->minHeight,
'maxWidth' => $maxWidth ?? $this->maxWidth,
'maxWidth' => $maxWidth ?? $this->maxWidth,
'maxHeight' => $maxHeight ?? $this->maxHeight,
];
return [

View file

@ -41,7 +41,7 @@ return [
|
*/
'debug' => (bool)env('APP_DEBUG', false),
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------

View file

@ -51,11 +51,11 @@ return [
'missing_routes' => false,
],
// @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#send-default-pii.
// See: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#send-default-pii.
'send_default_pii' => env('SENTRY_SEND_DEFAULT_PII', false),
// @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate.
'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float)env('SENTRY_TRACES_SAMPLE_RATE'),
// See: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate.
'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float) env('SENTRY_TRACES_SAMPLE_RATE'),
'before_send' => [\App\Lib\Helpers\ExceptionsHelper::class, 'sentryEventHandler'],
];

View file

@ -21,26 +21,28 @@
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/>
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod"/>
<rule ref="Generic.Commenting.DocComment.SpacingBeforeTags"/>
<rule ref="Generic.Commenting.Todo"/>
<rule ref="Generic.Commenting.Fixme"/>
<rule ref="Generic.Commenting.Todo"/>
<rule ref="Generic.ControlStructures.InlineControlStructure"/>
<rule ref="Generic.Files.ByteOrderMark"/>
<rule ref="Generic.Files.LineEndings"/>
<rule ref="Generic.Files.LineLength"/>
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<rule ref="Generic.Formatting.MultipleStatementAlignment"/>
<rule ref="Generic.Formatting.SpaceAfterCast"/>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<rule ref="Generic.Metrics.CyclomaticComplexity"/>
<rule ref="Generic.Metrics.NestingLevel"/>
<rule ref="Generic.NamingConventions.CamelCapsFunctionName"/>
<rule ref="Generic.NamingConventions.ConstructorName"/>
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<rule ref="Generic.NamingConventions.CamelCapsFunctionName"/>
<rule ref="Generic.PHP.DeprecatedFunctions"/>
<rule ref="Generic.PHP.DisallowShortOpenTag"/>
<rule ref="Generic.PHP.ForbiddenFunctions"/>
<rule ref="Generic.PHP.NoSilencedErrors"/>
<rule ref="Generic.Strings.UnnecessaryStringConcat"/>
<rule ref="Generic.WhiteSpace.DisallowTabIndent"/>
<rule ref="Generic.WhiteSpace.LanguageConstructSpacing"/>
<rule ref="Generic.WhiteSpace.ScopeIndent"/>
<rule ref="PEAR.Classes.ClassDeclaration"/>
<rule ref="PEAR.Commenting.InlineComment"/>
@ -103,10 +105,14 @@
<rule ref="Squiz.Commenting.EmptyCatchComment"/>
<rule ref="Squiz.Commenting.FunctionComment">
<exclude name="Squiz.Commenting.FunctionComment.MissingParamComment" />
<exclude name="Squiz.Commenting.FunctionComment.IncorrectTypeHint" />
</rule>
<rule ref="Squiz.Commenting.FunctionCommentThrowTag"/>
<rule ref="Squiz.Commenting.InlineComment">
<exclude name="Squiz.Commenting.InlineComment.DocBlock" />
<exclude name="Squiz.Commenting.InlineComment.NotCapital" />
<exclude name="Squiz.Commenting.InlineComment.InvalidEndChar" />
<exclude name="Squiz.Commenting.InlineComment.NoSpaceBefore" />
</rule>
<rule ref="Squiz.Commenting.LongConditionClosingComment">
<exclude name="Squiz.Commenting.LongConditionClosingComment.SpacingBefore" />
@ -119,5 +125,4 @@
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*/database/migrations/*</exclude-pattern>
</rule>
</ruleset>

View file

@ -6,5 +6,4 @@ parameters:
paths:
- app/
# Level 9 is the highest level
level: 5
level: 7