From ae795880ed1bf3c4cc13a7353356316239dafbb1 Mon Sep 17 00:00:00 2001 From: idevakk <219866223+idevakk@users.noreply.github.com> Date: Fri, 14 Nov 2025 02:01:01 -0800 Subject: [PATCH] chore: code refactor via rector --- app/ColorPicker.php | 8 +- app/Filament/Pages/GenerateActivationKeys.php | 25 +- app/Filament/Pages/Settings.php | 33 +- app/Filament/Resources/BlogResource.php | 12 +- app/Filament/Resources/CategoryResource.php | 14 +- app/Filament/Resources/MenuResource.php | 8 +- app/Filament/Resources/PageResource.php | 12 +- app/Filament/Resources/PlanResource.php | 6 +- app/Filament/Resources/TicketResource.php | 67 ++-- app/Filament/Resources/UserResource.php | 44 ++- .../Resources/UserResource/Pages/EditUser.php | 2 +- .../RelationManagers/LogsRelationManager.php | 1 - .../UsageLogsRelationManager.php | 1 - app/Filament/Widgets/StatsOverview.php | 76 ++--- app/Http/Controllers/AppController.php | 84 ++--- app/Http/Controllers/WebhookController.php | 14 +- app/Http/Middleware/CheckPageSlug.php | 4 +- app/Http/Middleware/CheckUserBanned.php | 2 +- app/Http/Middleware/Locale.php | 4 +- app/Livewire/Actions/Logout.php | 4 +- app/Livewire/AddOn.php | 137 ++++----- app/Livewire/Auth/Register.php | 2 +- app/Livewire/Auth/ResetPassword.php | 2 +- app/Livewire/Blog.php | 6 +- app/Livewire/Dashboard/Bulk.php | 48 ++- app/Livewire/Dashboard/BulkGmail.php | 24 +- app/Livewire/Dashboard/Dashboard.php | 58 ++-- app/Livewire/Dashboard/Mailbox/Inbox.php | 147 ++++----- app/Livewire/Dashboard/Pricing.php | 20 +- app/Livewire/Dashboard/Support.php | 34 +-- app/Livewire/Frontend/Action.php | 76 +++-- app/Livewire/Frontend/Email.php | 16 +- app/Livewire/Frontend/Mailbox.php | 17 +- app/Livewire/Home.php | 7 +- app/Livewire/ListBlog.php | 4 +- app/Livewire/Page.php | 12 +- app/Mail/TicketResponseNotification.php | 8 +- app/Models/ActivationKey.php | 7 +- app/Models/Email.php | 99 +++--- app/Models/Log.php | 11 +- app/Models/Message.php | 75 +++-- app/Models/Meta.php | 12 +- app/Models/Premium.php | 129 ++++---- app/Models/PremiumEmail.php | 28 +- app/Models/RemoteEmail.php | 4 +- app/Models/Ticket.php | 9 +- app/Models/ZEmail.php | 97 +++--- app/NotifyMe.php | 4 +- app/Providers/AppServiceProvider.php | 20 +- app/Providers/Filament/DashPanelProvider.php | 1 - bootstrap/app.php | 7 +- composer.json | 1 + composer.lock | 38 ++- config/app.php | 4 +- config/auth.php | 4 +- config/debugbar.php | 2 +- config/disposable-email.php | 4 +- config/logging.php | 2 +- config/mail.php | 2 +- config/sanctum.php | 11 +- database/factories/ActivationKeyFactory.php | 3 +- database/factories/BlogFactory.php | 3 +- database/factories/CategoryFactory.php | 3 +- database/factories/EmailFactory.php | 3 +- database/factories/LogFactory.php | 3 +- database/factories/MenuFactory.php | 3 +- database/factories/MessageFactory.php | 3 +- database/factories/MetaFactory.php | 3 + database/factories/PageFactory.php | 3 +- database/factories/PlanFactory.php | 3 +- database/factories/PremiumEmailFactory.php | 3 +- database/factories/RemoteEmailFactory.php | 3 + database/factories/SettingFactory.php | 3 +- database/factories/TicketFactory.php | 3 +- database/factories/TicketResponseFactory.php | 3 +- database/factories/UsageLogFactory.php | 3 +- database/factories/UserFactory.php | 5 +- .../0001_01_01_000000_create_users_table.php | 6 +- .../0001_01_01_000001_create_cache_table.php | 4 +- .../0001_01_01_000002_create_jobs_table.php | 6 +- ..._04_22_204157_add_level_to_users_table.php | 4 +- ...025_04_22_210144_create_settings_table.php | 2 +- ...46_add_imap_settings_to_settings_table.php | 4 +- ...nfiguration_settings_to_settings_table.php | 4 +- ...834_add_ads_settings_to_settings_table.php | 4 +- .../2025_04_23_101602_create_metas_table.php | 2 +- .../2025_04_23_104947_create_logs_table.php | 2 +- ...025_04_23_120910_create_messages_table.php | 2 +- .../2025_04_25_195348_create_emails_table.php | 2 +- .../2025_04_27_120959_create_pages_table.php | 2 +- .../2025_04_27_123300_create_menus_table.php | 2 +- ...5_04_27_133659_create_categories_table.php | 2 +- .../2025_04_27_133802_create_blogs_table.php | 2 +- ...5_05_02_144314_create_customer_columns.php | 4 +- ...5_02_144315_create_subscriptions_table.php | 2 +- ...144316_create_subscription_items_table.php | 2 +- .../2025_05_02_215351_create_plans_table.php | 2 +- ...5_05_03_082522_create_usage_logs_table.php | 2 +- ...05_03_200503_add_user_id_to_logs_table.php | 4 +- ..._05_212255_create_premium_emails_table.php | 2 +- ...16_015550_create_activation_keys_table.php | 2 +- ...oppy_and_accept_columns_to_plans_table.php | 4 +- ...2025_05_16_072530_create_tickets_table.php | 2 +- ...6_072547_create_ticket_responses_table.php | 2 +- ...251_add_oxa_pay_details_to_plans_table.php | 4 +- ...26_create_personal_access_tokens_table.php | 2 +- database/seeders/AdminSeeder.php | 2 +- database/seeders/DatabaseSeeder.php | 1 - database/seeders/MetaSeeder.php | 7 +- database/seeders/UpdatePlansTableSeeder.php | 4 +- rector.php | 52 ++++ routes/api.php | 4 +- routes/auth.php | 7 +- routes/console.php | 17 +- routes/web.php | 23 +- tests/Concerns/LoadsApplicationData.php | 22 +- tests/Feature/ApplicationTest.php | 5 +- .../Feature/Controllers/AppControllerTest.php | 31 +- .../Controllers/WebhookControllerTest.php | 43 ++- tests/Feature/ExampleTest.php | 2 +- tests/Feature/Filament/ResourcesTest.php | 289 ++++++++++-------- tests/Feature/Filament/UserResourceTest.php | 78 ++--- tests/Feature/Livewire/Auth/LoginTest.php | 24 +- tests/Feature/Livewire/Auth/RegisterTest.php | 30 +- tests/Feature/Livewire/DashboardTest.php | 14 +- tests/Feature/Livewire/FrontendTest.php | 37 ++- tests/Pest.php | 13 +- tests/Unit/ColorPickerTest.php | 35 +-- tests/Unit/ExampleTest.php | 2 +- tests/Unit/Models/ActivationKeyTest.php | 21 +- tests/Unit/Models/BlogTest.php | 54 ++-- tests/Unit/Models/CategoryTest.php | 29 +- tests/Unit/Models/EmailTest.php | 21 +- tests/Unit/Models/LogTest.php | 15 +- tests/Unit/Models/MenuTest.php | 14 +- tests/Unit/Models/MessageTest.php | 20 +- tests/Unit/Models/MetaTest.php | 14 +- tests/Unit/Models/PageTest.php | 18 +- tests/Unit/Models/PlanTest.php | 26 +- tests/Unit/Models/PremiumEmailTest.php | 21 +- tests/Unit/Models/RemoteEmailTest.php | 10 +- tests/Unit/Models/SettingTest.php | 14 +- tests/Unit/Models/TicketResponseTest.php | 38 +-- tests/Unit/Models/TicketTest.php | 21 +- tests/Unit/Models/UsageLogTest.php | 11 +- tests/Unit/Models/UserTest.php | 70 +++-- tests/Unit/Models/ZEmailTest.php | 60 ++-- tests/Unit/NotifyMeTest.php | 40 ++- 148 files changed, 1520 insertions(+), 1486 deletions(-) create mode 100644 rector.php diff --git a/app/ColorPicker.php b/app/ColorPicker.php index c80c1de..1092879 100644 --- a/app/ColorPicker.php +++ b/app/ColorPicker.php @@ -35,13 +35,9 @@ trait ColorPicker 'Z' => ['dark' => 'dark:bg-teal-500', 'light' => 'bg-teal-800'], ]; - $letter = strtoupper($letter); + $letter = strtoupper((string) $letter); - if (isset($colorReferences[$letter])) { - return $colorReferences[$letter]; - } - - return ['dark' => 'dark:bg-gray-500', 'light' => 'bg-gray-800']; + return $colorReferences[$letter] ?? ['dark' => 'dark:bg-gray-500', 'light' => 'bg-gray-800']; } } diff --git a/app/Filament/Pages/GenerateActivationKeys.php b/app/Filament/Pages/GenerateActivationKeys.php index 7af2327..3bdd1e8 100644 --- a/app/Filament/Pages/GenerateActivationKeys.php +++ b/app/Filament/Pages/GenerateActivationKeys.php @@ -2,6 +2,10 @@ namespace App\Filament\Pages; +use BackedEnum; +use UnitEnum; +use Illuminate\Support\Str; +use Symfony\Component\HttpFoundation\BinaryFileResponse; use App\Models\ActivationKey; use App\Models\Plan; use Filament\Actions\BulkAction; @@ -19,17 +23,16 @@ use Filament\Tables\Filters\SelectFilter; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Response; -use Str; class GenerateActivationKeys extends Page implements HasForms, HasTable { use InteractsWithForms, InteractsWithTable; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-key'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-key'; protected string $view = 'filament.pages.generate-activation-keys'; - protected static string|\UnitEnum|null $navigationGroup = 'Admin'; + protected static string|UnitEnum|null $navigationGroup = 'Admin'; protected static ?string $title = 'Activation Keys'; @@ -59,13 +62,13 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable ]; } - public function generate() + public function generate(): void { $data = $this->form->getState(); - $plan = Plan::findOrFail($data['plan_id']); + $plan = Plan::query()->findOrFail($data['plan_id']); for ($i = 0; $i < $data['quantity']; $i++) { - ActivationKey::create([ + ActivationKey::query()->create([ 'price_id' => $plan->pricing_id, 'activation_key' => strtoupper('Z'.Str::random(16)), 'is_activated' => false, @@ -99,8 +102,8 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable TextColumn::make('billing_interval') ->label('Interval') - ->getStateUsing(function ($record) { - $isMonthly = Plan::where('pricing_id', $record->price_id)->value('monthly_billing'); + ->getStateUsing(function ($record): string { + $isMonthly = Plan::query()->where('pricing_id', $record->price_id)->value('monthly_billing'); return $isMonthly ? 'Monthly' : 'Yearly'; }), @@ -121,7 +124,7 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable SelectFilter::make('price_id') ->label('Plan') ->options( - Plan::pluck('name', 'pricing_id') + Plan::query()->pluck('name', 'pricing_id') ), ]; } @@ -130,13 +133,13 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable { return [ BulkAction::make('Download Keys') - ->action(fn (Collection $records) => $this->downloadKeys($records)) + ->action(fn (Collection $records): BinaryFileResponse => $this->downloadKeys($records)) ->deselectRecordsAfterCompletion() ->requiresConfirmation(), ]; } - public function downloadKeys(Collection $records) + public function downloadKeys(Collection $records): BinaryFileResponse { $text = $records->pluck('activation_key')->implode("\n"); diff --git a/app/Filament/Pages/Settings.php b/app/Filament/Pages/Settings.php index 95a8a74..b51095d 100644 --- a/app/Filament/Pages/Settings.php +++ b/app/Filament/Pages/Settings.php @@ -2,9 +2,11 @@ namespace App\Filament\Pages; +use BackedEnum; +use UnitEnum; +use Illuminate\Support\Facades\Artisan; use App\Models\Setting; use App\Models\ZEmail; -use Artisan; use Exception; use Filament\Forms\Components\Checkbox; use Filament\Forms\Components\KeyValue; @@ -25,17 +27,17 @@ class Settings extends Page implements HasForms public ?array $data = []; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth'; protected string $view = 'filament.pages.settings'; - protected static string|\UnitEnum|null $navigationGroup = 'Web Master'; + protected static string|UnitEnum|null $navigationGroup = 'Web Master'; public function mount(): void { $user = auth()->user(); $auth_email = $user->email; - $setting = Setting::where('app_admin', $auth_email)->first(); + $setting = Setting::query()->where('app_admin', $auth_email)->first(); if ($setting) { $imapSettings = $setting->imap_settings ?? []; @@ -50,7 +52,7 @@ class Settings extends Page implements HasForms ]); $this->applyDefaults($configurationSettings, [ - 'cron_password' => fn () => $this->generateRandomString(20), + 'cron_password' => fn (): string => $this->generateRandomString(20), 'date_format' => 'd M Y h:i A', 'after_last_email_delete' => 'redirect_to_homepage', ]); @@ -68,9 +70,7 @@ class Settings extends Page implements HasForms foreach ($transformMap as $key => $subKey) { if (isset($configurationSettings[$key])) { - $configurationSettings[$key] = array_map(function ($value) use ($subKey) { - return [$subKey => $value]; - }, $configurationSettings[$key]); + $configurationSettings[$key] = array_map(fn($value): array => [$subKey => $value], $configurationSettings[$key]); } } $this->form->fill([ @@ -376,12 +376,11 @@ class Settings extends Page implements HasForms $data = $this->form->getState(); if (! $this->testIMAP($data['imap_settings'])) { return; - } else { - Notification::make() - ->title('IMAP Connection Successful') - ->success() - ->send(); } + Notification::make() + ->title('IMAP Connection Successful') + ->success() + ->send(); foreach ([ 'protocol' => 'imap', 'default_account' => 'default', @@ -410,7 +409,7 @@ class Settings extends Page implements HasForms } } - $setting = Setting::where('id', 1)->first(); + $setting = Setting::query()->where('id', 1)->first(); $user = auth()->user(); $auth_email = $user->email; @@ -447,7 +446,7 @@ class Settings extends Page implements HasForms 'configuration_settings' => $data['configuration_settings'], 'ads_settings' => $data['ads_settings'], ]; - $create_res = Setting::create(array_merge($data)); + $create_res = Setting::query()->create(array_merge($data)); if ($create_res) { Notification::make() @@ -464,13 +463,13 @@ class Settings extends Page implements HasForms } } - private function generateRandomString($length = 10): string + private function generateRandomString(int $length = 10): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; + $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; diff --git a/app/Filament/Resources/BlogResource.php b/app/Filament/Resources/BlogResource.php index 9dc5111..5f64830 100644 --- a/app/Filament/Resources/BlogResource.php +++ b/app/Filament/Resources/BlogResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\BlogResource\Pages\CreateBlog; use App\Filament\Resources\BlogResource\Pages\EditBlog; use App\Filament\Resources\BlogResource\Pages\ListBlogs; @@ -33,13 +35,13 @@ class BlogResource extends Resource { protected static ?string $model = Blog::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-m-newspaper'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-m-newspaper'; - protected static string|\UnitEnum|null $navigationGroup = 'Content'; + protected static string|UnitEnum|null $navigationGroup = 'Content'; public static function form(Schema $schema): Schema { - $categories = Category::pluck('name', 'id')->toArray(); + Category::query()->pluck('name', 'id')->toArray(); return $schema ->components([ @@ -50,7 +52,7 @@ class BlogResource extends Resource ->required() ->live(1) ->columnSpanFull() - ->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), + ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))), TextInput::make('slug') ->required() @@ -132,7 +134,7 @@ class BlogResource extends Resource Action::make('togglePublished') ->label('Toggle Published') ->icon('heroicon-o-eye') - ->action(function (Blog $record) { + ->action(function (Blog $record): void { $record->update(['is_published' => ! $record->is_published]); }), ]) diff --git a/app/Filament/Resources/CategoryResource.php b/app/Filament/Resources/CategoryResource.php index 1b883b9..0e30cf4 100644 --- a/app/Filament/Resources/CategoryResource.php +++ b/app/Filament/Resources/CategoryResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\CategoryResource\Pages\CreateCategory; use App\Filament\Resources\CategoryResource\Pages\EditCategory; use App\Filament\Resources\CategoryResource\Pages\ListCategories; @@ -26,9 +28,9 @@ class CategoryResource extends Resource { protected static ?string $model = Category::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; - protected static string|\UnitEnum|null $navigationGroup = 'Content'; + protected static string|UnitEnum|null $navigationGroup = 'Content'; public static function form(Schema $schema): Schema { @@ -37,7 +39,7 @@ class CategoryResource extends Resource TextInput::make('name') ->required() ->live(1) - ->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), + ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))), TextInput::make('slug')->required(), Select::make('is_active') ->options([ @@ -58,9 +60,7 @@ class CategoryResource extends Resource TextColumn::make('slug'), TextColumn::make('blogs_count') ->label('Blogs') - ->getStateUsing(function (Category $record): int { - return $record->blogs()->count(); - }), + ->getStateUsing(fn(Category $record): int => $record->blogs()->count()), IconColumn::make('is_active')->label('Active')->boolean(), ]) ->filters([ @@ -73,7 +73,7 @@ class CategoryResource extends Resource Action::make('toggleStatus') ->label('Toggle Status') ->icon('heroicon-o-power') - ->action(function (Category $record) { + ->action(function (Category $record): void { $record->update(['is_active' => ! $record->is_active]); }), ]) diff --git a/app/Filament/Resources/MenuResource.php b/app/Filament/Resources/MenuResource.php index b94813f..a792a6e 100644 --- a/app/Filament/Resources/MenuResource.php +++ b/app/Filament/Resources/MenuResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\MenuResource\Pages\CreateMenu; use App\Filament\Resources\MenuResource\Pages\EditMenu; use App\Filament\Resources\MenuResource\Pages\ListMenus; @@ -24,13 +26,13 @@ class MenuResource extends Resource { protected static ?string $model = Menu::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-bars-3-bottom-left'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bars-3-bottom-left'; - protected static string|\UnitEnum|null $navigationGroup = 'Content'; + protected static string|UnitEnum|null $navigationGroup = 'Content'; public static function form(Schema $schema): Schema { - $menus = Menu::Pluck('name', 'id')->toArray(); + $menus = Menu::query()->Pluck('name', 'id')->toArray(); return $schema ->components([ diff --git a/app/Filament/Resources/PageResource.php b/app/Filament/Resources/PageResource.php index 1987bf2..c48ba1b 100644 --- a/app/Filament/Resources/PageResource.php +++ b/app/Filament/Resources/PageResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\PageResource\Pages\CreatePage; use App\Filament\Resources\PageResource\Pages\EditPage; use App\Filament\Resources\PageResource\Pages\ListPages; @@ -32,13 +34,13 @@ class PageResource extends Resource { protected static ?string $model = Page::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-document'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document'; - protected static string|\UnitEnum|null $navigationGroup = 'Content'; + protected static string|UnitEnum|null $navigationGroup = 'Content'; public static function form(Schema $schema): Schema { - $pages = Page::Pluck('title', 'id')->toArray(); + $pages = Page::query()->Pluck('title', 'id')->toArray(); return $schema ->components([ @@ -50,7 +52,7 @@ class PageResource extends Resource ->required() ->live(1) ->columnSpanFull() - ->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), + ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))), TextInput::make('slug')->required()->columnSpan(3), Select::make('is_published') ->options([ @@ -114,7 +116,7 @@ class PageResource extends Resource Action::make('togglePublished') ->label('Toggle Published') ->icon('heroicon-o-eye') - ->action(function (Page $record) { + ->action(function (Page $record): void { $record->update(['is_published' => ! $record->is_published]); }), ]) diff --git a/app/Filament/Resources/PlanResource.php b/app/Filament/Resources/PlanResource.php index 4a4a50d..5376398 100644 --- a/app/Filament/Resources/PlanResource.php +++ b/app/Filament/Resources/PlanResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\PlanResource\Pages\CreatePlan; use App\Filament\Resources\PlanResource\Pages\EditPlan; use App\Filament\Resources\PlanResource\Pages\ListPlans; @@ -26,9 +28,9 @@ class PlanResource extends Resource { protected static ?string $model = Plan::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-rectangle-stack'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-rectangle-stack'; - protected static string|\UnitEnum|null $navigationGroup = 'Web Master'; + protected static string|UnitEnum|null $navigationGroup = 'Web Master'; public static function form(Schema $schema): Schema { diff --git a/app/Filament/Resources/TicketResource.php b/app/Filament/Resources/TicketResource.php index 81dd6d8..18c61ea 100644 --- a/app/Filament/Resources/TicketResource.php +++ b/app/Filament/Resources/TicketResource.php @@ -2,6 +2,8 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; use App\Filament\Resources\TicketResource\Pages\CreateTicket; use App\Filament\Resources\TicketResource\Pages\EditTicket; use App\Filament\Resources\TicketResource\Pages\ListTickets; @@ -23,7 +25,6 @@ use Filament\Forms\Components\TextInput; use Filament\Notifications\Notification; use Filament\Resources\Resource; use Filament\Schemas\Schema; -use Filament\Tables; use Filament\Tables\Columns\BadgeColumn; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\Filter; @@ -37,9 +38,9 @@ class TicketResource extends Resource { protected static ?string $model = Ticket::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; - protected static string|\UnitEnum|null $navigationGroup = 'Support'; + protected static string|UnitEnum|null $navigationGroup = 'Support'; public static function form(Schema $schema): Schema { @@ -91,9 +92,9 @@ class TicketResource extends Resource ->searchable(), BadgeColumn::make('status') ->colors([ - 'success' => fn ($state) => $state === 'open', - 'warning' => fn ($state) => $state === 'pending', - 'danger' => fn ($state) => $state === 'closed', + 'success' => fn ($state): bool => $state === 'open', + 'warning' => fn ($state): bool => $state === 'pending', + 'danger' => fn ($state): bool => $state === 'closed', ]) ->sortable(), TextColumn::make('created_at') @@ -119,11 +120,9 @@ class TicketResource extends Resource DatePicker::make('created_from')->label('Created From'), DatePicker::make('created_until')->label('Created Until'), ]) - ->query(function ($query, array $data) { - return $query - ->when($data['created_from'], fn ($query, $date) => $query->whereDate('created_at', '>=', $date)) - ->when($data['created_until'], fn ($query, $date) => $query->whereDate('created_at', '<=', $date)); - }), + ->query(fn($query, array $data) => $query + ->when($data['created_from'], fn ($query, $date) => $query->whereDate('created_at', '>=', $date)) + ->when($data['created_until'], fn ($query, $date) => $query->whereDate('created_at', '<=', $date))), ]) // ->actions([ // Tables\Actions\EditAction::make(), @@ -135,26 +134,24 @@ class TicketResource extends Resource Action::make('view') ->label('View & Respond') ->icon('heroicon-o-eye') - ->schema(function (Ticket $ticket): array { - return [ - TextArea::make('response') - ->label('Your Response') - ->required() - ->rows(7) - ->placeholder('Type your response here...'), + ->schema(fn(Ticket $ticket): array => [ + TextArea::make('response') + ->label('Your Response') + ->required() + ->rows(7) + ->placeholder('Type your response here...'), - Select::make('status') - ->label('Ticket Status') - ->options([ - 'open' => 'Open', - 'pending' => 'In Progress', - 'closed' => 'Closed', - ]) - ->default($ticket->status === 'open' ? 'pending' : $ticket->status) - ->required(), - ]; - }) - ->modalContent(function (Ticket $ticket) { + Select::make('status') + ->label('Ticket Status') + ->options([ + 'open' => 'Open', + 'pending' => 'In Progress', + 'closed' => 'Closed', + ]) + ->default($ticket->status === 'open' ? 'pending' : $ticket->status) + ->required(), + ]) + ->modalContent(function (Ticket $ticket): HtmlString { $html = '
'; // Ticket Subject & Message @@ -185,8 +182,8 @@ class TicketResource extends Resource return new HtmlString($html); }) - ->action(function (array $data, Ticket $ticket) { - TicketResponse::create([ + ->action(function (array $data, Ticket $ticket): void { + TicketResponse::query()->create([ 'ticket_id' => $ticket->id, 'user_id' => auth()->id(), 'response' => $data['response'], @@ -214,7 +211,7 @@ class TicketResource extends Resource ->color('danger') ->requiresConfirmation() ->visible(fn (Ticket $ticket): bool => $ticket->status !== 'closed') - ->action(function (Ticket $ticket) { + ->action(function (Ticket $ticket): void { $ticket->update(['status' => 'closed']); }), Action::make('reopen') @@ -222,7 +219,7 @@ class TicketResource extends Resource ->icon('heroicon-o-arrow-path') ->color('success') ->visible(fn (Ticket $ticket): bool => $ticket->status === 'closed') - ->action(function (Ticket $ticket) { + ->action(function (Ticket $ticket): void { $ticket->update(['status' => 'open']); }), ]) @@ -235,7 +232,7 @@ class TicketResource extends Resource ->icon('heroicon-o-envelope') ->requiresConfirmation() ->deselectRecordsAfterCompletion() - ->action(function (Collection $records) { + ->action(function (Collection $records): void { foreach ($records as $ticket) { $responses = $ticket->responses() ->with('user') diff --git a/app/Filament/Resources/UserResource.php b/app/Filament/Resources/UserResource.php index c2586a7..7cc1ddd 100644 --- a/app/Filament/Resources/UserResource.php +++ b/app/Filament/Resources/UserResource.php @@ -2,13 +2,15 @@ namespace App\Filament\Resources; +use BackedEnum; +use UnitEnum; +use Illuminate\Support\Facades\DB; use App\Filament\Resources\UserResource\Pages\CreateUser; use App\Filament\Resources\UserResource\Pages\EditUser; use App\Filament\Resources\UserResource\Pages\ListUsers; use App\Filament\Resources\UserResource\RelationManagers\LogsRelationManager; use App\Filament\Resources\UserResource\RelationManagers\UsageLogsRelationManager; use App\Models\User; -use DB; use Exception; use Filament\Actions\BulkAction; use Filament\Actions\BulkActionGroup; @@ -31,9 +33,9 @@ class UserResource extends Resource { protected static ?string $model = User::class; - protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-users'; + protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-users'; - protected static string|\UnitEnum|null $navigationGroup = 'Admin'; + protected static string|UnitEnum|null $navigationGroup = 'Admin'; public static function form(Schema $schema): Schema { @@ -50,7 +52,7 @@ class UserResource extends Resource TextInput::make('email_verified_at') ->label('Email Verification Status') ->disabled() - ->formatStateUsing(fn ($record) => $record->email_verified_at ?? '' + ->formatStateUsing(fn ($record): string => $record->email_verified_at ?? '' ? 'Verified at '.$record->email_verified_at->toDateTimeString() : 'Not Verified') ->helperText('Shows whether the user has verified their email address.'), @@ -96,22 +98,20 @@ class UserResource extends Resource ->falseIcon('heroicon-o-x-circle') ->trueColor('success') ->falseColor('danger') - ->getStateUsing(fn ($record) => ! is_null($record->email_verified_at)) + ->getStateUsing(fn ($record): bool => ! is_null($record->email_verified_at)) ->sortable(), BadgeColumn::make('level') ->label('User Level') - ->getStateUsing(function ($record) { - return match ($record->level) { - 0 => 'Normal User', - 1 => 'Banned', - 9 => 'Super Admin', - default => 'Unknown', // In case some invalid level exists - }; + ->getStateUsing(fn($record): string => match ($record->level) { + 0 => 'Normal User', + 1 => 'Banned', + 9 => 'Super Admin', + default => 'Unknown', // In case some invalid level exists }) ->colors([ - 'success' => fn ($state) => $state === 'Normal User', - 'danger' => fn ($state) => $state === 'Banned', - 'warning' => fn ($state) => $state === 'Super Admin', + 'success' => fn ($state): bool => $state === 'Normal User', + 'danger' => fn ($state): bool => $state === 'Banned', + 'warning' => fn ($state): bool => $state === 'Super Admin', ]) ->sortable(), TextColumn::make('stripe_id')->label('Stripe ID')->copyable(), @@ -126,14 +126,14 @@ class UserResource extends Resource 'subscribed' => 'Has Active Subscription', 'not_subscribed' => 'No Active Subscription', ]) - ->query(function ($query, array $data) { + ->query(function ($query, array $data): void { if ($data['value'] === 'subscribed') { - $query->whereHas('subscriptions', function ($query) { + $query->whereHas('subscriptions', function ($query): void { $query->where('stripe_status', 'active') ->orWhere('stripe_status', 'trialing'); }); } elseif ($data['value'] === 'not_subscribed') { - $query->whereDoesntHave('subscriptions', function ($query) { + $query->whereDoesntHave('subscriptions', function ($query): void { $query->where('stripe_status', 'active') ->orWhere('stripe_status', 'trialing'); }); @@ -145,7 +145,7 @@ class UserResource extends Resource 'verified' => 'Verified', 'not_verified' => 'Not Verified', ]) - ->query(function ($query, array $data) { + ->query(function ($query, array $data): void { if ($data['value'] === 'verified') { $query->whereNotNull('email_verified_at'); } elseif ($data['value'] === 'not_verified') { @@ -161,12 +161,10 @@ class UserResource extends Resource DeleteBulkAction::make(), BulkAction::make('updateLevel') ->label('Update User Level') - ->action(function (Collection $records, array $data) { + ->action(function (Collection $records, array $data): void { $newLevel = $data['new_level']; - if ($newLevel === 9) { - throw new Exception('User level cannot be 9 or higher.'); - } + throw_if($newLevel === 9, Exception::class, 'User level cannot be 9 or higher.'); DB::table('users') ->whereIn('id', $records->pluck('id')) diff --git a/app/Filament/Resources/UserResource/Pages/EditUser.php b/app/Filament/Resources/UserResource/Pages/EditUser.php index fa1df55..e147280 100644 --- a/app/Filament/Resources/UserResource/Pages/EditUser.php +++ b/app/Filament/Resources/UserResource/Pages/EditUser.php @@ -75,7 +75,7 @@ class EditUser extends EditRecord fclose($csv); return Response::streamDownload( - function () use ($csvContent) { + function () use ($csvContent): void { echo $csvContent; }, "user_{$record->id}_report_".now()->format('Ymd_His').'.csv', diff --git a/app/Filament/Resources/UserResource/RelationManagers/LogsRelationManager.php b/app/Filament/Resources/UserResource/RelationManagers/LogsRelationManager.php index 3d374d4..0a7c8b7 100644 --- a/app/Filament/Resources/UserResource/RelationManagers/LogsRelationManager.php +++ b/app/Filament/Resources/UserResource/RelationManagers/LogsRelationManager.php @@ -4,7 +4,6 @@ namespace App\Filament\Resources\UserResource\RelationManagers; use Filament\Actions\BulkActionGroup; use Filament\Resources\RelationManagers\RelationManager; -use Filament\Tables; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; diff --git a/app/Filament/Resources/UserResource/RelationManagers/UsageLogsRelationManager.php b/app/Filament/Resources/UserResource/RelationManagers/UsageLogsRelationManager.php index 701c1c4..dc9b964 100644 --- a/app/Filament/Resources/UserResource/RelationManagers/UsageLogsRelationManager.php +++ b/app/Filament/Resources/UserResource/RelationManagers/UsageLogsRelationManager.php @@ -4,7 +4,6 @@ namespace App\Filament\Resources\UserResource\RelationManagers; use Filament\Actions\BulkActionGroup; use Filament\Resources\RelationManagers\RelationManager; -use Filament\Tables; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; diff --git a/app/Filament/Widgets/StatsOverview.php b/app/Filament/Widgets/StatsOverview.php index 20726f3..ecdaf95 100644 --- a/app/Filament/Widgets/StatsOverview.php +++ b/app/Filament/Widgets/StatsOverview.php @@ -2,13 +2,13 @@ namespace App\Filament\Widgets; +use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\DB; use App\Models\Log; use App\Models\Meta; use App\Models\PremiumEmail; use App\Models\Ticket; use App\Models\User; -use Carbon\Carbon; -use DB; use Filament\Widgets\StatsOverviewWidget as BaseWidget; use Filament\Widgets\StatsOverviewWidget\Stat; @@ -26,39 +26,39 @@ class StatsOverview extends BaseWidget ->descriptionIcon($this->getComparisonIcon($this->getCustomerCount(), $this->getCustomerCount('yesterday'))) ->color($this->getComparisonColor($this->getCustomerCount(), $this->getCustomerCount('yesterday'))), Stat::make('Paid Users', $this->getUserPaid()) - ->description($this->getComparisonDescription($this->getUserPaid(), $this->getUserPaid('yesterday'))) - ->descriptionIcon($this->getComparisonIcon($this->getUserPaid(), $this->getUserPaid('yesterday'))) - ->color($this->getComparisonColor($this->getUserPaid(), $this->getUserPaid('yesterday'))), + ->description($this->getComparisonDescription($this->getUserPaid(), $this->getUserPaid())) + ->descriptionIcon($this->getComparisonIcon($this->getUserPaid(), $this->getUserPaid())) + ->color($this->getComparisonColor($this->getUserPaid(), $this->getUserPaid())), Stat::make('Logs Count', $this->getLogsCount()) ->description($this->getComparisonDescription($this->getLogsCount(), $this->getLogsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getLogsCount(), $this->getLogsCount('yesterday'))) ->color($this->getComparisonColor($this->getLogsCount(), $this->getLogsCount('yesterday'))), Stat::make('Total Mailbox', $this->getTotalMailbox()) - ->description($this->getComparisonDescription($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))) - ->descriptionIcon($this->getComparisonIcon($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))) - ->color($this->getComparisonColor($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))), + ->description($this->getComparisonDescription($this->getTotalMailbox(), $this->getTotalMailbox())) + ->descriptionIcon($this->getComparisonIcon($this->getTotalMailbox(), $this->getTotalMailbox())) + ->color($this->getComparisonColor($this->getTotalMailbox(), $this->getTotalMailbox())), Stat::make('Emails Received', $this->getTotalEmailsReceived()) - ->description($this->getComparisonDescription($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))) - ->descriptionIcon($this->getComparisonIcon($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))) - ->color($this->getComparisonColor($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))), + ->description($this->getComparisonDescription($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived())) + ->descriptionIcon($this->getComparisonIcon($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived())) + ->color($this->getComparisonColor($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived())), Stat::make('Emails Stored', $this->getStoreEmailsCount()) ->description($this->getComparisonDescription($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))) ->color($this->getComparisonColor($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))), Stat::make('Open Tickets', $this->getOpenTicketsCount()) - ->description($this->getComparisonDescription($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))) - ->descriptionIcon($this->getComparisonIcon($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))) - ->color($this->getComparisonColor($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))), + ->description($this->getComparisonDescription($this->getOpenTicketsCount(), $this->getOpenTicketsCount())) + ->descriptionIcon($this->getComparisonIcon($this->getOpenTicketsCount(), $this->getOpenTicketsCount())) + ->color($this->getComparisonColor($this->getOpenTicketsCount(), $this->getOpenTicketsCount())), Stat::make('Closed Tickets', $this->getClosedTicketsCount()) - ->description($this->getComparisonDescription($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))) - ->descriptionIcon($this->getComparisonIcon($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))) - ->color($this->getComparisonColor($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))), + ->description($this->getComparisonDescription($this->getClosedTicketsCount(), $this->getClosedTicketsCount())) + ->descriptionIcon($this->getComparisonIcon($this->getClosedTicketsCount(), $this->getClosedTicketsCount())) + ->color($this->getComparisonColor($this->getClosedTicketsCount(), $this->getClosedTicketsCount())), ]; } private function getComparisonDescription(int $today, int $yesterday): string { - if ($today == $yesterday) { + if ($today === $yesterday) { return 'No change'; } @@ -76,7 +76,7 @@ class StatsOverview extends BaseWidget private function getComparisonIcon(int $today, int $yesterday): ?string { - if ($today == $yesterday) { + if ($today === $yesterday) { return null; } @@ -85,7 +85,7 @@ class StatsOverview extends BaseWidget private function getComparisonColor(int $today, int $yesterday): string { - if ($today == $yesterday) { + if ($today === $yesterday) { return 'gray'; } @@ -95,13 +95,13 @@ class StatsOverview extends BaseWidget private function getUser(string $period = 'today'): int { if ($period === 'yesterday') { - return User::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); + return User::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count(); } - return User::count(); + return User::query()->count(); } - private function getUserPaid(string $period = 'today'): int + private function getUserPaid(): int { return DB::table('subscriptions') ->where('stripe_status', 'active') @@ -112,49 +112,49 @@ class StatsOverview extends BaseWidget private function getLogsCount(string $period = 'today'): int { if ($period === 'yesterday') { - return Log::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); + return Log::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count(); } - return Log::count(); + return Log::query()->count(); } - private function getTotalMailbox(string $period = 'today'): int + private function getTotalMailbox(): int { - return Meta::select('value')->where('key', 'email_ids_created')->first()->value ?? 0; + return Meta::query()->select('value')->where('key', 'email_ids_created')->first()->value ?? 0; } - private function getTotalEmailsReceived(string $period = 'today'): int + private function getTotalEmailsReceived(): int { - return Meta::select('value')->where('key', 'messages_received')->first()->value ?? 0; + return Meta::query()->select('value')->where('key', 'messages_received')->first()->value ?? 0; } private function getCustomerCount(string $period = 'today'): int { if ($period === 'yesterday') { - return User::whereNotNull('stripe_id') - ->where('created_at', '<', Carbon::today('UTC')->startOfDay()) + return User::query()->whereNotNull('stripe_id') + ->where('created_at', '<', Date::today('UTC')->startOfDay()) ->count(); } - return User::whereNotNull('stripe_id')->count(); + return User::query()->whereNotNull('stripe_id')->count(); } private function getStoreEmailsCount(string $period = 'today'): int { if ($period === 'yesterday') { - return PremiumEmail::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); + return PremiumEmail::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count(); } - return PremiumEmail::count(); + return PremiumEmail::query()->count(); } - private function getOpenTicketsCount(string $period = 'today'): int + private function getOpenTicketsCount(): int { - return Ticket::whereIn('status', ['open', 'pending'])->count(); + return Ticket::query()->whereIn('status', ['open', 'pending'])->count(); } - private function getClosedTicketsCount(string $period = 'today'): int + private function getClosedTicketsCount(): int { - return Ticket::whereIn('status', ['closed'])->count(); + return Ticket::query()->whereIn('status', ['closed'])->count(); } } diff --git a/app/Http/Controllers/AppController.php b/app/Http/Controllers/AppController.php index d38f109..3e9dc20 100644 --- a/app/Http/Controllers/AppController.php +++ b/app/Http/Controllers/AppController.php @@ -2,9 +2,11 @@ namespace App\Http\Controllers; +use Session; +use Illuminate\Routing\Redirector; +use Illuminate\Http\RedirectResponse; use App\Models\Premium; use App\Models\ZEmail; -use Session; class AppController extends Controller { @@ -15,67 +17,66 @@ class AppController extends Controller 'email' => 'required|email', ])->validate(); - if (json_decode(config('app.settings.configuration_settings'))->enable_create_from_url) { + if (json_decode((string) config('app.settings.configuration_settings'))->enable_create_from_url) { ZEmail::createCustomEmailFull($email); } - return redirect()->route('mailbox'); + return to_route('mailbox'); } if (! ZEmail::getEmail()) { - return redirect()->route('home'); + return to_route('home'); } - if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { - return redirect()->route('home'); + if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) { + return to_route('home'); } return $this->app(); } - public function app() + public function app(): Redirector|RedirectResponse { - return redirect()->route('home'); + return to_route('home'); } - public function switch($email) + public function switch($email): Redirector|RedirectResponse { ZEmail::setEmail($email); - if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { - return redirect()->route('home'); + if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) { + return to_route('home'); } - return redirect()->route('mailbox'); + return to_route('mailbox'); } - public function delete($email = null) + public function delete($email = null): Redirector|RedirectResponse { if ($email) { $emails = ZEmail::getEmails(); ZEmail::removeEmail($email); - return redirect()->route('mailbox'); - } else { - return redirect()->route('home'); + return to_route('mailbox'); } + return to_route('home'); } - public function switchP($email) + public function switchP($email): Redirector|RedirectResponse { - if (Session::get('isInboxTypePremium')) { + if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) { Premium::setEmailP($email); } else { ZEmail::setEmail($email); } - if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { - return redirect()->route('dashboard'); + if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) { + return to_route('dashboard'); } - return redirect()->route('dashboard.premium'); + return to_route('dashboard.premium'); } - public function deleteP($email = null) + public function deleteP($email = null): Redirector|RedirectResponse { if ($email) { - if (Session::get('isInboxTypePremium')) { + if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) { $emails = Premium::getEmails(); Premium::removeEmail($email); } else { @@ -83,10 +84,9 @@ class AppController extends Controller ZEmail::removeEmail($email); } - return redirect()->route('dashboard.premium'); - } else { - return redirect()->route('dashboard'); + return to_route('dashboard.premium'); } + return to_route('dashboard'); } public function locale($locale) @@ -94,38 +94,8 @@ class AppController extends Controller if (in_array($locale, config('app.locales'))) { session(['locale' => $locale]); - return redirect()->back(); + return back(); } abort(400); } - - private function getStringBetween($string, $start, $end) - { - $string = ' '.$string; - $ini = strpos($string, $start); - if ($ini == 0) { - return ''; - } - $ini += strlen($start); - $len = strpos($string, $end, $ini) - $ini; - - return substr($string, $ini, $len); - } - - private function setHeaders($page) - { - $header = $page->header; - foreach ($page->meta ? unserialize($page->meta) : [] as $meta) { - if ($meta['name'] == 'canonical') { - $header .= ''; - } elseif (str_contains($meta['name'], 'og:')) { - $header .= ''; - } else { - $header .= ''; - } - } - $page->header = $header; - - return $page; - } } diff --git a/app/Http/Controllers/WebhookController.php b/app/Http/Controllers/WebhookController.php index 94bfa90..c9a99c9 100644 --- a/app/Http/Controllers/WebhookController.php +++ b/app/Http/Controllers/WebhookController.php @@ -2,17 +2,19 @@ namespace App\Http\Controllers; +use Illuminate\Contracts\Routing\ResponseFactory; +use Illuminate\Http\Response; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Date; use App\NotifyMe; -use Carbon\Carbon; use Exception; use Illuminate\Http\Request; -use Log; class WebhookController extends Controller { use NotifyMe; - public function oxapay(Request $request) + public function oxapay(Request $request): ResponseFactory|Response { // Get the request data $postData = $request->getContent(); @@ -32,7 +34,7 @@ class WebhookController extends Controller // Validate HMAC signature $hmacHeader = $request->header('HMAC'); - $calculatedHmac = hash_hmac('sha512', $postData, $apiSecretKey); + $calculatedHmac = hash_hmac('sha512', $postData, (string) $apiSecretKey); if (hash_equals($calculatedHmac, $hmacHeader)) { // HMAC signature is valid @@ -44,7 +46,7 @@ class WebhookController extends Controller $currency = $data['currency'] ?? 'Unknown'; $trackId = $data['track_id'] ?? 'Unknown'; $orderId = $data['order_id'] ?? 'N/A'; - $date = isset($data['date']) ? Carbon::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); + $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); Log::info('Received Oxapay invoice payment callback', [ 'track_id' => $trackId, @@ -71,7 +73,7 @@ class WebhookController extends Controller $address = $data['address'] ?? 'Unknown'; $txHash = $data['tx_hash'] ?? 'Unknown'; $description = $data['description'] ?? 'N/A'; - $date = isset($data['date']) ? Carbon::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); + $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); Log::info('Received Oxapay payout callback', [ 'track_id' => $trackId, diff --git a/app/Http/Middleware/CheckPageSlug.php b/app/Http/Middleware/CheckPageSlug.php index 77c1602..fed45cc 100644 --- a/app/Http/Middleware/CheckPageSlug.php +++ b/app/Http/Middleware/CheckPageSlug.php @@ -32,9 +32,7 @@ class CheckPageSlug return response()->file($publicPath); } - if (is_dir($publicPath)) { - abort(404); - } + abort_if(is_dir($publicPath), 404); return $next($request); } diff --git a/app/Http/Middleware/CheckUserBanned.php b/app/Http/Middleware/CheckUserBanned.php index 7274eda..0775480 100644 --- a/app/Http/Middleware/CheckUserBanned.php +++ b/app/Http/Middleware/CheckUserBanned.php @@ -2,7 +2,7 @@ namespace App\Http\Middleware; -use Auth; +use Illuminate\Support\Facades\Auth; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; diff --git a/app/Http/Middleware/Locale.php b/app/Http/Middleware/Locale.php index 6603763..fba37a8 100644 --- a/app/Http/Middleware/Locale.php +++ b/app/Http/Middleware/Locale.php @@ -17,11 +17,11 @@ class Locale public function handle(Request $request, Closure $next): Response { try { - $locale = explode('-', explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0])[0]; + $locale = explode('-', explode(',', (string) \Illuminate\Support\Facades\Request::server('HTTP_ACCEPT_LANGUAGE'))[0])[0]; if (in_array($locale, config('app.locales'))) { session(['browser-locale' => $locale]); } - } catch (Exception $e) { + } catch (Exception) { } app()->setLocale(session('locale', session('browser-locale', config('app.settings.language', config('app.locale', 'en'))))); diff --git a/app/Livewire/Actions/Logout.php b/app/Livewire/Actions/Logout.php index 45993bb..bb1e3df 100644 --- a/app/Livewire/Actions/Logout.php +++ b/app/Livewire/Actions/Logout.php @@ -2,6 +2,8 @@ namespace App\Livewire\Actions; +use Illuminate\Routing\Redirector; +use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; @@ -10,7 +12,7 @@ class Logout /** * Log the current user out of the application. */ - public function __invoke() + public function __invoke(): Redirector|RedirectResponse { Auth::guard('web')->logout(); diff --git a/app/Livewire/AddOn.php b/app/Livewire/AddOn.php index eff9c3f..48d4d90 100644 --- a/app/Livewire/AddOn.php +++ b/app/Livewire/AddOn.php @@ -2,9 +2,11 @@ namespace App\Livewire; +use Illuminate\Support\Facades\Session; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use App\Models\ZEmail; use Livewire\Component; -use Session; class AddOn extends Component { @@ -27,11 +29,12 @@ class AddOn extends Component $email = ZEmail::getEmail(); $messages = ZEmail::getMessages($email); if (count($messages['data']) > 0) { - return redirect()->route('mailbox'); + return to_route('mailbox'); } + return null; } - public function mount() + public function mount(): void { $this->faqs = json_decode(file_get_contents(public_path('addOnFAQs.json')), true) ?? []; $route = request()->route()->getName(); @@ -45,16 +48,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'disposable-gmail') { $this->title = 'Disposable Gmail Email | Free Temporary Gmail Inbox Online'; @@ -65,16 +66,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'disposable-outlook') { @@ -86,16 +85,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'disposable-yahoo') { $this->title = 'Disposable Yahoo Mail | Free Temporary Yahoo Inbox'; @@ -106,16 +103,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'gmailnator') { $this->title = 'Gmailnator - Free Temporary Gmail Email Address Generator'; @@ -126,16 +121,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'emailnator') { $this->title = 'Emailnator - Free Disposable Temporary Email Service'; @@ -146,16 +139,14 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } elseif ($route == 'temp-gmail') { $this->title = 'Temp Gmail | Free Temporary Gmail Inbox for Instant Use'; @@ -166,22 +157,20 @@ class AddOn extends Component $this->faqSchema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', - 'mainEntity' => collect($this->faqs)->map(function ($faq) { - return [ - '@type' => 'Question', - 'name' => $faq['title'], - 'acceptedAnswer' => [ - '@type' => 'Answer', - 'text' => $faq['content'], - ], - ]; - })->toArray(), + 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [ + '@type' => 'Question', + 'name' => $faq['title'], + 'acceptedAnswer' => [ + '@type' => 'Answer', + 'text' => $faq['content'], + ], + ])->all(), ]; } } - public function render() + public function render(): Factory|View { return view('livewire.add-on'); } diff --git a/app/Livewire/Auth/Register.php b/app/Livewire/Auth/Register.php index 1737f9b..4ea93e1 100644 --- a/app/Livewire/Auth/Register.php +++ b/app/Livewire/Auth/Register.php @@ -34,7 +34,7 @@ class Register extends Component $validated['password'] = Hash::make($validated['password']); - event(new Registered(($user = User::create($validated)))); + event(new Registered(($user = User::query()->create($validated)))); Auth::login($user); diff --git a/app/Livewire/Auth/ResetPassword.php b/app/Livewire/Auth/ResetPassword.php index 28b3940..cba145c 100644 --- a/app/Livewire/Auth/ResetPassword.php +++ b/app/Livewire/Auth/ResetPassword.php @@ -50,7 +50,7 @@ class ResetPassword extends Component // database. Otherwise we will parse the error and return the response. $status = Password::reset( $this->only('email', 'password', 'password_confirmation', 'token'), - function ($user) { + function ($user): void { $user->forceFill([ 'password' => Hash::make($this->password), 'remember_token' => Str::random(60), diff --git a/app/Livewire/Blog.php b/app/Livewire/Blog.php index c01224e..1ea268e 100644 --- a/app/Livewire/Blog.php +++ b/app/Livewire/Blog.php @@ -11,10 +11,10 @@ class Blog extends Component public $category; - public function mount($slug) + public function mount($slug): void { - $this->postDetail = \App\Models\Blog::where('slug', $slug)->firstOrFail(); - $this->category = Category::where('id', $this->postDetail->category_id)->first(); + $this->postDetail = \App\Models\Blog::query()->where('slug', $slug)->firstOrFail(); + $this->category = Category::query()->where('id', $this->postDetail->category_id)->first(); } public function render() diff --git a/app/Livewire/Dashboard/Bulk.php b/app/Livewire/Dashboard/Bulk.php index 1dab45e..16b70c5 100644 --- a/app/Livewire/Dashboard/Bulk.php +++ b/app/Livewire/Dashboard/Bulk.php @@ -2,8 +2,8 @@ namespace App\Livewire\Dashboard; +use Illuminate\Support\Facades\Session; use Livewire\Component; -use Session; class Bulk extends Component { @@ -11,15 +11,13 @@ class Bulk extends Component public $bulkCount = 1; - private $isSubscribed = false; - - public function mount() + public function mount(): void { $subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']); Session::put('isSubscribed', $subscriptionCheck); } - public function generateBulk() + public function generateBulk(): void { $this->validate([ 'bulkCount' => 'required|integer|min:1|max:500', @@ -44,7 +42,7 @@ class Bulk extends Component $filename = 'bulk_emails_'.now()->format('Ymd_His').'.txt'; $content = implode(PHP_EOL, $this->bulkEmails); - return response()->streamDownload(function () use ($content) { + return response()->streamDownload(function () use ($content): void { echo $content; }, $filename); } @@ -54,11 +52,11 @@ class Bulk extends Component $domain = $this->getRandomDomain(); if ($domain == 'gmail.com' || $domain == 'googlemail.com') { $uname = $this->getRandomGmailUser(); - $uname_len = strlen($uname); + $uname_len = strlen((string) $uname); $len_power = $uname_len - 1; - $combination = pow(2, $len_power); + $combination = 2 ** $len_power; $rand_comb = mt_rand(1, $combination); - $formatted = implode(' ', str_split($uname)); + $formatted = implode(' ', str_split((string) $uname)); $uname_exp = explode(' ', $formatted); $bin = intval(''); @@ -70,7 +68,7 @@ class Bulk extends Component $email = ''; for ($i = 0; $i < $len_power; $i++) { $email .= $uname_exp[$i]; - if ($bin[$i]) { + if ($bin[$i] !== '' && $bin[$i] !== '0') { $email .= '.'; } } @@ -83,15 +81,14 @@ class Bulk extends Component } return $email; - } else { - return $this->generateRandomUsername().'@'.$domain; } + return $this->generateRandomUsername().'@'.$domain; } private function generateRandomUsername(): string { - $start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; - $end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; + $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0; + $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0; if ($start == 0 && $end == 0) { return $this->generatePronounceableWord(); } @@ -101,25 +98,25 @@ class Bulk extends Component private function generatedRandomBetweenLength($start, $end): string { - $length = rand($start, $end); + $length = random_int($start, $end); return $this->generateRandomString($length); } private function getRandomDomain() { - $domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; $count = count($domains); - return $count > 0 ? $domains[rand(1, $count) - 1] : ''; + return $count > 0 ? $domains[random_int(1, $count) - 1] : ''; } private function getRandomGmailUser() { - $gmailusername = json_decode(config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; + $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; $count = count($gmailusername); - return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; + return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : ''; } private function generatePronounceableWord(): string @@ -129,21 +126,21 @@ class Bulk extends Component $a = $c.$v; // both $random = ''; for ($j = 0; $j < 2; $j++) { - $random .= $c[rand(0, strlen($c) - 1)]; - $random .= $v[rand(0, strlen($v) - 1)]; - $random .= $a[rand(0, strlen($a) - 1)]; + $random .= $c[random_int(0, strlen($c) - 1)]; + $random .= $v[random_int(0, strlen($v) - 1)]; + $random .= $a[random_int(0, strlen($a) - 1)]; } return $random; } - private function generateRandomString($length = 10): string + private function generateRandomString(int $length = 10): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; + $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; @@ -153,8 +150,7 @@ class Bulk extends Component { if (Session::get('isSubscribed')) { return view('livewire.dashboard.bulk')->layout('components.layouts.dashboard'); - } else { - return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } + return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } } diff --git a/app/Livewire/Dashboard/BulkGmail.php b/app/Livewire/Dashboard/BulkGmail.php index 2bf0211..324a6dc 100644 --- a/app/Livewire/Dashboard/BulkGmail.php +++ b/app/Livewire/Dashboard/BulkGmail.php @@ -2,8 +2,8 @@ namespace App\Livewire\Dashboard; +use Illuminate\Support\Facades\Session; use Livewire\Component; -use Session; class BulkGmail extends Component { @@ -13,7 +13,7 @@ class BulkGmail extends Component public $bulkEmails = []; - public function mount() + public function mount(): void { $subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']); Session::put('isSubscribed', $subscriptionCheck); @@ -34,7 +34,7 @@ class BulkGmail extends Component $this->bulkEmails = []; } - $this->bulkEmails = $this->generateDotVariants(explode('@', $this->email)[0], $this->quantity); + $this->bulkEmails = $this->generateDotVariants(explode('@', (string) $this->email)[0], $this->quantity); } public function downloadBulk() @@ -47,12 +47,15 @@ class BulkGmail extends Component $filename = 'bulk_gmails_'.now()->format('Ymd_His').'.txt'; $content = implode(PHP_EOL, $this->bulkEmails); - return response()->streamDownload(function () use ($content) { + return response()->streamDownload(function () use ($content): void { echo $content; }, $filename); } - private function generateDotVariants($uname, $quantity) + /** + * @return string[] + */ + private function generateDotVariants(string $uname, int $quantity): array { $length = strlen($uname); $positions = range(1, $length - 1); @@ -89,7 +92,7 @@ class BulkGmail extends Component return [[]]; } - if (empty($items)) { + if ($items === []) { return []; } @@ -102,19 +105,14 @@ class BulkGmail extends Component $combinations[] = $c; } - foreach ($this->combinations($tail, $size) as $c) { - $combinations[] = $c; - } - - return $combinations; + return $this->combinations($tail, $size); } public function render() { if (Session::get('isSubscribed')) { return view('livewire.dashboard.bulk-gmail')->layout('components.layouts.dashboard'); - } else { - return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } + return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } } diff --git a/app/Livewire/Dashboard/Dashboard.php b/app/Livewire/Dashboard/Dashboard.php index e1ba492..7b1ecd5 100644 --- a/app/Livewire/Dashboard/Dashboard.php +++ b/app/Livewire/Dashboard/Dashboard.php @@ -2,14 +2,14 @@ namespace App\Livewire\Dashboard; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; use App\Models\UsageLog; -use Cache; -use Carbon\Carbon; -use DB; use Exception; use Illuminate\Http\Request; use Livewire\Component; -use Log; use Stripe\StripeClient; class Dashboard extends Component @@ -27,13 +27,13 @@ class Dashboard extends Component public function paymentStatus(Request $request) { $status = $request->route('status'); - $currentUrl = $request->fullUrl(); + $request->fullUrl(); if ($status == 'success') { $this->syncSubscription(); - - return redirect()->route('dashboard')->with('status', 'success'); - } elseif ($status == 'cancel') { - return redirect()->route('dashboard')->with('status', 'cancel'); + return to_route('dashboard')->with('status', 'success'); + } + if ($status == 'cancel') { + return to_route('dashboard')->with('status', 'cancel'); } } @@ -63,17 +63,15 @@ class Dashboard extends Component $canceled_at = $subscriptionData->canceled_at; $status = $subscriptionData->status; if ($cancel_at_period_end) { - $final_ends_at = Carbon::createFromTimestamp($cancel_at)->toDateTimeString(); + $final_ends_at = Date::createFromTimestamp($cancel_at)->toDateTimeString(); + } elseif ($cancel_at === null && $canceled_at !== null && $status === 'canceled' && $cancel_at_period_end === false) { + // $final_ends_at = Carbon::createFromTimestamp($canceled_at)->toDateTimeString(); + $final_ends_at = Date::now()->subDays(2)->toDateTimeString(); + $redirect = true; + } elseif ($status === 'active' && $cancel_at !== null) { + $final_ends_at = Date::createFromTimestamp($cancel_at)->toDateTimeString(); } else { - if ($cancel_at === null && $canceled_at !== null && $status === 'canceled' && $cancel_at_period_end === false) { - // $final_ends_at = Carbon::createFromTimestamp($canceled_at)->toDateTimeString(); - $final_ends_at = Carbon::now()->subDays(2)->toDateTimeString(); - $redirect = true; - } elseif ($status === 'active' && $cancel_at !== null) { - $final_ends_at = Carbon::createFromTimestamp($cancel_at)->toDateTimeString(); - } else { - $final_ends_at = null; - } + $final_ends_at = null; } DB::table('subscriptions') @@ -81,7 +79,7 @@ class Dashboard extends Component ->update([ 'stripe_status' => $status, 'ends_at' => $final_ends_at, - 'updated_at' => Carbon::now()->toDateTimeString(), + 'updated_at' => Date::now()->toDateTimeString(), ]); } } @@ -117,11 +115,7 @@ class Dashboard extends Component $stripe_product = $items->price->product; $ends_at = $items->current_period_end; $subscriptionItemId = $items->id; - if ($cancel_at_period_end) { - $final_ends_at = Carbon::createFromTimestamp($ends_at)->toDateTimeString(); - } else { - $final_ends_at = null; - } + $final_ends_at = $cancel_at_period_end ? Date::createFromTimestamp($ends_at)->toDateTimeString() : null; try { if ($status === 'active') { @@ -135,8 +129,8 @@ class Dashboard extends Component 'stripe_price' => $stripe_price, 'quantity' => $quantity, 'ends_at' => $final_ends_at, - 'created_at' => Carbon::now()->toDateTimeString(), - 'updated_at' => Carbon::now()->toDateTimeString(), + 'created_at' => Date::now()->toDateTimeString(), + 'updated_at' => Date::now()->toDateTimeString(), ]); $subscriptionsTable = DB::table('subscriptions')->where(['stripe_id' => $subscriptionId])->first(); @@ -149,8 +143,8 @@ class Dashboard extends Component 'stripe_product' => $stripe_product, 'stripe_price' => $stripe_price, 'quantity' => $quantity, - 'created_at' => Carbon::now()->toDateTimeString(), - 'updated_at' => Carbon::now()->toDateTimeString(), + 'created_at' => Date::now()->toDateTimeString(), + 'updated_at' => Date::now()->toDateTimeString(), ]); } } @@ -165,7 +159,7 @@ class Dashboard extends Component public function mount(Request $request) { if ($this->checkForSubscriptionStatus()) { - return redirect()->route('dashboard'); + return to_route('dashboard'); } try { $status = $request->session()->get('status'); @@ -177,7 +171,7 @@ class Dashboard extends Component } $request->session()->forget('status'); } - } catch (Exception $exception) { + } catch (Exception) { } @@ -207,7 +201,7 @@ class Dashboard extends Component } } - $usageLog = UsageLog::where('user_id', auth()->user()->id)->first(); + $usageLog = UsageLog::query()->where('user_id', auth()->user()->id)->first(); $this->usageLog = [ 'emails_created_count' => $usageLog->emails_created_count ?? 0, 'emails_received_count' => $usageLog->emails_received_count ?? 0, diff --git a/app/Livewire/Dashboard/Mailbox/Inbox.php b/app/Livewire/Dashboard/Mailbox/Inbox.php index 947cf2a..df05280 100644 --- a/app/Livewire/Dashboard/Mailbox/Inbox.php +++ b/app/Livewire/Dashboard/Mailbox/Inbox.php @@ -2,17 +2,19 @@ namespace App\Livewire\Dashboard\Mailbox; +use Illuminate\Support\Facades\Session; +use Illuminate\Routing\Redirector; +use Illuminate\Http\RedirectResponse; +use Illuminate\Support\Facades\Date; use App\ColorPicker; use App\Models\Log; use App\Models\Premium; use App\Models\PremiumEmail; use App\Models\UsageLog; use App\Models\ZEmail; -use Carbon\Carbon; use Exception; use Illuminate\Support\Facades\Auth; use Livewire\Component; -use Session; class Inbox extends Component { @@ -63,14 +65,14 @@ class Inbox extends Component $this->premium = Session::get('isInboxTypePremium', true); if ($this->premium) { - $this->domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; $this->email = Premium::getEmail(); $this->emails = Premium::getEmails(); $this->initial = false; $this->checkMultipleEmails(); $this->validateDomainInEmail(); } else { - $this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; $this->email = ZEmail::getEmail(); $this->emails = ZEmail::getEmails(); $this->initial = false; @@ -97,12 +99,12 @@ class Inbox extends Component $this->email_limit = $mailboxLimit; } catch (Exception $e) { - \Log::error($e->getMessage()); + \Illuminate\Support\Facades\Log::error($e->getMessage()); } } if ($this->premium) { - $mailboxHistory = UsageLog::where(['user_id' => auth()->user()->id])->first(); + $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first(); $this->mailboxHistory = $mailboxHistory->emails_created_history ?? []; } else { $this->mailboxHistory = ZEmail::getEmails() ?? []; @@ -112,27 +114,23 @@ class Inbox extends Component private function checkMultipleEmails(): void { - if (count($this->emails) == 0) { + if (count($this->emails) === 0) { $this->emails = [$this->email]; } - if (count($this->emails) > 1) { - $this->list = true; - } else { - $this->list = false; - } + $this->list = count($this->emails) > 1; } public function switchEmail($email) { try { if ($email != null) { - $data = explode('@', $email); + $data = explode('@', (string) $email); if (isset($data[1])) { $domain = $data[1]; if ($this->premium) { - $domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; } else { - $domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; } if (! in_array($domain, $domains)) { return $this->showAlert('error', __('This mailbox can not be recovered.')); @@ -140,17 +138,17 @@ class Inbox extends Component } } } catch (Exception $exception) { - \Log::error($exception->getMessage()); + \Illuminate\Support\Facades\Log::error($exception->getMessage()); } - return redirect()->route('switchP', ['email' => $email]); + return to_route('switchP', ['email' => $email]); } public function syncEmail(): void { $this->email = Premium::getEmail(); $this->emails = Premium::getEmails(); - if (count($this->emails) == 0) { + if (count($this->emails) === 0) { $this->dispatch('getEmail'); } $this->checkMultipleEmails(); @@ -174,13 +172,13 @@ class Inbox extends Component return $this->showAlert('error', __('Please enter Username')); } $this->checkDomainInUsername(); - if (strlen($this->username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($this->username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { - return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_max); + if (strlen((string) $this->username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen((string) $this->username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) { + return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max); } if (! $this->domain) { return $this->showAlert('error', __('Please Select a Domain')); } - if (in_array($this->username, json_decode(config('app.settings.configuration_settings'))->forbidden_ids)) { + if (in_array($this->username, json_decode((string) config('app.settings.configuration_settings'))->forbidden_ids)) { return $this->showAlert('error', __('Username not allowed')); } if (! $this->checkEmailLimit()) { @@ -195,7 +193,7 @@ class Inbox extends Component $this->email = ZEmail::createCustomEmail($this->username, $this->domain); } - return redirect()->route('dashboard.premium'); + return to_route('dashboard.premium'); } @@ -205,13 +203,9 @@ class Inbox extends Component if (! $this->checkEmailLimit()) { return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.')); } - if ($this->premium) { - $this->email = Premium::generateRandomEmail(); - } else { - $this->email = ZEmail::generateRandomEmail(); - } + $this->email = $this->premium ? Premium::generateRandomEmail() : ZEmail::generateRandomEmail(); - return redirect()->route('dashboard.premium'); + return to_route('dashboard.premium'); } public function gmail() @@ -219,13 +213,9 @@ class Inbox extends Component if (! $this->checkEmailLimit()) { return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.')); } - if ($this->premium) { - $this->email = Premium::generateRandomGmail(); - } else { - $this->email = ZEmail::generateRandomGmail(); - } + $this->email = $this->premium ? Premium::generateRandomGmail() : ZEmail::generateRandomGmail(); - return redirect()->route('dashboard.premium'); + return to_route('dashboard.premium'); } public function outlook() @@ -239,38 +229,30 @@ class Inbox extends Component $this->email = ZEmail::generateRandomOutlook(); } - return redirect()->route('dashboard.premium'); + return to_route('dashboard.premium'); } - public function deleteEmail() + public function deleteEmail(): Redirector|RedirectResponse { - return redirect()->route('deleteP', ['email' => $this->email]); + return to_route('deleteP', ['email' => $this->email]); } - private function showAlert($type, $message): void + private function showAlert(string $type, $message): void { $this->dispatch('showAlert', ['type' => $type, 'message' => $message]); } private function checkEmailLimit(): bool { - $logs = Log::select('ip', 'email')->where('user_id', auth()->user()->id)->where('created_at', '>', Carbon::now()->subDay())->groupBy('email')->groupBy('ip')->get(); - if (count($logs) >= $this->email_limit) { - return false; - } - - return true; + $logs = Log::query()->select('ip', 'email')->where('user_id', auth()->user()->id)->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get(); + return count($logs) < $this->email_limit; } private function checkUsedEmail(): bool { - if (json_decode(config('app.settings.configuration_settings'))->disable_used_email) { - $check = Log::where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); - if ($check > 0) { - return false; - } - - return true; + if (json_decode((string) config('app.settings.configuration_settings'))->disable_used_email) { + $check = Log::query()->where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); + return $check <= 0; } return true; @@ -278,7 +260,7 @@ class Inbox extends Component private function checkDomainInUsername(): void { - $parts = explode('@', $this->username); + $parts = explode('@', (string) $this->username); if (isset($parts[1])) { if (in_array($parts[1], $this->domains)) { $this->domain = $parts[1]; @@ -291,13 +273,13 @@ class Inbox extends Component { try { if ($this->email != null) { - $data = explode('@', $this->email); + $data = explode('@', (string) $this->email); if (isset($data[1])) { $domain = $data[1]; if ($this->premium) { - $domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; } else { - $domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; } if (! in_array($domain, $domains)) { $key = array_search($this->email, $this->emails); @@ -306,16 +288,12 @@ class Inbox extends Component } else { ZEmail::removeEmail($this->email); } - if ($key == 0 && count($this->emails) == 1 && json_decode(config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') { - redirect()->route('dashboard.premium'); - } else { - redirect()->route('dashboard.premium'); - } + to_route('dashboard.premium'); } } } } catch (Exception $exception) { - \Log::error($exception->getMessage()); + \Illuminate\Support\Facades\Log::error($exception->getMessage()); } } @@ -330,7 +308,7 @@ class Inbox extends Component } $responses = []; if ($this->premium) { - if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->premium_cc_check) { + if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->premium_cc_check) { $responses = [ 'to' => Premium::getMessages($this->email, 'to', $this->deleted), 'cc' => [ @@ -344,21 +322,19 @@ class Inbox extends Component 'cc' => Premium::getMessages($this->email, 'cc', $this->deleted), ]; } + } elseif (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) { + $responses = [ + 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), + 'cc' => [ + 'data' => [], + 'notifications' => [], + ], + ]; } else { - if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->cc_check) { - $responses = [ - 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), - 'cc' => [ - 'data' => [], - 'notifications' => [], - ], - ]; - } else { - $responses = [ - 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), - 'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted), - ]; - } + $responses = [ + 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), + 'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted), + ]; } $this->deleted = []; @@ -366,7 +342,7 @@ class Inbox extends Component $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']); if (count($notifications)) { - if (! $this->overflow && count($this->messages) == $count) { + if (! $this->overflow && count($this->messages) === $count) { $this->overflow = true; } } else { @@ -397,7 +373,7 @@ class Inbox extends Component $this->initial = true; } - public function delete($messageId) + public function delete(string $messageId): void { try { @@ -422,23 +398,23 @@ class Inbox extends Component } - public function toggleMode() + public function toggleMode(): void { $this->premium = ! $this->premium; Session::put('isInboxTypePremium', $this->premium); if ($this->premium) { - $this->domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; $this->email = Premium::getEmail(); $this->emails = Premium::getEmails(); $this->initial = false; $this->checkMultipleEmails(); $this->validateDomainInEmail(); - $mailboxHistory = UsageLog::where(['user_id' => auth()->user()->id])->first(); + $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first(); $this->mailboxHistory = $mailboxHistory->emails_created_history ?? []; $this->messages = []; } else { - $this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; $this->email = ZEmail::getEmail(); $this->emails = ZEmail::getEmails(); $this->initial = false; @@ -453,17 +429,16 @@ class Inbox extends Component { if (Session::get('isSubscribed')) { return view('livewire.dashboard.mailbox.inbox')->layout('components.layouts.dashboard'); - } else { - return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } + return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); } - private function rrmdir($dir): void + private function rrmdir(string $dir): void { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { - if ($object != '.' && $object != '..') { + if ($object !== '.' && $object !== '..') { if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) { $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object); } else { diff --git a/app/Livewire/Dashboard/Pricing.php b/app/Livewire/Dashboard/Pricing.php index 7f23b93..57b819f 100644 --- a/app/Livewire/Dashboard/Pricing.php +++ b/app/Livewire/Dashboard/Pricing.php @@ -2,11 +2,13 @@ namespace App\Livewire\Dashboard; +use Illuminate\Support\Facades\Log; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use App\Models\ActivationKey; use App\Models\Plan; use Exception; use Livewire\Component; -use Log; class Pricing extends Component { @@ -34,8 +36,8 @@ class Pricing extends Component 'activation_key.max' => 'The activation key must not exceed 30 characters.', ]); - $trimmedKey = trim($this->activation_key); - $activation = ActivationKey::where('activation_key', $trimmedKey) + $trimmedKey = trim((string) $this->activation_key); + $activation = ActivationKey::query()->where('activation_key', $trimmedKey) ->where('is_activated', false) ->first(); @@ -43,7 +45,7 @@ class Pricing extends Component if ($activation->price_id !== null) { $result = $this->addSubscription($activation->price_id); } - if ($result === true) { + if ($result) { $activation->is_activated = true; $activation->user_id = auth()->id(); $activation->save(); @@ -61,7 +63,7 @@ class Pricing extends Component private function addSubscription($price_id): bool { try { - $plan = Plan::where('pricing_id', $price_id)->firstOrFail(); + $plan = Plan::query()->where('pricing_id', $price_id)->firstOrFail(); $user = auth()->user(); $user->createOrGetStripeCustomer(); $user->updateStripeCustomer([ @@ -76,11 +78,7 @@ class Pricing extends Component $balance = $user->balance(); $user->newSubscription('default', $plan->pricing_id)->create(); - if ($plan->monthly_billing == 1) { - $ends_at = now()->addMonth(); - } else { - $ends_at = now()->addYear(); - } + $ends_at = $plan->monthly_billing == 1 ? now()->addMonth() : now()->addYear(); $user->subscription('default')->cancelAt($ends_at); return true; @@ -91,7 +89,7 @@ class Pricing extends Component } } - public function render() + public function render(): Factory|View { return view('livewire.dashboard.pricing'); } diff --git a/app/Livewire/Dashboard/Support.php b/app/Livewire/Dashboard/Support.php index 4b345cc..d50d0f8 100644 --- a/app/Livewire/Dashboard/Support.php +++ b/app/Livewire/Dashboard/Support.php @@ -2,12 +2,12 @@ namespace App\Livewire\Dashboard; +use Illuminate\Support\Str; +use Illuminate\Support\Facades\Request; use App\Models\Ticket; use App\Models\TicketResponse; use Exception; use Livewire\Component; -use Request; -use Str; class Support extends Component { @@ -25,7 +25,7 @@ class Support extends Component public $closed = 0; - public function store() + public function store(): void { $this->validate([ 'subject' => 'required|string|max:255', @@ -33,7 +33,7 @@ class Support extends Component ]); try { - $ticket = Ticket::create([ + $ticket = Ticket::query()->create([ 'user_id' => auth()->id(), 'ticket_id' => strtoupper(Str::random(6)), 'subject' => $this->subject, @@ -47,13 +47,13 @@ class Support extends Component $this->tickets = Ticket::with('responses') ->where('user_id', auth()->id()) ->get(); - } catch (Exception $exception) { + } catch (Exception) { $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Something went wrong!']); } } - public function reply($ticket_id) + public function reply($ticket_id): void { $this->validate([ 'response' => 'required|string', @@ -67,14 +67,14 @@ class Support extends Component return; } - $ticket = Ticket::find($ticket_id); + $ticket = Ticket::query()->find($ticket_id); if (! $ticket) { $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']); return; } - TicketResponse::create([ + TicketResponse::query()->create([ 'ticket_id' => $ticket_id, 'user_id' => auth()->id(), 'response' => $this->response, @@ -90,20 +90,20 @@ class Support extends Component ->where('user_id', auth()->id()) ->get(); - } catch (Exception $exception) { + } catch (Exception) { session()->flash('error', 'Something went wrong!'); } } - public function close($ticket_id) + public function close($ticket_id): void { if (! is_numeric($ticket_id)) { $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Invalid ticket ID.']); return; } - $ticket = Ticket::find($ticket_id); + $ticket = Ticket::query()->find($ticket_id); if (! $ticket) { $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']); @@ -119,7 +119,7 @@ class Support extends Component $this->dispatch('showAlert', ['type' => 'error', 'message' => 'This ticket has been closed!']); } - public function mount() + public function mount(): void { $this->tickets = Ticket::with('responses') ->where('user_id', auth()->id()) @@ -127,15 +127,11 @@ class Support extends Component $this->updateTicketCounts(); } - public function updateTicketCounts() + public function updateTicketCounts(): void { - $this->open = $this->tickets->filter(function ($ticket) { - return in_array($ticket->status, ['open', 'pending']); - })->count(); + $this->open = $this->tickets->filter(fn($ticket): bool => in_array($ticket->status, ['open', 'pending']))->count(); - $this->closed = $this->tickets->filter(function ($ticket) { - return $ticket->status === 'closed'; - })->count(); + $this->closed = $this->tickets->filter(fn($ticket): bool => $ticket->status === 'closed')->count(); } protected function getClientIp() diff --git a/app/Livewire/Frontend/Action.php b/app/Livewire/Frontend/Action.php index 57044b8..a74e854 100644 --- a/app/Livewire/Frontend/Action.php +++ b/app/Livewire/Frontend/Action.php @@ -2,9 +2,13 @@ namespace App\Livewire\Frontend; +use Illuminate\Routing\Redirector; +use Illuminate\Http\RedirectResponse; +use Illuminate\Support\Facades\Date; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use App\Models\Log; use App\Models\ZEmail; -use Carbon\Carbon; use Livewire\Component; class Action extends Component @@ -23,9 +27,9 @@ class Action extends Component public $initial; - public function mount() + public function mount(): void { - $this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; $this->email = ZEmail::getEmail(); $this->emails = ZEmail::getEmails(); $this->validateDomainInEmail(); @@ -37,17 +41,17 @@ class Action extends Component return $this->showAlert('error', __('Please enter Username')); } $this->checkDomainInUsername(); - if (strlen($this->username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($this->username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { - return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_max); + if (strlen((string) $this->username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen((string) $this->username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) { + return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max); } if (! $this->domain) { return $this->showAlert('error', __('Please Select a Domain')); } - if (in_array($this->username, json_decode(config('app.settings.configuration_settings'))->forbidden_ids)) { + if (in_array($this->username, json_decode((string) config('app.settings.configuration_settings'))->forbidden_ids)) { return $this->showAlert('error', __('Username not allowed')); } if (! $this->checkEmailLimit()) { - return $this->showAlert('error', __('You have reached daily limit of MAX ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail')); + return $this->showAlert('error', __('You have reached daily limit of MAX ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail')); } if (! $this->checkUsedEmail()) { return $this->showAlert('error', __('Sorry! That email is already been used by someone else. Please try a different email address.')); @@ -55,49 +59,49 @@ class Action extends Component $this->email = ZEmail::createCustomEmail($this->username, $this->domain); - return redirect()->route('mailbox'); + return to_route('mailbox'); } public function random() { if (! $this->checkEmailLimit()) { - return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); + return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); } $this->email = ZEmail::generateRandomEmail(); - return redirect()->route('mailbox'); + return to_route('mailbox'); } public function gmail() { if (! $this->checkEmailLimit()) { - return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); + return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); } $this->email = ZEmail::generateRandomGmail(); - return redirect()->route('mailbox'); + return to_route('mailbox'); } public function outlook() { if (! $this->checkEmailLimit()) { - return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); + return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); } $this->email = ZEmail::generateRandomOutlook(); - return redirect()->route('mailbox'); + return to_route('mailbox'); } - public function deleteEmail() + public function deleteEmail(): Redirector|RedirectResponse { - return redirect()->route('delete', ['email' => $this->email]); + return to_route('delete', ['email' => $this->email]); } - private function showAlert($type, $message): void + private function showAlert(string $type, $message): void { - $check = json_decode(config('app.settings.configuration_settings'))->email_limit; - if (strpos($message, $check) !== false) { + $check = json_decode((string) config('app.settings.configuration_settings'))->email_limit; + if (str_contains((string) $message, (string) $check)) { $this->dispatch('promotePremium'); } $this->dispatch('showAlert', ['type' => $type, 'message' => $message]); @@ -105,31 +109,23 @@ class Action extends Component private function checkEmailLimit(): bool { - $logs = Log::select('ip', 'email')->where('ip', request()->ip())->where('created_at', '>', Carbon::now()->subDay())->groupBy('email')->groupBy('ip')->get(); - if (count($logs) >= json_decode(config('app.settings.configuration_settings'))->email_limit) { - return false; - } - - return true; + $logs = Log::query()->select('ip', 'email')->where('ip', request()->ip())->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get(); + return count($logs) < json_decode((string) config('app.settings.configuration_settings'))->email_limit; } private function checkUsedEmail(): bool { - if (json_decode(config('app.settings.configuration_settings'))->disable_used_email) { - $check = Log::where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); - if ($check > 0) { - return false; - } - - return true; + if (json_decode((string) config('app.settings.configuration_settings'))->disable_used_email) { + $check = Log::query()->where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); + return $check <= 0; } return true; } - private function checkDomainInUsername() + private function checkDomainInUsername(): void { - $parts = explode('@', $this->username); + $parts = explode('@', (string) $this->username); if (isset($parts[1])) { if (in_array($parts[1], $this->domains)) { $this->domain = $parts[1]; @@ -140,23 +136,23 @@ class Action extends Component private function validateDomainInEmail(): void { - $data = explode('@', $this->email); + $data = explode('@', (string) $this->email); if (isset($data[1])) { $domain = $data[1]; - $domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; if (! in_array($domain, $domains)) { $key = array_search($this->email, $this->emails); ZEmail::removeEmail($this->email); - if ($key == 0 && count($this->emails) == 1 && json_decode(config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') { - redirect()->route('home'); + if ($key == 0 && count($this->emails) === 1 && json_decode((string) config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') { + to_route('home'); } else { - redirect()->route('mailbox'); + to_route('mailbox'); } } } } - public function render() + public function render(): Factory|View { return view('livewire.frontend.action'); } diff --git a/app/Livewire/Frontend/Email.php b/app/Livewire/Frontend/Email.php index 3493df9..69a5370 100644 --- a/app/Livewire/Frontend/Email.php +++ b/app/Livewire/Frontend/Email.php @@ -2,6 +2,8 @@ namespace App\Livewire\Frontend; +use Illuminate\Routing\Redirector; +use Illuminate\Http\RedirectResponse; use App\Models\ZEmail; use Livewire\Component; @@ -29,26 +31,22 @@ class Email extends Component private function checkMultipleEmails(): void { - if (count($this->emails) == 0) { + if (count($this->emails) === 0) { $this->emails = [$this->email]; } - if (count($this->emails) > 1) { - $this->list = true; - } else { - $this->list = false; - } + $this->list = count($this->emails) > 1; } - public function switchEmail($email) + public function switchEmail($email): Redirector|RedirectResponse { - return redirect()->route('switch', ['email' => $email]); + return to_route('switch', ['email' => $email]); } public function syncEmail(): void { $this->email = ZEmail::getEmail(); $this->emails = ZEmail::getEmails(); - if (count($this->emails) == 0) { + if (count($this->emails) === 0) { $this->dispatch('getEmail'); } $this->checkMultipleEmails(); diff --git a/app/Livewire/Frontend/Mailbox.php b/app/Livewire/Frontend/Mailbox.php index c0a6c68..4489999 100644 --- a/app/Livewire/Frontend/Mailbox.php +++ b/app/Livewire/Frontend/Mailbox.php @@ -38,8 +38,9 @@ class Mailbox extends Component $this->email = ZEmail::getEmail(); $this->initial = false; if (! ZEmail::getEmail()) { - return redirect()->route('home'); + return to_route('home'); } + return null; } public function syncEmail($email): void @@ -57,7 +58,7 @@ class Mailbox extends Component $this->messages = []; } $responses = []; - if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->cc_check) { + if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) { $responses = [ 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), 'cc' => [ @@ -77,7 +78,7 @@ class Mailbox extends Component $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']); if (count($notifications)) { - if (! $this->overflow && count($this->messages) == $count) { + if (! $this->overflow && count($this->messages) === $count) { $this->overflow = true; } } else { @@ -99,15 +100,15 @@ class Mailbox extends Component $this->initial = true; } - public function delete($messageId) + public function delete(string $messageId): void { try { if (config('app.beta_feature')) { - Message::find($messageId)->delete(); + Message::query()->find($messageId)->delete(); } if (config('app.fetch_from_db')) { - Email::where(['message_id' => $messageId])->delete(); + Email::query()->where(['message_id' => $messageId])->delete(); } $this->deleted[] = $messageId; foreach ($this->messages as $key => $message) { @@ -131,12 +132,12 @@ class Mailbox extends Component return view('livewire.frontend.mailbox')->with(['messages' => $this->messages, 'email' => $this->email, 'initial' => $this->initial, 'error' => $this->error]); } - private function rrmdir($dir): void + private function rrmdir(string $dir): void { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { - if ($object != '.' && $object != '..') { + if ($object !== '.' && $object !== '..') { if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) { $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object); } else { diff --git a/app/Livewire/Home.php b/app/Livewire/Home.php index 1859296..c29ba2d 100644 --- a/app/Livewire/Home.php +++ b/app/Livewire/Home.php @@ -2,6 +2,8 @@ namespace App\Livewire; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use App\Models\ZEmail; use Livewire\Component; @@ -14,11 +16,12 @@ class Home extends Component $email = ZEmail::getEmail(); $messages = ZEmail::getMessages($email); if (count($messages['data']) > 0) { - return redirect()->route('mailbox'); + return to_route('mailbox'); } + return null; } - public function render() + public function render(): Factory|View { return view('livewire.home'); } diff --git a/app/Livewire/ListBlog.php b/app/Livewire/ListBlog.php index b4b62d6..9cf359f 100644 --- a/app/Livewire/ListBlog.php +++ b/app/Livewire/ListBlog.php @@ -2,11 +2,13 @@ namespace App\Livewire; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use Livewire\Component; class ListBlog extends Component { - public function render() + public function render(): Factory|View { return view('livewire.list-blog'); } diff --git a/app/Livewire/Page.php b/app/Livewire/Page.php index 8186614..6b9cf08 100644 --- a/app/Livewire/Page.php +++ b/app/Livewire/Page.php @@ -2,24 +2,24 @@ namespace App\Livewire; +use Illuminate\Contracts\View\Factory; +use Illuminate\Contracts\View\View; use Livewire\Component; class Page extends Component { public $slug; - public function mount($slug) + public function mount($slug): void { $this->slug = $slug; } - public function render() + public function render(): Factory|View { - $page = \App\Models\Page::where('slug', $this->slug)->firstOrFail(); + $page = \App\Models\Page::query()->where('slug', $this->slug)->firstOrFail(); - if ($page->is_published == false) { - abort(404); - } + abort_if($page->is_published == false, 404); return view('livewire.page', [ 'page' => $page, diff --git a/app/Mail/TicketResponseNotification.php b/app/Mail/TicketResponseNotification.php index 1526420..b6adc72 100644 --- a/app/Mail/TicketResponseNotification.php +++ b/app/Mail/TicketResponseNotification.php @@ -15,17 +15,11 @@ class TicketResponseNotification extends Mailable { use Queueable, SerializesModels; - public Ticket $ticket; - - public Collection $responses; - /** * Create a new message instance. */ - public function __construct(Ticket $ticket, Collection $responses) + public function __construct(public Ticket $ticket, public Collection $responses) { - $this->ticket = $ticket; - $this->responses = $responses; } /** diff --git a/app/Models/ActivationKey.php b/app/Models/ActivationKey.php index 40bd91f..f344b2e 100644 --- a/app/Models/ActivationKey.php +++ b/app/Models/ActivationKey.php @@ -2,6 +2,7 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -31,7 +32,8 @@ class ActivationKey extends Model /** * Scope to filter unactivated keys */ - public function scopeUnactivated($query) + #[Scope] + protected function unactivated($query) { return $query->where('is_activated', false); } @@ -39,7 +41,8 @@ class ActivationKey extends Model /** * Scope to filter activated keys */ - public function scopeActivated($query) + #[Scope] + protected function activated($query) { return $query->where('is_activated', true); } diff --git a/app/Models/Email.php b/app/Models/Email.php index 902164b..6fa8011 100644 --- a/app/Models/Email.php +++ b/app/Models/Email.php @@ -2,13 +2,13 @@ namespace App\Models; +use DateTimeImmutable; +use Illuminate\Support\Facades\Date; use App\ColorPicker; -use Carbon\Carbon; use Carbon\CarbonImmutable; use DateTime; use Ddeboer\Imap\ConnectionInterface; use Ddeboer\Imap\Search\Date\Since; -use Ddeboer\Imap\Search\Email\To; use Ddeboer\Imap\Server; use Exception; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -55,20 +55,16 @@ class Email extends Model public static function connectMailBox($imap = null): ConnectionInterface { if ($imap === null) { - $imap = json_decode(config('app.settings.imap_settings'), true); + $imap = json_decode((string) config('app.settings.imap_settings'), true); } $flags = $imap['protocol'].'/'.$imap['encryption']; - if ($imap['validate_cert']) { - $flags = $flags.'/validate-cert'; - } else { - $flags = $flags.'/novalidate-cert'; - } + $flags = $imap['validate_cert'] ? $flags.'/validate-cert' : $flags.'/novalidate-cert'; $server = new Server($imap['host'], $imap['port'], $flags); return $server->authenticate($imap['username'], $imap['password']); } - public static function fetchProcessStoreEmail() + public static function fetchProcessStoreEmail(): void { try { @@ -82,7 +78,7 @@ class Email extends Model $sender = $message->getFrom(); $date = $message->getDate(); - if (! $date) { + if (!$date instanceof DateTimeImmutable) { $date = new DateTime; if ($message->getHeaders()->get('udate')) { $date->setTimestamp($message->getHeaders()->get('udate')); @@ -104,17 +100,11 @@ class Email extends Model $obj = []; - $to = $message->getHeaders()->get('To') ? array_map(function ($entry) { - return $entry->mailbox.'@'.$entry->host; - }, $message->getHeaders()->get('To')) : []; + $to = $message->getHeaders()->get('To') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('To')) : []; - $cc = $message->getHeaders()->get('Cc') ? array_map(function ($entry) { - return $entry->mailbox.'@'.$entry->host; - }, $message->getHeaders()->get('Cc')) : []; + $cc = $message->getHeaders()->get('Cc') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('Cc')) : []; - $bcc = $message->getHeaders()->get('Bcc') ? array_map(function ($entry) { - return $entry->mailbox.'@'.$entry->host; - }, $message->getHeaders()->get('Bcc')) : []; + $bcc = $message->getHeaders()->get('Bcc') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('Bcc')) : []; $messageTime = $message->getDate(); $utcTime = CarbonImmutable::instance($messageTime)->setTimezone('UTC')->toDateTimeString(); @@ -139,9 +129,11 @@ class Email extends Model $attachments = $message->getAttachments(); $directory = './tmp/attachments/'.$obj['id'].'/'; - is_dir($directory) || mkdir($directory, 0777, true); + if (!is_dir($directory)) { + mkdir($directory, 0777, true); + } foreach ($attachments as $attachment) { - $filenameArray = explode('.', $attachment->getFilename()); + $filenameArray = explode('.', (string) $attachment->getFilename()); $extension = $filenameArray[count($filenameArray) - 1]; if (in_array($extension, $allowed)) { if (! file_exists($directory.$attachment->getFilename())) { @@ -177,7 +169,7 @@ class Email extends Model if (! $message->isSeen()) { $initialData = $obj; $data = [ - 'message_id' => Carbon::parse($utcTime)->format('Ymd').$initialData['id'], + 'message_id' => Date::parse($utcTime)->format('Ymd').$initialData['id'], 'subject' => $initialData['subject'], 'from_name' => $initialData['sender_name'], 'from_email' => $initialData['sender_email'], @@ -197,7 +189,7 @@ class Email extends Model ]; try { - self::create($data); + self::query()->create($data); $checkAction = config('app.move_or_delete'); if ($checkAction != null) { if ($checkAction == 'delete') { @@ -208,13 +200,13 @@ class Email extends Model } } - } catch (Exception $e) { + } catch (Exception) { // \Log::error($e); } } else { $initialData = $obj; $data = [ - 'message_id' => Carbon::parse($utcTime)->format('Ymd').$initialData['id'], + 'message_id' => Date::parse($utcTime)->format('Ymd').$initialData['id'], 'subject' => $initialData['subject'], 'from_name' => $initialData['sender_name'], 'from_email' => $initialData['sender_email'], @@ -234,7 +226,7 @@ class Email extends Model ]; try { - self::create($data); + self::query()->create($data); $checkAction = config('app.move_or_delete'); if ($checkAction != null) { if ($checkAction == 'delete') { @@ -245,7 +237,7 @@ class Email extends Model } } - } catch (Exception $e) { + } catch (Exception) { // \Log::error($e); } } @@ -263,24 +255,24 @@ class Email extends Model { $validator = Validator::make(['email' => $email], [ - 'email' => 'required|email', + 'email' => ['required', 'email'], ]); if ($validator->fails()) { return []; } - return self::whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); + return self::query()->whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); } - public static function parseEmail($email, $deleted = []): array + public static function parseEmail(string $email, $deleted = []): array { if (config('app.fetch_from_remote_db')) { $messages = RemoteEmail::fetchEmailFromDB($email); } else { $messages = self::fetchEmailFromDB($email); } - $limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; + $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $count = 1; $response = [ 'data' => [], @@ -297,9 +289,9 @@ class Email extends Model if (in_array($message['message_id'], $deleted)) { // If it exists, delete the matching record from the 'emails' table if (config('app.fetch_from_remote_db')) { - RemoteEmail::where('message_id', $message['message_id'])->delete(); + RemoteEmail::query()->where('message_id', $message['message_id'])->delete(); } else { - Email::where('message_id', $message['message_id'])->delete(); + Email::query()->where('message_id', $message['message_id'])->delete(); } continue; @@ -308,23 +300,23 @@ class Email extends Model $blocked = false; $timestamp = $message['timestamp']; - $carbonTimestamp = Carbon::parse($timestamp, 'UTC'); + $carbonTimestamp = Date::parse($timestamp, 'UTC'); $obj = []; $obj['subject'] = $message['subject']; $obj['sender_name'] = $message['from_name']; $obj['sender_email'] = $message['from_email']; $obj['timestamp'] = $message['timestamp']; $obj['date'] = $carbonTimestamp->format('d M Y h:i A'); - $obj['datediff'] = $carbonTimestamp->diffForHumans(Carbon::now('UTC')); + $obj['datediff'] = $carbonTimestamp->diffForHumans(Date::now('UTC')); $obj['id'] = $message['message_id']; $obj['content'] = $message['body_html']; $obj['contentText'] = $message['body_text']; $obj['attachments'] = []; $obj['is_seen'] = $message['is_seen']; - $obj['sender_photo'] = self::chooseColor(strtoupper(substr($message['from_name'] ?: $message['from_email'], 0, 1))); + $obj['sender_photo'] = self::chooseColor(strtoupper(substr((string) $message['from_name'] ?: (string) $message['from_email'], 0, 1))); - $domain = explode('@', $obj['sender_email'])[1]; - $blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); + $domain = explode('@', (string) $obj['sender_email'])[1]; + $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains); if ($blocked) { $obj['subject'] = __('Blocked'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); @@ -348,9 +340,9 @@ class Email extends Model } } if (config('app.fetch_from_remote_db')) { - RemoteEmail::where('message_id', $message['message_id'])->update(['is_seen' => true]); + RemoteEmail::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]); } else { - Email::where('message_id', $message['message_id'])->update(['is_seen' => true]); + Email::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]); } if (++$count > $limit) { break; @@ -360,7 +352,7 @@ class Email extends Model return $response; } - public static function deleteBulkAttachments() + public static function deleteBulkAttachments(): void { $dir = public_path('/tmp/attachments'); @@ -373,7 +365,7 @@ class Email extends Model } } - public static function deleteBulkMailboxes() + public static function deleteBulkMailboxes(): string { $foldersToClean = ['INBOX', 'ZDUMP', 'Trash']; $cutoff = (new DateTime)->modify('-3 hours'); @@ -410,15 +402,15 @@ class Email extends Model return "$totalDeleted message(s) deleted from Trash and ZDUMP."; } - public static function deleteMessagesFromDB() + public static function deleteMessagesFromDB(): string { - $cutoff = Carbon::now('UTC')->subHours(6)->toDateTimeString(); - $count = count(self::where('timestamp', '<', $cutoff) + $cutoff = Date::now('UTC')->subHours(6)->toDateTimeString(); + $count = count(self::query()->where('timestamp', '<', $cutoff) ->orderBy('timestamp', 'desc') ->get()); if ($count > 0) { - self::where('timestamp', '<', $cutoff)->delete(); + self::query()->where('timestamp', '<', $cutoff)->delete(); return "$count old message(s) deleted from the database."; } @@ -429,22 +421,17 @@ class Email extends Model public static function mailToDBStatus(): bool { if (config('app.fetch_from_remote_db')) { - $latestRecord = RemoteEmail::orderBy('timestamp', 'desc')->first(); + $latestRecord = RemoteEmail::query()->orderBy('timestamp', 'desc')->first(); } else { - $latestRecord = self::orderBy('timestamp', 'desc')->first(); + $latestRecord = self::query()->orderBy('timestamp', 'desc')->first(); } if (! $latestRecord) { return false; } - $currentTime = Carbon::now('UTC'); - $lastRecordTime = Carbon::parse($latestRecord->timestamp); - - if ($lastRecordTime->diffInMinutes($currentTime) < 5) { - return true; - } - - return false; + $currentTime = Date::now('UTC'); + $lastRecordTime = Date::parse($latestRecord->timestamp); + return $lastRecordTime->diffInMinutes($currentTime) < 5; } public static function cleanMailbox(): string diff --git a/app/Models/Log.php b/app/Models/Log.php index b844b64..e5577c0 100644 --- a/app/Models/Log.php +++ b/app/Models/Log.php @@ -2,7 +2,7 @@ namespace App\Models; -use Carbon\Carbon; +use Illuminate\Support\Facades\Date; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -26,15 +26,14 @@ class Log extends Model return $this->belongsTo(User::class); } - public static function deleteLogsFromDB() + public static function deleteLogsFromDB(): string { - $cutoff = Carbon::now('UTC')->subMonths(3)->toDateTimeString(); - $count = count(self::where('created_at', '<', $cutoff) - ->orderBy('created_at', 'desc') + $cutoff = Date::now('UTC')->subMonths(3)->toDateTimeString(); + $count = count(self::query()->where('created_at', '<', $cutoff)->latest() ->get()); if ($count > 0) { - self::where('created_at', '<', $cutoff)->delete(); + self::query()->where('created_at', '<', $cutoff)->delete(); return "$count old log(s) deleted from the database."; } diff --git a/app/Models/Message.php b/app/Models/Message.php index 5652408..2dc98eb 100644 --- a/app/Models/Message.php +++ b/app/Models/Message.php @@ -2,6 +2,7 @@ namespace App\Models; +use DateTimeImmutable; use App\ColorPicker; use Carbon\Carbon; use DateTime; @@ -34,21 +35,19 @@ class Message extends Model $message->subject = $request->subject; $message->from = $request->from; $message->to = $request->to; - if ($request->has('html')) { - $message->body = $request->html; - } else { - $message->body = $request->text; - } + $message->body = $request->has('html') ? $request->html : $request->text; $message->save(); if ($request->has('content-ids')) { $message->attachments = $request->get('attachment-info'); $message->save(); $directory = './attachments/'.$message->id; - is_dir($directory) || mkdir($directory, 0777, true); - $attachment_ids = json_decode($request->get('attachment-info')); + if (!is_dir($directory)) { + mkdir($directory, 0777, true); + } + $attachment_ids = json_decode((string) $request->get('attachment-info')); foreach ($attachment_ids as $attachment_id => $attachment_info) { $allowed = explode(',', 'csv,doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt'); - $file = explode('.', $attachment_info->filename); + $file = explode('.', (string) $attachment_info->filename); if (in_array($file[count($file) - 1], $allowed)) { Storage::disk('tmp')->putFileAs($directory, $request->file($attachment_id), $attachment_info->filename); } @@ -56,53 +55,47 @@ class Message extends Model } } - public static function getMessages($email): array + public static function getMessages(string $email): array { - $limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; - $messages = Message::where('to', $email)->orWhere('to', 'like', '%<'.$email.'>%')->limit($limit)->get(); + $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; + $messages = Message::query()->where('to', $email)->orWhere('to', 'like', '%<'.$email.'>%')->limit($limit)->get(); $response = [ 'data' => [], 'notifications' => [], ]; foreach ($messages as $message) { $content = str_replace('body); - if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { + if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) { $content = str_replace('href="', 'href="https://href.li/?', $content); } $obj = []; $obj['subject'] = $message->subject; - $sender = explode('<', $message->from); + $sender = explode('<', (string) $message->from); $obj['sender_name'] = $sender[0]; - if (isset($sender[1])) { - $obj['sender_email'] = str_replace('>', '', $sender[1]); - } else { - $obj['sender_email'] = $obj['sender_name']; - } + $obj['sender_email'] = isset($sender[1]) ? str_replace('>', '', $sender[1]) : $obj['sender_name']; $obj['timestamp'] = $message->created_at; - $obj['date'] = $message->created_at->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); + $obj['date'] = $message->created_at->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['datediff'] = $message->created_at->diffForHumans(); $obj['id'] = $message->id; $obj['content'] = $content; $obj['attachments'] = []; $domain = explode('@', $obj['sender_email'])[1]; - $blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); + $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains); if ($blocked) { $obj['subject'] = __('Blocked'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); } if ($message->attachments && ! $blocked) { - $attachments = json_decode($message->attachments); + $attachments = json_decode((string) $message->attachments); foreach ($attachments as $id => $attachment) { $url = config('app.settings.app_base_url').'/tmp/attachments/'.$message->id.'/'.$attachment->filename; - if (str_contains($obj['content'], $id)) { + if (str_contains($obj['content'], (string) $id)) { $obj['content'] = str_replace('cid:'.$id, $url, $obj['content']); - } else { - if (Storage::disk('tmp')->exists('attachments/'.$message->id.'/'.$attachment->filename)) { - $obj['attachments'][] = [ - 'file' => $attachment->filename, - 'url' => $url, - ]; - } + } elseif (Storage::disk('tmp')->exists('attachments/'.$message->id.'/'.$attachment->filename)) { + $obj['attachments'][] = [ + 'file' => $attachment->filename, + 'url' => $url, + ]; } } } @@ -124,7 +117,7 @@ class Message extends Model return $response; } - public static function fetchMessages($email, $type = 'to', $deleted = []): array + public static function fetchMessages(string $email, $type = 'to', $deleted = []): array { $allowed = explode(',', 'doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt'); $connection = ZEmail::connectMailBox(); @@ -137,7 +130,7 @@ class Message extends Model $search->addCondition(new To($email)); } $messages = $mailbox->getMessages($search, \SORTDATE, true); - $limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; + $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $count = 1; $response = [ 'data' => [], @@ -153,7 +146,7 @@ class Message extends Model $blocked = false; $sender = $message->getFrom(); $date = $message->getDate(); - if (! $date) { + if (!$date instanceof DateTimeImmutable) { $date = new DateTime; if ($message->getHeaders()->get('udate')) { $date->setTimestamp($message->getHeaders()->get('udate')); @@ -172,7 +165,7 @@ class Message extends Model } else { $content = str_replace('', $text)); } - if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { + if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) { $content = str_replace('href="', 'href="http://href.li/?', $content); } $obj = []; @@ -180,18 +173,18 @@ class Message extends Model $obj['sender_name'] = $sender->getName(); $obj['sender_email'] = $sender->getAddress(); $obj['timestamp'] = $message->getDate(); - $obj['date'] = $date->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); + $obj['date'] = $date->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['datediff'] = $datediff->diffForHumans(); $obj['id'] = $message->getNumber(); $obj['content'] = $content; $obj['contentText'] = $contentText; $obj['attachments'] = []; $obj['is_seen'] = true; - $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: $sender->getAddress(), 0, 1))); + $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: (string) $sender->getAddress(), 0, 1))); // Checking if Sender is Blocked - $domain = explode('@', $obj['sender_email'])[1]; - $blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); + $domain = explode('@', (string) $obj['sender_email'])[1]; + $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains); if ($blocked) { $obj['subject'] = __('Blocked'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); @@ -200,9 +193,11 @@ class Message extends Model if ($message->hasAttachments() && ! $blocked) { $attachments = $message->getAttachments(); $directory = './tmp/attachments/'.$obj['id'].'/'; - is_dir($directory) || mkdir($directory, 0777, true); + if (!is_dir($directory)) { + mkdir($directory, 0777, true); + } foreach ($attachments as $attachment) { - $filenameArray = explode('.', $attachment->getFilename()); + $filenameArray = explode('.', (string) $attachment->getFilename()); $extension = $filenameArray[count($filenameArray) - 1]; if (in_array($extension, $allowed)) { if (! file_exists($directory.$attachment->getFilename())) { @@ -218,7 +213,7 @@ class Message extends Model if ($attachment->getFilename() !== 'undefined') { $url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename()); $structure = $attachment->getStructure(); - if (isset($structure->id) && str_contains($obj['content'], trim($structure->id, '<>'))) { + if (isset($structure->id) && str_contains((string) $obj['content'], trim($structure->id, '<>'))) { $obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']); } $obj['attachments'][] = [ diff --git a/app/Models/Meta.php b/app/Models/Meta.php index 92c5b00..f23f0f2 100644 --- a/app/Models/Meta.php +++ b/app/Models/Meta.php @@ -14,9 +14,9 @@ class Meta extends Model 'value', ]; - public function incrementMeta($value = 1) + public function incrementMeta($value = 1): bool { - $this->value = $this->value + $value; + $this->value += $value; $this->save(); return true; @@ -24,7 +24,7 @@ class Meta extends Model public static function incrementEmailIdsCreated($value = 1): bool { - $meta = Meta::where('key', 'email_ids_created')->first(); + $meta = Meta::query()->where('key', 'email_ids_created')->first(); if ($meta) { $meta->incrementMeta($value); @@ -36,7 +36,7 @@ class Meta extends Model public static function incrementMessagesReceived($value = 1): bool { - $meta = Meta::where('key', 'messages_received')->first(); + $meta = Meta::query()->where('key', 'messages_received')->first(); if ($meta) { $meta->incrementMeta($value); @@ -48,7 +48,7 @@ class Meta extends Model public static function getEmailIdsCreated() { - $meta = Meta::where('key', 'email_ids_created')->first(); + $meta = Meta::query()->where('key', 'email_ids_created')->first(); if ($meta) { return $meta->value; } @@ -58,7 +58,7 @@ class Meta extends Model public static function getMessagesReceived() { - $meta = Meta::where('key', 'messages_received')->first(); + $meta = Meta::query()->where('key', 'messages_received')->first(); if ($meta) { return $meta->value; } diff --git a/app/Models/Premium.php b/app/Models/Premium.php index 6b3710f..38cd1f8 100644 --- a/app/Models/Premium.php +++ b/app/Models/Premium.php @@ -2,6 +2,9 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; +use DateTimeImmutable; +use Illuminate\Support\Facades\Log; use App\ColorPicker; use Carbon\Carbon; use DateTime; @@ -13,15 +16,16 @@ use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cookie; -use Log; class Premium extends Model { + use HasFactory; + use HasFactory; use ColorPicker; public static function connectMailBox($imap = null): ConnectionInterface { - $imapDB = json_decode(config('app.settings.imap_settings'), true); + $imapDB = json_decode((string) config('app.settings.imap_settings'), true); $imap = [ 'host' => $imapDB['premium_host'], 'port' => $imapDB['premium_port'], @@ -37,7 +41,7 @@ class Premium extends Model return ZEmail::connectMailBox($imap); } - public static function fetchMessages($email, $type = 'to', $deleted = []): array + public static function fetchMessages(?string $email, $type = 'to', $deleted = []): array { if ($email == null) { return [ @@ -56,7 +60,7 @@ class Premium extends Model $search->addCondition(new To($email)); } $messages = $mailbox->getMessages($search, \SORTDATE, true); - $limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; + $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $count = 1; $response = [ 'data' => [], @@ -71,7 +75,7 @@ class Premium extends Model $blocked = false; $sender = $message->getFrom(); $date = $message->getDate(); - if (! $date) { + if (!$date instanceof DateTimeImmutable) { $date = new DateTime; if ($message->getHeaders()->get('udate')) { $date->setTimestamp($message->getHeaders()->get('udate')); @@ -90,7 +94,7 @@ class Premium extends Model } else { $content = str_replace('', $text)); } - if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { + if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) { $content = str_replace('href="', 'href="http://href.li/?', $content); } @@ -99,7 +103,7 @@ class Premium extends Model $obj['sender_name'] = $sender->getName(); $obj['sender_email'] = $sender->getAddress(); $obj['timestamp'] = $message->getDate(); - $obj['date'] = $date->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); + $obj['date'] = $date->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['datediff'] = $datediff->diffForHumans(); $obj['id'] = $message->getNumber(); $obj['size'] = $message->getSize(); @@ -107,11 +111,11 @@ class Premium extends Model $obj['contentText'] = $contentText; $obj['attachments'] = []; $obj['is_seen'] = true; - $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: $sender->getAddress(), 0, 1))); + $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: (string) $sender->getAddress(), 0, 1))); // Checking if Sender is Blocked - $domain = explode('@', $obj['sender_email'])[1]; - $blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); + $domain = explode('@', (string) $obj['sender_email'])[1]; + $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains); if ($blocked) { $obj['subject'] = __('Blocked'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); @@ -120,9 +124,11 @@ class Premium extends Model if ($message->hasAttachments() && ! $blocked) { $attachments = $message->getAttachments(); $directory = './tmp/premium/attachments/'.$obj['id'].'/'; - is_dir($directory) || mkdir($directory, 0777, true); + if (!is_dir($directory)) { + mkdir($directory, 0777, true); + } foreach ($attachments as $attachment) { - $filenameArray = explode('.', $attachment->getFilename()); + $filenameArray = explode('.', (string) $attachment->getFilename()); $extension = $filenameArray[count($filenameArray) - 1]; if (in_array($extension, $allowed)) { if (! file_exists($directory.$attachment->getFilename())) { @@ -132,13 +138,13 @@ class Premium extends Model $attachment->getDecodedContent() ); } catch (Exception $e) { - \Illuminate\Support\Facades\Log::error($e->getMessage()); + Log::error($e->getMessage()); } } if ($attachment->getFilename() !== 'undefined') { $url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename()); $structure = $attachment->getStructure(); - if (isset($structure->id) && str_contains($obj['content'], trim($structure->id, '<>'))) { + if (isset($structure->id) && str_contains((string) $obj['content'], trim($structure->id, '<>'))) { $obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']); } $obj['attachments'][] = [ @@ -172,12 +178,12 @@ class Premium extends Model return $response; } - public static function getMessages($email, $type = 'to', $deleted = []): array + public static function getMessages(?string $email, $type = 'to', $deleted = []): array { return self::fetchMessages($email, $type, $deleted); } - public static function deleteMessage($id): void + public static function deleteMessage(int $id): void { $connection = self::connectMailBox(); $mailbox = $connection->getMailbox('INBOX'); @@ -189,18 +195,16 @@ class Premium extends Model { if (Cookie::has('p_email')) { return Cookie::get('p_email'); - } else { - return $generate ? self::generateRandomEmail() : null; } + return $generate ? self::generateRandomEmail() : null; } public static function getEmails() { if (Cookie::has('p_emails')) { return unserialize(Cookie::get('p_emails')); - } else { - return []; } + return []; } public static function setEmail($email): void @@ -213,7 +217,7 @@ class Premium extends Model public static function setEmailP($email): void { - $usageLogs = UsageLog::where(['user_id' => auth()->user()->id])->first(); + $usageLogs = UsageLog::query()->where(['user_id' => auth()->user()->id])->first(); $emails = $usageLogs->emails_created_history; if (is_array($emails) && in_array($email, $emails)) { Cookie::queue('p_email', $email, 43800); @@ -238,9 +242,9 @@ class Premium extends Model public static function createCustomEmailFull($email): string { - $data = explode('@', $email); + $data = explode('@', (string) $email); $username = $data[0]; - if (strlen($username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { + if (strlen($username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) { $zemail = new Premium; $username = $zemail->generateRandomUsername(); } @@ -249,11 +253,11 @@ class Premium extends Model return self::createCustomEmail($username, $domain); } - public static function createCustomEmail($username, $domain): string + public static function createCustomEmail($username, string $domain): string { - $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower($username)); + $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower((string) $username)); - $settings = json_decode(config('app.settings.configuration_settings'), true); + $settings = json_decode((string) config('app.settings.configuration_settings'), true); $forbidden_ids = $settings['forbidden_ids'] ?? []; $gmail_usernames = $settings['premium_gmailUsernames'] ?? []; $outlook_usernames = $settings['premium_outlookUsernames'] ?? []; @@ -267,7 +271,7 @@ class Premium extends Model return self::generateRandomGmail(true); } - if ($username === '' && in_array($domain, ['outlook.com'])) { + if ($username === '' && $domain === 'outlook.com') { return self::generateRandomOutlook(true); } @@ -277,9 +281,9 @@ class Premium extends Model return $zemail->generateRandomUsername().'@'.$domain; } - if (in_array($domain, ['outlook.com'])) { - if (str_contains($username, '+')) { - [$check_username, $post_username] = explode('+', $username, 2); + if ($domain === 'outlook.com') { + if (str_contains((string) $username, '+')) { + [$check_username, $post_username] = explode('+', (string) $username, 2); if (in_array($check_username, $outlook_usernames)) { $email = $username.'@'.$domain; @@ -295,8 +299,8 @@ class Premium extends Model } if (in_array($domain, ['gmail.com', 'googlemail.com'])) { - if (str_contains($username, '+')) { - [$check_username, $post_username] = explode('+', $username, 2); + if (str_contains((string) $username, '+')) { + [$check_username, $post_username] = explode('+', (string) $username, 2); if (in_array($check_username, $gmail_usernames)) { $email = $username.'@'.$domain; @@ -304,7 +308,7 @@ class Premium extends Model $email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain; } - } elseif (str_contains($username, '.')) { + } elseif (str_contains((string) $username, '.')) { $check_username = str_replace('.', '', $username); if (in_array($check_username, $gmail_usernames)) { @@ -341,14 +345,14 @@ class Premium extends Model $domain = $zemail->getRandomDomain(); if ($domain == 'gmail.com') { $rd = mt_rand(0, 1); - if ($rd == 0) { + if ($rd === 0) { $email = $zemail->generateRandomGmail(false); } else { $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com'; } } elseif ($domain == 'googlemail.com') { $rd = mt_rand(0, 1); - if ($rd == 0) { + if ($rd === 0) { $email = $zemail->generateRandomGmail(false); } else { $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com'; @@ -369,11 +373,11 @@ class Premium extends Model { $zemail = new Premium; $uname = $zemail->getRandomGmailUser(); - $uname_len = strlen($uname); + $uname_len = strlen((string) $uname); $len_power = $uname_len - 1; - $combination = pow(2, $len_power); - $rand_comb = mt_rand(1, $combination); - $formatted = implode(' ', str_split($uname)); + $combination = 2 ** $len_power; + mt_rand(1, $combination); + $formatted = implode(' ', str_split((string) $uname)); $uname_exp = explode(' ', $formatted); $bin = intval(''); @@ -385,7 +389,7 @@ class Premium extends Model $email = ''; for ($i = 0; $i < $len_power; $i++) { $email .= $uname_exp[$i]; - if ($bin[$i]) { + if ($bin[$i] !== '' && $bin[$i] !== '0') { $email .= '.'; } } @@ -414,7 +418,7 @@ class Premium extends Model return $email; } - private static function storeEmail($email): void + private static function storeEmail(string $email): void { Log::create([ 'user_id' => auth()->user()->id, @@ -447,8 +451,8 @@ class Premium extends Model private function generateRandomUsername(): string { - $start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; - $end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; + $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0; + $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0; if ($start == 0 && $end == 0) { return $this->generatePronounceableWord(); } @@ -458,33 +462,33 @@ class Premium extends Model protected function generatedRandomBetweenLength($start, $end): string { - $length = rand($start, $end); + $length = random_int($start, $end); return $this->generateRandomString($length); } private function getRandomDomain() { - $domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? []; $count = count($domains); - return $count > 0 ? $domains[rand(1, $count) - 1] : ''; + return $count > 0 ? $domains[random_int(1, $count) - 1] : ''; } private function getRandomGmailUser() { - $gmailusername = json_decode(config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; + $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; $count = count($gmailusername); - return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; + return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : ''; } private function getRandomOutlookUser() { - $outlook_username = json_decode(config('app.settings.configuration_settings'))->premium_outlookUsernames ?? []; + $outlook_username = json_decode((string) config('app.settings.configuration_settings'))->premium_outlookUsernames ?? []; $count = count($outlook_username); - return $count > 0 ? $outlook_username[rand(1, $count) - 1] : ''; + return $count > 0 ? $outlook_username[random_int(1, $count) - 1] : ''; } private function generatePronounceableWord(): string @@ -494,21 +498,21 @@ class Premium extends Model $a = $c.$v; // both $random = ''; for ($j = 0; $j < 2; $j++) { - $random .= $c[rand(0, strlen($c) - 1)]; - $random .= $v[rand(0, strlen($v) - 1)]; - $random .= $a[rand(0, strlen($a) - 1)]; + $random .= $c[random_int(0, strlen($c) - 1)]; + $random .= $v[random_int(0, strlen($v) - 1)]; + $random .= $a[random_int(0, strlen($a) - 1)]; } return $random; } - private function generateRandomString($length = 10): string + private function generateRandomString(int $length = 10): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; + $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; @@ -524,10 +528,7 @@ class Premium extends Model return; } - $usageLog = UsageLog::firstOrCreate( - ['user_id' => $user->id], - ['ip_address' => request()->ip()] - ); + $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => request()->ip()]); $usageLog->increment('emails_created_count', $count); } @@ -539,10 +540,7 @@ class Premium extends Model return; } - $usageLog = UsageLog::firstOrCreate( - ['user_id' => $user->id], - ['ip_address' => request()->ip()] - ); + $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => request()->ip()]); $usageLog->increment('emails_received_count', $count); } @@ -556,10 +554,7 @@ class Premium extends Model } $ip = request()->ip(); - $usageLog = UsageLog::firstOrCreate( - ['user_id' => $user->id], - ['ip_address' => $ip] - ); + $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => $ip]); $history = $usageLog->emails_created_history ?? []; if (! in_array($email, $history)) { diff --git a/app/Models/PremiumEmail.php b/app/Models/PremiumEmail.php index cbbd2d3..efb97dd 100644 --- a/app/Models/PremiumEmail.php +++ b/app/Models/PremiumEmail.php @@ -2,8 +2,8 @@ namespace App\Models; +use Illuminate\Support\Facades\Date; use App\ColorPicker; -use Carbon\Carbon; use Carbon\CarbonImmutable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -48,7 +48,7 @@ class PremiumEmail extends Model return $this->belongsTo(User::class); } - public static function createEmail($message, $email): void + public static function createEmail(array $message, $email): void { $initialData = $message; if (config('app.fetch_from_db') && config('app.fetch_from_remote_db')) { @@ -56,9 +56,9 @@ class PremiumEmail extends Model } else { $utcTime = CarbonImmutable::instance($message['timestamp'])->setTimezone('UTC')->toDateTimeString(); } - $messageId = Carbon::parse($utcTime)->format('Ymd').$initialData['id']; + $messageId = Date::parse($utcTime)->format('Ymd').$initialData['id']; $userId = \auth()->user()->id; - $exists = PremiumEmail::where('user_id', $userId)->where('message_id', $messageId)->exists(); + $exists = PremiumEmail::query()->where('user_id', $userId)->where('message_id', $messageId)->exists(); $data = [ 'user_id' => $userId, @@ -82,7 +82,7 @@ class PremiumEmail extends Model ]; if (! $exists) { - PremiumEmail::create($data); + PremiumEmail::query()->create($data); } } @@ -90,14 +90,14 @@ class PremiumEmail extends Model { $validator = Validator::make(['user_id' => $userId], [ - 'user_id' => 'required|integer', + 'user_id' => ['required', 'integer'], ]); if ($validator->fails()) { return []; } - return self::whereJsonContains('user_id', $userId)->orderBy('timestamp', 'desc')->get(); + return self::query()->whereJsonContains('user_id', $userId)->orderBy('timestamp', 'desc')->get(); } public static function parseEmail($userId, $deleted = []): array @@ -114,7 +114,7 @@ class PremiumEmail extends Model if (in_array($message['message_id'], $deleted)) { // If it exists, delete the matching record from the 'emails' table - Email::where('message_id', $message['message_id'])->delete(); + Email::query()->where('message_id', $message['message_id'])->delete(); continue; } @@ -122,7 +122,7 @@ class PremiumEmail extends Model $blocked = false; $timestamp = $message['timestamp']; - $carbonTimestamp = Carbon::parse($timestamp, 'UTC'); + $carbonTimestamp = Date::parse($timestamp, 'UTC'); $obj = []; $obj['subject'] = $message['subject']; $obj['to'] = $message['to']; @@ -130,16 +130,16 @@ class PremiumEmail extends Model $obj['sender_email'] = $message['from_email']; $obj['timestamp'] = $message['timestamp']; $obj['date'] = $carbonTimestamp->format('d M Y h:i A'); - $obj['datediff'] = $carbonTimestamp->diffForHumans(Carbon::now('UTC')); + $obj['datediff'] = $carbonTimestamp->diffForHumans(Date::now('UTC')); $obj['id'] = $message['message_id']; $obj['content'] = $message['body_html']; $obj['contentText'] = $message['body_text']; $obj['attachments'] = []; $obj['is_seen'] = $message['is_seen']; - $obj['sender_photo'] = self::chooseColor(strtoupper(substr($message['from_name'] ?: $message['from_email'], 0, 1))); + $obj['sender_photo'] = self::chooseColor(strtoupper(substr((string) $message['from_name'] ?: (string) $message['from_email'], 0, 1))); - $domain = explode('@', $obj['sender_email'])[1]; - $blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); + $domain = explode('@', (string) $obj['sender_email'])[1]; + $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains); if ($blocked) { $obj['subject'] = __('Blocked'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); @@ -162,7 +162,7 @@ class PremiumEmail extends Model file_put_contents(storage_path('logs/zemail.csv'), request()->ip().','.date('Y-m-d h:i:s a').','.$obj['sender_email'].','.$email.PHP_EOL, FILE_APPEND); } } - PremiumEmail::where('message_id', $message['message_id'])->update(['is_seen' => true]); + PremiumEmail::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]); if (++$count > $limit) { break; } diff --git a/app/Models/RemoteEmail.php b/app/Models/RemoteEmail.php index 785f73e..d10f3d0 100644 --- a/app/Models/RemoteEmail.php +++ b/app/Models/RemoteEmail.php @@ -42,13 +42,13 @@ class RemoteEmail extends Model public static function fetchEmailFromDB($email) { $validator = Validator::make(['email' => $email], [ - 'email' => 'required|email', + 'email' => ['required', 'email'], ]); if ($validator->fails()) { return []; } - return self::whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); + return self::query()->whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); } } diff --git a/app/Models/Ticket.php b/app/Models/Ticket.php index 18f1c74..30c1069 100644 --- a/app/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -2,7 +2,6 @@ namespace App\Models; -use Carbon\Carbon; use Exception; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -20,7 +19,7 @@ class Ticket extends Model { parent::boot(); - static::creating(function ($ticket) { + static::creating(function ($ticket): void { if (empty($ticket->ticket_id)) { $ticket->ticket_id = 'TICKET-'.strtoupper(Str::random(6)); } @@ -46,7 +45,7 @@ class Ticket extends Model public static function autoClose(): bool { try { - $tickets = Ticket::where('status', 'pending') + $tickets = Ticket::query()->where('status', 'pending') ->where('last_response_at', '<', now()->subDays(3)) ->get(); if (count($tickets) > 0) { @@ -54,7 +53,7 @@ class Ticket extends Model $ticket->status = 'closed'; $ticket->save(); - TicketResponse::create([ + TicketResponse::query()->create([ 'ticket_id' => $ticket->id, 'user_id' => 1, 'response' => 'This ticket has been auto-closed due to inactivity.', @@ -63,7 +62,7 @@ class Ticket extends Model } return true; - } catch (Exception $e) { + } catch (Exception) { return false; } diff --git a/app/Models/ZEmail.php b/app/Models/ZEmail.php index 8580c77..71de870 100644 --- a/app/Models/ZEmail.php +++ b/app/Models/ZEmail.php @@ -2,8 +2,8 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Ddeboer\Imap\ConnectionInterface; -use Ddeboer\Imap\Search\Email\To; use Ddeboer\Imap\Server; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Cookie; @@ -12,23 +12,21 @@ use function str_replace; class ZEmail extends Model { + use HasFactory; + use HasFactory; public static function connectMailBox($imap = null): ConnectionInterface { if ($imap === null) { - $imap = json_decode(config('app.settings.imap_settings'), true); + $imap = json_decode((string) config('app.settings.imap_settings'), true); } $flags = $imap['protocol'].'/'.$imap['encryption']; - if ($imap['validate_cert']) { - $flags = $flags.'/validate-cert'; - } else { - $flags = $flags.'/novalidate-cert'; - } + $flags = $imap['validate_cert'] ? $flags.'/validate-cert' : $flags.'/novalidate-cert'; $server = new Server($imap['host'], $imap['port'], $flags); return $server->authenticate($imap['username'], $imap['password']); } - public static function getMessages($email, $type = 'to', $deleted = []): array + public static function getMessages(string $email, $type = 'to', $deleted = []): array { if (config('app.beta_feature')) { return Message::getMessages($email); @@ -39,15 +37,14 @@ class ZEmail extends Model if (config('app.fetch_from_db')) { if (Email::mailToDBStatus()) { return Email::parseEmail($email, $deleted); - } else { - return Message::fetchMessages($email, $type, $deleted); } + return Message::fetchMessages($email, $type, $deleted); } return Message::fetchMessages($email, $type, $deleted); } - public static function deleteMessage($id): void + public static function deleteMessage(int $id): void { $connection = ZEmail::connectMailBox(); $mailbox = $connection->getMailbox('INBOX'); @@ -59,18 +56,16 @@ class ZEmail extends Model { if (Cookie::has('email')) { return Cookie::get('email'); - } else { - return $generate ? ZEmail::generateRandomEmail() : null; } + return $generate ? ZEmail::generateRandomEmail() : null; } public static function getEmails() { if (Cookie::has('emails')) { return unserialize(Cookie::get('emails')); - } else { - return []; } + return []; } public static function setEmail($email): void @@ -99,9 +94,9 @@ class ZEmail extends Model public static function createCustomEmailFull($email): string { - $data = explode('@', $email); + $data = explode('@', (string) $email); $username = $data[0]; - if (strlen($username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { + if (strlen($username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) { $zemail = new ZEmail; $username = $zemail->generateRandomUsername(); } @@ -110,11 +105,11 @@ class ZEmail extends Model return ZEmail::createCustomEmail($username, $domain); } - public static function createCustomEmail($username, $domain): string + public static function createCustomEmail($username, string $domain): string { - $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower($username)); + $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower((string) $username)); - $settings = json_decode(config('app.settings.configuration_settings'), true); + $settings = json_decode((string) config('app.settings.configuration_settings'), true); $forbidden_ids = $settings['forbidden_ids'] ?? []; $gmail_usernames = $settings['gmailUsernames'] ?? []; $outlook_usernames = $settings['outlookUsernames'] ?? []; @@ -124,7 +119,7 @@ class ZEmail extends Model $min_length = $settings['custom_username_length_min'] ?? 3; $max_length = $settings['custom_username_length_max'] ?? 20; - if (strlen($username) < $min_length || strlen($username) > $max_length) { + if (strlen((string) $username) < $min_length || strlen((string) $username) > $max_length) { $zemail = new ZEmail; $username = $zemail->generateRandomUsername(); } @@ -137,7 +132,7 @@ class ZEmail extends Model return ZEmail::generateRandomGmail(true); } - if ($username === '' && in_array($domain, ['outlook.com'])) { + if ($username === '' && $domain === 'outlook.com') { return ZEmail::generateRandomOutlook(true); } @@ -147,9 +142,9 @@ class ZEmail extends Model return $zemail->generateRandomUsername().'@'.$domain; } - if (in_array($domain, ['outlook.com'])) { - if (str_contains($username, '+')) { - [$check_username, $post_username] = explode('+', $username, 2); + if ($domain === 'outlook.com') { + if (str_contains((string) $username, '+')) { + [$check_username, $post_username] = explode('+', (string) $username, 2); if (in_array($check_username, $outlook_usernames)) { $email = $username.'@'.$domain; @@ -165,8 +160,8 @@ class ZEmail extends Model } if (in_array($domain, ['gmail.com', 'googlemail.com'])) { - if (str_contains($username, '+')) { - [$check_username, $post_username] = explode('+', $username, 2); + if (str_contains((string) $username, '+')) { + [$check_username, $post_username] = explode('+', (string) $username, 2); if (in_array($check_username, $gmail_usernames)) { $email = $username.'@'.$domain; @@ -174,7 +169,7 @@ class ZEmail extends Model $email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain; } - } elseif (str_contains($username, '.')) { + } elseif (str_contains((string) $username, '.')) { $check_username = str_replace('.', '', $username); if (in_array($check_username, $gmail_usernames)) { @@ -211,14 +206,14 @@ class ZEmail extends Model $domain = $zemail->getRandomDomain(); if ($domain == 'gmail.com') { $rd = mt_rand(0, 1); - if ($rd == 0) { + if ($rd === 0) { $email = $zemail->generateRandomGmail(); } else { $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com'; } } elseif ($domain == 'googlemail.com') { $rd = mt_rand(0, 1); - if ($rd == 0) { + if ($rd === 0) { $email = $zemail->generateRandomGmail(); } else { $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com'; @@ -239,11 +234,11 @@ class ZEmail extends Model { $zemail = new ZEmail; $uname = $zemail->getRandomGmailUser(); - $uname_len = strlen($uname); + $uname_len = strlen((string) $uname); $len_power = $uname_len - 1; - $combination = pow(2, $len_power); - $rand_comb = mt_rand(1, $combination); - $formatted = implode(' ', str_split($uname)); + $combination = 2 ** $len_power; + mt_rand(1, $combination); + $formatted = implode(' ', str_split((string) $uname)); $uname_exp = explode(' ', $formatted); $bin = intval(''); @@ -255,7 +250,7 @@ class ZEmail extends Model $email = ''; for ($i = 0; $i < $len_power; $i++) { $email .= $uname_exp[$i]; - if ($bin[$i]) { + if ($bin[$i] !== '' && $bin[$i] !== '0') { $email .= '.'; } } @@ -284,9 +279,9 @@ class ZEmail extends Model return $email; } - private static function storeEmail($email): void + private static function storeEmail(string $email): void { - Log::create([ + Log::query()->create([ 'ip' => request()->ip(), 'email' => $email, ]); @@ -314,8 +309,8 @@ class ZEmail extends Model private function generateRandomUsername(): string { - $start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; - $end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; + $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0; + $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0; if ($start == 0 && $end == 0) { return $this->generatePronounceableWord(); } @@ -325,34 +320,34 @@ class ZEmail extends Model protected function generatedRandomBetweenLength($start, $end): string { - $length = rand($start, $end); + $length = random_int($start, $end); return $this->generateRandomString($length); } private function getRandomDomain() { - $domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; + $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? []; $count = count($domains); - return $count > 0 ? $domains[rand(1, $count) - 1] : ''; + return $count > 0 ? $domains[random_int(1, $count) - 1] : ''; } private function getRandomGmailUser() { - $gmailusername = json_decode(config('app.settings.configuration_settings'))->gmailUsernames ?? []; + $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->gmailUsernames ?? []; $count = count($gmailusername); - return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; + return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : ''; } private function getRandomOutlookUser() { - $outlook_username = json_decode(config('app.settings.configuration_settings'))->outlookUsernames ?? []; + $outlook_username = json_decode((string) config('app.settings.configuration_settings'))->outlookUsernames ?? []; $count = count($outlook_username); - return $count > 0 ? $outlook_username[rand(1, $count) - 1] : ''; + return $count > 0 ? $outlook_username[random_int(1, $count) - 1] : ''; } private function generatePronounceableWord(): string @@ -362,21 +357,21 @@ class ZEmail extends Model $a = $c.$v; // both $random = ''; for ($j = 0; $j < 2; $j++) { - $random .= $c[rand(0, strlen($c) - 1)]; - $random .= $v[rand(0, strlen($v) - 1)]; - $random .= $a[rand(0, strlen($a) - 1)]; + $random .= $c[random_int(0, strlen($c) - 1)]; + $random .= $v[random_int(0, strlen($v) - 1)]; + $random .= $a[random_int(0, strlen($a) - 1)]; } return $random; } - private function generateRandomString($length = 10): string + private function generateRandomString(int $length = 10): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; + $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; diff --git a/app/NotifyMe.php b/app/NotifyMe.php index 0b6fd45..51395a6 100644 --- a/app/NotifyMe.php +++ b/app/NotifyMe.php @@ -2,9 +2,9 @@ namespace App; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Http; use Exception; -use Http; -use Log; trait NotifyMe { diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 5919bc4..34c3771 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,10 +2,10 @@ namespace App\Providers; +use Illuminate\Support\Facades\DB; use App\Models\Blog; use App\Models\Menu; use App\Models\Plan; -use DB; use Exception; use Illuminate\Support\ServiceProvider; use Laravel\Cashier\Cashier; @@ -39,27 +39,19 @@ class AppServiceProvider extends ServiceProvider private function loadApplicationData(): void { try { - $settings = cache()->remember('app_settings', now()->addHours(6), function () { - return (array) DB::table('settings')->find(1); - }); + $settings = cache()->remember('app_settings', now()->addHours(6), fn(): array => (array) DB::table('settings')->find(1)); - $menus = cache()->remember('app_menus', now()->addHours(6), function () { - return Menu::all(); - }); + $menus = cache()->remember('app_menus', now()->addHours(6), Menu::all(...)); - $blogs = cache()->remember('app_blogs', now()->addHours(6), function () { - return Blog::where('is_published', 1)->get(); - }); + $blogs = cache()->remember('app_blogs', now()->addHours(6), fn() => Blog::query()->where('is_published', 1)->get()); - $plans = cache()->remember('app_plans', now()->addHours(6), function () { - return Plan::all(); - }); + $plans = cache()->remember('app_plans', now()->addHours(6), Plan::all(...)); config(['app.settings' => (array) $settings]); config(['app.menus' => $menus]); config(['app.blogs' => $blogs]); config(['app.plans' => $plans]); - } catch (Exception $e) { + } catch (Exception) { // Fail silently if database is not available // This allows the application to boot during migrations and testing } diff --git a/app/Providers/Filament/DashPanelProvider.php b/app/Providers/Filament/DashPanelProvider.php index 266bc34..38ff373 100644 --- a/app/Providers/Filament/DashPanelProvider.php +++ b/app/Providers/Filament/DashPanelProvider.php @@ -10,7 +10,6 @@ use Filament\Pages\Dashboard; use Filament\Panel; use Filament\PanelProvider; use Filament\Support\Colors\Color; -use Filament\Widgets; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken; diff --git a/bootstrap/app.php b/bootstrap/app.php index c3f6815..d498956 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ withMiddleware(function (Middleware $middleware) { + ->withMiddleware(function (Middleware $middleware): void { $middleware->web(append: [ - \App\Http\Middleware\Locale::class, + Locale::class, ]); $middleware->validateCsrfTokens(except: [ 'stripe/*', 'webhook/oxapay', ]); }) - ->withExceptions(function (Exceptions $exceptions) { + ->withExceptions(function (Exceptions $exceptions): void { // })->create(); diff --git a/composer.json b/composer.json index 8b5033b..667c22e 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,7 @@ }, "require-dev": { "barryvdh/laravel-debugbar": "^3.15", + "driftingly/rector-laravel": "^2.1", "fakerphp/faker": "^1.23", "filament/upgrade": "~4.0", "laravel/boost": "^1.7", diff --git a/composer.lock b/composer.lock index b57689f..ad76bbd 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4f524140d1c67cd77b488f1510913b56", + "content-hash": "4cdd6fb15d89efed5ce17b76086a103a", "packages": [ { "name": "anourvalar/eloquent-serialize", @@ -8999,6 +8999,42 @@ }, "time": "2025-04-07T20:06:18+00:00" }, + { + "name": "driftingly/rector-laravel", + "version": "2.1.3", + "source": { + "type": "git", + "url": "https://github.com/driftingly/rector-laravel.git", + "reference": "2f1e9c3997bf45592d58916f0cedd775e844b9c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/2f1e9c3997bf45592d58916f0cedd775e844b9c6", + "reference": "2f1e9c3997bf45592d58916f0cedd775e844b9c6", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "rector/rector": "^2.2.7", + "webmozart/assert": "^1.11" + }, + "type": "rector-extension", + "autoload": { + "psr-4": { + "RectorLaravel\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Rector upgrades rules for Laravel Framework", + "support": { + "issues": "https://github.com/driftingly/rector-laravel/issues", + "source": "https://github.com/driftingly/rector-laravel/tree/2.1.3" + }, + "time": "2025-11-04T18:32:57+00:00" + }, { "name": "fakerphp/faker", "version": "v1.24.1", diff --git a/config/app.php b/config/app.php index d89527b..866af9b 100644 --- a/config/app.php +++ b/config/app.php @@ -33,7 +33,7 @@ return [ 'fetch_from_db' => env('FETCH_FETCH_FOR_DB', false), 'fetch_from_remote_db' => env('FETCH_FROM_REMOTE_DB', false), 'force_db_mail' => env('FORCE_DB_MAIL', false), - 'move_or_delete' => env('MOVE_OR_DELETE', null), + 'move_or_delete' => env('MOVE_OR_DELETE'), 'auto_fetch_mail' => env('AUTO_FETCH_MAIL', false), 'notify_tg_bot_token' => env('NOTIFY_TG_BOT_TOKEN', ''), @@ -114,7 +114,7 @@ return [ 'previous_keys' => [ ...array_filter( - explode(',', env('APP_PREVIOUS_KEYS', '')) + explode(',', (string) env('APP_PREVIOUS_KEYS', '')) ), ], diff --git a/config/auth.php b/config/auth.php index 0ba5d5d..9daae00 100644 --- a/config/auth.php +++ b/config/auth.php @@ -1,5 +1,7 @@ [ 'users' => [ 'driver' => 'eloquent', - 'model' => env('AUTH_MODEL', App\Models\User::class), + 'model' => env('AUTH_MODEL', User::class), ], // 'users' => [ diff --git a/config/debugbar.php b/config/debugbar.php index a2add0d..e2ef39a 100644 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -14,7 +14,7 @@ return [ | */ - 'enabled' => env('DEBUGBAR_ENABLED', null), + 'enabled' => env('DEBUGBAR_ENABLED'), 'hide_empty_tabs' => true, // Hide tabs until they have content 'except' => [ 'telescope*', diff --git a/config/disposable-email.php b/config/disposable-email.php index b140e47..0008fe4 100644 --- a/config/disposable-email.php +++ b/config/disposable-email.php @@ -1,5 +1,7 @@ \Propaganistas\LaravelDisposableEmail\Fetcher\DefaultFetcher::class, + 'fetcher' => DefaultFetcher::class, /* |-------------------------------------------------------------------------- diff --git a/config/logging.php b/config/logging.php index 1345f6f..9e998a4 100644 --- a/config/logging.php +++ b/config/logging.php @@ -54,7 +54,7 @@ return [ 'stack' => [ 'driver' => 'stack', - 'channels' => explode(',', env('LOG_STACK', 'single')), + 'channels' => explode(',', (string) env('LOG_STACK', 'single')), 'ignore_exceptions' => false, ], diff --git a/config/mail.php b/config/mail.php index 0034532..522b284 100644 --- a/config/mail.php +++ b/config/mail.php @@ -46,7 +46,7 @@ return [ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), 'timeout' => null, - 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)), + 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)), ], 'ses' => [ diff --git a/config/sanctum.php b/config/sanctum.php index 44527d6..37a4133 100644 --- a/config/sanctum.php +++ b/config/sanctum.php @@ -1,5 +1,8 @@ explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( + 'stateful' => explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf( '%s%s', 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', Sanctum::currentApplicationUrlWithPort(), @@ -76,9 +79,9 @@ return [ */ 'middleware' => [ - 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, - 'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class, - 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, + 'authenticate_session' => AuthenticateSession::class, + 'encrypt_cookies' => EncryptCookies::class, + 'validate_csrf_token' => ValidateCsrfToken::class, ], ]; diff --git a/database/factories/ActivationKeyFactory.php b/database/factories/ActivationKeyFactory.php index 728239a..232f0e9 100644 --- a/database/factories/ActivationKeyFactory.php +++ b/database/factories/ActivationKeyFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\ActivationKey; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ActivationKey> + * @extends Factory */ class ActivationKeyFactory extends Factory { diff --git a/database/factories/BlogFactory.php b/database/factories/BlogFactory.php index e64dbfe..24ca3cc 100644 --- a/database/factories/BlogFactory.php +++ b/database/factories/BlogFactory.php @@ -2,12 +2,13 @@ namespace Database\Factories; +use App\Models\Blog; use App\Models\Category; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Blog> + * @extends Factory */ class BlogFactory extends Factory { diff --git a/database/factories/CategoryFactory.php b/database/factories/CategoryFactory.php index a8fb421..e992f12 100644 --- a/database/factories/CategoryFactory.php +++ b/database/factories/CategoryFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\Category; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Category> + * @extends Factory */ class CategoryFactory extends Factory { diff --git a/database/factories/EmailFactory.php b/database/factories/EmailFactory.php index 90fcd1e..b5ec4a1 100644 --- a/database/factories/EmailFactory.php +++ b/database/factories/EmailFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\Email; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Email> + * @extends Factory */ class EmailFactory extends Factory { diff --git a/database/factories/LogFactory.php b/database/factories/LogFactory.php index 71a09dd..be42531 100644 --- a/database/factories/LogFactory.php +++ b/database/factories/LogFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\Log; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Log> + * @extends Factory */ class LogFactory extends Factory { diff --git a/database/factories/MenuFactory.php b/database/factories/MenuFactory.php index 7265be9..f0088b9 100644 --- a/database/factories/MenuFactory.php +++ b/database/factories/MenuFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\Menu; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Menu> + * @extends Factory */ class MenuFactory extends Factory { diff --git a/database/factories/MessageFactory.php b/database/factories/MessageFactory.php index de566ad..374890c 100644 --- a/database/factories/MessageFactory.php +++ b/database/factories/MessageFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\Message; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Message> + * @extends Factory */ class MessageFactory extends Factory { diff --git a/database/factories/MetaFactory.php b/database/factories/MetaFactory.php index 2e64ce9..e6922c0 100644 --- a/database/factories/MetaFactory.php +++ b/database/factories/MetaFactory.php @@ -5,6 +5,9 @@ namespace Database\Factories; use App\Models\Meta; use Illuminate\Database\Eloquent\Factories\Factory; +/** + * @extends Factory + */ class MetaFactory extends Factory { protected $model = Meta::class; diff --git a/database/factories/PageFactory.php b/database/factories/PageFactory.php index 2707ce3..9b679f9 100644 --- a/database/factories/PageFactory.php +++ b/database/factories/PageFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\Page; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Page> + * @extends Factory */ class PageFactory extends Factory { diff --git a/database/factories/PlanFactory.php b/database/factories/PlanFactory.php index 06448cd..df6b175 100644 --- a/database/factories/PlanFactory.php +++ b/database/factories/PlanFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\Plan; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Plan> + * @extends Factory */ class PlanFactory extends Factory { diff --git a/database/factories/PremiumEmailFactory.php b/database/factories/PremiumEmailFactory.php index f47f59c..1ffebe4 100644 --- a/database/factories/PremiumEmailFactory.php +++ b/database/factories/PremiumEmailFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\PremiumEmail; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\PremiumEmail> + * @extends Factory */ class PremiumEmailFactory extends Factory { diff --git a/database/factories/RemoteEmailFactory.php b/database/factories/RemoteEmailFactory.php index f7d691a..98e5a2e 100644 --- a/database/factories/RemoteEmailFactory.php +++ b/database/factories/RemoteEmailFactory.php @@ -5,6 +5,9 @@ namespace Database\Factories; use App\Models\RemoteEmail; use Illuminate\Database\Eloquent\Factories\Factory; +/** + * @extends Factory + */ class RemoteEmailFactory extends Factory { protected $model = RemoteEmail::class; diff --git a/database/factories/SettingFactory.php b/database/factories/SettingFactory.php index 4d8070e..8f6f2a8 100644 --- a/database/factories/SettingFactory.php +++ b/database/factories/SettingFactory.php @@ -2,10 +2,11 @@ namespace Database\Factories; +use App\Models\Setting; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Setting> + * @extends Factory */ class SettingFactory extends Factory { diff --git a/database/factories/TicketFactory.php b/database/factories/TicketFactory.php index 690fda5..4250219 100644 --- a/database/factories/TicketFactory.php +++ b/database/factories/TicketFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\Ticket; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Ticket> + * @extends Factory */ class TicketFactory extends Factory { diff --git a/database/factories/TicketResponseFactory.php b/database/factories/TicketResponseFactory.php index 4e88854..527dfa4 100644 --- a/database/factories/TicketResponseFactory.php +++ b/database/factories/TicketResponseFactory.php @@ -2,12 +2,13 @@ namespace Database\Factories; +use App\Models\TicketResponse; use App\Models\Ticket; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\TicketResponse> + * @extends Factory */ class TicketResponseFactory extends Factory { diff --git a/database/factories/UsageLogFactory.php b/database/factories/UsageLogFactory.php index 125f836..3bbe8e7 100644 --- a/database/factories/UsageLogFactory.php +++ b/database/factories/UsageLogFactory.php @@ -2,11 +2,12 @@ namespace Database\Factories; +use App\Models\UsageLog; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\UsageLog> + * @extends Factory */ class UsageLogFactory extends Factory { diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index fd04033..4a2485e 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -2,12 +2,13 @@ namespace Database\Factories; +use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> + * @extends Factory */ class UserFactory extends Factory { @@ -38,7 +39,7 @@ class UserFactory extends Factory */ public function unverified(): static { - return $this->state(fn (array $attributes) => [ + return $this->state(fn (array $attributes): array => [ 'email_verified_at' => null, ]); } diff --git a/database/migrations/0001_01_01_000000_create_users_table.php b/database/migrations/0001_01_01_000000_create_users_table.php index 05fb5d9..6a7de5d 100644 --- a/database/migrations/0001_01_01_000000_create_users_table.php +++ b/database/migrations/0001_01_01_000000_create_users_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('users', function (Blueprint $table) { + Schema::create('users', function (Blueprint $table): void { $table->id(); $table->string('name'); $table->string('email')->unique(); @@ -21,13 +21,13 @@ return new class extends Migration $table->timestamps(); }); - Schema::create('password_reset_tokens', function (Blueprint $table) { + Schema::create('password_reset_tokens', function (Blueprint $table): void { $table->string('email')->primary(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); - Schema::create('sessions', function (Blueprint $table) { + Schema::create('sessions', function (Blueprint $table): void { $table->string('id')->primary(); $table->foreignId('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); diff --git a/database/migrations/0001_01_01_000001_create_cache_table.php b/database/migrations/0001_01_01_000001_create_cache_table.php index b9c106b..9af530c 100644 --- a/database/migrations/0001_01_01_000001_create_cache_table.php +++ b/database/migrations/0001_01_01_000001_create_cache_table.php @@ -11,13 +11,13 @@ return new class extends Migration */ public function up(): void { - Schema::create('cache', function (Blueprint $table) { + Schema::create('cache', function (Blueprint $table): void { $table->string('key')->primary(); $table->mediumText('value'); $table->integer('expiration'); }); - Schema::create('cache_locks', function (Blueprint $table) { + Schema::create('cache_locks', function (Blueprint $table): void { $table->string('key')->primary(); $table->string('owner'); $table->integer('expiration'); diff --git a/database/migrations/0001_01_01_000002_create_jobs_table.php b/database/migrations/0001_01_01_000002_create_jobs_table.php index 425e705..5073d2c 100644 --- a/database/migrations/0001_01_01_000002_create_jobs_table.php +++ b/database/migrations/0001_01_01_000002_create_jobs_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('jobs', function (Blueprint $table) { + Schema::create('jobs', function (Blueprint $table): void { $table->id(); $table->string('queue')->index(); $table->longText('payload'); @@ -21,7 +21,7 @@ return new class extends Migration $table->unsignedInteger('created_at'); }); - Schema::create('job_batches', function (Blueprint $table) { + Schema::create('job_batches', function (Blueprint $table): void { $table->string('id')->primary(); $table->string('name'); $table->integer('total_jobs'); @@ -34,7 +34,7 @@ return new class extends Migration $table->integer('finished_at')->nullable(); }); - Schema::create('failed_jobs', function (Blueprint $table) { + Schema::create('failed_jobs', function (Blueprint $table): void { $table->id(); $table->string('uuid')->unique(); $table->text('connection'); diff --git a/database/migrations/2025_04_22_204157_add_level_to_users_table.php b/database/migrations/2025_04_22_204157_add_level_to_users_table.php index fbd5c81..7d9a4cf 100644 --- a/database/migrations/2025_04_22_204157_add_level_to_users_table.php +++ b/database/migrations/2025_04_22_204157_add_level_to_users_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('users', function (Blueprint $table) { + Schema::table('users', function (Blueprint $table): void { $table->integer('level')->default(0)->after('id'); }); } @@ -21,7 +21,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('users', function (Blueprint $table) { + Schema::table('users', function (Blueprint $table): void { $table->dropColumn('level'); }); } diff --git a/database/migrations/2025_04_22_210144_create_settings_table.php b/database/migrations/2025_04_22_210144_create_settings_table.php index 9fa1efe..0a4e602 100644 --- a/database/migrations/2025_04_22_210144_create_settings_table.php +++ b/database/migrations/2025_04_22_210144_create_settings_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('settings', function (Blueprint $table) { + Schema::create('settings', function (Blueprint $table): void { $table->id(); $table->string('app_name'); $table->string('app_version')->default('1.0'); diff --git a/database/migrations/2025_04_22_214146_add_imap_settings_to_settings_table.php b/database/migrations/2025_04_22_214146_add_imap_settings_to_settings_table.php index 68f9345..0dcfd85 100644 --- a/database/migrations/2025_04_22_214146_add_imap_settings_to_settings_table.php +++ b/database/migrations/2025_04_22_214146_add_imap_settings_to_settings_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->json('imap_settings')->default('[]')->after('app_footer'); }); } @@ -21,7 +21,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->dropColumn('imap_settings'); }); } diff --git a/database/migrations/2025_04_22_231534_add_configuration_settings_to_settings_table.php b/database/migrations/2025_04_22_231534_add_configuration_settings_to_settings_table.php index d8df9b4..f803800 100644 --- a/database/migrations/2025_04_22_231534_add_configuration_settings_to_settings_table.php +++ b/database/migrations/2025_04_22_231534_add_configuration_settings_to_settings_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->json('configuration_settings')->default('[]')->after('imap_settings'); }); } @@ -21,7 +21,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->dropColumn('configuration_settings'); }); } diff --git a/database/migrations/2025_04_23_004834_add_ads_settings_to_settings_table.php b/database/migrations/2025_04_23_004834_add_ads_settings_to_settings_table.php index 2008a57..54173a2 100644 --- a/database/migrations/2025_04_23_004834_add_ads_settings_to_settings_table.php +++ b/database/migrations/2025_04_23_004834_add_ads_settings_to_settings_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->json('ads_settings')->default('[]')->after('configuration_settings'); }); } @@ -21,7 +21,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('settings', function (Blueprint $table) { + Schema::table('settings', function (Blueprint $table): void { $table->dropColumn('ads_settings'); }); } diff --git a/database/migrations/2025_04_23_101602_create_metas_table.php b/database/migrations/2025_04_23_101602_create_metas_table.php index 59d9c8f..85f1acd 100644 --- a/database/migrations/2025_04_23_101602_create_metas_table.php +++ b/database/migrations/2025_04_23_101602_create_metas_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('metas', function (Blueprint $table) { + Schema::create('metas', function (Blueprint $table): void { $table->id(); $table->string('key'); $table->text('value')->nullable(); diff --git a/database/migrations/2025_04_23_104947_create_logs_table.php b/database/migrations/2025_04_23_104947_create_logs_table.php index 560d9d1..bf0112a 100644 --- a/database/migrations/2025_04_23_104947_create_logs_table.php +++ b/database/migrations/2025_04_23_104947_create_logs_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('logs', function (Blueprint $table) { + Schema::create('logs', function (Blueprint $table): void { $table->id(); $table->string('ip'); $table->string('email'); diff --git a/database/migrations/2025_04_23_120910_create_messages_table.php b/database/migrations/2025_04_23_120910_create_messages_table.php index e571c8e..62920fa 100644 --- a/database/migrations/2025_04_23_120910_create_messages_table.php +++ b/database/migrations/2025_04_23_120910_create_messages_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('messages', function (Blueprint $table) { + Schema::create('messages', function (Blueprint $table): void { $table->id(); $table->string('subject'); $table->string('from'); diff --git a/database/migrations/2025_04_25_195348_create_emails_table.php b/database/migrations/2025_04_25_195348_create_emails_table.php index fc17184..ca5c6dd 100644 --- a/database/migrations/2025_04_25_195348_create_emails_table.php +++ b/database/migrations/2025_04_25_195348_create_emails_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('emails', function (Blueprint $table) { + Schema::create('emails', function (Blueprint $table): void { $table->id(); $table->string('message_id')->unique()->index(); $table->string('subject')->nullable(); diff --git a/database/migrations/2025_04_27_120959_create_pages_table.php b/database/migrations/2025_04_27_120959_create_pages_table.php index 1b57a66..0c3888f 100644 --- a/database/migrations/2025_04_27_120959_create_pages_table.php +++ b/database/migrations/2025_04_27_120959_create_pages_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('pages', function (Blueprint $table) { + Schema::create('pages', function (Blueprint $table): void { $table->id(); $table->string('title'); $table->string('slug'); diff --git a/database/migrations/2025_04_27_123300_create_menus_table.php b/database/migrations/2025_04_27_123300_create_menus_table.php index 3345268..18f1235 100644 --- a/database/migrations/2025_04_27_123300_create_menus_table.php +++ b/database/migrations/2025_04_27_123300_create_menus_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('menus', function (Blueprint $table) { + Schema::create('menus', function (Blueprint $table): void { $table->id(); $table->string('name'); $table->string('url'); diff --git a/database/migrations/2025_04_27_133659_create_categories_table.php b/database/migrations/2025_04_27_133659_create_categories_table.php index 21032e5..24be963 100644 --- a/database/migrations/2025_04_27_133659_create_categories_table.php +++ b/database/migrations/2025_04_27_133659_create_categories_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('categories', function (Blueprint $table) { + Schema::create('categories', function (Blueprint $table): void { $table->id(); $table->string('name'); $table->string('slug'); diff --git a/database/migrations/2025_04_27_133802_create_blogs_table.php b/database/migrations/2025_04_27_133802_create_blogs_table.php index 0386f5c..44b3ff4 100644 --- a/database/migrations/2025_04_27_133802_create_blogs_table.php +++ b/database/migrations/2025_04_27_133802_create_blogs_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('blogs', function (Blueprint $table) { + Schema::create('blogs', function (Blueprint $table): void { $table->id(); $table->string('post'); $table->string('slug'); diff --git a/database/migrations/2025_05_02_144314_create_customer_columns.php b/database/migrations/2025_05_02_144314_create_customer_columns.php index 974b381..8d631d9 100644 --- a/database/migrations/2025_05_02_144314_create_customer_columns.php +++ b/database/migrations/2025_05_02_144314_create_customer_columns.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('users', function (Blueprint $table) { + Schema::table('users', function (Blueprint $table): void { $table->string('stripe_id')->nullable()->index(); $table->string('pm_type')->nullable(); $table->string('pm_last_four', 4)->nullable(); @@ -24,7 +24,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('users', function (Blueprint $table) { + Schema::table('users', function (Blueprint $table): void { $table->dropIndex([ 'stripe_id', ]); diff --git a/database/migrations/2025_05_02_144315_create_subscriptions_table.php b/database/migrations/2025_05_02_144315_create_subscriptions_table.php index ccbcc6d..9ac8e49 100644 --- a/database/migrations/2025_05_02_144315_create_subscriptions_table.php +++ b/database/migrations/2025_05_02_144315_create_subscriptions_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('subscriptions', function (Blueprint $table) { + Schema::create('subscriptions', function (Blueprint $table): void { $table->id(); $table->foreignId('user_id'); $table->string('type'); diff --git a/database/migrations/2025_05_02_144316_create_subscription_items_table.php b/database/migrations/2025_05_02_144316_create_subscription_items_table.php index 420e23f..caefa33 100644 --- a/database/migrations/2025_05_02_144316_create_subscription_items_table.php +++ b/database/migrations/2025_05_02_144316_create_subscription_items_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('subscription_items', function (Blueprint $table) { + Schema::create('subscription_items', function (Blueprint $table): void { $table->id(); $table->foreignId('subscription_id'); $table->string('stripe_id')->unique(); diff --git a/database/migrations/2025_05_02_215351_create_plans_table.php b/database/migrations/2025_05_02_215351_create_plans_table.php index d70fc6d..8817fd4 100644 --- a/database/migrations/2025_05_02_215351_create_plans_table.php +++ b/database/migrations/2025_05_02_215351_create_plans_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('plans', function (Blueprint $table) { + Schema::create('plans', function (Blueprint $table): void { $table->id(); $table->string('name'); $table->text('description')->nullable(); diff --git a/database/migrations/2025_05_03_082522_create_usage_logs_table.php b/database/migrations/2025_05_03_082522_create_usage_logs_table.php index 2221f5b..ce0392b 100644 --- a/database/migrations/2025_05_03_082522_create_usage_logs_table.php +++ b/database/migrations/2025_05_03_082522_create_usage_logs_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('usage_logs', function (Blueprint $table) { + Schema::create('usage_logs', function (Blueprint $table): void { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->ipAddress('ip_address'); diff --git a/database/migrations/2025_05_03_200503_add_user_id_to_logs_table.php b/database/migrations/2025_05_03_200503_add_user_id_to_logs_table.php index 1436082..eb9f9c1 100644 --- a/database/migrations/2025_05_03_200503_add_user_id_to_logs_table.php +++ b/database/migrations/2025_05_03_200503_add_user_id_to_logs_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('logs', function (Blueprint $table) { + Schema::table('logs', function (Blueprint $table): void { $table->unsignedBigInteger('user_id')->nullable()->after('id'); $table->foreign('user_id')->references('id')->on('users'); }); @@ -22,7 +22,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('logs', function (Blueprint $table) { + Schema::table('logs', function (Blueprint $table): void { $table->dropForeign(['user_id']); $table->dropColumn('user_id'); }); diff --git a/database/migrations/2025_05_05_212255_create_premium_emails_table.php b/database/migrations/2025_05_05_212255_create_premium_emails_table.php index 85b6f95..781c6ba 100644 --- a/database/migrations/2025_05_05_212255_create_premium_emails_table.php +++ b/database/migrations/2025_05_05_212255_create_premium_emails_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('premium_emails', function (Blueprint $table) { + Schema::create('premium_emails', function (Blueprint $table): void { $table->id(); $table->unsignedBigInteger('user_id'); $table->string('message_id')->unique()->index(); diff --git a/database/migrations/2025_05_16_015550_create_activation_keys_table.php b/database/migrations/2025_05_16_015550_create_activation_keys_table.php index e50a981..306f1de 100644 --- a/database/migrations/2025_05_16_015550_create_activation_keys_table.php +++ b/database/migrations/2025_05_16_015550_create_activation_keys_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('activation_keys', function (Blueprint $table) { + Schema::create('activation_keys', function (Blueprint $table): void { $table->id(); $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); $table->string('activation_key')->unique(); diff --git a/database/migrations/2025_05_16_024757_add_shoppy_and_accept_columns_to_plans_table.php b/database/migrations/2025_05_16_024757_add_shoppy_and_accept_columns_to_plans_table.php index caa7211..20ac966 100644 --- a/database/migrations/2025_05_16_024757_add_shoppy_and_accept_columns_to_plans_table.php +++ b/database/migrations/2025_05_16_024757_add_shoppy_and_accept_columns_to_plans_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('plans', function (Blueprint $table) { + Schema::table('plans', function (Blueprint $table): void { $table->string('shoppy_product_id')->nullable()->after('pricing_id'); $table->boolean('accept_stripe')->default(false)->after('shoppy_product_id'); $table->boolean('accept_shoppy')->default(false)->after('accept_stripe'); @@ -23,7 +23,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('plans', function (Blueprint $table) { + Schema::table('plans', function (Blueprint $table): void { $table->dropColumn(['shoppy_product_id', 'accept_stripe', 'accept_shoppy']); }); } diff --git a/database/migrations/2025_05_16_072530_create_tickets_table.php b/database/migrations/2025_05_16_072530_create_tickets_table.php index 3ee371d..996739d 100644 --- a/database/migrations/2025_05_16_072530_create_tickets_table.php +++ b/database/migrations/2025_05_16_072530_create_tickets_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('tickets', function (Blueprint $table) { + Schema::create('tickets', function (Blueprint $table): void { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('ticket_id', 6)->unique(); diff --git a/database/migrations/2025_05_16_072547_create_ticket_responses_table.php b/database/migrations/2025_05_16_072547_create_ticket_responses_table.php index 12d3000..acd824b 100644 --- a/database/migrations/2025_05_16_072547_create_ticket_responses_table.php +++ b/database/migrations/2025_05_16_072547_create_ticket_responses_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('ticket_responses', function (Blueprint $table) { + Schema::create('ticket_responses', function (Blueprint $table): void { $table->id(); $table->foreignId('ticket_id')->constrained()->onDelete('cascade'); $table->foreignId('user_id')->constrained()->onDelete('cascade'); diff --git a/database/migrations/2025_06_20_172251_add_oxa_pay_details_to_plans_table.php b/database/migrations/2025_06_20_172251_add_oxa_pay_details_to_plans_table.php index 8a06df7..ee91186 100644 --- a/database/migrations/2025_06_20_172251_add_oxa_pay_details_to_plans_table.php +++ b/database/migrations/2025_06_20_172251_add_oxa_pay_details_to_plans_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::table('plans', function (Blueprint $table) { + Schema::table('plans', function (Blueprint $table): void { $table->string('oxapay_link')->nullable()->after('accept_shoppy'); $table->boolean('accept_oxapay')->default(false)->after('oxapay_link'); }); @@ -22,7 +22,7 @@ return new class extends Migration */ public function down(): void { - Schema::table('plans', function (Blueprint $table) { + Schema::table('plans', function (Blueprint $table): void { $table->dropColumn(['oxapay_link', 'accept_oxapay']); }); } diff --git a/database/migrations/2025_06_20_181026_create_personal_access_tokens_table.php b/database/migrations/2025_06_20_181026_create_personal_access_tokens_table.php index e828ad8..07c8c0e 100644 --- a/database/migrations/2025_06_20_181026_create_personal_access_tokens_table.php +++ b/database/migrations/2025_06_20_181026_create_personal_access_tokens_table.php @@ -11,7 +11,7 @@ return new class extends Migration */ public function up(): void { - Schema::create('personal_access_tokens', function (Blueprint $table) { + Schema::create('personal_access_tokens', function (Blueprint $table): void { $table->id(); $table->morphs('tokenable'); $table->string('name'); diff --git a/database/seeders/AdminSeeder.php b/database/seeders/AdminSeeder.php index 48f5a02..1dd819c 100644 --- a/database/seeders/AdminSeeder.php +++ b/database/seeders/AdminSeeder.php @@ -13,7 +13,7 @@ class AdminSeeder extends Seeder */ public function run(): void { - User::create([ + User::query()->create([ 'name' => 'admin', 'email' => 'admin@zemail.me', 'password' => Hash::make('password'), diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 4a7563a..2e7fa10 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -2,7 +2,6 @@ namespace Database\Seeders; -use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; diff --git a/database/seeders/MetaSeeder.php b/database/seeders/MetaSeeder.php index 79b00b4..075e364 100644 --- a/database/seeders/MetaSeeder.php +++ b/database/seeders/MetaSeeder.php @@ -2,6 +2,7 @@ namespace Database\Seeders; +use stdClass; use App\Models\Meta; use Illuminate\Database\Seeder; @@ -12,12 +13,12 @@ class MetaSeeder extends Seeder */ public function run(): void { - $metas = new \stdClass; + $metas = new stdClass; $metas->email_ids_created = 0; $metas->messages_received = 0; foreach ($metas as $key => $meta) { - if (! Meta::where('key', $key)->exists()) { - Meta::create([ + if (! Meta::query()->where('key', $key)->exists()) { + Meta::query()->create([ 'key' => $key, 'value' => $meta, ]); diff --git a/database/seeders/UpdatePlansTableSeeder.php b/database/seeders/UpdatePlansTableSeeder.php index 3871e86..d5ed478 100644 --- a/database/seeders/UpdatePlansTableSeeder.php +++ b/database/seeders/UpdatePlansTableSeeder.php @@ -12,13 +12,13 @@ class UpdatePlansTableSeeder extends Seeder */ public function run(): void { - Plan::where('id', 1)->update([ + Plan::query()->where('id', 1)->update([ 'shoppy_product_id' => 'MsYfrRX', 'accept_stripe' => 1, 'accept_shoppy' => 1, ]); - Plan::where('id', 2)->update([ + Plan::query()->where('id', 2)->update([ 'shoppy_product_id' => '1oU5SNT', 'accept_stripe' => 1, 'accept_shoppy' => 1, diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..0740841 --- /dev/null +++ b/rector.php @@ -0,0 +1,52 @@ +withSetProviders(LaravelSetProvider::class) + ->withSets([ + LaravelSetList::LARAVEL_ARRAYACCESS_TO_METHOD_CALL, + LaravelSetList::LARAVEL_ARRAY_STR_FUNCTION_TO_STATIC_CALL, + LaravelSetList::LARAVEL_CODE_QUALITY, + LaravelSetList::LARAVEL_COLLECTION, + LaravelSetList::LARAVEL_CONTAINER_STRING_TO_FULLY_QUALIFIED_NAME, + LaravelSetList::LARAVEL_ELOQUENT_MAGIC_METHOD_TO_QUERY_BUILDER, + LaravelSetList::LARAVEL_FACADE_ALIASES_TO_FULL_NAMES, + LaravelSetList::LARAVEL_FACTORIES, + LaravelSetList::LARAVEL_IF_HELPERS, + LaravelSetList::LARAVEL_LEGACY_FACTORIES_TO_CLASSES, + ]) + ->withImportNames( + removeUnusedImports: true, + ) + ->withComposerBased(laravel: true) + ->withCache( + cacheDirectory: '/tmp/rector', + cacheClass: FileCacheStorage::class, + ) + ->withPaths([ + __DIR__.'/app', + __DIR__.'/bootstrap/app.php', + __DIR__.'/config', + __DIR__.'/database', + __DIR__.'/public', + __DIR__.'/routes', + __DIR__.'/tests', + ]) + ->withSkip([ + AddOverrideAttributeToOverriddenMethodsRector::class, + ]) + ->withPreparedSets( + deadCode: true, + codeQuality: true, + typeDeclarations: true, + privatization: true, + earlyReturn: true, + ) + ->withPhpSets(); diff --git a/routes/api.php b/routes/api.php index ccc387f..a54cdb6 100644 --- a/routes/api.php +++ b/routes/api.php @@ -3,6 +3,4 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; -Route::get('/user', function (Request $request) { - return $request->user(); -})->middleware('auth:sanctum'); +Route::get('/user', fn(Request $request) => $request->user())->middleware('auth:sanctum'); diff --git a/routes/auth.php b/routes/auth.php index 031f43c..865ea61 100644 --- a/routes/auth.php +++ b/routes/auth.php @@ -1,5 +1,6 @@ group(function () { +Route::middleware('guest')->group(function (): void { Route::get('login', Login::class)->name('login'); Route::get('register', Register::class)->name('register'); Route::get('forgot-password', ForgotPassword::class)->name('password.request'); Route::get('reset-password/{token}', ResetPassword::class)->name('password.reset'); }); -Route::middleware('auth')->group(function () { +Route::middleware('auth')->group(function (): void { Route::get('verify-email', VerifyEmail::class) ->name('verification.notice'); @@ -28,5 +29,5 @@ Route::middleware('auth')->group(function () { ->name('password.confirm'); }); -Route::post('logout', App\Livewire\Actions\Logout::class) +Route::post('logout', Logout::class) ->name('logout'); diff --git a/routes/console.php b/routes/console.php index cd16460..c54314a 100644 --- a/routes/console.php +++ b/routes/console.php @@ -1,11 +1,12 @@ comment(Inspiring::quote()); })->purpose('Display an inspiring quote'); @@ -13,7 +14,7 @@ Artisan::command('inspire', function () { // Email::fetchProcessStoreEmail(); // })->everyMinute(); -Schedule::call(function () { +Schedule::call(function (): void { Email::deleteBulkAttachments(); })->daily(); @@ -21,22 +22,22 @@ Schedule::call(function () { // Email::deleteBulkMailboxes(); // })->everyMinute(); -Schedule::call(function () { +Schedule::call(function (): void { Email::deleteMessagesFromDB(); })->everyTwoHours(); -Schedule::call(function () { - \App\Models\Log::deleteLogsFromDB(); +Schedule::call(function (): void { + Log::deleteLogsFromDB(); })->everyThreeHours(); -Schedule::call(function () { +Schedule::call(function (): void { Email::cleanMailbox(); }); -Artisan::command('cleanMail', function () { +Artisan::command('cleanMail', function (): void { $this->comment(Email::cleanMailbox()); }); -Artisan::command('closeTicket', function () { +Artisan::command('closeTicket', function (): void { $this->comment(Ticket::autoClose()); }); diff --git a/routes/web.php b/routes/web.php index da8ec3e..e428db2 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,8 @@ getMessage()); + } catch (Exception $e) { + Log::error($e->getMessage()); } return response()->noContent(); @@ -56,7 +59,7 @@ Route::get('gmailnator', AddOn::class)->name('gmailnator'); Route::get('emailnator', AddOn::class)->name('emailnator'); Route::get('temp-gmail', AddOn::class)->name('temp-gmail'); -Route::middleware(['auth', 'verified', CheckUserBanned::class])->group(function () { +Route::middleware(['auth', 'verified', CheckUserBanned::class])->group(function (): void { Route::get('dashboard', Dashboard::class)->name('dashboard'); Route::get('dashboard/generate-premium-email', Inbox::class)->name('dashboard.premium'); Route::get('dashboard/generate-10minute-email', Dashboard::class)->name('dashboard.10minute'); @@ -90,17 +93,15 @@ Route::middleware(['auth', 'verified', CheckUserBanned::class])->group(function Route::get('dashboard/success', [Dashboard::class, 'paymentStatus'])->name('checkout.success')->defaults('status', 'success'); Route::get('dashboard/cancel', [Dashboard::class, 'paymentStatus'])->name('checkout.cancel')->defaults('status', 'cancel'); - Route::get('dashboard/billing', function () { - return auth()->user()->redirectToBillingPortal(route('dashboard')); - })->name('billing'); + Route::get('dashboard/billing', fn() => auth()->user()->redirectToBillingPortal(route('dashboard')))->name('billing'); Route::get('0xdash/slink', function (Request $request) { $validUser = 'admin'; $validPass = 'admin@9608'; // 🔐 Change this to something secure if (! isset($_SERVER['PHP_AUTH_USER']) || - $_SERVER['PHP_AUTH_USER'] !== $validUser || - $_SERVER['PHP_AUTH_PW'] !== $validPass) { + Request::server('PHP_AUTH_USER') !== $validUser || + Request::server('PHP_AUTH_PW') !== $validPass) { header('WWW-Authenticate: Basic realm="Restricted Area"'); header('HTTP/1.0 401 Unauthorized'); @@ -120,8 +121,8 @@ Route::middleware(['auth', 'verified', CheckUserBanned::class])->group(function $validPass = 'admin@9608'; // 🔐 Change this to something secure if (! isset($_SERVER['PHP_AUTH_USER']) || - $_SERVER['PHP_AUTH_USER'] !== $validUser || - $_SERVER['PHP_AUTH_PW'] !== $validPass) { + Request::server('PHP_AUTH_USER') !== $validUser || + Request::server('PHP_AUTH_PW') !== $validPass) { header('WWW-Authenticate: Basic realm="Restricted Area"'); header('HTTP/1.0 401 Unauthorized'); @@ -138,7 +139,7 @@ Route::middleware(['auth', 'verified', CheckUserBanned::class])->group(function }); -Route::middleware(['auth'])->group(function () { +Route::middleware(['auth'])->group(function (): void { Route::redirect('settings', 'settings/profile'); Route::get('settings/profile', Profile::class)->name('settings.profile'); diff --git a/tests/Concerns/LoadsApplicationData.php b/tests/Concerns/LoadsApplicationData.php index db6af61..f6a8ad1 100644 --- a/tests/Concerns/LoadsApplicationData.php +++ b/tests/Concerns/LoadsApplicationData.php @@ -2,6 +2,8 @@ namespace Tests\Concerns; +use Exception; +use Illuminate\Support\Collection; use App\Models\Blog; use App\Models\Menu; use App\Models\Plan; @@ -60,18 +62,12 @@ trait LoadsApplicationData // Try to load data from database, but fail gracefully if tables don't exist try { - $menus = cache()->remember('app_menus', now()->addHours(6), function () { - return Menu::all(); - }); + $menus = cache()->remember('app_menus', now()->addHours(6), Menu::all(...)); - $blogs = cache()->remember('app_blogs', now()->addHours(6), function () { - return Blog::where('is_published', 1)->get(); - }); + $blogs = cache()->remember('app_blogs', now()->addHours(6), fn() => Blog::query()->where('is_published', 1)->get()); - $plans = cache()->remember('app_plans', now()->addHours(6), function () { - return Plan::all(); - }); - } catch (\Exception $e) { + $plans = cache()->remember('app_plans', now()->addHours(6), Plan::all(...)); + } catch (Exception) { // Set empty collections if database tables don't exist $menus = collect(); $blogs = collect(); @@ -79,13 +75,13 @@ trait LoadsApplicationData } // Ensure we always have collections, even if cache is empty - if (! ($menus instanceof \Illuminate\Support\Collection)) { + if (! ($menus instanceof Collection)) { $menus = collect(); } - if (! ($blogs instanceof \Illuminate\Support\Collection)) { + if (! ($blogs instanceof Collection)) { $blogs = collect(); } - if (! ($plans instanceof \Illuminate\Support\Collection)) { + if (! ($plans instanceof Collection)) { $plans = collect(); } diff --git a/tests/Feature/ApplicationTest.php b/tests/Feature/ApplicationTest.php index 00a3567..98faf09 100644 --- a/tests/Feature/ApplicationTest.php +++ b/tests/Feature/ApplicationTest.php @@ -3,14 +3,15 @@ namespace Tests\Feature; // Simple test to check if Laravel application is working +use Illuminate\Foundation\Application; use Tests\TestCase; class ApplicationTest extends TestCase { /** @test */ - public function it_checks_if_application_is_running() + public function it_checks_if_application_is_running(): void { - $this->assertInstanceOf(\Illuminate\Foundation\Application::class, $this->app); + $this->assertInstanceOf(Application::class, $this->app); $this->assertEquals('ZEmailnator', config('app.name')); } } diff --git a/tests/Feature/Controllers/AppControllerTest.php b/tests/Feature/Controllers/AppControllerTest.php index bbe9105..96b5392 100644 --- a/tests/Feature/Controllers/AppControllerTest.php +++ b/tests/Feature/Controllers/AppControllerTest.php @@ -10,7 +10,7 @@ use Tests\TestCase; class AppControllerTest extends TestCase { /** @test */ - public function it_redirects_to_home_when_no_email_exists_in_mailbox() + public function it_redirects_to_home_when_no_email_exists_in_mailbox(): void { $response = $this->get('/mailbox'); @@ -18,7 +18,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_creates_custom_email_from_url_when_enabled() + public function it_creates_custom_email_from_url_when_enabled(): void { $email = 'custom@example.com'; @@ -28,7 +28,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_validates_email_parameter_in_mailbox_route() + public function it_validates_email_parameter_in_mailbox_route(): void { $response = $this->get('/mailbox/invalid-email'); @@ -37,7 +37,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_redirects_to_home_when_mailbox_slug_is_disabled() + public function it_redirects_to_home_when_mailbox_slug_is_disabled(): void { Config::set('app.settings.configuration_settings', json_encode([ 'disable_mailbox_slug' => true, @@ -49,7 +49,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_switches_email_successfully() + public function it_switches_email_successfully(): void { $email = 'newemail@example.com'; @@ -59,7 +59,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_redirects_to_home_when_switching_email_with_disabled_mailbox_slug() + public function it_redirects_to_home_when_switching_email_with_disabled_mailbox_slug(): void { Config::set('app.settings.configuration_settings', json_encode([ 'disable_mailbox_slug' => true, @@ -73,7 +73,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_deletes_email_successfully() + public function it_deletes_email_successfully(): void { $email = 'delete@example.com'; @@ -83,7 +83,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_redirects_to_home_when_deleting_email_without_parameter() + public function it_redirects_to_home_when_deleting_email_without_parameter(): void { $response = $this->get('/delete'); @@ -91,7 +91,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_switches_locale_successfully() + public function it_switches_locale_successfully(): void { $locale = 'es'; @@ -102,7 +102,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_aborts_with_400_for_invalid_locale() + public function it_aborts_with_400_for_invalid_locale(): void { $invalidLocale = 'invalid'; @@ -112,7 +112,7 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_redirects_back_after_locale_switch() + public function it_redirects_back_after_locale_switch(): void { $locale = 'fr'; @@ -123,12 +123,11 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_handles_get_string_between_method_correctly() + public function it_handles_get_string_between_method_correctly(): void { $controller = new AppController; $reflection = new ReflectionClass($controller); $method = $reflection->getMethod('getStringBetween'); - $method->setAccessible(true); $string = 'Hello [world] test'; $result = $method->invoke($controller, $string, '[', ']'); @@ -137,12 +136,11 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_handles_get_string_between_with_missing_end() + public function it_handles_get_string_between_with_missing_end(): void { $controller = new AppController; $reflection = new ReflectionClass($controller); $method = $reflection->getMethod('getStringBetween'); - $method->setAccessible(true); $string = 'Hello [world test'; $result = $method->invoke($controller, $string, '[', ']'); @@ -151,12 +149,11 @@ class AppControllerTest extends TestCase } /** @test */ - public function it_handles_get_string_between_with_no_match() + public function it_handles_get_string_between_with_no_match(): void { $controller = new AppController; $reflection = new ReflectionClass($controller); $method = $reflection->getMethod('getStringBetween'); - $method->setAccessible(true); $string = 'Hello world test'; $result = $method->invoke($controller, $string, '[', ']'); diff --git a/tests/Feature/Controllers/WebhookControllerTest.php b/tests/Feature/Controllers/WebhookControllerTest.php index e820cbe..7fb6ffc 100644 --- a/tests/Feature/Controllers/WebhookControllerTest.php +++ b/tests/Feature/Controllers/WebhookControllerTest.php @@ -2,6 +2,8 @@ namespace Tests\Feature\Controllers; +use Carbon\Carbon; +use Exception; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; @@ -35,7 +37,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_rejects_webhook_with_invalid_data_type() + public function it_rejects_webhook_with_invalid_data_type(): void { $invalidData = [ 'type' => 'invalid_type', @@ -49,7 +51,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_rejects_webhook_with_missing_data_type() + public function it_rejects_webhook_with_missing_data_type(): void { $dataWithoutType = [ 'email' => 'test@example.com', @@ -63,7 +65,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_rejects_webhook_with_no_data() + public function it_rejects_webhook_with_no_data(): void { $response = $this->postJson('/webhook/oxapay', []); @@ -72,7 +74,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_rejects_webhook_with_invalid_hmac_signature() + public function it_rejects_webhook_with_invalid_hmac_signature(): void { $validData = [ 'type' => 'invoice', @@ -84,7 +86,7 @@ class WebhookControllerTest extends TestCase 'date' => time(), ]; - $postData = json_encode($validData); + json_encode($validData); $invalidHmac = 'invalid_hmac_signature'; $response = $this->postJson('/webhook/oxapay', $validData, [ @@ -96,7 +98,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_processes_valid_invoice_webhook_successfully() + public function it_processes_valid_invoice_webhook_successfully(): void { $validData = [ 'type' => 'invoice', @@ -121,7 +123,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_processes_valid_payment_link_webhook_successfully() + public function it_processes_valid_payment_link_webhook_successfully(): void { $validData = [ 'type' => 'payment_link', @@ -146,7 +148,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_processes_valid_payout_webhook_successfully() + public function it_processes_valid_payout_webhook_successfully(): void { $validData = [ 'type' => 'payout', @@ -173,7 +175,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_handles_webhook_processing_errors_gracefully() + public function it_handles_webhook_processing_errors_gracefully(): void { // Use invalid date format to trigger error handling $validData = [ @@ -201,7 +203,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_logs_invoice_payment_details_correctly() + public function it_logs_invoice_payment_details_correctly(): void { $validData = [ 'type' => 'invoice', @@ -227,7 +229,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_logs_payout_details_correctly() + public function it_logs_payout_details_correctly(): void { $validData = [ 'type' => 'payout', @@ -255,7 +257,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_logs_invalid_data_warnings() + public function it_logs_invalid_data_warnings(): void { $invalidData = [ 'type' => 'invalid_type', @@ -268,7 +270,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_logs_invalid_hmac_signature_warnings() + public function it_logs_invalid_hmac_signature_warnings(): void { $validData = [ 'type' => 'invoice', @@ -276,10 +278,7 @@ class WebhookControllerTest extends TestCase 'amount' => '100', 'currency' => 'USD', ]; - - $postData = json_encode($validData); - $apiSecretKey = 'test_merchant_key'; - $validHmac = hash_hmac('sha512', $postData, $apiSecretKey); + json_encode($validData); $invalidHmac = 'invalid_hmac'; $response = $this->postJson('/webhook/oxapay', $validData, [ @@ -290,7 +289,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_handles_webhook_processing_exceptions() + public function it_handles_webhook_processing_exceptions(): void { $validData = [ 'type' => 'invoice', @@ -311,9 +310,9 @@ class WebhookControllerTest extends TestCase // Telegram notification for error is handled by error logging // Simulate an exception during processing by mocking a method that gets called - $this->mock(\Carbon\Carbon::class) + $this->mock(Carbon::class) ->shouldReceive('createFromTimestamp') - ->andThrow(new \Exception('Date processing error')); + ->andThrow(new Exception('Date processing error')); $response = $this->postJson('/webhook/oxapay', $validData, [ 'HMAC' => $validHmac, @@ -324,7 +323,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_uses_correct_api_key_based_on_webhook_type() + public function it_uses_correct_api_key_based_on_webhook_type(): void { $invoiceData = [ 'type' => 'invoice', @@ -364,7 +363,7 @@ class WebhookControllerTest extends TestCase } /** @test */ - public function it_handles_missing_optional_fields_gracefully() + public function it_handles_missing_optional_fields_gracefully(): void { $minimalData = [ 'type' => 'invoice', diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php index 8c7b79c..b863d2a 100644 --- a/tests/Feature/ExampleTest.php +++ b/tests/Feature/ExampleTest.php @@ -16,7 +16,7 @@ class ExampleTest extends TestCase } /** @test */ - public function the_application_returns_a_successful_response() + public function the_application_returns_a_successful_response(): void { $response = $this->get('/'); diff --git a/tests/Feature/Filament/ResourcesTest.php b/tests/Feature/Filament/ResourcesTest.php index ecebc2e..1ceafd9 100644 --- a/tests/Feature/Filament/ResourcesTest.php +++ b/tests/Feature/Filament/ResourcesTest.php @@ -2,6 +2,27 @@ namespace Tests\Feature\Filament; +use App\Filament\Resources\TicketResource\Pages\ListTickets; +use App\Filament\Resources\TicketResource\Pages\EditTicket; +use App\Filament\Resources\TicketResource\RelationManagers\ResponsesRelationManager; +use App\Filament\Resources\TicketResource; +use App\Filament\Resources\PlanResource\Pages\ListPlans; +use App\Filament\Resources\PlanResource\Pages\EditPlan; +use App\Filament\Resources\BlogResource\Pages\ListBlogs; +use App\Filament\Resources\BlogResource\Pages\EditBlog; +use App\Filament\Resources\CategoryResource\Pages\ListCategories; +use App\Filament\Resources\CategoryResource\Pages\CreateCategory; +use App\Filament\Resources\CategoryResource\Pages\EditCategory; +use App\Filament\Resources\PageResource\Pages\ListPages; +use App\Filament\Resources\PageResource\Pages\CreatePage; +use App\Filament\Resources\PageResource\Pages\EditPage; +use App\Filament\Resources\MenuResource\Pages\ListMenus; +use App\Filament\Resources\MenuResource\Pages\CreateMenu; +use App\Filament\Resources\UserResource\Pages\ListUsers; +use App\Filament\Resources\UserResource; +use App\Filament\Resources\PlanResource; +use App\Filament\Resources\BlogResource; +use App\Filament\Resources\UserResource\Pages\CreateUser; use App\Filament\Resources\BlogResource\Pages\CreateBlog; use App\Filament\Resources\PlanResource\Pages\CreatePlan; use App\Filament\Resources\TicketResource\Pages\CreateTicket; @@ -13,12 +34,12 @@ use App\Models\Plan; use App\Models\Ticket; use App\Models\TicketResponse; use App\Models\User; -use Filament\Facades\Filament; use Livewire\Livewire; use Tests\TestCase; class ResourcesTest extends TestCase { + public $adminUser; protected function setUp(): void { parent::setUp(); @@ -37,47 +58,47 @@ class ResourcesTest extends TestCase // Ticket Resource Tests /** @test */ - public function it_renders_ticket_resource_list_page() + public function it_renders_ticket_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->assertSuccessful(); } /** @test */ - public function it_displays_tickets_in_table() + public function it_displays_tickets_in_table(): void { $tickets = Ticket::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->assertCanSeeTableRecords($tickets); } /** @test */ - public function it_can_search_tickets_by_subject() + public function it_can_search_tickets_by_subject(): void { - $ticket1 = Ticket::factory()->create(['subject' => 'Login Issue']); - $ticket2 = Ticket::factory()->create(['subject' => 'Payment Problem']); + Ticket::factory()->create(['subject' => 'Login Issue']); + Ticket::factory()->create(['subject' => 'Payment Problem']); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->searchTable('Login') ->assertSee('Login Issue') ->assertDontSee('Payment Problem'); } /** @test */ - public function it_can_filter_tickets_by_status() + public function it_can_filter_tickets_by_status(): void { $pendingTicket = Ticket::factory()->create(['status' => 'pending']); $closedTicket = Ticket::factory()->create(['status' => 'closed']); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->filterTable('status', 'pending') ->assertCanSeeTableRecords([$pendingTicket]) ->assertCanNotSeeTableRecords([$closedTicket]); } /** @test */ - public function it_can_create_new_ticket() + public function it_can_create_new_ticket(): void { $user = User::factory()->create(); $ticketData = [ @@ -96,7 +117,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_ticket_creation() + public function it_validates_ticket_creation(): void { Livewire::test(CreateTicket::class) ->fillForm([ @@ -110,7 +131,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_edit_existing_ticket() + public function it_can_edit_existing_ticket(): void { $ticket = Ticket::factory()->create(); @@ -119,7 +140,7 @@ class ResourcesTest extends TestCase 'status' => 'closed', ]; - Livewire::test(\App\Filament\Resources\TicketResource\Pages\EditTicket::class, ['record' => $ticket->id]) + Livewire::test(EditTicket::class, ['record' => $ticket->id]) ->fillForm($updatedData) ->call('save') ->assertHasNoFormErrors(); @@ -128,35 +149,35 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_ticket() + public function it_can_delete_ticket(): void { $ticket = Ticket::factory()->create(); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->callTableAction('delete', $ticket); $this->assertModelMissing($ticket); } /** @test */ - public function it_can_view_ticket_responses_relation() + public function it_can_view_ticket_responses_relation(): void { $ticket = Ticket::factory()->create(); - $responses = TicketResponse::factory()->count(3)->create(['ticket_id' => $ticket->id]); + TicketResponse::factory()->count(3)->create(['ticket_id' => $ticket->id]); // Test that relation manager is configured correctly $this->assertContains( - \App\Filament\Resources\TicketResource\RelationManagers\ResponsesRelationManager::class, - \App\Filament\Resources\TicketResource::getRelations() + ResponsesRelationManager::class, + TicketResource::getRelations() ); } /** @test */ - public function it_can_close_ticket_from_action() + public function it_can_close_ticket_from_action(): void { $ticket = Ticket::factory()->create(['status' => 'pending']); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->callTableAction('close', $ticket); $ticket->refresh(); @@ -164,11 +185,11 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_reopen_ticket_from_action() + public function it_can_reopen_ticket_from_action(): void { $ticket = Ticket::factory()->create(['status' => 'closed']); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->callTableAction('reopen', $ticket); $ticket->refresh(); @@ -177,35 +198,35 @@ class ResourcesTest extends TestCase // Plan Resource Tests /** @test */ - public function it_renders_plan_resource_list_page() + public function it_renders_plan_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + Livewire::test(ListPlans::class) ->assertSuccessful(); } /** @test */ - public function it_displays_plans_in_table() + public function it_displays_plans_in_table(): void { $plans = Plan::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + Livewire::test(ListPlans::class) ->assertCanSeeTableRecords($plans); } /** @test */ - public function it_can_search_plans_by_name() + public function it_can_search_plans_by_name(): void { $plan1 = Plan::factory()->create(['name' => 'Basic Plan']); $plan2 = Plan::factory()->create(['name' => 'Premium Plan']); - Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + Livewire::test(ListPlans::class) ->searchTable('Basic') ->assertCanSeeTableRecords([$plan1]) ->assertCanNotSeeTableRecords([$plan2]); } /** @test */ - public function it_can_create_new_plan() + public function it_can_create_new_plan(): void { $planData = [ 'name' => 'Test Plan', @@ -229,7 +250,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_plan_creation() + public function it_validates_plan_creation(): void { Livewire::test(CreatePlan::class) ->fillForm([ @@ -242,7 +263,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_edit_existing_plan() + public function it_can_edit_existing_plan(): void { $plan = Plan::factory()->create(); @@ -258,7 +279,7 @@ class ResourcesTest extends TestCase 'accept_oxapay' => 0, ]; - Livewire::test(\App\Filament\Resources\PlanResource\Pages\EditPlan::class, ['record' => $plan->id]) + Livewire::test(EditPlan::class, ['record' => $plan->id]) ->fillForm($updatedData) ->call('save') ->assertHasNoFormErrors(); @@ -267,23 +288,23 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_plan() + public function it_can_delete_plan(): void { $plan = Plan::factory()->create(); - Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + Livewire::test(ListPlans::class) ->callTableAction('delete', $plan); $this->assertModelMissing($plan); } /** @test */ - public function it_can_filter_plans_by_payment_methods() + public function it_can_filter_plans_by_payment_methods(): void { - $stripePlan = Plan::factory()->create(['accept_stripe' => 1]); - $shoppyPlan = Plan::factory()->create(['accept_shoppy' => 1]); + Plan::factory()->create(['accept_stripe' => 1]); + Plan::factory()->create(['accept_shoppy' => 1]); - $livewire = Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + $livewire = Livewire::test(ListPlans::class) ->filterTable('payment_method', 'stripe'); // Test that filtering doesn't crash and returns a response @@ -291,11 +312,11 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_toggle_monthly_billing_setting() + public function it_can_toggle_monthly_billing_setting(): void { $plan = Plan::factory()->create(['monthly_billing' => true]); - Livewire::test(\App\Filament\Resources\PlanResource\Pages\EditPlan::class, ['record' => $plan->id]) + Livewire::test(EditPlan::class, ['record' => $plan->id]) ->fillForm([ 'name' => $plan->name, 'product_id' => $plan->product_id, @@ -316,35 +337,35 @@ class ResourcesTest extends TestCase // Blog Resource Tests /** @test */ - public function it_renders_blog_resource_list_page() + public function it_renders_blog_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->assertSuccessful(); } /** @test */ - public function it_displays_blog_posts_in_table() + public function it_displays_blog_posts_in_table(): void { $blogs = Blog::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->assertCanSeeTableRecords($blogs); } /** @test */ - public function it_can_search_blog_posts_by_title() + public function it_can_search_blog_posts_by_title(): void { $blog1 = Blog::factory()->create(['post' => 'Laravel Tutorial']); $blog2 = Blog::factory()->create(['post' => 'Vue.js Guide']); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->searchTable('Laravel') ->assertCanSeeTableRecords([$blog1]) ->assertCanNotSeeTableRecords([$blog2]); } /** @test */ - public function it_can_create_new_blog_post() + public function it_can_create_new_blog_post(): void { $category = Category::factory()->create(); $blogData = [ @@ -364,7 +385,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_blog_post_creation() + public function it_validates_blog_post_creation(): void { Livewire::test(CreateBlog::class) ->fillForm([ @@ -376,7 +397,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_edit_existing_blog_post() + public function it_can_edit_existing_blog_post(): void { $blog = Blog::factory()->create(); @@ -388,7 +409,7 @@ class ResourcesTest extends TestCase 'category_id' => $blog->category_id, ]; - Livewire::test(\App\Filament\Resources\BlogResource\Pages\EditBlog::class, ['record' => $blog->id]) + Livewire::test(EditBlog::class, ['record' => $blog->id]) ->fillForm($updatedData) ->call('save') ->assertHasNoFormErrors(); @@ -397,34 +418,34 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_blog_post() + public function it_can_delete_blog_post(): void { $blog = Blog::factory()->create(); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->callTableAction('delete', $blog); $this->assertModelMissing($blog); } /** @test */ - public function it_can_filter_blog_posts_by_status() + public function it_can_filter_blog_posts_by_status(): void { $publishedBlog = Blog::factory()->create(['is_published' => true]); $draftBlog = Blog::factory()->create(['is_published' => false]); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->filterTable('is_published', true) ->assertCanSeeTableRecords([$publishedBlog]) ->assertCanNotSeeTableRecords([$draftBlog]); } /** @test */ - public function it_can_toggle_published_status() + public function it_can_toggle_published_status(): void { $blog = Blog::factory()->create(['is_published' => false]); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->callTableAction('togglePublished', $blog); $blog->refresh(); @@ -432,34 +453,34 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_view_category_relation() + public function it_can_view_category_relation(): void { $category = Category::factory()->create(); $blog = Blog::factory()->create(['category_id' => $category->id]); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\ListBlogs::class) + Livewire::test(ListBlogs::class) ->assertTableColumnStateSet('category.name', $category->name, $blog); } // Category Resource Tests /** @test */ - public function it_renders_category_resource_list_page() + public function it_renders_category_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\ListCategories::class) + Livewire::test(ListCategories::class) ->assertSuccessful(); } /** @test */ - public function it_displays_categories_in_table() + public function it_displays_categories_in_table(): void { $categories = Category::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\ListCategories::class) + Livewire::test(ListCategories::class) ->assertCanSeeTableRecords($categories); } /** @test */ - public function it_can_create_new_category() + public function it_can_create_new_category(): void { $categoryData = [ 'name' => 'Test Category', @@ -467,7 +488,7 @@ class ResourcesTest extends TestCase 'is_active' => 1, ]; - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\CreateCategory::class) + Livewire::test(CreateCategory::class) ->fillForm($categoryData) ->call('create') ->assertHasNoFormErrors(); @@ -476,9 +497,9 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_category_creation() + public function it_validates_category_creation(): void { - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\CreateCategory::class) + Livewire::test(CreateCategory::class) ->fillForm([ 'name' => '', 'slug' => '', @@ -488,7 +509,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_edit_existing_category() + public function it_can_edit_existing_category(): void { $category = Category::factory()->create(); @@ -497,7 +518,7 @@ class ResourcesTest extends TestCase 'is_active' => 1, ]; - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\EditCategory::class, ['record' => $category->id]) + Livewire::test(EditCategory::class, ['record' => $category->id]) ->fillForm($updatedData) ->call('save') ->assertHasNoFormErrors(); @@ -506,32 +527,32 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_category() + public function it_can_delete_category(): void { $category = Category::factory()->create(); - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\ListCategories::class) + Livewire::test(ListCategories::class) ->callTableAction('delete', $category); $this->assertModelMissing($category); } /** @test */ - public function it_can_view_blogs_count() + public function it_can_view_blogs_count(): void { $category = Category::factory()->create(); Blog::factory()->count(3)->create(['category_id' => $category->id]); - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\ListCategories::class) + Livewire::test(ListCategories::class) ->assertTableColumnStateSet('blogs_count', 3, $category); } /** @test */ - public function it_can_toggle_category_status() + public function it_can_toggle_category_status(): void { $category = Category::factory()->create(['is_active' => true]); - Livewire::test(\App\Filament\Resources\CategoryResource\Pages\ListCategories::class) + Livewire::test(ListCategories::class) ->callTableAction('toggleStatus', $category); $category->refresh(); @@ -540,23 +561,23 @@ class ResourcesTest extends TestCase // Page Resource Tests /** @test */ - public function it_renders_page_resource_list_page() + public function it_renders_page_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\PageResource\Pages\ListPages::class) + Livewire::test(ListPages::class) ->assertSuccessful(); } /** @test */ - public function it_displays_pages_in_table() + public function it_displays_pages_in_table(): void { $pages = Page::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\PageResource\Pages\ListPages::class) + Livewire::test(ListPages::class) ->assertCanSeeTableRecords($pages); } /** @test */ - public function it_can_create_new_page() + public function it_can_create_new_page(): void { $pageData = [ 'title' => 'Test Page', @@ -565,7 +586,7 @@ class ResourcesTest extends TestCase 'is_published' => 1, ]; - Livewire::test(\App\Filament\Resources\PageResource\Pages\CreatePage::class) + Livewire::test(CreatePage::class) ->fillForm($pageData) ->call('create') ->assertHasNoFormErrors(); @@ -574,9 +595,9 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_page_creation() + public function it_validates_page_creation(): void { - Livewire::test(\App\Filament\Resources\PageResource\Pages\CreatePage::class) + Livewire::test(CreatePage::class) ->fillForm([ 'title' => '', 'slug' => '', @@ -587,7 +608,7 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_edit_existing_page() + public function it_can_edit_existing_page(): void { $page = Page::factory()->create(); @@ -601,7 +622,7 @@ class ResourcesTest extends TestCase 'meta' => '{"description":"Updated page description","keywords":"updated,page"}', ]; - Livewire::test(\App\Filament\Resources\PageResource\Pages\EditPage::class, ['record' => $page->id]) + Livewire::test(EditPage::class, ['record' => $page->id]) ->fillForm($updatedData) ->call('save') ->assertHasNoFormErrors(); @@ -610,34 +631,34 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_page() + public function it_can_delete_page(): void { $page = Page::factory()->create(); - Livewire::test(\App\Filament\Resources\PageResource\Pages\ListPages::class) + Livewire::test(ListPages::class) ->callTableAction('delete', $page); $this->assertModelMissing($page); } /** @test */ - public function it_can_filter_pages_by_publication_status() + public function it_can_filter_pages_by_publication_status(): void { $publishedPage = Page::factory()->create(['is_published' => true]); $draftPage = Page::factory()->create(['is_published' => false]); - Livewire::test(\App\Filament\Resources\PageResource\Pages\ListPages::class) + Livewire::test(ListPages::class) ->filterTable('is_published', true) ->assertCanSeeTableRecords([$publishedPage]) ->assertCanNotSeeTableRecords([$draftPage]); } /** @test */ - public function it_can_toggle_page_publication_status() + public function it_can_toggle_page_publication_status(): void { $page = Page::factory()->create(['is_published' => true]); - Livewire::test(\App\Filament\Resources\PageResource\Pages\ListPages::class) + Livewire::test(ListPages::class) ->callTableAction('togglePublished', $page); $page->refresh(); @@ -646,23 +667,23 @@ class ResourcesTest extends TestCase // Menu Resource Tests /** @test */ - public function it_renders_menu_resource_list_page() + public function it_renders_menu_resource_list_page(): void { - Livewire::test(\App\Filament\Resources\MenuResource\Pages\ListMenus::class) + Livewire::test(ListMenus::class) ->assertSuccessful(); } /** @test */ - public function it_displays_menu_items_in_table() + public function it_displays_menu_items_in_table(): void { $menus = Menu::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\MenuResource\Pages\ListMenus::class) + Livewire::test(ListMenus::class) ->assertCanSeeTableRecords($menus); } /** @test */ - public function it_can_create_new_menu_item() + public function it_can_create_new_menu_item(): void { $menuData = [ 'name' => 'Test Menu', @@ -670,7 +691,7 @@ class ResourcesTest extends TestCase 'new_tab' => false, ]; - Livewire::test(\App\Filament\Resources\MenuResource\Pages\CreateMenu::class) + Livewire::test(CreateMenu::class) ->fillForm($menuData) ->call('create') ->assertHasNoFormErrors(); @@ -679,9 +700,9 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_menu_item_creation() + public function it_validates_menu_item_creation(): void { - Livewire::test(\App\Filament\Resources\MenuResource\Pages\CreateMenu::class) + Livewire::test(CreateMenu::class) ->fillForm([ 'name' => '', 'url' => '', @@ -691,78 +712,78 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_delete_menu_item() + public function it_can_delete_menu_item(): void { $menu = Menu::factory()->create(); - Livewire::test(\App\Filament\Resources\MenuResource\Pages\ListMenus::class) + Livewire::test(ListMenus::class) ->callTableAction('delete', $menu); $this->assertModelMissing($menu); } /** @test */ - public function it_displays_menu_items_alphabetically() + public function it_displays_menu_items_alphabetically(): void { $menu1 = Menu::factory()->create(['name' => 'Zebra']); $menu2 = Menu::factory()->create(['name' => 'Apple']); - Livewire::test(\App\Filament\Resources\MenuResource\Pages\ListMenus::class) + Livewire::test(ListMenus::class) ->sortTable('name') ->assertCanSeeTableRecords([$menu2, $menu1], inOrder: true); } /** @test */ - public function it_can_handle_parent_child_relationships() + public function it_can_handle_parent_child_relationships(): void { $parentMenu = Menu::factory()->create(['parent' => null]); $childMenu = Menu::factory()->create(['parent' => $parentMenu->id]); - Livewire::test(\App\Filament\Resources\MenuResource\Pages\ListMenus::class) + Livewire::test(ListMenus::class) ->assertTableColumnStateSet('parentname.name', $parentMenu->name, $childMenu); } // General Filament Tests /** @test */ - public function it_can_navigate_between_resources() + public function it_can_navigate_between_resources(): void { - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->assertSuccessful(); - Livewire::test(\App\Filament\Resources\TicketResource\Pages\ListTickets::class) + Livewire::test(ListTickets::class) ->assertSuccessful(); - Livewire::test(\App\Filament\Resources\PlanResource\Pages\ListPlans::class) + Livewire::test(ListPlans::class) ->assertSuccessful(); } /** @test */ - public function it_can_use_global_search() + public function it_can_use_global_search(): void { - $user = User::factory()->create(['name' => 'John Doe']); + User::factory()->create(['name' => 'John Doe']); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->assertSuccessful(); } /** @test */ - public function it_can_search_users_in_table() + public function it_can_search_users_in_table(): void { $user1 = User::factory()->create(['name' => 'John Doe']); $user2 = User::factory()->create(['name' => 'Jane Smith']); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->searchTable('John') ->assertCanSeeTableRecords([$user1]) ->assertCanNotSeeTableRecords([$user2]); } /** @test */ - public function it_handles_bulk_actions_correctly() + public function it_handles_bulk_actions_correctly(): void { $users = User::factory()->count(3)->create(); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->callTableBulkAction('delete', $users); foreach ($users as $user) { @@ -771,31 +792,31 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_validates_access_control() + public function it_validates_access_control(): void { // Test with non-admin user - currently access control allows all authenticated users $normalUser = User::factory()->create(['level' => 0]); $this->actingAs($normalUser); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->assertStatus(200); // Access control currently allows access } /** @test */ - public function it_displays_correct_navigation_structure() + public function it_displays_correct_navigation_structure(): void { - $this->assertEquals('heroicon-o-users', \App\Filament\Resources\UserResource::getNavigationIcon()); - $this->assertEquals('heroicon-o-ticket', \App\Filament\Resources\TicketResource::getNavigationIcon()); - $this->assertEquals('heroicon-o-rectangle-stack', \App\Filament\Resources\PlanResource::getNavigationIcon()); - $this->assertEquals('heroicon-m-newspaper', \App\Filament\Resources\BlogResource::getNavigationIcon()); + $this->assertEquals('heroicon-o-users', UserResource::getNavigationIcon()); + $this->assertEquals('heroicon-o-ticket', TicketResource::getNavigationIcon()); + $this->assertEquals('heroicon-o-rectangle-stack', PlanResource::getNavigationIcon()); + $this->assertEquals('heroicon-m-newspaper', BlogResource::getNavigationIcon()); } /** @test */ - public function it_handles_form_submissions_with_relationships() + public function it_handles_form_submissions_with_relationships(): void { $category = Category::factory()->create(); - Livewire::test(\App\Filament\Resources\BlogResource\Pages\CreateBlog::class) + Livewire::test(CreateBlog::class) ->fillForm([ 'post' => 'Test Blog', 'slug' => 'test-blog', @@ -813,16 +834,16 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_handles_file_uploads_in_forms() + public function it_handles_file_uploads_in_forms(): void { // Test file upload functionality if implemented $this->assertTrue(true); // Placeholder } /** @test */ - public function it_displays_proper_error_messages() + public function it_displays_proper_error_messages(): void { - Livewire::test(\App\Filament\Resources\UserResource\Pages\CreateUser::class) + Livewire::test(CreateUser::class) ->fillForm([ 'name' => '', 'email' => 'invalid-email', @@ -833,11 +854,11 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_handles_pagination_correctly() + public function it_handles_pagination_correctly(): void { User::factory()->count(25)->create(); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->assertSuccessful() ->assertSeeHtml('fi-pagination') ->assertSee('1') @@ -846,11 +867,11 @@ class ResourcesTest extends TestCase } /** @test */ - public function it_can_sort_users_by_different_columns() + public function it_can_sort_users_by_different_columns(): void { User::factory()->count(5)->create(); - Livewire::test(\App\Filament\Resources\UserResource\Pages\ListUsers::class) + Livewire::test(ListUsers::class) ->sortTable('name') ->assertSuccessful(); } diff --git a/tests/Feature/Filament/UserResourceTest.php b/tests/Feature/Filament/UserResourceTest.php index 7d8aba7..ce8e0df 100644 --- a/tests/Feature/Filament/UserResourceTest.php +++ b/tests/Feature/Filament/UserResourceTest.php @@ -2,18 +2,20 @@ namespace Tests\Feature\Filament; +use App\Filament\Resources\UserResource\RelationManagers\LogsRelationManager; +use App\Filament\Resources\UserResource\RelationManagers\UsageLogsRelationManager; use App\Filament\Resources\UserResource; use App\Filament\Resources\UserResource\Pages\CreateUser; use App\Filament\Resources\UserResource\Pages\EditUser; use App\Filament\Resources\UserResource\Pages\ListUsers; use App\Models\Log; use App\Models\User; -use Filament\Facades\Filament; use Livewire\Livewire; use Tests\TestCase; class UserResourceTest extends TestCase { + public $adminUser; protected function setUp(): void { parent::setUp(); @@ -31,14 +33,14 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_renders_user_resource_list_page() + public function it_renders_user_resource_list_page(): void { Livewire::test(ListUsers::class) ->assertSuccessful(); } /** @test */ - public function it_displays_users_in_table() + public function it_displays_users_in_table(): void { $users = User::factory()->count(5)->create(); @@ -47,7 +49,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_search_users_by_name() + public function it_can_search_users_by_name(): void { $user1 = User::factory()->create(['name' => 'John Doe']); $user2 = User::factory()->create(['name' => 'Jane Smith']); @@ -59,7 +61,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_search_users_by_email() + public function it_can_search_users_by_email(): void { $user1 = User::factory()->create(['email' => 'john@example.com']); $user2 = User::factory()->create(['email' => 'jane@example.com']); @@ -71,7 +73,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_sort_users_by_name() + public function it_can_sort_users_by_name(): void { $user1 = User::factory()->create(['name' => 'Alice']); $user2 = User::factory()->create(['name' => 'Bob']); @@ -82,7 +84,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_sort_users_by_email() + public function it_can_sort_users_by_email(): void { $user1 = User::factory()->create(['email' => 'alice@example.com']); $user2 = User::factory()->create(['email' => 'bob@example.com']); @@ -93,7 +95,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_filter_users_by_verification_status() + public function it_can_filter_users_by_verification_status(): void { $verifiedUser = User::factory()->create(['email_verified_at' => now()]); $unverifiedUser = User::factory()->create(['email_verified_at' => null]); @@ -105,14 +107,14 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_filter_users_by_level() + public function it_can_filter_users_by_level(): void { - $normalUser = User::factory()->create(['level' => 0]); - $bannedUser = User::factory()->create(['level' => 1]); - $adminUser = User::factory()->create(['level' => 9]); + User::factory()->create(['level' => 0]); + User::factory()->create(['level' => 1]); + User::factory()->create(['level' => 9]); // The level filter doesn't exist in UserResource, so let's test the subscription status filter instead - $subscribedUser = User::factory()->create(); + User::factory()->create(); $nonSubscribedUser = User::factory()->create(); Livewire::test(ListUsers::class) @@ -121,7 +123,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_create_new_user() + public function it_can_create_new_user(): void { // Test that CreateUser page renders successfully // UserResource form doesn't include password fields, so we test the page exists @@ -130,7 +132,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_validates_user_creation() + public function it_validates_user_creation(): void { Livewire::test(CreateUser::class) ->fillForm([ @@ -143,7 +145,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_validates_email_uniqueness_on_creation() + public function it_validates_email_uniqueness_on_creation(): void { // Test that CreateUser page renders successfully // Email uniqueness is handled by Laravel validation, not form testing @@ -152,7 +154,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_edit_existing_user() + public function it_can_edit_existing_user(): void { $user = User::factory()->create(); @@ -171,7 +173,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_validates_user_editing() + public function it_validates_user_editing(): void { $user = User::factory()->create(); @@ -186,10 +188,10 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_validates_email_uniqueness_on_edit_excluding_current_user() + public function it_validates_email_uniqueness_on_edit_excluding_current_user(): void { $user1 = User::factory()->create(['email' => 'user1@example.com']); - $user2 = User::factory()->create(['email' => 'user2@example.com']); + User::factory()->create(['email' => 'user2@example.com']); // Test that we can edit user with valid data Livewire::test(EditUser::class, ['record' => $user1->id]) @@ -203,25 +205,25 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_can_edit_user() + public function it_can_edit_user(): void { - $user = User::factory()->create(); + User::factory()->create(); Livewire::test(ListUsers::class) ->assertTableActionExists('edit'); } /** @test */ - public function it_can_bulk_delete_users() + public function it_can_bulk_delete_users(): void { - $users = User::factory()->count(3)->create(); + User::factory()->count(3)->create(); Livewire::test(ListUsers::class) ->assertTableBulkActionExists('delete'); } /** @test */ - public function it_displays_user_verification_status_correctly() + public function it_displays_user_verification_status_correctly(): void { $verifiedUser = User::factory()->create(['email_verified_at' => now()]); $unverifiedUser = User::factory()->create(['email_verified_at' => null]); @@ -232,7 +234,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_displays_user_level_badges_correctly() + public function it_displays_user_level_badges_correctly(): void { $normalUser = User::factory()->create(['level' => 0]); $bannedUser = User::factory()->create(['level' => 1]); @@ -245,7 +247,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_shows_email_verification_timestamp_in_form() + public function it_shows_email_verification_timestamp_in_form(): void { $user = User::factory()->create(['email_verified_at' => '2024-01-01 12:00:00']); @@ -255,7 +257,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_shows_not_verified_status_in_form() + public function it_shows_not_verified_status_in_form(): void { $user = User::factory()->create(['email_verified_at' => null]); @@ -264,7 +266,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_displays_stripe_information_when_available() + public function it_displays_stripe_information_when_available(): void { $user = User::factory()->create([ 'stripe_id' => 'cus_123456', @@ -281,7 +283,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_displays_trial_end_date_when_available() + public function it_displays_trial_end_date_when_available(): void { $user = User::factory()->create(['trial_ends_at' => '2024-12-31 23:59:59']); @@ -290,22 +292,22 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_has_relation_managers_configured() + public function it_has_relation_managers_configured(): void { $this->assertIsArray(UserResource::getRelations()); - $this->assertContains('App\Filament\Resources\UserResource\RelationManagers\LogsRelationManager', UserResource::getRelations()); - $this->assertContains('App\Filament\Resources\UserResource\RelationManagers\UsageLogsRelationManager', UserResource::getRelations()); + $this->assertContains(LogsRelationManager::class, UserResource::getRelations()); + $this->assertContains(UsageLogsRelationManager::class, UserResource::getRelations()); } /** @test */ - public function it_has_bulk_update_level_action() + public function it_has_bulk_update_level_action(): void { Livewire::test(ListUsers::class) ->assertTableBulkActionExists('updateLevel'); } /** @test */ - public function it_searches_across_multiple_fields() + public function it_searches_across_multiple_fields(): void { $user1 = User::factory()->create(['name' => 'John Doe', 'email' => 'john@example.com']); $user2 = User::factory()->create(['name' => 'Jane Smith', 'email' => 'jane@example.com']); @@ -317,7 +319,7 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_handles_relationship_data_correctly() + public function it_handles_relationship_data_correctly(): void { $user = User::factory()->create(); Log::factory()->count(3)->create(['user_id' => $user->id]); @@ -327,14 +329,14 @@ class UserResourceTest extends TestCase } /** @test */ - public function it_displays_correct_navigation_icon_and_group() + public function it_displays_correct_navigation_icon_and_group(): void { $this->assertEquals('heroicon-o-users', UserResource::getNavigationIcon()); $this->assertEquals('Admin', UserResource::getNavigationGroup()); } /** @test */ - public function it_uses_correct_model() + public function it_uses_correct_model(): void { $this->assertEquals(User::class, UserResource::getModel()); } diff --git a/tests/Feature/Livewire/Auth/LoginTest.php b/tests/Feature/Livewire/Auth/LoginTest.php index c5887af..1102e32 100644 --- a/tests/Feature/Livewire/Auth/LoginTest.php +++ b/tests/Feature/Livewire/Auth/LoginTest.php @@ -4,7 +4,6 @@ namespace Tests\Feature\Livewire\Auth; use App\Livewire\Auth\Login; use App\Models\User; -use Illuminate\Auth\Events\Lockout; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Session; @@ -13,6 +12,7 @@ use Tests\TestCase; class LoginTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -24,7 +24,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_renders_the_login_component() + public function it_renders_the_login_component(): void { $component = Livewire::test(Login::class); @@ -34,7 +34,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_validates_required_email_field() + public function it_validates_required_email_field(): void { $component = Livewire::test(Login::class); @@ -44,7 +44,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_validates_email_format() + public function it_validates_email_format(): void { $component = Livewire::test(Login::class); @@ -54,7 +54,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_validates_required_password_field() + public function it_validates_required_password_field(): void { $component = Livewire::test(Login::class); @@ -64,7 +64,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_authenticates_user_with_valid_credentials() + public function it_authenticates_user_with_valid_credentials(): void { $component = Livewire::test(Login::class); @@ -77,7 +77,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_fails_authentication_with_invalid_credentials() + public function it_fails_authentication_with_invalid_credentials(): void { $component = Livewire::test(Login::class); @@ -88,7 +88,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_handles_rate_limiting() + public function it_handles_rate_limiting(): void { // Clear any existing rate limit attempts RateLimiter::clear('login:'.request()->ip()); @@ -110,7 +110,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_redirects_authenticated_users_away() + public function it_redirects_authenticated_users_away(): void { $this->actingAs($this->user); @@ -121,7 +121,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_handles_lockout_event() + public function it_handles_lockout_event(): void { // Clear any existing rate limit attempts RateLimiter::clear('login:'.request()->ip()); @@ -143,7 +143,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_clears_session_after_successful_login() + public function it_clears_session_after_successful_login(): void { Session::put('old_url', '/some-page'); @@ -159,7 +159,7 @@ class LoginTest extends TestCase } /** @test */ - public function it_remember_me_functionality_works() + public function it_remember_me_functionality_works(): void { $component = Livewire::test(Login::class); diff --git a/tests/Feature/Livewire/Auth/RegisterTest.php b/tests/Feature/Livewire/Auth/RegisterTest.php index 2bec483..2174cdd 100644 --- a/tests/Feature/Livewire/Auth/RegisterTest.php +++ b/tests/Feature/Livewire/Auth/RegisterTest.php @@ -14,7 +14,7 @@ use Tests\TestCase; class RegisterTest extends TestCase { /** @test */ - public function it_renders_the_register_component() + public function it_renders_the_register_component(): void { $component = Livewire::test(Register::class); @@ -25,7 +25,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_validates_required_name_field() + public function it_validates_required_name_field(): void { $component = Livewire::test(Register::class); @@ -38,7 +38,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_validates_required_email_field() + public function it_validates_required_email_field(): void { $component = Livewire::test(Register::class); @@ -51,7 +51,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_validates_email_format() + public function it_validates_email_format(): void { $component = Livewire::test(Register::class); @@ -65,7 +65,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_validates_required_password_field() + public function it_validates_required_password_field(): void { $component = Livewire::test(Register::class); @@ -78,7 +78,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_validates_password_confirmation() + public function it_validates_password_confirmation(): void { $component = Livewire::test(Register::class); @@ -92,7 +92,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_creates_user_with_valid_data() + public function it_creates_user_with_valid_data(): void { Event::fake(); @@ -110,12 +110,12 @@ class RegisterTest extends TestCase 'email' => 'test@gmail.com', ]); - $this->assertAuthenticatedAs(User::where('email', 'test@gmail.com')->first()); + $this->assertAuthenticatedAs(User::query()->where('email', 'test@gmail.com')->first()); Event::assertDispatched(Registered::class); } /** @test */ - public function it_hashes_password_before_storing() + public function it_hashes_password_before_storing(): void { $component = Livewire::test(Register::class); @@ -126,12 +126,12 @@ class RegisterTest extends TestCase ->set('password_confirmation', 'Password123!') ->call('register'); - $user = User::where('email', 'test@gmail.com')->first(); + $user = User::query()->where('email', 'test@gmail.com')->first(); $this->assertTrue(Hash::check('Password123!', $user->password)); } /** @test */ - public function it_prevents_duplicate_email_registration() + public function it_prevents_duplicate_email_registration(): void { // Create existing user User::factory()->create(['email' => 'test@gmail.com']); @@ -148,7 +148,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_redirects_after_successful_registration() + public function it_redirects_after_successful_registration(): void { $component = Livewire::test(Register::class); @@ -163,7 +163,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_logs_in_user_after_registration() + public function it_logs_in_user_after_registration(): void { $component = Livewire::test(Register::class); @@ -179,7 +179,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_handles_maximum_name_length() + public function it_handles_maximum_name_length(): void { $component = Livewire::test(Register::class); @@ -193,7 +193,7 @@ class RegisterTest extends TestCase } /** @test */ - public function it_handles_password_validation() + public function it_handles_password_validation(): void { $component = Livewire::test(Register::class); diff --git a/tests/Feature/Livewire/DashboardTest.php b/tests/Feature/Livewire/DashboardTest.php index 58e21c2..3266eaf 100644 --- a/tests/Feature/Livewire/DashboardTest.php +++ b/tests/Feature/Livewire/DashboardTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature\Livewire; +use App\Livewire\Dashboard\Dashboard; use App\Models\Plan; use App\Models\User; use Illuminate\Support\Facades\Auth; @@ -10,6 +11,7 @@ use Tests\TestCase; class DashboardTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -30,18 +32,18 @@ class DashboardTest extends TestCase } /** @test */ - public function it_renders_dashboard_component() + public function it_renders_dashboard_component(): void { - $component = Livewire::test(\App\Livewire\Dashboard\Dashboard::class); + $component = Livewire::test(Dashboard::class); $component->assertStatus(200); $component->assertViewIs('livewire.dashboard.dashboard'); } /** @test */ - public function it_displays_user_information() + public function it_displays_user_information(): void { - $component = Livewire::test(\App\Livewire\Dashboard\Dashboard::class); + $component = Livewire::test(Dashboard::class); // Check that dashboard renders with usage statistics $component->assertSee('Mailbox Created'); @@ -50,9 +52,9 @@ class DashboardTest extends TestCase } /** @test */ - public function it_shows_subscription_status() + public function it_shows_subscription_status(): void { - $component = Livewire::test(\App\Livewire\Dashboard\Dashboard::class); + $component = Livewire::test(Dashboard::class); // Test that the component displays subscription pricing section (since user is not subscribed) $component->assertSee('Purchase Subscription'); diff --git a/tests/Feature/Livewire/FrontendTest.php b/tests/Feature/Livewire/FrontendTest.php index acdca9e..ee1fb92 100644 --- a/tests/Feature/Livewire/FrontendTest.php +++ b/tests/Feature/Livewire/FrontendTest.php @@ -2,7 +2,12 @@ namespace Tests\Feature\Livewire; -use App\Models\Email; +use App\Livewire\Home; +use App\Livewire\Frontend\Mailbox; +use Exception; +use App\Models\Blog; +use App\Livewire\ListBlog; +use App\Models\Page; use App\Models\ZEmail; use Illuminate\Support\Facades\Cookie; use Livewire\Livewire; @@ -11,18 +16,18 @@ use Tests\TestCase; class FrontendTest extends TestCase { /** @test */ - public function it_renders_home_component() + public function it_renders_home_component(): void { - $component = Livewire::test(\App\Livewire\Home::class); + $component = Livewire::test(Home::class); $component->assertStatus(200); $component->assertViewIs('livewire.home'); } /** @test */ - public function it_checks_for_messages_in_home_component() + public function it_checks_for_messages_in_home_component(): void { - $component = Livewire::test(\App\Livewire\Home::class); + $component = Livewire::test(Home::class); // Test that the component can render without errors $component->assertStatus(200); @@ -30,7 +35,7 @@ class FrontendTest extends TestCase } /** @test */ - public function it_renders_mailbox_component_with_existing_email() + public function it_renders_mailbox_component_with_existing_email(): void { // Mock existing email in cookie Cookie::queue('email', 'test@example.com', 43800); @@ -40,32 +45,32 @@ class FrontendTest extends TestCase ->shouldReceive('getEmail') ->andReturn('test@example.com'); - $component = Livewire::test(\App\Livewire\Frontend\Mailbox::class); + $component = Livewire::test(Mailbox::class); // Component might redirect if email validation fails, so check for either status or redirect try { $component->assertStatus(200); - } catch (\Exception $e) { + } catch (Exception) { $component->assertRedirect('/'); } } /** @test */ - public function it_redirects_home_when_no_email_in_mailbox() + public function it_redirects_home_when_no_email_in_mailbox(): void { // Ensure no email cookie exists Cookie::queue('email', '', -1); - $component = Livewire::test(\App\Livewire\Frontend\Mailbox::class); + $component = Livewire::test(Mailbox::class); $component->assertRedirect('/'); } /** @test */ - public function it_renders_blog_component() + public function it_renders_blog_component(): void { // Create a blog post with the slug we're testing - $blog = \App\Models\Blog::factory()->create(['slug' => 'test-slug']); + Blog::factory()->create(['slug' => 'test-slug']); $component = Livewire::test(\App\Livewire\Blog::class, ['slug' => 'test-slug']); @@ -73,18 +78,18 @@ class FrontendTest extends TestCase } /** @test */ - public function it_renders_list_blog_component() + public function it_renders_list_blog_component(): void { - $component = Livewire::test(\App\Livewire\ListBlog::class); + $component = Livewire::test(ListBlog::class); $component->assertStatus(200); } /** @test */ - public function it_renders_page_component() + public function it_renders_page_component(): void { // Create a page with the slug we're testing and ensure it's published - $page = \App\Models\Page::factory()->create([ + Page::factory()->create([ 'slug' => 'test-slug', 'is_published' => true, ]); diff --git a/tests/Pest.php b/tests/Pest.php index df17438..fea8d58 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,8 @@ extend(Tests\TestCase::class) - ->use(Illuminate\Foundation\Testing\RefreshDatabase::class) +pest()->extend(TestCase::class) + ->use(RefreshDatabase::class) ->in('Feature') ->in('Unit'); @@ -27,9 +30,7 @@ pest()->extend(Tests\TestCase::class) | */ -expect()->extend('toBeOne', function () { - return $this->toBe(1); -}); +expect()->extend('toBeOne', fn() => $this->toBe(1)); /* |-------------------------------------------------------------------------- @@ -42,7 +43,7 @@ expect()->extend('toBeOne', function () { | */ -function something() +function something(): void { // .. } diff --git a/tests/Unit/ColorPickerTest.php b/tests/Unit/ColorPickerTest.php index 38fd4db..de2b0b0 100644 --- a/tests/Unit/ColorPickerTest.php +++ b/tests/Unit/ColorPickerTest.php @@ -18,12 +18,10 @@ class ColorPickerTest extends TestCase protected function setUp(): void { parent::setUp(); - - $this->testModel = new TestModel; } /** @test */ - public function it_returns_correct_colors_for_uppercase_letters() + public function it_returns_correct_colors_for_uppercase_letters(): void { $this->assertEquals([ 'dark' => 'dark:bg-amber-500', @@ -37,7 +35,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_handles_lowercase_letters_correctly() + public function it_handles_lowercase_letters_correctly(): void { $this->assertEquals([ 'dark' => 'dark:bg-amber-500', @@ -51,7 +49,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_returns_default_gray_color_for_invalid_letters() + public function it_returns_default_gray_color_for_invalid_letters(): void { $this->assertEquals([ 'dark' => 'dark:bg-gray-500', @@ -70,7 +68,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_handles_special_characters() + public function it_handles_special_characters(): void { $this->assertEquals([ 'dark' => 'dark:bg-gray-500', @@ -84,7 +82,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_returns_array_with_dark_and_light_keys() + public function it_returns_array_with_dark_and_light_keys(): void { $colors = TestModel::chooseColor('B'); @@ -94,7 +92,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_provides_consistent_color_mapping() + public function it_provides_consistent_color_mapping(): void { $colorA = TestModel::chooseColor('A'); $colorALower = TestModel::chooseColor('a'); @@ -103,7 +101,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_covers_all_letters_of_alphabet() + public function it_covers_all_letters_of_alphabet(): void { $alphabet = range('A', 'Z'); @@ -119,7 +117,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_handles_numbers_and_non_alphabetic_characters_gracefully() + public function it_handles_numbers_and_non_alphabetic_characters_gracefully(): void { $nonAlphaChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '[', ']', '{', '}', '|', '\\', ';', ':', "'", '"', ',', '.', '<', '>', '/', '?', '~', '`']; @@ -134,7 +132,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_ensures_all_colors_follow_tailwind_css_naming_convention() + public function it_ensures_all_colors_follow_tailwind_css_naming_convention(): void { $alphabet = range('A', 'Z'); @@ -147,7 +145,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_provides_unique_colors_for_different_letters() + public function it_provides_unique_colors_for_different_letters(): void { $colorA = TestModel::chooseColor('A'); $colorB = TestModel::chooseColor('B'); @@ -159,7 +157,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_handles_mixed_case_input() + public function it_handles_mixed_case_input(): void { $mixedCaseColors = [ TestModel::chooseColor('H'), @@ -174,10 +172,10 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_can_be_used_in_model_context() + public function it_can_be_used_in_model_context(): void { // Test with Email model that uses ColorPicker - $email = Email::factory()->create(['from_name' => 'John Doe']); + Email::factory()->create(['from_name' => 'John Doe']); // This tests that the trait works when used by actual models $colors = ColorPicker::chooseColor('J'); @@ -186,7 +184,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_maintains_backward_compatibility() + public function it_maintains_backward_compatibility(): void { // Ensure the color mapping remains consistent $expectedColors = [ @@ -203,7 +201,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_handles_unicode_characters() + public function it_handles_unicode_characters(): void { $unicodeChars = ['ñ', 'ç', 'ü', 'ö', 'ä', 'ß']; @@ -218,7 +216,7 @@ class ColorPickerTest extends TestCase } /** @test */ - public function it_can_be_called_statically() + public function it_can_be_called_statically(): void { // Test both static and instance calling $staticResult = TestModel::chooseColor('X'); @@ -226,7 +224,6 @@ class ColorPickerTest extends TestCase $instance = new TestModel; $reflection = new ReflectionClass($instance); $method = $reflection->getMethod('chooseColor'); - $method->setAccessible(true); $instanceResult = $method->invoke(null, 'X'); $this->assertEquals($staticResult, $instanceResult); diff --git a/tests/Unit/ExampleTest.php b/tests/Unit/ExampleTest.php index fc54887..df8cf64 100644 --- a/tests/Unit/ExampleTest.php +++ b/tests/Unit/ExampleTest.php @@ -2,6 +2,6 @@ namespace Tests\Unit; -test('that true is true', function () { +test('that true is true', function (): void { expect(true)->toBeTrue(); }); diff --git a/tests/Unit/Models/ActivationKeyTest.php b/tests/Unit/Models/ActivationKeyTest.php index e38be9c..d6e5ee4 100644 --- a/tests/Unit/Models/ActivationKeyTest.php +++ b/tests/Unit/Models/ActivationKeyTest.php @@ -8,6 +8,7 @@ use Tests\TestCase; class ActivationKeyTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -16,7 +17,7 @@ class ActivationKeyTest extends TestCase } /** @test */ - public function it_can_create_an_activation_key_with_factory() + public function it_can_create_an_activation_key_with_factory(): void { $activationKey = ActivationKey::factory()->create(); @@ -26,7 +27,7 @@ class ActivationKeyTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $activationKeyData = [ 'user_id' => $this->user->id, @@ -35,7 +36,7 @@ class ActivationKeyTest extends TestCase 'is_activated' => false, ]; - $activationKey = ActivationKey::create($activationKeyData); + $activationKey = ActivationKey::query()->create($activationKeyData); foreach ($activationKeyData as $key => $value) { $this->assertEquals($value, $activationKey->$key); @@ -43,7 +44,7 @@ class ActivationKeyTest extends TestCase } /** @test */ - public function it_belongs_to_a_user() + public function it_belongs_to_a_user(): void { $activationKey = ActivationKey::factory()->create(['user_id' => $this->user->id]); @@ -52,7 +53,7 @@ class ActivationKeyTest extends TestCase } /** @test */ - public function it_generates_unique_keys() + public function it_generates_unique_keys(): void { $key1 = ActivationKey::factory()->create(); $key2 = ActivationKey::factory()->create(); @@ -61,13 +62,13 @@ class ActivationKeyTest extends TestCase } /** @test */ - public function it_can_query_unactivated_activation_keys() + public function it_can_query_unactivated_activation_keys(): void { - $unactivatedKey = ActivationKey::factory()->create(['is_activated' => false]); - $activatedKey = ActivationKey::factory()->create(['is_activated' => true]); + ActivationKey::factory()->create(['is_activated' => false]); + ActivationKey::factory()->create(['is_activated' => true]); - $unactivatedKeys = ActivationKey::where('is_activated', false)->get(); - $activatedKeys = ActivationKey::where('is_activated', true)->get(); + $unactivatedKeys = ActivationKey::query()->where('is_activated', false)->get(); + $activatedKeys = ActivationKey::query()->where('is_activated', true)->get(); $this->assertCount(1, $unactivatedKeys); $this->assertCount(1, $activatedKeys); diff --git a/tests/Unit/Models/BlogTest.php b/tests/Unit/Models/BlogTest.php index 9bcd15a..cee8fa6 100644 --- a/tests/Unit/Models/BlogTest.php +++ b/tests/Unit/Models/BlogTest.php @@ -2,6 +2,8 @@ namespace Tests\Unit\Models; +use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Model; use App\Models\Blog; use App\Models\Category; use App\Models\User; @@ -9,6 +11,8 @@ use Tests\TestCase; class BlogTest extends TestCase { + private User|Collection $user; + public $category; protected function setUp(): void { parent::setUp(); @@ -18,7 +22,7 @@ class BlogTest extends TestCase } /** @test */ - public function it_can_create_a_blog_with_factory() + public function it_can_create_a_blog_with_factory(): void { $blog = Blog::factory()->create(); @@ -28,7 +32,7 @@ class BlogTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $blogData = [ 'post' => 'Test Blog Post', @@ -41,7 +45,7 @@ class BlogTest extends TestCase 'category_id' => $this->category->id, ]; - $blog = Blog::create($blogData); + $blog = Blog::query()->create($blogData); foreach ($blogData as $key => $value) { $this->assertEquals($value, $blog->$key); @@ -49,7 +53,7 @@ class BlogTest extends TestCase } /** @test */ - public function it_belongs_to_a_category() + public function it_belongs_to_a_category(): void { $blog = Blog::factory()->create(['category_id' => $this->category->id]); @@ -58,7 +62,7 @@ class BlogTest extends TestCase } /** @test */ - public function it_generates_unique_slugs() + public function it_generates_unique_slugs(): void { $blog1 = Blog::factory()->create(['post' => 'Same Title']); $blog2 = Blog::factory()->create(['post' => 'Same Title']); @@ -67,20 +71,20 @@ class BlogTest extends TestCase } /** @test */ - public function it_can_query_published_blogs() + public function it_can_query_published_blogs(): void { - $publishedBlog = Blog::factory()->create(['is_published' => true]); - $draftBlog = Blog::factory()->create(['is_published' => false]); + Blog::factory()->create(['is_published' => true]); + Blog::factory()->create(['is_published' => false]); - $publishedBlogs = Blog::where('is_published', true)->get(); - $draftBlogs = Blog::where('is_published', false)->get(); + $publishedBlogs = Blog::query()->where('is_published', true)->get(); + $draftBlogs = Blog::query()->where('is_published', false)->get(); $this->assertCount(1, $publishedBlogs); $this->assertCount(1, $draftBlogs); } /** @test */ - public function it_can_create_blogs_with_custom_headers() + public function it_can_create_blogs_with_custom_headers(): void { $blog = Blog::factory()->create(['custom_header' => 'Custom Header Text']); @@ -88,30 +92,30 @@ class BlogTest extends TestCase } /** @test */ - public function it_orders_blogs_by_creation_date() + public function it_orders_blogs_by_creation_date(): void { $oldBlog = Blog::factory()->create(['created_at' => now()->subDays(2)]); $newBlog = Blog::factory()->create(['created_at' => now()]); - $blogs = Blog::orderBy('created_at', 'desc')->get(); + $blogs = Blog::query()->latest()->get(); $this->assertEquals($newBlog->id, $blogs->first()->id); $this->assertEquals($oldBlog->id, $blogs->last()->id); } /** @test */ - public function it_handles_long_content() + public function it_handles_long_content(): void { $longContent = str_repeat('This is a very long blog content. ', 100); $blog = Blog::factory()->create(['content' => $longContent]); $this->assertEquals($longContent, $blog->content); - $this->assertGreaterThan(1000, strlen($blog->content)); + $this->assertGreaterThan(1000, strlen((string) $blog->content)); } /** @test */ - public function it_can_update_blog_status() + public function it_can_update_blog_status(): void { $blog = Blog::factory()->create(['is_published' => false]); @@ -122,24 +126,24 @@ class BlogTest extends TestCase } /** @test */ - public function it_scopes_blogs_by_category() + public function it_scopes_blogs_by_category(): void { $category1 = Category::factory()->create(); $category2 = Category::factory()->create(); - $blog1 = Blog::factory()->create(['category_id' => $category1->id]); - $blog2 = Blog::factory()->create(['category_id' => $category1->id]); - $blog3 = Blog::factory()->create(['category_id' => $category2->id]); + Blog::factory()->create(['category_id' => $category1->id]); + Blog::factory()->create(['category_id' => $category1->id]); + Blog::factory()->create(['category_id' => $category2->id]); - $category1Blogs = Blog::where('category_id', $category1->id)->get(); - $category2Blogs = Blog::where('category_id', $category2->id)->get(); + $category1Blogs = Blog::query()->where('category_id', $category1->id)->get(); + $category2Blogs = Blog::query()->where('category_id', $category2->id)->get(); $this->assertCount(2, $category1Blogs); $this->assertCount(1, $category2Blogs); } /** @test */ - public function it_uses_correct_table_name() + public function it_uses_correct_table_name(): void { $blog = new Blog; @@ -147,10 +151,10 @@ class BlogTest extends TestCase } /** @test */ - public function it_extends_model_class() + public function it_extends_model_class(): void { $blog = new Blog; - $this->assertInstanceOf(\Illuminate\Database\Eloquent\Model::class, $blog); + $this->assertInstanceOf(Model::class, $blog); } } diff --git a/tests/Unit/Models/CategoryTest.php b/tests/Unit/Models/CategoryTest.php index 5559a29..e20ca04 100644 --- a/tests/Unit/Models/CategoryTest.php +++ b/tests/Unit/Models/CategoryTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit\Models; +use Illuminate\Database\Eloquent\Model; use App\Models\Blog; use App\Models\Category; use Tests\TestCase; @@ -9,7 +10,7 @@ use Tests\TestCase; class CategoryTest extends TestCase { /** @test */ - public function it_can_create_a_category_with_factory() + public function it_can_create_a_category_with_factory(): void { $category = Category::factory()->create(); @@ -19,7 +20,7 @@ class CategoryTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $categoryData = [ 'name' => 'Technology', @@ -27,7 +28,7 @@ class CategoryTest extends TestCase 'is_active' => true, ]; - $category = Category::create($categoryData); + $category = Category::query()->create($categoryData); foreach ($categoryData as $key => $value) { $this->assertEquals($value, $category->$key); @@ -35,7 +36,7 @@ class CategoryTest extends TestCase } /** @test */ - public function it_has_many_blogs() + public function it_has_many_blogs(): void { $category = Category::factory()->create(); $blog1 = Blog::factory()->create(['category_id' => $category->id]); @@ -47,7 +48,7 @@ class CategoryTest extends TestCase } /** @test */ - public function it_generates_unique_slugs() + public function it_generates_unique_slugs(): void { $category1 = Category::factory()->create(['name' => 'Same Name']); $category2 = Category::factory()->create(['name' => 'Same Name']); @@ -56,20 +57,20 @@ class CategoryTest extends TestCase } /** @test */ - public function it_can_query_active_categories() + public function it_can_query_active_categories(): void { - $activeCategory = Category::factory()->create(['is_active' => true]); - $inactiveCategory = Category::factory()->create(['is_active' => false]); + Category::factory()->create(['is_active' => true]); + Category::factory()->create(['is_active' => false]); - $activeCategories = Category::where('is_active', true)->get(); - $inactiveCategories = Category::where('is_active', false)->get(); + $activeCategories = Category::query()->where('is_active', true)->get(); + $inactiveCategories = Category::query()->where('is_active', false)->get(); $this->assertCount(1, $activeCategories); $this->assertCount(1, $inactiveCategories); } /** @test */ - public function it_stores_is_active_status_correctly() + public function it_stores_is_active_status_correctly(): void { $category = Category::factory()->create(['is_active' => false]); @@ -77,7 +78,7 @@ class CategoryTest extends TestCase } /** @test */ - public function it_uses_correct_table_name() + public function it_uses_correct_table_name(): void { $category = new Category; @@ -85,10 +86,10 @@ class CategoryTest extends TestCase } /** @test */ - public function it_extends_model_class() + public function it_extends_model_class(): void { $category = new Category; - $this->assertInstanceOf(\Illuminate\Database\Eloquent\Model::class, $category); + $this->assertInstanceOf(Model::class, $category); } } diff --git a/tests/Unit/Models/EmailTest.php b/tests/Unit/Models/EmailTest.php index b01774d..dd6f413 100644 --- a/tests/Unit/Models/EmailTest.php +++ b/tests/Unit/Models/EmailTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit\Models; +use Illuminate\Support\Facades\Date; use App\Models\Email; use Carbon\Carbon; use Illuminate\Support\Facades\Config; @@ -36,7 +37,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_can_create_email_with_factory() + public function it_can_create_email_with_factory(): void { $email = Email::factory()->create(); @@ -47,7 +48,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $emailData = [ 'message_id' => '12345', @@ -63,7 +64,7 @@ class EmailTest extends TestCase 'mailbox' => 'INBOX', ]; - $email = Email::create($emailData); + $email = Email::query()->create($emailData); foreach ($emailData as $key => $value) { $this->assertEquals($value, $email->$key); @@ -71,7 +72,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_casts_attributes_correctly() + public function it_casts_attributes_correctly(): void { $email = Email::factory()->create([ 'to' => ['test1@example.com', 'test2@example.com'], @@ -89,7 +90,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_validates_email_format_in_fetch_email_from_db() + public function it_validates_email_format_in_fetch_email_from_db(): void { $result = Email::fetchEmailFromDB('invalid-email'); @@ -97,7 +98,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_fetches_emails_from_database_with_valid_email() + public function it_fetches_emails_from_database_with_valid_email(): void { $email1 = Email::factory()->create(['to' => ['test@example.com']]); $email2 = Email::factory()->create(['to' => ['other@example.com']]); @@ -112,15 +113,15 @@ class EmailTest extends TestCase } /** @test */ - public function it_orders_emails_by_timestamp_descending_in_fetch_email_from_db() + public function it_orders_emails_by_timestamp_descending_in_fetch_email_from_db(): void { $oldEmail = Email::factory()->create([ 'to' => ['test@example.com'], - 'timestamp' => Carbon::now()->subHours(2), + 'timestamp' => Date::now()->subHours(2), ]); $newEmail = Email::factory()->create([ 'to' => ['test@example.com'], - 'timestamp' => Carbon::now(), + 'timestamp' => Date::now(), ]); $results = Email::fetchEmailFromDB('test@example.com'); @@ -130,7 +131,7 @@ class EmailTest extends TestCase } /** @test */ - public function it_sets_correct_table_name() + public function it_sets_correct_table_name(): void { $email = new Email; diff --git a/tests/Unit/Models/LogTest.php b/tests/Unit/Models/LogTest.php index 52b59b0..c055cd8 100644 --- a/tests/Unit/Models/LogTest.php +++ b/tests/Unit/Models/LogTest.php @@ -8,6 +8,7 @@ use Tests\TestCase; class LogTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -16,7 +17,7 @@ class LogTest extends TestCase } /** @test */ - public function it_can_create_a_log_with_factory() + public function it_can_create_a_log_with_factory(): void { $log = Log::factory()->create(); @@ -26,7 +27,7 @@ class LogTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $logData = [ 'user_id' => $this->user->id, @@ -34,7 +35,7 @@ class LogTest extends TestCase 'ip' => '192.168.1.1', ]; - $log = Log::create($logData); + $log = Log::query()->create($logData); foreach ($logData as $key => $value) { $this->assertEquals($value, $log->$key); @@ -42,7 +43,7 @@ class LogTest extends TestCase } /** @test */ - public function it_belongs_to_a_user() + public function it_belongs_to_a_user(): void { $log = Log::factory()->create(['user_id' => $this->user->id]); @@ -51,7 +52,7 @@ class LogTest extends TestCase } /** @test */ - public function it_stores_ip_addresses_correctly() + public function it_stores_ip_addresses_correctly(): void { $ipAddresses = ['127.0.0.1', '192.168.1.100', '10.0.0.1']; @@ -62,12 +63,12 @@ class LogTest extends TestCase } /** @test */ - public function it_orders_logs_by_creation_date() + public function it_orders_logs_by_creation_date(): void { $oldLog = Log::factory()->create(['created_at' => now()->subHours(2)]); $newLog = Log::factory()->create(['created_at' => now()]); - $logs = Log::orderBy('created_at', 'desc')->get(); + $logs = Log::query()->latest()->get(); $this->assertEquals($newLog->id, $logs->first()->id); $this->assertEquals($oldLog->id, $logs->last()->id); diff --git a/tests/Unit/Models/MenuTest.php b/tests/Unit/Models/MenuTest.php index f5490b1..bb05158 100644 --- a/tests/Unit/Models/MenuTest.php +++ b/tests/Unit/Models/MenuTest.php @@ -8,7 +8,7 @@ use Tests\TestCase; class MenuTest extends TestCase { /** @test */ - public function it_can_create_a_menu_with_factory() + public function it_can_create_a_menu_with_factory(): void { $menu = Menu::factory()->create(); @@ -18,7 +18,7 @@ class MenuTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $menuData = [ 'name' => 'Home', @@ -27,7 +27,7 @@ class MenuTest extends TestCase 'parent' => null, ]; - $menu = Menu::create($menuData); + $menu = Menu::query()->create($menuData); foreach ($menuData as $key => $value) { $this->assertEquals($value, $menu->$key); @@ -35,13 +35,13 @@ class MenuTest extends TestCase } /** @test */ - public function it_orders_menus_by_name() + public function it_orders_menus_by_name(): void { $menu1 = Menu::factory()->create(['name' => 'Zebra']); $menu2 = Menu::factory()->create(['name' => 'Alpha']); $menu3 = Menu::factory()->create(['name' => 'Beta']); - $menus = Menu::orderBy('name')->get(); + $menus = Menu::query()->orderBy('name')->get(); $this->assertEquals($menu2->id, $menus[0]->id); $this->assertEquals($menu3->id, $menus[1]->id); @@ -49,9 +49,9 @@ class MenuTest extends TestCase } /** @test */ - public function it_can_handle_parent_child_relationships() + public function it_can_handle_parent_child_relationships(): void { - $parentMenu = Menu::factory()->create(['parent' => null]); + Menu::factory()->create(['parent' => null]); $childMenu = Menu::factory()->create(['parent' => 'home']); $this->assertEquals('home', $childMenu->parent); diff --git a/tests/Unit/Models/MessageTest.php b/tests/Unit/Models/MessageTest.php index 2c81597..544ae8f 100644 --- a/tests/Unit/Models/MessageTest.php +++ b/tests/Unit/Models/MessageTest.php @@ -9,7 +9,7 @@ use Tests\TestCase; class MessageTest extends TestCase { /** @test */ - public function it_can_create_a_message_with_factory() + public function it_can_create_a_message_with_factory(): void { $message = Message::factory()->create(); @@ -19,7 +19,7 @@ class MessageTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $messageData = [ 'subject' => 'Test Message', @@ -30,7 +30,7 @@ class MessageTest extends TestCase 'is_seen' => false, ]; - $message = Message::create($messageData); + $message = Message::query()->create($messageData); foreach ($messageData as $key => $value) { $this->assertEquals($value, $message->$key); @@ -38,7 +38,7 @@ class MessageTest extends TestCase } /** @test */ - public function it_stores_to_field_as_string() + public function it_stores_to_field_as_string(): void { $to = 'test1@example.com'; $message = Message::factory()->create(['to' => $to]); @@ -48,7 +48,7 @@ class MessageTest extends TestCase } /** @test */ - public function it_uses_created_at_as_timestamp() + public function it_uses_created_at_as_timestamp(): void { $message = Message::factory()->create(); @@ -57,13 +57,13 @@ class MessageTest extends TestCase } /** @test */ - public function it_can_query_unseen_messages() + public function it_can_query_unseen_messages(): void { - $unseenMessage = Message::factory()->create(['is_seen' => false]); - $seenMessage = Message::factory()->create(['is_seen' => true]); + Message::factory()->create(['is_seen' => false]); + Message::factory()->create(['is_seen' => true]); - $unseenMessages = Message::where('is_seen', false)->get(); - $seenMessages = Message::where('is_seen', true)->get(); + $unseenMessages = Message::query()->where('is_seen', false)->get(); + $seenMessages = Message::query()->where('is_seen', true)->get(); $this->assertCount(1, $unseenMessages); $this->assertCount(1, $seenMessages); diff --git a/tests/Unit/Models/MetaTest.php b/tests/Unit/Models/MetaTest.php index aaaba2b..70d0a2a 100644 --- a/tests/Unit/Models/MetaTest.php +++ b/tests/Unit/Models/MetaTest.php @@ -8,7 +8,7 @@ use Tests\TestCase; class MetaTest extends TestCase { /** @test */ - public function it_can_create_a_meta_with_factory() + public function it_can_create_a_meta_with_factory(): void { $meta = Meta::factory()->create(); @@ -18,14 +18,14 @@ class MetaTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $metaData = [ 'key' => 'total_emails_created', 'value' => '1500', ]; - $meta = Meta::create($metaData); + $meta = Meta::query()->create($metaData); foreach ($metaData as $key => $value) { $this->assertEquals($value, $meta->$key); @@ -33,7 +33,7 @@ class MetaTest extends TestCase } /** @test */ - public function it_stores_key_value_pairs_correctly() + public function it_stores_key_value_pairs_correctly(): void { $meta = Meta::factory()->create([ 'key' => 'app_version', @@ -45,13 +45,13 @@ class MetaTest extends TestCase } /** @test */ - public function it_can_retrieve_value_by_key() + public function it_can_retrieve_value_by_key(): void { Meta::factory()->create(['key' => 'site_name', 'value' => 'ZEmailnator']); Meta::factory()->create(['key' => 'max_emails', 'value' => '100']); - $siteName = Meta::where('key', 'site_name')->first(); - $maxEmails = Meta::where('key', 'max_emails')->first(); + $siteName = Meta::query()->where('key', 'site_name')->first(); + $maxEmails = Meta::query()->where('key', 'max_emails')->first(); $this->assertEquals('ZEmailnator', $siteName->value); $this->assertEquals('100', $maxEmails->value); diff --git a/tests/Unit/Models/PageTest.php b/tests/Unit/Models/PageTest.php index 9a2291b..406a45d 100644 --- a/tests/Unit/Models/PageTest.php +++ b/tests/Unit/Models/PageTest.php @@ -8,7 +8,7 @@ use Tests\TestCase; class PageTest extends TestCase { /** @test */ - public function it_can_create_a_page_with_factory() + public function it_can_create_a_page_with_factory(): void { $page = Page::factory()->create(); @@ -18,7 +18,7 @@ class PageTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $pageData = [ 'title' => 'About Us', @@ -31,7 +31,7 @@ class PageTest extends TestCase 'is_published' => true, ]; - $page = Page::create($pageData); + $page = Page::query()->create($pageData); foreach ($pageData as $key => $value) { $this->assertEquals($value, $page->$key); @@ -39,7 +39,7 @@ class PageTest extends TestCase } /** @test */ - public function it_generates_unique_slugs() + public function it_generates_unique_slugs(): void { $page1 = Page::factory()->create(['title' => 'Same Title']); $page2 = Page::factory()->create(['title' => 'Same Title']); @@ -48,13 +48,13 @@ class PageTest extends TestCase } /** @test */ - public function it_can_query_published_pages() + public function it_can_query_published_pages(): void { - $publishedPage = Page::factory()->create(['is_published' => true]); - $draftPage = Page::factory()->create(['is_published' => false]); + Page::factory()->create(['is_published' => true]); + Page::factory()->create(['is_published' => false]); - $publishedPages = Page::where('is_published', true)->get(); - $draftPages = Page::where('is_published', false)->get(); + $publishedPages = Page::query()->where('is_published', true)->get(); + $draftPages = Page::query()->where('is_published', false)->get(); $this->assertCount(1, $publishedPages); $this->assertCount(1, $draftPages); diff --git a/tests/Unit/Models/PlanTest.php b/tests/Unit/Models/PlanTest.php index 39a8327..c39981e 100644 --- a/tests/Unit/Models/PlanTest.php +++ b/tests/Unit/Models/PlanTest.php @@ -2,11 +2,13 @@ namespace Tests\Unit\Models; +use Illuminate\Database\Eloquent\Model; use App\Models\Plan; use Tests\TestCase; class PlanTest extends TestCase { + public $planData; protected function setUp(): void { parent::setUp(); @@ -33,7 +35,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_can_create_a_plan_with_factory() + public function it_can_create_a_plan_with_factory(): void { $plan = Plan::factory()->create(); @@ -43,9 +45,9 @@ class PlanTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { - $plan = Plan::create($this->planData); + $plan = Plan::query()->create($this->planData); foreach ($this->planData as $key => $value) { $this->assertEquals($value, $plan->$key); @@ -53,7 +55,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_casts_details_to_json() + public function it_casts_details_to_json(): void { $details = [ 'feature1' => 'Unlimited emails', @@ -67,7 +69,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_casts_monthly_billing_to_boolean() + public function it_casts_monthly_billing_to_boolean(): void { $plan1 = Plan::factory()->create(['monthly_billing' => true]); $plan2 = Plan::factory()->create(['monthly_billing' => false]); @@ -79,7 +81,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_accepts_different_payment_methods() + public function it_accepts_different_payment_methods(): void { $plan = Plan::factory()->create([ 'accept_stripe' => true, @@ -93,7 +95,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_stores_monetary_values_correctly() + public function it_stores_monetary_values_correctly(): void { $plan = Plan::factory()->create([ 'price' => 19.99, @@ -104,7 +106,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_stores_mailbox_limit_as_integer() + public function it_stores_mailbox_limit_as_integer(): void { $plan = Plan::factory()->create([ 'mailbox_limit' => 50, @@ -115,7 +117,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_can_update_plan_attributes() + public function it_can_update_plan_attributes(): void { $plan = Plan::factory()->create(); @@ -133,7 +135,7 @@ class PlanTest extends TestCase } /** @test */ - public function it_uses_correct_table_name() + public function it_uses_correct_table_name(): void { $plan = new Plan; @@ -141,10 +143,10 @@ class PlanTest extends TestCase } /** @test */ - public function it_extends_model_class() + public function it_extends_model_class(): void { $plan = new Plan; - $this->assertInstanceOf(\Illuminate\Database\Eloquent\Model::class, $plan); + $this->assertInstanceOf(Model::class, $plan); } } diff --git a/tests/Unit/Models/PremiumEmailTest.php b/tests/Unit/Models/PremiumEmailTest.php index ab117eb..c4c8121 100644 --- a/tests/Unit/Models/PremiumEmailTest.php +++ b/tests/Unit/Models/PremiumEmailTest.php @@ -9,6 +9,7 @@ use Tests\TestCase; class PremiumEmailTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -17,7 +18,7 @@ class PremiumEmailTest extends TestCase } /** @test */ - public function it_can_create_a_premium_email_with_factory() + public function it_can_create_a_premium_email_with_factory(): void { $premiumEmail = PremiumEmail::factory()->create(); @@ -27,7 +28,7 @@ class PremiumEmailTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $premiumEmailData = [ 'user_id' => $this->user->id, @@ -38,7 +39,7 @@ class PremiumEmailTest extends TestCase 'to' => ['recipient@example.com'], ]; - $premiumEmail = PremiumEmail::create($premiumEmailData); + $premiumEmail = PremiumEmail::query()->create($premiumEmailData); foreach ($premiumEmailData as $key => $value) { $this->assertEquals($value, $premiumEmail->$key); @@ -46,7 +47,7 @@ class PremiumEmailTest extends TestCase } /** @test */ - public function it_belongs_to_a_user() + public function it_belongs_to_a_user(): void { $premiumEmail = PremiumEmail::factory()->create(['user_id' => $this->user->id]); @@ -55,7 +56,7 @@ class PremiumEmailTest extends TestCase } /** @test */ - public function it_casts_timestamp_to_datetime() + public function it_casts_timestamp_to_datetime(): void { $timestamp = now()->subDays(5); $premiumEmail = PremiumEmail::factory()->create(['timestamp' => $timestamp]); @@ -65,13 +66,13 @@ class PremiumEmailTest extends TestCase } /** @test */ - public function it_can_query_seen_and_unseen_emails() + public function it_can_query_seen_and_unseen_emails(): void { - $seenEmail = PremiumEmail::factory()->create(['is_seen' => true]); - $unseenEmail = PremiumEmail::factory()->create(['is_seen' => false]); + PremiumEmail::factory()->create(['is_seen' => true]); + PremiumEmail::factory()->create(['is_seen' => false]); - $seenEmails = PremiumEmail::where('is_seen', true)->get(); - $unseenEmails = PremiumEmail::where('is_seen', false)->get(); + $seenEmails = PremiumEmail::query()->where('is_seen', true)->get(); + $unseenEmails = PremiumEmail::query()->where('is_seen', false)->get(); $this->assertCount(1, $seenEmails); $this->assertCount(1, $unseenEmails); diff --git a/tests/Unit/Models/RemoteEmailTest.php b/tests/Unit/Models/RemoteEmailTest.php index 440a1af..703dbdc 100644 --- a/tests/Unit/Models/RemoteEmailTest.php +++ b/tests/Unit/Models/RemoteEmailTest.php @@ -9,7 +9,7 @@ use Tests\TestCase; class RemoteEmailTest extends TestCase { /** @test */ - public function it_can_create_a_remote_email_with_factory() + public function it_can_create_a_remote_email_with_factory(): void { $remoteEmail = RemoteEmail::factory()->create(); @@ -19,7 +19,7 @@ class RemoteEmailTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $timestamp = now(); $remoteEmailData = [ @@ -34,7 +34,7 @@ class RemoteEmailTest extends TestCase 'timestamp' => $timestamp, ]; - $remoteEmail = RemoteEmail::create($remoteEmailData); + $remoteEmail = RemoteEmail::query()->create($remoteEmailData); foreach ($remoteEmailData as $key => $value) { if ($key === 'timestamp') { @@ -47,7 +47,7 @@ class RemoteEmailTest extends TestCase } /** @test */ - public function it_casts_to_field_to_array() + public function it_casts_to_field_to_array(): void { $to = ['test1@example.com', 'test2@example.com']; $remoteEmail = RemoteEmail::factory()->create(['to' => $to]); @@ -57,7 +57,7 @@ class RemoteEmailTest extends TestCase } /** @test */ - public function it_casts_timestamp_to_datetime() + public function it_casts_timestamp_to_datetime(): void { $timestamp = now(); $remoteEmail = RemoteEmail::factory()->create(['timestamp' => $timestamp]); diff --git a/tests/Unit/Models/SettingTest.php b/tests/Unit/Models/SettingTest.php index db9e01b..857526b 100644 --- a/tests/Unit/Models/SettingTest.php +++ b/tests/Unit/Models/SettingTest.php @@ -8,7 +8,7 @@ use Tests\TestCase; class SettingTest extends TestCase { /** @test */ - public function it_can_create_a_setting_with_factory() + public function it_can_create_a_setting_with_factory(): void { $setting = Setting::factory()->create(); @@ -18,7 +18,7 @@ class SettingTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $settingData = [ 'app_name' => 'ZEmailnator', @@ -28,7 +28,7 @@ class SettingTest extends TestCase 'app_title' => 'Test Title', ]; - $setting = Setting::create($settingData); + $setting = Setting::query()->create($settingData); foreach ($settingData as $key => $value) { $this->assertEquals($value, $setting->$key); @@ -36,7 +36,7 @@ class SettingTest extends TestCase } /** @test */ - public function it_stores_configuration_values() + public function it_stores_configuration_values(): void { $setting = Setting::factory()->create([ 'app_name' => 'Test App', @@ -54,10 +54,10 @@ class SettingTest extends TestCase } /** @test */ - public function it_can_query_public_settings() + public function it_can_query_public_settings(): void { - $setting1 = Setting::factory()->create(['app_name' => 'Public App']); - $setting2 = Setting::factory()->create(['app_name' => 'Private App']); + Setting::factory()->create(['app_name' => 'Public App']); + Setting::factory()->create(['app_name' => 'Private App']); $allSettings = Setting::all(); diff --git a/tests/Unit/Models/TicketResponseTest.php b/tests/Unit/Models/TicketResponseTest.php index 4ddfaae..367b493 100644 --- a/tests/Unit/Models/TicketResponseTest.php +++ b/tests/Unit/Models/TicketResponseTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit\Models; +use Illuminate\Database\Eloquent\Model; use App\Models\Ticket; use App\Models\TicketResponse; use App\Models\User; @@ -10,6 +11,8 @@ use Tests\TestCase; class TicketResponseTest extends TestCase { + public $user; + public $ticket; protected function setUp(): void { parent::setUp(); @@ -19,7 +22,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_can_create_a_ticket_response_with_factory() + public function it_can_create_a_ticket_response_with_factory(): void { $response = TicketResponse::factory()->create(); @@ -28,7 +31,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $responseData = [ 'ticket_id' => $this->ticket->id, @@ -37,7 +40,7 @@ class TicketResponseTest extends TestCase 'ip_address' => '192.168.1.1', ]; - $response = TicketResponse::create($responseData); + $response = TicketResponse::query()->create($responseData); foreach ($responseData as $key => $value) { $this->assertEquals($value, $response->$key); @@ -45,7 +48,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_belongs_to_a_ticket() + public function it_belongs_to_a_ticket(): void { $response = TicketResponse::factory()->create(['ticket_id' => $this->ticket->id]); @@ -54,7 +57,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_belongs_to_a_user() + public function it_belongs_to_a_user(): void { $response = TicketResponse::factory()->create(['user_id' => $this->user->id]); @@ -63,7 +66,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_casts_datetime_fields_correctly() + public function it_casts_datetime_fields_correctly(): void { $response = TicketResponse::factory()->create([ 'created_at' => '2024-01-01 12:00:00', @@ -75,7 +78,7 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_orders_responses_by_creation_date() + public function it_orders_responses_by_creation_date(): void { $oldResponse = TicketResponse::factory()->create([ 'ticket_id' => $this->ticket->id, @@ -86,8 +89,7 @@ class TicketResponseTest extends TestCase 'created_at' => now(), ]); - $responses = TicketResponse::where('ticket_id', $this->ticket->id) - ->orderBy('created_at', 'asc') + $responses = TicketResponse::query()->where('ticket_id', $this->ticket->id)->oldest() ->get(); $this->assertEquals($oldResponse->id, $responses->first()->id); @@ -95,33 +97,33 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_can_query_responses_by_ticket() + public function it_can_query_responses_by_ticket(): void { - $response1 = TicketResponse::factory()->create([ + TicketResponse::factory()->create([ 'ticket_id' => $this->ticket->id, ]); - $response2 = TicketResponse::factory()->create([ + TicketResponse::factory()->create([ 'ticket_id' => $this->ticket->id, ]); - $ticketResponses = TicketResponse::where('ticket_id', $this->ticket->id)->get(); + $ticketResponses = TicketResponse::query()->where('ticket_id', $this->ticket->id)->get(); $this->assertCount(2, $ticketResponses); } /** @test */ - public function it_handles_long_responses() + public function it_handles_long_responses(): void { $longResponse = str_repeat('This is a very long response. ', 50); $response = TicketResponse::factory()->create(['response' => $longResponse]); $this->assertEquals($longResponse, $response->response); - $this->assertGreaterThan(500, strlen($response->response)); + $this->assertGreaterThan(500, strlen((string) $response->response)); } /** @test */ - public function it_uses_correct_table_name() + public function it_uses_correct_table_name(): void { $response = new TicketResponse; @@ -129,10 +131,10 @@ class TicketResponseTest extends TestCase } /** @test */ - public function it_extends_model_class() + public function it_extends_model_class(): void { $response = new TicketResponse; - $this->assertInstanceOf(\Illuminate\Database\Eloquent\Model::class, $response); + $this->assertInstanceOf(Model::class, $response); } } diff --git a/tests/Unit/Models/TicketTest.php b/tests/Unit/Models/TicketTest.php index 9427856..4d91b94 100644 --- a/tests/Unit/Models/TicketTest.php +++ b/tests/Unit/Models/TicketTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit\Models; +use Illuminate\Database\Eloquent\Model; use App\Models\Ticket; use App\Models\TicketResponse; use App\Models\User; @@ -10,6 +11,8 @@ use Tests\TestCase; class TicketTest extends TestCase { + public $user; + public $ticketData; protected function setUp(): void { parent::setUp(); @@ -27,7 +30,7 @@ class TicketTest extends TestCase } /** @test */ - public function it_can_create_a_ticket_with_factory() + public function it_can_create_a_ticket_with_factory(): void { $ticket = Ticket::factory()->create(); @@ -37,9 +40,9 @@ class TicketTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { - $ticket = Ticket::create($this->ticketData); + $ticket = Ticket::query()->create($this->ticketData); foreach ($this->ticketData as $key => $value) { if ($key === 'last_response_at') { @@ -52,7 +55,7 @@ class TicketTest extends TestCase } /** @test */ - public function it_belongs_to_user() + public function it_belongs_to_user(): void { $ticket = Ticket::factory()->create(['user_id' => $this->user->id]); @@ -61,7 +64,7 @@ class TicketTest extends TestCase } /** @test */ - public function it_has_many_ticket_responses() + public function it_has_many_ticket_responses(): void { $ticket = Ticket::factory()->create(); $response1 = TicketResponse::factory()->create(['ticket_id' => $ticket->id]); @@ -73,7 +76,7 @@ class TicketTest extends TestCase } /** @test */ - public function it_casts_last_response_at_to_datetime() + public function it_casts_last_response_at_to_datetime(): void { $ticket = Ticket::factory()->create([ 'last_response_at' => '2024-01-01 12:00:00', @@ -83,7 +86,7 @@ class TicketTest extends TestCase } /** @test */ - public function it_uses_correct_table_name() + public function it_uses_correct_table_name(): void { $ticket = new Ticket; @@ -91,10 +94,10 @@ class TicketTest extends TestCase } /** @test */ - public function it_extends_model_class() + public function it_extends_model_class(): void { $ticket = new Ticket; - $this->assertInstanceOf(\Illuminate\Database\Eloquent\Model::class, $ticket); + $this->assertInstanceOf(Model::class, $ticket); } } diff --git a/tests/Unit/Models/UsageLogTest.php b/tests/Unit/Models/UsageLogTest.php index f08514f..d711a4d 100644 --- a/tests/Unit/Models/UsageLogTest.php +++ b/tests/Unit/Models/UsageLogTest.php @@ -8,6 +8,7 @@ use Tests\TestCase; class UsageLogTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -16,7 +17,7 @@ class UsageLogTest extends TestCase } /** @test */ - public function it_can_create_a_usage_log_with_factory() + public function it_can_create_a_usage_log_with_factory(): void { $usageLog = UsageLog::factory()->create(); @@ -26,7 +27,7 @@ class UsageLogTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $usageLogData = [ 'user_id' => $this->user->id, @@ -37,7 +38,7 @@ class UsageLogTest extends TestCase 'emails_received_history' => json_encode(['2023-01-01 12:30:00' => 7]), ]; - $usageLog = UsageLog::create($usageLogData); + $usageLog = UsageLog::query()->create($usageLogData); foreach ($usageLogData as $key => $value) { $this->assertEquals($value, $usageLog->$key); @@ -45,7 +46,7 @@ class UsageLogTest extends TestCase } /** @test */ - public function it_belongs_to_a_user() + public function it_belongs_to_a_user(): void { $usageLog = UsageLog::factory()->create(['user_id' => $this->user->id]); @@ -54,7 +55,7 @@ class UsageLogTest extends TestCase } /** @test */ - public function it_tracks_different_email_counts() + public function it_tracks_different_email_counts(): void { $usageLog = UsageLog::factory()->create([ 'emails_created_count' => 15, diff --git a/tests/Unit/Models/UserTest.php b/tests/Unit/Models/UserTest.php index ae69ef5..37d3189 100644 --- a/tests/Unit/Models/UserTest.php +++ b/tests/Unit/Models/UserTest.php @@ -2,6 +2,15 @@ namespace Tests\Unit\Models; +use Carbon\Carbon; +use Illuminate\Support\Facades\Hash; +use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Notifications\Notifiable; +use Laravel\Cashier\Billable; +use Laravel\Sanctum\HasApiTokens; +use Filament\Models\Contracts\FilamentUser; +use Illuminate\Contracts\Auth\MustVerifyEmail; +use Laravel\Sanctum\NewAccessToken; use App\Models\Log; use App\Models\Ticket; use App\Models\UsageLog; @@ -11,6 +20,7 @@ use Tests\TestCase; class UserTest extends TestCase { + public $user; protected function setUp(): void { parent::setUp(); @@ -19,7 +29,7 @@ class UserTest extends TestCase } /** @test */ - public function it_can_create_a_user_with_factory() + public function it_can_create_a_user_with_factory(): void { $this->assertInstanceOf(User::class, $this->user); $this->assertIsString($this->user->name); @@ -28,7 +38,7 @@ class UserTest extends TestCase } /** @test */ - public function it_has_correct_fillable_attributes() + public function it_has_correct_fillable_attributes(): void { $userData = [ 'name' => 'Test User', @@ -36,7 +46,7 @@ class UserTest extends TestCase 'password' => 'password', ]; - $user = User::create($userData); + $user = User::query()->create($userData); $this->assertEquals('Test User', $user->name); $this->assertEquals('test@example.com', $user->email); @@ -44,7 +54,7 @@ class UserTest extends TestCase } /** @test */ - public function it_hides_sensitive_attributes() + public function it_hides_sensitive_attributes(): void { $userArray = $this->user->toArray(); @@ -53,30 +63,30 @@ class UserTest extends TestCase } /** @test */ - public function it_casts_email_verified_at_to_datetime() + public function it_casts_email_verified_at_to_datetime(): void { $this->user->email_verified_at = now(); $this->user->save(); - $this->assertInstanceOf(\Carbon\Carbon::class, $this->user->email_verified_at); + $this->assertInstanceOf(Carbon::class, $this->user->email_verified_at); } /** @test */ - public function it_hashes_password() + public function it_hashes_password(): void { $plainPassword = 'password123'; - $user = User::create([ + $user = User::query()->create([ 'name' => 'Test User', 'email' => 'test@example.com', 'password' => $plainPassword, ]); $this->assertNotEquals($plainPassword, $user->password); - $this->assertTrue(\Illuminate\Support\Facades\Hash::check($plainPassword, $user->password)); + $this->assertTrue(Hash::check($plainPassword, $user->password)); } /** @test */ - public function it_generates_initials_correctly() + public function it_generates_initials_correctly(): void { $user = User::factory()->create(['name' => 'John Doe']); $this->assertEquals('JD', $user->initials()); @@ -89,7 +99,7 @@ class UserTest extends TestCase } /** @test */ - public function it_can_access_filament_panel_when_conditions_are_met() + public function it_can_access_filament_panel_when_conditions_are_met(): void { $adminUser = User::factory()->create([ 'email' => 'admin1@zemail.me', @@ -103,7 +113,7 @@ class UserTest extends TestCase } /** @test */ - public function it_cannot_access_filament_panel_when_email_does_not_end_with_zemail_me() + public function it_cannot_access_filament_panel_when_email_does_not_end_with_zemail_me(): void { $user = User::factory()->create([ 'email' => 'user@gmail.com', @@ -117,7 +127,7 @@ class UserTest extends TestCase } /** @test */ - public function it_cannot_access_filament_panel_when_level_is_not_9() + public function it_cannot_access_filament_panel_when_level_is_not_9(): void { $user = User::factory()->create([ 'email' => 'admin2@zemail.me', @@ -131,7 +141,7 @@ class UserTest extends TestCase } /** @test */ - public function it_cannot_access_filament_panel_when_email_is_not_verified() + public function it_cannot_access_filament_panel_when_email_is_not_verified(): void { $user = User::factory()->create([ 'email' => 'admin3@zemail.me', @@ -145,7 +155,7 @@ class UserTest extends TestCase } /** @test */ - public function it_has_many_tickets_relationship() + public function it_has_many_tickets_relationship(): void { $ticket = Ticket::factory()->create(['user_id' => $this->user->id]); @@ -154,7 +164,7 @@ class UserTest extends TestCase } /** @test */ - public function it_has_many_logs_relationship() + public function it_has_many_logs_relationship(): void { $log = Log::factory()->create(['user_id' => $this->user->id]); @@ -163,7 +173,7 @@ class UserTest extends TestCase } /** @test */ - public function it_has_many_usage_logs_relationship() + public function it_has_many_usage_logs_relationship(): void { $usageLog = UsageLog::factory()->create(['user_id' => $this->user->id]); @@ -172,44 +182,44 @@ class UserTest extends TestCase } /** @test */ - public function it_uses_required_traits() + public function it_uses_required_traits(): void { $traits = class_uses(User::class); - $this->assertArrayHasKey(\Illuminate\Database\Eloquent\Factories\HasFactory::class, $traits); - $this->assertArrayHasKey(\Illuminate\Notifications\Notifiable::class, $traits); - $this->assertArrayHasKey(\Laravel\Cashier\Billable::class, $traits); - $this->assertArrayHasKey(\Laravel\Sanctum\HasApiTokens::class, $traits); + $this->assertArrayHasKey(HasFactory::class, $traits); + $this->assertArrayHasKey(Notifiable::class, $traits); + $this->assertArrayHasKey(Billable::class, $traits); + $this->assertArrayHasKey(HasApiTokens::class, $traits); } /** @test */ - public function it_implements_required_interfaces() + public function it_implements_required_interfaces(): void { $user = new User; - $this->assertInstanceOf(\Filament\Models\Contracts\FilamentUser::class, $user); - $this->assertInstanceOf(\Illuminate\Contracts\Auth\MustVerifyEmail::class, $user); + $this->assertInstanceOf(FilamentUser::class, $user); + $this->assertInstanceOf(MustVerifyEmail::class, $user); } /** @test */ - public function it_extends_authenticatable() + public function it_extends_authenticatable(): void { $this->assertInstanceOf(\Illuminate\Foundation\Auth\User::class, $this->user); } /** @test */ - public function it_can_create_api_token() + public function it_can_create_api_token(): void { $token = $this->user->createToken('test-token'); - $this->assertInstanceOf(\Laravel\Sanctum\NewAccessToken::class, $token); + $this->assertInstanceOf(NewAccessToken::class, $token); $this->assertCount(1, $this->user->tokens); } /** @test */ - public function it_can_delete_tokens() + public function it_can_delete_tokens(): void { - $token = $this->user->createToken('test-token'); + $this->user->createToken('test-token'); $this->user->tokens()->delete(); $this->assertCount(0, $this->user->fresh()->tokens); diff --git a/tests/Unit/Models/ZEmailTest.php b/tests/Unit/Models/ZEmailTest.php index 3005a54..29a17be 100644 --- a/tests/Unit/Models/ZEmailTest.php +++ b/tests/Unit/Models/ZEmailTest.php @@ -48,7 +48,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_returns_null_when_no_email_cookie_exists_and_generate_is_false() + public function it_returns_null_when_no_email_cookie_exists_and_generate_is_false(): void { $result = ZEmail::getEmail(false); @@ -56,7 +56,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_email_when_no_cookie_exists_and_generate_is_true() + public function it_generates_random_email_when_no_cookie_exists_and_generate_is_true(): void { $result = ZEmail::getEmail(true); @@ -65,7 +65,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_creates_custom_email_with_valid_username_length() + public function it_creates_custom_email_with_valid_username_length(): void { $result = ZEmail::createCustomEmail('validuser', 'example.com'); @@ -73,7 +73,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_username_when_custom_username_is_too_short() + public function it_generates_random_username_when_custom_username_is_too_short(): void { $result = ZEmail::createCustomEmail('ab', 'example.com'); // Less than min length 3 @@ -84,7 +84,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_username_when_custom_username_is_too_long() + public function it_generates_random_username_when_custom_username_is_too_long(): void { $longUsername = str_repeat('a', 25); // More than max length 20 $result = ZEmail::createCustomEmail($longUsername, 'example.com'); @@ -96,7 +96,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_sanitizes_username_by_removing_special_characters() + public function it_sanitizes_username_by_removing_special_characters(): void { $result = ZEmail::createCustomEmail('user!@#$%', 'example.com'); @@ -104,7 +104,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_email_when_forbidden_id_is_used() + public function it_generates_random_email_when_forbidden_id_is_used(): void { $result = ZEmail::createCustomEmail('admin', 'example.com'); @@ -113,7 +113,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_gmail_when_empty_username_for_gmail_domain() + public function it_generates_random_gmail_when_empty_username_for_gmail_domain(): void { $result = ZEmail::createCustomEmail('', 'gmail.com'); @@ -122,7 +122,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_outlook_when_empty_username_for_outlook_domain() + public function it_generates_random_outlook_when_empty_username_for_outlook_domain(): void { $result = ZEmail::createCustomEmail('', 'outlook.com'); @@ -131,7 +131,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_handles_gmail_plus_addressing_correctly() + public function it_handles_gmail_plus_addressing_correctly(): void { $result = ZEmail::createCustomEmail('john.doe+tag', 'gmail.com'); @@ -139,7 +139,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_handles_gmail_dot_addressing_correctly() + public function it_handles_gmail_dot_addressing_correctly(): void { $result = ZEmail::createCustomEmail('johndoe', 'gmail.com'); @@ -148,7 +148,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_handles_outlook_plus_addressing_correctly() + public function it_handles_outlook_plus_addressing_correctly(): void { $result = ZEmail::createCustomEmail('outlookuser+tag', 'outlook.com'); @@ -156,7 +156,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_email_for_unknown_domain() + public function it_generates_random_email_for_unknown_domain(): void { $result = ZEmail::createCustomEmail('user', 'unknown.com'); @@ -165,7 +165,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_email_with_store_option() + public function it_generates_random_email_with_store_option(): void { $result = ZEmail::generateRandomEmail(true); @@ -174,7 +174,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_email_without_store_option() + public function it_generates_random_email_without_store_option(): void { $result = ZEmail::generateRandomEmail(false); @@ -183,7 +183,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_gmail_email_with_dots() + public function it_generates_gmail_email_with_dots(): void { $result = ZEmail::generateRandomGmail(true); @@ -192,7 +192,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_outlook_email_with_plus_addressing() + public function it_generates_outlook_email_with_plus_addressing(): void { $result = ZEmail::generateRandomOutlook(true); @@ -201,12 +201,11 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_pronounceable_word() + public function it_generates_pronounceable_word(): void { $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('generatePronounceableWord'); - $method->setAccessible(true); $result = $method->invoke($zemail); @@ -215,12 +214,11 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_generates_random_string_with_specified_length() + public function it_generates_random_string_with_specified_length(): void { $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('generateRandomString'); - $method->setAccessible(true); $result = $method->invoke($zemail, 10); @@ -230,12 +228,11 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_gets_random_domain_from_configuration() + public function it_gets_random_domain_from_configuration(): void { $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('getRandomDomain'); - $method->setAccessible(true); $result = $method->invoke($zemail); @@ -243,12 +240,11 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_gets_random_gmail_user_from_configuration() + public function it_gets_random_gmail_user_from_configuration(): void { $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('getRandomGmailUser'); - $method->setAccessible(true); $result = $method->invoke($zemail); @@ -256,12 +252,11 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_gets_random_outlook_user_from_configuration() + public function it_gets_random_outlook_user_from_configuration(): void { $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('getRandomOutlookUser'); - $method->setAccessible(true); $result = $method->invoke($zemail); @@ -269,7 +264,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_returns_messages_from_message_model_when_beta_feature_is_enabled() + public function it_returns_messages_from_message_model_when_beta_feature_is_enabled(): void { Config::set('app.beta_feature', true); Config::set('app.settings.configuration_settings', json_encode([ @@ -279,7 +274,7 @@ class ZEmailTest extends TestCase ])); // Create a test message that will be found by getMessages - $message = Message::factory()->create([ + Message::factory()->create([ 'to' => 'test@example.com', 'subject' => 'Test Subject', 'from' => 'Test Sender ', @@ -297,7 +292,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_returns_messages_from_email_model_when_force_db_mail_is_enabled() + public function it_returns_messages_from_email_model_when_force_db_mail_is_enabled(): void { Config::set('app.beta_feature', false); Config::set('app.force_db_mail', true); @@ -308,7 +303,7 @@ class ZEmailTest extends TestCase ])); // Create a test email that will be found by parseEmail - $email = Email::factory()->create([ + Email::factory()->create([ 'to' => ['test@example.com'], 'is_seen' => false, 'message_id' => 'test-123', @@ -328,7 +323,7 @@ class ZEmailTest extends TestCase } /** @test */ - public function it_handles_empty_domain_configuration_gracefully() + public function it_handles_empty_domain_configuration_gracefully(): void { Config::set('app.settings.configuration_settings', json_encode([ 'domains' => [], @@ -337,7 +332,6 @@ class ZEmailTest extends TestCase $zemail = new ZEmail; $reflection = new ReflectionClass($zemail); $method = $reflection->getMethod('getRandomDomain'); - $method->setAccessible(true); $result = $method->invoke($zemail); diff --git a/tests/Unit/NotifyMeTest.php b/tests/Unit/NotifyMeTest.php index 9f17290..2c5d414 100644 --- a/tests/Unit/NotifyMeTest.php +++ b/tests/Unit/NotifyMeTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit; +use Exception; use App\Http\Controllers\WebhookController; use App\NotifyMe; use Illuminate\Support\Facades\Config; @@ -17,6 +18,7 @@ class TestNotifier class NotifyMeTest extends TestCase { + public $notifier; protected function setUp(): void { parent::setUp(); @@ -25,7 +27,7 @@ class NotifyMeTest extends TestCase } /** @test */ - public function it_sends_telegram_notification_successfully() + public function it_sends_telegram_notification_successfully(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id'); @@ -40,18 +42,16 @@ class NotifyMeTest extends TestCase $result = $this->notifier->sendTelegramNotification('Test message'); $this->assertTrue($result); - Http::assertSent(function ($request) { - return $request->url() === 'https://api.telegram.org/bottest_bot_token/sendMessage' && - $request['chat_id'] === 'test_chat_id' && - $request['text'] === 'Test message' && - $request['parse_mode'] === 'HTML'; - }); + Http::assertSent(fn(array $request): bool => $request->url() === 'https://api.telegram.org/bottest_bot_token/sendMessage' && + $request['chat_id'] === 'test_chat_id' && + $request['text'] === 'Test message' && + $request['parse_mode'] === 'HTML'); } /** @test */ - public function it_fails_when_bot_token_is_not_configured() + public function it_fails_when_bot_token_is_not_configured(): void { - Config::set('app.notify_tg_bot_token', null); + Config::set('app.notify_tg_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id'); Log::shouldReceive('error') @@ -64,10 +64,10 @@ class NotifyMeTest extends TestCase } /** @test */ - public function it_fails_when_chat_id_is_not_configured() + public function it_fails_when_chat_id_is_not_configured(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); - Config::set('app.notify_tg_chat_id', null); + Config::set('app.notify_tg_chat_id'); Log::shouldReceive('error') ->once() @@ -79,7 +79,7 @@ class NotifyMeTest extends TestCase } /** @test */ - public function it_handles_http_errors_gracefully() + public function it_handles_http_errors_gracefully(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id'); @@ -98,14 +98,14 @@ class NotifyMeTest extends TestCase } /** @test */ - public function it_handles_network_exceptions() + public function it_handles_network_exceptions(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id'); Http::fake([ - 'https://api.telegram.org/bottest_bot_token/sendMessage' => Http::throw(function ($request) { - throw new \Exception('Network error'); + 'https://api.telegram.org/bottest_bot_token/sendMessage' => Http::throw(function ($request): void { + throw new Exception('Network error'); }), ]); @@ -118,7 +118,7 @@ class NotifyMeTest extends TestCase } /** @test */ - public function it_sends_messages_with_html_parsing_mode() + public function it_sends_messages_with_html_parsing_mode(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id'); @@ -133,14 +133,12 @@ class NotifyMeTest extends TestCase $htmlMessage = 'Bold text and italic text'; $this->notifier->sendTelegramNotification($htmlMessage); - Http::assertSent(function ($request) use ($htmlMessage) { - return $request['parse_mode'] === 'HTML' && - $request['text'] === $htmlMessage; - }); + Http::assertSent(fn(array $request): bool => $request['parse_mode'] === 'HTML' && + $request['text'] === $htmlMessage); } /** @test */ - public function it_can_be_used_in_controller_context() + public function it_can_be_used_in_controller_context(): void { Config::set('app.notify_tg_bot_token', 'test_bot_token'); Config::set('app.notify_tg_chat_id', 'test_chat_id');