From 5b510398f37e613df3aa7ab398cb669ad743b9bc Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:45 +0000 Subject: [PATCH 01/19] Apply Laravel coding style Shift automatically applies the Laravel coding style - which uses the PSR-2 coding style as a base with some minor additions. You may customize the adopted coding style by adding a [PHP CS Fixer][1] or [PHP CodeSniffer][2] config to your project root. Feel free to use [Shift's Laravel ruleset][3] to help you get started. For more information on customizing the code style applied by Shift, [watch this short video][4]. [1]: https://github.com/FriendsOfPHP/PHP-CS-Fixer [2]: https://github.com/squizlabs/PHP_CodeSniffer [3]: https://gist.github.com/laravel-shift/cab527923ed2a109dda047b97d53c200 [4]: https://laravelshift.com/videos/shift-code-style --- app/Actions/Activity.php | 2 +- app/Actions/ActivityService.php | 6 +- app/Actions/Tag.php | 4 +- app/Actions/TagRepo.php | 4 +- app/Api/ApiDocsGenerator.php | 4 +- app/Api/ApiTokenGuard.php | 8 +- app/Api/ListingResponseBuilder.php | 10 +- app/Auth/Access/ExternalBaseUserProvider.php | 2 +- .../Guards/ExternalBaseSessionGuard.php | 8 +- app/Auth/Access/Guards/LdapSessionGuard.php | 2 +- app/Auth/Access/LdapService.php | 12 +-- app/Auth/Access/LoginService.php | 6 +- app/Auth/Access/Mfa/BackupCodeService.php | 4 +- app/Auth/Access/Mfa/MfaSession.php | 4 +- app/Auth/Access/Oidc/OidcIdToken.php | 10 +- app/Auth/Access/Oidc/OidcJwtSigningKey.php | 2 +- app/Auth/Access/Oidc/OidcProviderSettings.php | 14 +-- app/Auth/Access/Oidc/OidcService.php | 2 +- app/Auth/Access/RegistrationService.php | 10 +- app/Auth/Access/Saml2Service.php | 16 +-- app/Auth/Access/SocialAuthService.php | 26 ++--- app/Auth/Access/UserTokenService.php | 2 +- app/Auth/Permissions/PermissionService.php | 36 +++---- app/Auth/User.php | 6 +- app/Auth/UserRepo.php | 10 +- app/Console/Commands/CleanupImages.php | 8 +- app/Console/Commands/CopyShelfPermissions.php | 12 +-- app/Console/Commands/CreateAdmin.php | 2 +- app/Console/Commands/ResetMfa.php | 4 +- app/Console/Commands/UpdateUrl.php | 4 +- .../Commands/UpgradeDatabaseEncoding.php | 8 +- app/Console/Kernel.php | 2 +- app/Entities/Models/Book.php | 4 +- app/Entities/Models/Bookshelf.php | 4 +- app/Entities/Models/Chapter.php | 2 +- app/Entities/Models/Deletion.php | 2 +- app/Entities/Models/Entity.php | 8 +- app/Entities/Models/Page.php | 2 +- app/Entities/Models/PageRevision.php | 4 +- app/Entities/Repos/BookshelfRepo.php | 4 +- app/Entities/Repos/PageRepo.php | 16 +-- app/Entities/Tools/BookContents.php | 8 +- app/Entities/Tools/ExportFormatter.php | 20 ++-- .../Markdown/CustomStrikethroughRenderer.php | 4 +- app/Entities/Tools/PageContent.php | 26 ++--- app/Entities/Tools/PageEditActivity.php | 2 +- app/Entities/Tools/PermissionsUpdater.php | 6 +- app/Entities/Tools/SearchIndex.php | 2 +- app/Entities/Tools/SearchOptions.php | 6 +- app/Entities/Tools/SearchRunner.php | 34 +++--- app/Entities/Tools/ShelfContext.php | 2 +- app/Entities/Tools/SiblingFetcher.php | 2 +- app/Entities/Tools/SlugGenerator.php | 2 +- app/Exceptions/NotifyException.php | 2 +- app/Exceptions/PrettyException.php | 2 +- .../Api/AttachmentApiController.php | 2 +- .../Api/BookExportApiController.php | 8 +- .../Api/ChapterExportApiController.php | 8 +- .../Controllers/Api/PageApiController.php | 4 +- .../Api/PageExportApiController.php | 8 +- .../Controllers/Auth/HandlesPartialLogins.php | 2 +- app/Http/Controllers/Auth/LoginController.php | 2 +- .../Auth/MfaBackupCodesController.php | 8 +- .../Controllers/Auth/MfaTotpController.php | 2 +- app/Http/Controllers/Auth/Saml2Controller.php | 6 +- .../Controllers/Auth/SocialController.php | 4 +- app/Http/Controllers/BookController.php | 4 +- app/Http/Controllers/BookExportController.php | 8 +- app/Http/Controllers/BookSortController.php | 2 +- app/Http/Controllers/BookshelfController.php | 4 +- .../Controllers/ChapterExportController.php | 8 +- app/Http/Controllers/Controller.php | 8 +- app/Http/Controllers/FavouriteController.php | 8 +- app/Http/Controllers/HomeController.php | 8 +- .../Images/DrawioImageController.php | 2 +- .../Controllers/Images/ImageController.php | 4 +- .../Controllers/MaintenanceController.php | 6 +- app/Http/Controllers/PageController.php | 4 +- app/Http/Controllers/PageExportController.php | 8 +- .../Controllers/PageTemplateController.php | 2 +- app/Http/Controllers/SearchController.php | 4 +- app/Http/Controllers/SettingController.php | 4 +- .../Controllers/UserApiTokenController.php | 8 +- app/Http/Controllers/UserController.php | 26 ++--- app/Http/Controllers/UserSearchController.php | 6 +- app/Http/Middleware/ApiAuthenticate.php | 2 +- app/Http/Middleware/Authenticate.php | 2 +- app/Http/Middleware/CheckEmailConfirmed.php | 2 +- app/Http/Middleware/CheckGuard.php | 2 +- .../Middleware/CheckUserHasPermission.php | 2 +- app/Http/Middleware/Localization.php | 2 +- .../Middleware/RedirectIfAuthenticated.php | 2 +- app/Http/Middleware/RunThemeActions.php | 2 +- app/Http/Request.php | 2 +- app/Notifications/ConfirmEmail.php | 2 +- app/Notifications/ResetPassword.php | 2 +- app/Notifications/UserInvite.php | 2 +- .../CustomValidationServiceProvider.php | 2 +- app/Providers/RouteServiceProvider.php | 2 +- app/Settings/SettingService.php | 12 +-- app/Theming/CustomHtmlHeadContentProvider.php | 4 +- app/Theming/ThemeService.php | 4 +- app/Uploads/Attachment.php | 8 +- app/Uploads/AttachmentService.php | 22 ++-- app/Uploads/ImageRepo.php | 6 +- app/Uploads/ImageService.php | 44 ++++---- app/Uploads/UserAvatars.php | 6 +- app/Util/CspService.php | 6 +- app/Util/HtmlContentFilter.php | 12 +-- app/Util/HtmlNonceApplicator.php | 2 +- app/helpers.php | 24 ++--- config/services.php | 22 ++-- config/session.php | 2 +- config/view.php | 2 +- database/factories/ModelFactory.php | 8 +- ...08_29_105422_add_roles_and_permissions.php | 8 +- ...27_120329_update_permissions_and_roles.php | 12 +-- ...9_100730_add_view_permissions_to_roles.php | 6 +- ..._192649_create_joint_permissions_table.php | 4 +- ..._10_09_142037_create_attachments_table.php | 6 +- .../2017_04_20_185112_add_revision_counts.php | 4 +- ...017_08_01_130541_create_comments_table.php | 6 +- ..._08_04_115700_create_bookshelves_table.php | 8 +- .../2021_03_08_215138_add_user_slug.php | 2 +- database/seeds/DummyContentSeeder.php | 2 +- database/seeds/LargeContentSeeder.php | 2 +- tests/Api/ApiConfigTest.php | 4 +- tests/Api/ApiDocsTest.php | 2 +- tests/Api/ApiListingTest.php | 16 +-- tests/Api/AttachmentsApiTest.php | 6 +- tests/Api/BooksApiTest.php | 32 +++--- tests/Api/ChaptersApiTest.php | 30 +++--- tests/Api/PagesApiTest.php | 36 +++---- tests/Api/ShelvesApiTest.php | 12 +-- tests/AuditLogTest.php | 14 +-- tests/Auth/AuthTest.php | 16 +-- tests/Auth/LdapTest.php | 42 ++++---- tests/Auth/OidcTest.php | 28 ++--- tests/Auth/Saml2Test.php | 8 +- tests/Auth/SocialAuthTest.php | 2 +- tests/Auth/UserInviteTest.php | 20 ++-- tests/CreatesApplication.php | 2 +- tests/DebugViewTest.php | 8 +- tests/Entity/BookShelfTest.php | 18 ++-- tests/Entity/BookTest.php | 24 ++--- tests/Entity/ChapterTest.php | 4 +- tests/Entity/CommentTest.php | 2 +- tests/Entity/EntitySearchTest.php | 90 ++++++++-------- tests/Entity/ExportTest.php | 38 +++---- tests/Entity/PageContentTest.php | 18 ++-- tests/Entity/PageDraftTest.php | 20 ++-- tests/Entity/PageEditorTest.php | 8 +- tests/Entity/PageRevisionTest.php | 14 +-- tests/Entity/PageTemplateTest.php | 4 +- tests/Entity/PageTest.php | 12 +-- tests/Entity/SortTest.php | 30 +++--- tests/Entity/TagTest.php | 8 +- tests/Helpers/OidcJwtHelper.php | 2 +- tests/HomepageTest.php | 2 +- tests/OpenGraphTest.php | 8 +- tests/Permissions/EntityPermissionsTest.php | 102 +++++++++--------- tests/Permissions/ExportPermissionsTest.php | 4 +- tests/Permissions/RolesTest.php | 82 +++++++------- tests/PublicActionTest.php | 6 +- tests/RecycleBinTest.php | 12 +-- tests/SecurityHeaderTest.php | 4 +- tests/SharedTestHelpers.php | 4 +- tests/TestEmailTest.php | 4 +- tests/TestResponse.php | 44 ++++---- tests/ThemeTest.php | 4 +- tests/Unit/OidcIdTokenTest.php | 8 +- tests/Uploads/AttachmentTest.php | 12 +-- tests/Uploads/AvatarTest.php | 4 +- tests/Uploads/DrawioTest.php | 2 +- tests/Uploads/ImageTest.php | 40 +++---- tests/Uploads/UsesImages.php | 4 +- tests/User/UserApiTokenTest.php | 26 ++--- tests/User/UserManagementTest.php | 26 ++--- tests/User/UserPreferencesTest.php | 16 +-- tests/User/UserProfileTest.php | 24 ++--- 180 files changed, 936 insertions(+), 936 deletions(-) diff --git a/app/Actions/Activity.php b/app/Actions/Activity.php index 3b1408cb94d..3eb7c3ca75b 100644 --- a/app/Actions/Activity.php +++ b/app/Actions/Activity.php @@ -45,7 +45,7 @@ public function user(): BelongsTo */ public function getText(): string { - return trans('activities.' . $this->type); + return trans('activities.'.$this->type); } /** diff --git a/app/Actions/ActivityService.php b/app/Actions/ActivityService.php index bc7a6b6b7c3..a060b6f131b 100644 --- a/app/Actions/ActivityService.php +++ b/app/Actions/ActivityService.php @@ -160,7 +160,7 @@ protected function filterSimilar(iterable $activities): array $previousItem = null; foreach ($activities as $activityItem) { - if (!$previousItem || !$activityItem->isSimilarTo($previousItem)) { + if (! $previousItem || ! $activityItem->isSimilarTo($previousItem)) { $newActivity[] = $activityItem; } @@ -175,7 +175,7 @@ protected function filterSimilar(iterable $activities): array */ protected function setNotification(string $type) { - $notificationTextKey = 'activities.' . $type . '_notification'; + $notificationTextKey = 'activities.'.$type.'_notification'; if (trans()->has($notificationTextKey)) { $message = trans($notificationTextKey); session()->flash('success', $message); @@ -189,7 +189,7 @@ protected function setNotification(string $type) public function logFailedLogin(string $username) { $message = config('logging.failed_login.message'); - if (!$message) { + if (! $message) { return; } diff --git a/app/Actions/Tag.php b/app/Actions/Tag.php index ce0954f00cd..f9f278570cc 100644 --- a/app/Actions/Tag.php +++ b/app/Actions/Tag.php @@ -23,7 +23,7 @@ public function entity(): MorphTo */ public function nameUrl(): string { - return url('/search?term=%5B' . urlencode($this->name) . '%5D'); + return url('/search?term=%5B'.urlencode($this->name).'%5D'); } /** @@ -31,6 +31,6 @@ public function nameUrl(): string */ public function valueUrl(): string { - return url('/search?term=%5B' . urlencode($this->name) . '%3D' . urlencode($this->value) . '%5D'); + return url('/search?term=%5B'.urlencode($this->name).'%3D'.urlencode($this->value).'%5D'); } } diff --git a/app/Actions/TagRepo.php b/app/Actions/TagRepo.php index b892efe5779..a3b1db98a1e 100644 --- a/app/Actions/TagRepo.php +++ b/app/Actions/TagRepo.php @@ -32,7 +32,7 @@ public function getNameSuggestions(?string $searchTerm): Collection ->groupBy('name'); if ($searchTerm) { - $query = $query->where('name', 'LIKE', $searchTerm . '%')->orderBy('name', 'desc'); + $query = $query->where('name', 'LIKE', $searchTerm.'%')->orderBy('name', 'desc'); } else { $query = $query->orderBy('count', 'desc')->take(50); } @@ -54,7 +54,7 @@ public function getValueSuggestions(?string $searchTerm, ?string $tagName): Coll ->groupBy('value'); if ($searchTerm) { - $query = $query->where('value', 'LIKE', $searchTerm . '%')->orderBy('value', 'desc'); + $query = $query->where('value', 'LIKE', $searchTerm.'%')->orderBy('value', 'desc'); } else { $query = $query->orderBy('count', 'desc')->take(50); } diff --git a/app/Api/ApiDocsGenerator.php b/app/Api/ApiDocsGenerator.php index 0ed7e6712d3..47719d41b34 100644 --- a/app/Api/ApiDocsGenerator.php +++ b/app/Api/ApiDocsGenerator.php @@ -24,7 +24,7 @@ class ApiDocsGenerator public static function generateConsideringCache(): Collection { $appVersion = trim(file_get_contents(base_path('version'))); - $cacheKey = 'api-docs::' . $appVersion; + $cacheKey = 'api-docs::'.$appVersion; if (Cache::has($cacheKey) && config('app.env') === 'production') { $docs = Cache::get($cacheKey); } else { @@ -139,7 +139,7 @@ protected function getFlatApiRoutes(): Collection })->map(function ($route) { [$controller, $controllerMethod] = explode('@', $route->action['uses']); $baseModelName = explode('.', explode('/', $route->uri)[1])[0]; - $shortName = $baseModelName . '-' . $controllerMethod; + $shortName = $baseModelName.'-'.$controllerMethod; return [ 'name' => $shortName, diff --git a/app/Api/ApiTokenGuard.php b/app/Api/ApiTokenGuard.php index 1bb672556df..4c79ca75313 100644 --- a/app/Api/ApiTokenGuard.php +++ b/app/Api/ApiTokenGuard.php @@ -48,7 +48,7 @@ public function user() { // Return the user if we've already retrieved them. // Effectively a request-instance cache for this method. - if (!is_null($this->user)) { + if (! is_null($this->user)) { return $this->user; } @@ -74,7 +74,7 @@ public function user() */ public function authenticate() { - if (!is_null($user = $this->user())) { + if (! is_null($user = $this->user())) { return $user; } @@ -137,7 +137,7 @@ protected function validateToken(?ApiToken $token, string $secret): void throw new ApiAuthException(trans('errors.api_user_token_not_found')); } - if (!Hash::check($secret, $token->secret)) { + if (! Hash::check($secret, $token->secret)) { throw new ApiAuthException(trans('errors.api_incorrect_token_secret')); } @@ -146,7 +146,7 @@ protected function validateToken(?ApiToken $token, string $secret): void throw new ApiAuthException(trans('errors.api_user_token_expired'), 403); } - if (!$token->user->can('access-api')) { + if (! $token->user->can('access-api')) { throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403); } } diff --git a/app/Api/ListingResponseBuilder.php b/app/Api/ListingResponseBuilder.php index 02b3f680cf0..21b8adfd22d 100644 --- a/app/Api/ListingResponseBuilder.php +++ b/app/Api/ListingResponseBuilder.php @@ -66,14 +66,14 @@ protected function filterQuery(Builder $query): Builder { $query = clone $query; $requestFilters = $this->request->get('filter', []); - if (!is_array($requestFilters)) { + if (! is_array($requestFilters)) { return $query; } $queryFilters = collect($requestFilters)->map(function ($value, $key) { return $this->requestFilterToQueryFilter($key, $value); })->filter(function ($value) { - return !is_null($value); + return ! is_null($value); })->values()->toArray(); return $query->where($queryFilters); @@ -88,11 +88,11 @@ protected function requestFilterToQueryFilter($fieldKey, $value): ?array $field = $splitKey[0]; $filterOperator = $splitKey[1] ?? 'eq'; - if (!in_array($field, $this->fields)) { + if (! in_array($field, $this->fields)) { return null; } - if (!in_array($filterOperator, array_keys($this->filterOperators))) { + if (! in_array($filterOperator, array_keys($this->filterOperators))) { $filterOperator = 'eq'; } @@ -117,7 +117,7 @@ protected function sortQuery(Builder $query): Builder } $sortName = ltrim($sort, '+- '); - if (!in_array($sortName, $this->fields)) { + if (! in_array($sortName, $this->fields)) { $sortName = $defaultSortName; } diff --git a/app/Auth/Access/ExternalBaseUserProvider.php b/app/Auth/Access/ExternalBaseUserProvider.php index fde610c3e18..55abbfd2714 100644 --- a/app/Auth/Access/ExternalBaseUserProvider.php +++ b/app/Auth/Access/ExternalBaseUserProvider.php @@ -31,7 +31,7 @@ public function __construct(string $model) */ public function createModel() { - $class = '\\' . ltrim($this->model, '\\'); + $class = '\\'.ltrim($this->model, '\\'); return new $class(); } diff --git a/app/Auth/Access/Guards/ExternalBaseSessionGuard.php b/app/Auth/Access/Guards/ExternalBaseSessionGuard.php index 99bfd2e795e..ac8d2ddaa52 100644 --- a/app/Auth/Access/Guards/ExternalBaseSessionGuard.php +++ b/app/Auth/Access/Guards/ExternalBaseSessionGuard.php @@ -84,7 +84,7 @@ public function user() // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. - if (!is_null($this->user)) { + if (! is_null($this->user)) { return $this->user; } @@ -92,7 +92,7 @@ public function user() // First we will try to load the user using the // identifier in the session if one exists. - if (!is_null($id)) { + if (! is_null($id)) { $this->user = $this->provider->retrieveById($id); } @@ -142,7 +142,7 @@ public function once(array $credentials = []) */ public function onceUsingId($id) { - if (!is_null($user = $this->provider->retrieveById($id))) { + if (! is_null($user = $this->provider->retrieveById($id))) { $this->setUser($user); return $user; @@ -264,7 +264,7 @@ public function getLastAttempted() */ public function getName() { - return 'login_' . $this->name . '_' . sha1(static::class); + return 'login_'.$this->name.'_'.sha1(static::class); } /** diff --git a/app/Auth/Access/Guards/LdapSessionGuard.php b/app/Auth/Access/Guards/LdapSessionGuard.php index 7f6965937a1..4576d7ace9c 100644 --- a/app/Auth/Access/Guards/LdapSessionGuard.php +++ b/app/Auth/Access/Guards/LdapSessionGuard.php @@ -76,7 +76,7 @@ public function attempt(array $credentials = [], $remember = false) ]); } - if (!$this->ldapService->validateUserCredentials($userDetails, $credentials['password'])) { + if (! $this->ldapService->validateUserCredentials($userDetails, $credentials['password'])) { return false; } diff --git a/app/Auth/Access/LdapService.php b/app/Auth/Access/LdapService.php index e3a38537ac3..d7804f89488 100644 --- a/app/Auth/Access/LdapService.php +++ b/app/Auth/Access/LdapService.php @@ -181,7 +181,7 @@ protected function bindSystemUser($connection) $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass); } - if (!$ldapBind) { + if (! $ldapBind) { throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed'))); } } @@ -201,7 +201,7 @@ protected function getConnection() } // Check LDAP extension in installed - if (!function_exists('ldap_connect') && config('app.env') !== 'testing') { + if (! function_exists('ldap_connect') && config('app.env') !== 'testing') { throw new LdapException(trans('errors.ldap_extension_not_installed')); } @@ -226,7 +226,7 @@ protected function getConnection() // Start and verify TLS if it's enabled if ($this->config['start_tls']) { $started = $this->ldap->startTls($ldapConnection); - if (!$started) { + if (! $started) { throw new LdapException('Could not start TLS connection'); } } @@ -263,7 +263,7 @@ protected function buildFilter(string $filterString, array $attrs): string { $newAttrs = []; foreach ($attrs as $key => $attrText) { - $newKey = '${' . $key . '}'; + $newKey = '${'.$key.'}'; $newAttrs[$newKey] = $this->ldap->escape($attrText); } @@ -332,7 +332,7 @@ private function getGroupGroups(string $groupName): array $baseDn = $this->config['base_dn']; $groupsAttr = strtolower($this->config['group_attribute']); - $groupFilter = 'CN=' . $this->ldap->escape($groupName); + $groupFilter = 'CN='.$this->ldap->escape($groupName); $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]); if ($groups['count'] === 0) { return []; @@ -357,7 +357,7 @@ protected function groupFilter(array $userGroupSearchResponse): array for ($i = 0; $i < $count; $i++) { $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1); - if (!in_array($dnComponents[0], $ldapGroups)) { + if (! in_array($dnComponents[0], $ldapGroups)) { $ldapGroups[] = $dnComponents[0]; } } diff --git a/app/Auth/Access/LoginService.php b/app/Auth/Access/LoginService.php index f41570417ef..dd4aba01974 100644 --- a/app/Auth/Access/LoginService.php +++ b/app/Auth/Access/LoginService.php @@ -90,7 +90,7 @@ public function getLastLoginAttemptUser(): ?User protected function getLastLoginAttemptDetails(): array { $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY); - if (!$value) { + if (! $value) { return ['user_id' => null, 'method' => null]; } @@ -131,7 +131,7 @@ protected function clearLastLoginAttempted(): void */ public function needsMfaVerification(User $user): bool { - return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user); + return ! $this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user); } /** @@ -139,7 +139,7 @@ public function needsMfaVerification(User $user): bool */ public function awaitingEmailConfirmation(User $user): bool { - return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed; + return $this->emailConfirmationService->confirmationRequired() && ! $user->email_confirmed; } /** diff --git a/app/Auth/Access/Mfa/BackupCodeService.php b/app/Auth/Access/Mfa/BackupCodeService.php index d58d28ae12f..32faf73ba48 100644 --- a/app/Auth/Access/Mfa/BackupCodeService.php +++ b/app/Auth/Access/Mfa/BackupCodeService.php @@ -13,8 +13,8 @@ public function generateNewSet(): array { $codes = []; while (count($codes) < 16) { - $code = Str::random(5) . '-' . Str::random(5); - if (!in_array($code, $codes)) { + $code = Str::random(5).'-'.Str::random(5); + if (! in_array($code, $codes)) { $codes[] = strtolower($code); } } diff --git a/app/Auth/Access/Mfa/MfaSession.php b/app/Auth/Access/Mfa/MfaSession.php index 72163b58ec4..69a8b817155 100644 --- a/app/Auth/Access/Mfa/MfaSession.php +++ b/app/Auth/Access/Mfa/MfaSession.php @@ -21,7 +21,7 @@ public function isRequiredForUser(User $user): bool */ public function isPendingMfaSetup(User $user): bool { - return $this->isRequiredForUser($user) && !$user->mfaValues()->exists(); + return $this->isRequiredForUser($user) && ! $user->mfaValues()->exists(); } /** @@ -55,6 +55,6 @@ public function markVerifiedForUser(User $user): void */ protected function getMfaVerifiedSessionKey(User $user): string { - return 'mfa-verification-passed:' . $user->id; + return 'mfa-verification-passed:'.$user->id; } } diff --git a/app/Auth/Access/Oidc/OidcIdToken.php b/app/Auth/Access/Oidc/OidcIdToken.php index c955c3b0915..83538755496 100644 --- a/app/Auth/Access/Oidc/OidcIdToken.php +++ b/app/Auth/Access/Oidc/OidcIdToken.php @@ -115,12 +115,12 @@ public function getAllClaims(): array protected function validateTokenStructure(): void { foreach (['header', 'payload'] as $prop) { - if (empty($this->$prop) || !is_array($this->$prop)) { + if (empty($this->$prop) || ! is_array($this->$prop)) { throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token"); } } - if (empty($this->signature) || !is_string($this->signature)) { + if (empty($this->signature) || ! is_string($this->signature)) { throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token'); } } @@ -140,13 +140,13 @@ protected function validateTokenSignature(): void try { return new OidcJwtSigningKey($key); } catch (OidcInvalidKeyException $e) { - throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage()); + throw new OidcInvalidTokenException('Failed to read signing key with error: '.$e->getMessage()); } }, $this->keys); $parsedKeys = array_filter($parsedKeys); - $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1]; + $contentToSign = $this->tokenParts[0].'.'.$this->tokenParts[1]; /** @var OidcJwtSigningKey $parsedKey */ foreach ($parsedKeys as $parsedKey) { if ($parsedKey->verify($contentToSign, $this->signature)) { @@ -181,7 +181,7 @@ protected function validateTokenClaims(string $clientId): void $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud']; if (count($aud) !== 1) { - throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1'); + throw new OidcInvalidTokenException('Token audience value has '.count($aud).' values, Expected 1'); } if ($aud[0] !== $clientId) { diff --git a/app/Auth/Access/Oidc/OidcJwtSigningKey.php b/app/Auth/Access/Oidc/OidcJwtSigningKey.php index 9a5b3833ade..4828ecb9c09 100644 --- a/app/Auth/Access/Oidc/OidcJwtSigningKey.php +++ b/app/Auth/Access/Oidc/OidcJwtSigningKey.php @@ -48,7 +48,7 @@ protected function loadFromPath(string $path) throw new OidcInvalidKeyException("Failed to load key from file path with error: {$exception->getMessage()}"); } - if (!($this->key instanceof RSA)) { + if (! ($this->key instanceof RSA)) { throw new OidcInvalidKeyException('Key loaded from file path is not an RSA key as expected'); } } diff --git a/app/Auth/Access/Oidc/OidcProviderSettings.php b/app/Auth/Access/Oidc/OidcProviderSettings.php index 32946d058cf..71b0cf7af39 100644 --- a/app/Auth/Access/Oidc/OidcProviderSettings.php +++ b/app/Auth/Access/Oidc/OidcProviderSettings.php @@ -111,7 +111,7 @@ public function validate(): void public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes) { try { - $cacheKey = 'oidc-discovery::' . $this->issuer; + $cacheKey = 'oidc-discovery::'.$this->issuer; $discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function () use ($httpClient) { return $this->loadSettingsFromIssuerDiscovery($httpClient); }); @@ -127,12 +127,12 @@ public function discoverFromIssuer(ClientInterface $httpClient, Repository $cach */ protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): array { - $issuerUrl = rtrim($this->issuer, '/') . '/.well-known/openid-configuration'; + $issuerUrl = rtrim($this->issuer, '/').'/.well-known/openid-configuration'; $request = new Request('GET', $issuerUrl); $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); - if (empty($result) || !is_array($result)) { + if (empty($result) || ! is_array($result)) { throw new OidcIssuerDiscoveryException("Error discovering provider settings from issuer at URL {$issuerUrl}"); } @@ -142,15 +142,15 @@ protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): $discoveredSettings = []; - if (!empty($result['authorization_endpoint'])) { + if (! empty($result['authorization_endpoint'])) { $discoveredSettings['authorizationEndpoint'] = $result['authorization_endpoint']; } - if (!empty($result['token_endpoint'])) { + if (! empty($result['token_endpoint'])) { $discoveredSettings['tokenEndpoint'] = $result['token_endpoint']; } - if (!empty($result['jwks_uri'])) { + if (! empty($result['jwks_uri'])) { $keys = $this->loadKeysFromUri($result['jwks_uri'], $httpClient); $discoveredSettings['keys'] = $this->filterKeys($keys); } @@ -180,7 +180,7 @@ protected function loadKeysFromUri(string $uri, ClientInterface $httpClient): ar $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); - if (empty($result) || !is_array($result) || !isset($result['keys'])) { + if (empty($result) || ! is_array($result) || ! isset($result['keys'])) { throw new OidcIssuerDiscoveryException('Error reading keys from issuer jwks_uri'); } diff --git a/app/Auth/Access/Oidc/OidcService.php b/app/Auth/Access/Oidc/OidcService.php index b8e017b4b13..9b1717bd6ee 100644 --- a/app/Auth/Access/Oidc/OidcService.php +++ b/app/Auth/Access/Oidc/OidcService.php @@ -94,7 +94,7 @@ protected function getProviderSettings(): OidcProviderSettings ]); // Use keys if configured - if (!empty($config['jwt_public_key'])) { + if (! empty($config['jwt_public_key'])) { $settings->keys = [$config['jwt_public_key']]; } diff --git a/app/Auth/Access/RegistrationService.php b/app/Auth/Access/RegistrationService.php index dcdb68bd5cd..149c8f574de 100644 --- a/app/Auth/Access/RegistrationService.php +++ b/app/Auth/Access/RegistrationService.php @@ -34,7 +34,7 @@ public function __construct(UserRepo $userRepo, EmailConfirmationService $emailC */ public function ensureRegistrationAllowed() { - if (!$this->registrationAllowed()) { + if (! $this->registrationAllowed()) { throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login'); } } @@ -90,7 +90,7 @@ public function registerUser(array $userData, ?SocialAccount $socialAccount = nu $this->ensureEmailDomainAllowed($userEmail); // Ensure user does not already exist - $alreadyUser = !is_null($this->userRepo->getByEmail($userEmail)); + $alreadyUser = ! is_null($this->userRepo->getByEmail($userEmail)); if ($alreadyUser) { throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login'); } @@ -107,7 +107,7 @@ public function registerUser(array $userData, ?SocialAccount $socialAccount = nu Theme::dispatch(ThemeEvents::AUTH_REGISTER, $socialAccount ? $socialAccount->driver : auth()->getDefaultDriver(), $newUser); // Start email confirmation flow if required - if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) { + if ($this->emailConfirmationService->confirmationRequired() && ! $emailConfirmed) { $newUser->save(); try { @@ -133,13 +133,13 @@ protected function ensureEmailDomainAllowed(string $userEmail): void { $registrationRestrict = setting('registration-restrict'); - if (!$registrationRestrict) { + if (! $registrationRestrict) { return; } $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict)); $userEmailDomain = $domain = mb_substr(mb_strrchr($userEmail, '@'), 1); - if (!in_array($userEmailDomain, $restrictedEmailDomains)) { + if (! in_array($userEmailDomain, $restrictedEmailDomains)) { $redirect = $this->registrationAllowed() ? '/register' : '/login'; throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), $redirect); diff --git a/app/Auth/Access/Saml2Service.php b/app/Auth/Access/Saml2Service.php index ad889faf7c1..bcd441a64c7 100644 --- a/app/Auth/Access/Saml2Service.php +++ b/app/Auth/Access/Saml2Service.php @@ -108,13 +108,13 @@ public function processAcsResponse(string $requestId, string $samlResponse): ?Us $toolkit->processResponse($requestId); $errors = $toolkit->getErrors(); - if (!empty($errors)) { + if (! empty($errors)) { throw new Error( - 'Invalid ACS Response: ' . implode(', ', $errors) + 'Invalid ACS Response: '.implode(', ', $errors) ); } - if (!$toolkit->isAuthenticated()) { + if (! $toolkit->isAuthenticated()) { return null; } @@ -141,9 +141,9 @@ public function processSlsResponse(?string $requestId): ?string $redirect = $toolkit->processSLO(true, $requestId, true, null, true); $errors = $toolkit->getErrors(); - if (!empty($errors)) { + if (! empty($errors)) { throw new Error( - 'Invalid SLS Response: ' . implode(', ', $errors) + 'Invalid SLS Response: '.implode(', ', $errors) ); } @@ -173,9 +173,9 @@ public function metadata(): string $metadata = $settings->getSPMetadata(); $errors = $settings->validateMetadata($metadata); - if (!empty($errors)) { + if (! empty($errors)) { throw new Error( - 'Invalid SP metadata: ' . implode(', ', $errors), + 'Invalid SP metadata: '.implode(', ', $errors), Error::METADATA_SP_INVALID ); } @@ -305,7 +305,7 @@ public function getUserGroups(array $samlAttributes): array $groupsAttr = $this->config['group_attribute']; $userGroups = $samlAttributes[$groupsAttr] ?? null; - if (!is_array($userGroups)) { + if (! is_array($userGroups)) { $userGroups = []; } diff --git a/app/Auth/Access/SocialAuthService.php b/app/Auth/Access/SocialAuthService.php index d165e76b121..9210f386fa2 100644 --- a/app/Auth/Access/SocialAuthService.php +++ b/app/Auth/Access/SocialAuthService.php @@ -140,7 +140,7 @@ public function handleLoginCallback(string $socialDriver, SocialUser $socialUser // When a user is not logged in and a matching SocialAccount exists, // Simply log the user into the application. - if (!$isLoggedIn && $socialAccount !== null) { + if (! $isLoggedIn && $socialAccount !== null) { $this->loginService->login($socialAccount->user, $socialDriver); return redirect()->intended('/'); @@ -188,11 +188,11 @@ protected function validateDriver(string $socialDriver): string { $driver = trim(strtolower($socialDriver)); - if (!in_array($driver, $this->validSocialDrivers)) { + if (! in_array($driver, $this->validSocialDrivers)) { abort(404, trans('errors.social_driver_not_found')); } - if (!$this->checkDriverConfigured($driver)) { + if (! $this->checkDriverConfigured($driver)) { throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)])); } @@ -205,10 +205,10 @@ protected function validateDriver(string $socialDriver): string protected function checkDriverConfigured(string $driver): bool { $lowerName = strtolower($driver); - $configPrefix = 'services.' . $lowerName . '.'; - $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')]; + $configPrefix = 'services.'.$lowerName.'.'; + $config = [config($configPrefix.'client_id'), config($configPrefix.'client_secret'), config('services.callback_url')]; - return !in_array(false, $config) && !in_array(null, $config); + return ! in_array(false, $config) && ! in_array(null, $config); } /** @@ -232,7 +232,7 @@ public function getActiveDrivers(): array */ public function getDriverName(string $driver): string { - return config('services.' . strtolower($driver) . '.name'); + return config('services.'.strtolower($driver).'.name'); } /** @@ -240,7 +240,7 @@ public function getDriverName(string $driver): string */ public function driverAutoRegisterEnabled(string $driver): bool { - return config('services.' . strtolower($driver) . '.auto_register') === true; + return config('services.'.strtolower($driver).'.auto_register') === true; } /** @@ -248,7 +248,7 @@ public function driverAutoRegisterEnabled(string $driver): bool */ public function driverAutoConfirmEmailEnabled(string $driver): bool { - return config('services.' . strtolower($driver) . '.auto_confirm') === true; + return config('services.'.strtolower($driver).'.auto_confirm') === true; } /** @@ -306,11 +306,11 @@ public function addSocialDriver( callable $configureForRedirect = null ) { $this->validSocialDrivers[] = $driverName; - config()->set('services.' . $driverName, $config); - config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback')); - config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName); + config()->set('services.'.$driverName, $config); + config()->set('services.'.$driverName.'.redirect', url('/login/service/'.$driverName.'/callback')); + config()->set('services.'.$driverName.'.name', $config['name'] ?? $driverName); Event::listen(SocialiteWasCalled::class, $socialiteHandler); - if (!is_null($configureForRedirect)) { + if (! is_null($configureForRedirect)) { $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect; } } diff --git a/app/Auth/Access/UserTokenService.php b/app/Auth/Access/UserTokenService.php index ffd828ab509..dd60ae47847 100644 --- a/app/Auth/Access/UserTokenService.php +++ b/app/Auth/Access/UserTokenService.php @@ -55,7 +55,7 @@ public function checkTokenAndGetUserId(string $token): int $entry = $this->getEntryByToken($token); if (is_null($entry)) { - throw new UserTokenNotFoundException('Token "' . $token . '" not found'); + throw new UserTokenNotFoundException('Token "'.$token.'" not found'); } if ($this->entryExpired($entry)) { diff --git a/app/Auth/Permissions/PermissionService.php b/app/Auth/Permissions/PermissionService.php index 13972533971..9c1764dc172 100644 --- a/app/Auth/Permissions/PermissionService.php +++ b/app/Auth/Permissions/PermissionService.php @@ -68,7 +68,7 @@ protected function readyEntityCache(array $entities = []) foreach ($entities as $entity) { $class = get_class($entity); - if (!isset($this->entityCache[$class])) { + if (! isset($this->entityCache[$class])) { $this->entityCache[$class] = collect(); } $this->entityCache[$class]->put($entity->id, $entity); @@ -106,7 +106,7 @@ protected function getChapter(int $chapterId): ?Chapter */ protected function getCurrentUserRoles(): array { - if (!is_null($this->userRoles)) { + if (! is_null($this->userRoles)) { return $this->userRoles; } @@ -338,7 +338,7 @@ protected function createManyJointPermissions(array $entities, array $roles) $entityRestrictedMap = []; $permissionFetch = EntityPermission::query(); foreach ($entities as $entity) { - $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted')); + $entityRestrictedMap[$entity->getMorphClass().':'.$entity->id] = boolval($entity->getRawAttribute('restricted')); $permissionFetch->orWhere(function ($query) use ($entity) { $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass()); }); @@ -348,8 +348,8 @@ protected function createManyJointPermissions(array $entities, array $roles) // Create a mapping of explicit entity permissions $permissionMap = []; foreach ($permissions as $permission) { - $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action; - $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id]; + $key = $permission->restrictable_type.':'.$permission->restrictable_id.':'.$permission->role_id.':'.$permission->action; + $isRestricted = $entityRestrictedMap[$permission->restrictable_type.':'.$permission->restrictable_id]; $permissionMap[$key] = $isRestricted; } @@ -357,7 +357,7 @@ protected function createManyJointPermissions(array $entities, array $roles) $rolePermissionMap = []; foreach ($roles as $role) { foreach ($role->permissions as $permission) { - $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true; + $rolePermissionMap[$role->getRawAttribute('id').':'.$permission->getRawAttribute('name')] = true; } } @@ -399,9 +399,9 @@ protected function getActions(Entity $entity): array */ protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array { - $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action; - $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']); - $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']); + $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType().'-') : '').$action; + $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id').':'.$permissionPrefix.'-all']); + $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id').':'.$permissionPrefix.'-own']); $explodedAction = explode('-', $action); $restrictionAction = end($explodedAction); @@ -422,12 +422,12 @@ protected function createJointPermissionData(Entity $entity, Role $role, string // For chapters and pages, Check if explicit permissions are set on the Book. $book = $this->getBook($entity->book_id); $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction); - $hasPermissiveAccessToParents = !$book->restricted; + $hasPermissiveAccessToParents = ! $book->restricted; // For pages with a chapter, Check if explicit permissions are set on the Chapter if ($entity instanceof Page && intval($entity->chapter_id) !== 0) { $chapter = $this->getChapter($entity->chapter_id); - $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted; + $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && ! $chapter->restricted; if ($chapter->restricted) { $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction); } @@ -447,7 +447,7 @@ protected function createJointPermissionData(Entity $entity, Role $role, string */ protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool { - $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action; + $key = $entity->getMorphClass().':'.$entity->getRawAttribute('id').':'.$role->getRawAttribute('id').':'.$action; return $entityMap[$key] ?? false; } @@ -486,8 +486,8 @@ public function checkOwnableUserAccess(Model $ownable, string $permission): bool // Handle non entity specific jointPermissions if (in_array($explodedPermission[0], $nonJointPermissions)) { - $allPermission = $user && $user->can($permission . '-all'); - $ownPermission = $user && $user->can($permission . '-own'); + $allPermission = $user && $user->can($permission.'-all'); + $ownPermission = $user && $user->can($permission.'-own'); $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by'; $isOwner = $user && $user->id === $ownable->$ownerField; @@ -521,7 +521,7 @@ public function checkUserHasPermissionOnAnything(string $permission, ?string $en $this->addJointHasPermissionCheck($query, $userId); }); - if (!is_null($entityClass)) { + if (! is_null($entityClass)) { $entityInstance = app($entityClass); $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass()); } @@ -613,8 +613,8 @@ public function filterRestrictedEntityRelations($query, string $tableName, strin $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) { /** @var Builder $permissionQuery */ $permissionQuery->select(['role_id'])->from('joint_permissions') - ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) - ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn']) + ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'].'.'.$tableDetails['entityIdColumn']) + ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'].'.'.$tableDetails['entityTypeColumn']) ->where('action', '=', $action) ->whereIn('role_id', $this->getCurrentUserRoles()) ->where(function (QueryBuilder $query) { @@ -642,7 +642,7 @@ public function filterRelatedEntity(string $entityClass, Builder $query, string $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) { /** @var Builder $permissionQuery */ $permissionQuery->select('id')->from('joint_permissions') - ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) + ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'].'.'.$tableDetails['entityIdColumn']) ->where('entity_type', '=', $morphClass) ->where('action', '=', 'view') ->whereIn('role_id', $this->getCurrentUserRoles()) diff --git a/app/Auth/User.php b/app/Auth/User.php index aa8b44e9fd8..ae126576811 100644 --- a/app/Auth/User.php +++ b/app/Auth/User.php @@ -92,7 +92,7 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon */ public static function getDefault(): self { - if (!is_null(static::$defaultUser)) { + if (! is_null(static::$defaultUser)) { return static::$defaultUser; } @@ -293,7 +293,7 @@ public function scopeWithLastActivityAt(Builder $query) */ public function getEditUrl(string $path = ''): string { - $uri = '/settings/users/' . $this->id . '/' . trim($path, '/'); + $uri = '/settings/users/'.$this->id.'/'.trim($path, '/'); return url(rtrim($uri, '/')); } @@ -303,7 +303,7 @@ public function getEditUrl(string $path = ''): string */ public function getProfileUrl(): string { - return url('/user/' . $this->slug); + return url('/user/'.$this->slug); } /** diff --git a/app/Auth/UserRepo.php b/app/Auth/UserRepo.php index 6d48f124020..cefa9dbe395 100644 --- a/app/Auth/UserRepo.php +++ b/app/Auth/UserRepo.php @@ -75,7 +75,7 @@ public function getAllUsersPaginatedAndSorted(int $count, array $sortData): Leng ->orderBy($sort, $sortData['order']); if ($sortData['search']) { - $term = '%' . $sortData['search'] . '%'; + $term = '%'.$sortData['search'].'%'; $query->where(function ($query) use ($term) { $query->where('name', 'like', $term) ->orWhere('email', 'like', $term); @@ -116,7 +116,7 @@ public function attachSystemRole(User $user, string $systemRoleName) */ public function isOnlyAdmin(User $user): bool { - if (!$user->hasSystemRole('admin')) { + if (! $user->hasSystemRole('admin')) { return false; } @@ -150,7 +150,7 @@ protected function demotingLastAdmin(User $user, array $newRoles): bool { if ($this->isOnlyAdmin($user)) { $adminRole = Role::getSystemRole('admin'); - if (!in_array(strval($adminRole->id), $newRoles)) { + if (! in_array(strval($adminRole->id), $newRoles)) { return true; } } @@ -195,9 +195,9 @@ public function destroy(User $user, ?int $newOwnerId = null) // Delete user profile images $this->userAvatar->destroyAllForUser($user); - if (!empty($newOwnerId)) { + if (! empty($newOwnerId)) { $newOwner = User::query()->find($newOwnerId); - if (!is_null($newOwner)) { + if (! is_null($newOwner)) { $this->migrateOwnership($user, $newOwner); } } diff --git a/app/Console/Commands/CleanupImages.php b/app/Console/Commands/CleanupImages.php index 7221501979a..b4c17fab025 100644 --- a/app/Console/Commands/CleanupImages.php +++ b/app/Console/Commands/CleanupImages.php @@ -48,9 +48,9 @@ public function handle() $checkRevisions = $this->option('all') ? false : true; $dryRun = $this->option('force') ? false : true; - if (!$dryRun) { + if (! $dryRun) { $proceed = $this->confirm("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\nAre you sure you want to proceed?"); - if (!$proceed) { + if (! $proceed) { return; } } @@ -60,7 +60,7 @@ public function handle() if ($dryRun) { $this->comment('Dry run, No images have been deleted'); - $this->comment($deleteCount . ' images found that would have been deleted'); + $this->comment($deleteCount.' images found that would have been deleted'); $this->showDeletedImages($deleted); $this->comment('Run with -f or --force to perform deletions'); @@ -68,7 +68,7 @@ public function handle() } $this->showDeletedImages($deleted); - $this->comment($deleteCount . ' images deleted'); + $this->comment($deleteCount.' images deleted'); } protected function showDeletedImages($paths) diff --git a/app/Console/Commands/CopyShelfPermissions.php b/app/Console/Commands/CopyShelfPermissions.php index 32adf06839c..6485dc364b3 100644 --- a/app/Console/Commands/CopyShelfPermissions.php +++ b/app/Console/Commands/CopyShelfPermissions.php @@ -52,7 +52,7 @@ public function handle() $cascadeAll = $this->option('all'); $shelves = null; - if (!$cascadeAll && !$shelfSlug) { + if (! $cascadeAll && ! $shelfSlug) { $this->error('Either a --slug or --all option must be provided.'); return; @@ -60,12 +60,12 @@ public function handle() if ($cascadeAll) { $continue = $this->confirm( - 'Permission settings for all shelves will be cascaded. ' . - 'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' . + 'Permission settings for all shelves will be cascaded. '. + 'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. '. 'Are you sure you want to proceed?' ); - if (!$continue && !$this->hasOption('no-interaction')) { + if (! $continue && ! $this->hasOption('no-interaction')) { return; } @@ -81,9 +81,9 @@ public function handle() foreach ($shelves as $shelf) { $this->bookshelfRepo->copyDownPermissions($shelf, false); - $this->info('Copied permissions for shelf [' . $shelf->id . ']'); + $this->info('Copied permissions for shelf ['.$shelf->id.']'); } - $this->info('Permissions copied for ' . $shelves->count() . ' shelves.'); + $this->info('Permissions copied for '.$shelves->count().' shelves.'); } } diff --git a/app/Console/Commands/CreateAdmin.php b/app/Console/Commands/CreateAdmin.php index a0fb8f31506..362b431ae2f 100644 --- a/app/Console/Commands/CreateAdmin.php +++ b/app/Console/Commands/CreateAdmin.php @@ -48,7 +48,7 @@ public function handle() if (empty($email)) { $email = $this->ask('Please specify an email address for the new admin user'); } - if (mb_strlen($email) < 5 || !filter_var($email, FILTER_VALIDATE_EMAIL)) { + if (mb_strlen($email) < 5 || ! filter_var($email, FILTER_VALIDATE_EMAIL)) { return $this->error('Invalid email address provided'); } diff --git a/app/Console/Commands/ResetMfa.php b/app/Console/Commands/ResetMfa.php index 031bec04bf2..f7a9628fefb 100644 --- a/app/Console/Commands/ResetMfa.php +++ b/app/Console/Commands/ResetMfa.php @@ -43,7 +43,7 @@ public function handle() { $id = $this->option('id'); $email = $this->option('email'); - if (!$id && !$email) { + if (! $id && ! $email) { $this->error('Either a --id= or --email= option must be provided.'); return 1; @@ -56,7 +56,7 @@ public function handle() ->where($field, '=', $value) ->first(); - if (!$user) { + if (! $user) { $this->error("A user where {$field}={$value} could not be found."); return 1; diff --git a/app/Console/Commands/UpdateUrl.php b/app/Console/Commands/UpdateUrl.php index a4bb6cf2288..206753530d8 100644 --- a/app/Console/Commands/UpdateUrl.php +++ b/app/Console/Commands/UpdateUrl.php @@ -47,13 +47,13 @@ public function handle() $newUrl = str_replace("'", '', $this->argument('newUrl')); $urlPattern = '/https?:\/\/(.+)/'; - if (!preg_match($urlPattern, $oldUrl) || !preg_match($urlPattern, $newUrl)) { + if (! preg_match($urlPattern, $oldUrl) || ! preg_match($urlPattern, $newUrl)) { $this->error('The given urls are expected to be full urls starting with http:// or https://'); return 1; } - if (!$this->checkUserOkayToProceed($oldUrl, $newUrl)) { + if (! $this->checkUserOkayToProceed($oldUrl, $newUrl)) { return 1; } diff --git a/app/Console/Commands/UpgradeDatabaseEncoding.php b/app/Console/Commands/UpgradeDatabaseEncoding.php index 32808729a54..6bde93252fe 100644 --- a/app/Console/Commands/UpgradeDatabaseEncoding.php +++ b/app/Console/Commands/UpgradeDatabaseEncoding.php @@ -43,12 +43,12 @@ public function handle() $database = DB::getDatabaseName(); $tables = DB::select('SHOW TABLES'); - $this->line('ALTER DATABASE `' . $database . '` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); - $this->line('USE `' . $database . '`;'); - $key = 'Tables_in_' . $database; + $this->line('ALTER DATABASE `'.$database.'` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); + $this->line('USE `'.$database.'`;'); + $key = 'Tables_in_'.$database; foreach ($tables as $table) { $tableName = $table->$key; - $this->line('ALTER TABLE `' . $tableName . '` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); + $this->line('ALTER TABLE `'.$tableName.'` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); } DB::setDefaultConnection($connection); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 11c8018c8d6..eac23b4fe8f 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -35,6 +35,6 @@ protected function schedule(Schedule $schedule) */ protected function commands() { - $this->load(__DIR__ . '/Commands'); + $this->load(__DIR__.'/Commands'); } } diff --git a/app/Entities/Models/Book.php b/app/Entities/Models/Book.php index 1e4591bd75d..7a4a6df500d 100644 --- a/app/Entities/Models/Book.php +++ b/app/Entities/Models/Book.php @@ -31,7 +31,7 @@ class Book extends Entity implements HasCoverImage */ public function getUrl(string $path = ''): string { - return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')])); + return url('/books/'.implode('/', [urlencode($this->slug), trim($path, '/')])); } /** @@ -45,7 +45,7 @@ public function getUrl(string $path = ''): string public function getBookCover($width = 440, $height = 250) { $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - if (!$this->image_id) { + if (! $this->image_id) { return $default; } diff --git a/app/Entities/Models/Bookshelf.php b/app/Entities/Models/Bookshelf.php index f427baf49fc..bc706050bf9 100644 --- a/app/Entities/Models/Bookshelf.php +++ b/app/Entities/Models/Bookshelf.php @@ -42,7 +42,7 @@ public function visibleBooks(): BelongsToMany */ public function getUrl(string $path = ''): string { - return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')])); + return url('/shelves/'.implode('/', [urlencode($this->slug), trim($path, '/')])); } /** @@ -57,7 +57,7 @@ public function getBookCover($width = 440, $height = 250) { // TODO - Make generic, focused on books right now, Perhaps set-up a better image $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - if (!$this->image_id) { + if (! $this->image_id) { return $default; } diff --git a/app/Entities/Models/Chapter.php b/app/Entities/Models/Chapter.php index f6f8427a3a0..988d5e71ffb 100644 --- a/app/Entities/Models/Chapter.php +++ b/app/Entities/Models/Chapter.php @@ -42,7 +42,7 @@ public function getUrl($path = ''): string trim($path, '/'), ]; - return url('/' . implode('/', $parts)); + return url('/'.implode('/', $parts)); } /** diff --git a/app/Entities/Models/Deletion.php b/app/Entities/Models/Deletion.php index dab89ce3742..d8330de0bc9 100644 --- a/app/Entities/Models/Deletion.php +++ b/app/Entities/Models/Deletion.php @@ -56,6 +56,6 @@ public function logDescriptor(): string */ public function getUrl($path): string { - return url("/settings/recycle-bin/{$this->id}/" . ltrim($path, '/')); + return url("/settings/recycle-bin/{$this->id}/".ltrim($path, '/')); } } diff --git a/app/Entities/Models/Entity.php b/app/Entities/Models/Entity.php index f5f9d91f0c8..84789a64608 100644 --- a/app/Entities/Models/Entity.php +++ b/app/Entities/Models/Entity.php @@ -82,7 +82,7 @@ public function scopeHasPermission(Builder $query, string $permission) public function scopeWithLastView(Builder $query) { $viewedAtQuery = View::query()->select('updated_at') - ->whereColumn('viewable_id', '=', $this->getTable() . '.id') + ->whereColumn('viewable_id', '=', $this->getTable().'.id') ->where('viewable_type', '=', $this->getMorphClass()) ->where('user_id', '=', user()->id) ->take(1); @@ -96,7 +96,7 @@ public function scopeWithLastView(Builder $query) public function scopeWithViewCount(Builder $query) { $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count') - ->whereColumn('viewable_id', '=', $this->getTable() . '.id') + ->whereColumn('viewable_id', '=', $this->getTable().'.id') ->where('viewable_type', '=', $this->getMorphClass())->take(1); $query->addSelect(['view_count' => $viewCountQuery]); @@ -235,7 +235,7 @@ public function getShortName(int $length = 25): string return $this->name; } - return mb_substr($this->name, 0, $length - 3) . '...'; + return mb_substr($this->name, 0, $length - 3).'...'; } /** @@ -254,7 +254,7 @@ public function getExcerpt(int $length = 100): string $text = $this->getText(); if (mb_strlen($text) > $length) { - $text = mb_substr($text, 0, $length - 3) . '...'; + $text = mb_substr($text, 0, $length - 3).'...'; } return trim($text); diff --git a/app/Entities/Models/Page.php b/app/Entities/Models/Page.php index 45296566717..1078b1318d0 100644 --- a/app/Entities/Models/Page.php +++ b/app/Entities/Models/Page.php @@ -113,7 +113,7 @@ public function getUrl($path = ''): string trim($path, '/'), ]; - return url('/' . implode('/', $parts)); + return url('/'.implode('/', $parts)); } /** diff --git a/app/Entities/Models/PageRevision.php b/app/Entities/Models/PageRevision.php index b994e7a04ce..59d9b8c6f65 100644 --- a/app/Entities/Models/PageRevision.php +++ b/app/Entities/Models/PageRevision.php @@ -52,9 +52,9 @@ public function page(): BelongsTo */ public function getUrl($path = null) { - $url = $this->page->getUrl() . '/revisions/' . $this->id; + $url = $this->page->getUrl().'/revisions/'.$this->id; if ($path) { - return $url . '/' . trim($path, '/'); + return $url.'/'.trim($path, '/'); } return $url; diff --git a/app/Entities/Repos/BookshelfRepo.php b/app/Entities/Repos/BookshelfRepo.php index 3990bfbdcf0..ed904e1e13a 100644 --- a/app/Entities/Repos/BookshelfRepo.php +++ b/app/Entities/Repos/BookshelfRepo.php @@ -102,7 +102,7 @@ public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshe { $this->baseRepo->update($shelf, $input); - if (!is_null($bookIds)) { + if (! is_null($bookIds)) { $this->updateBooks($shelf, $bookIds); } @@ -153,7 +153,7 @@ public function copyDownPermissions(Bookshelf $shelf, $checkUserPermissions = tr /** @var Book $book */ foreach ($shelfBooks as $book) { - if ($checkUserPermissions && !userCan('restrictions-manage', $book)) { + if ($checkUserPermissions && ! userCan('restrictions-manage', $book)) { continue; } $book->permissions()->delete(); diff --git a/app/Entities/Repos/PageRepo.php b/app/Entities/Repos/PageRepo.php index ffa06d45954..eab96fec8a6 100644 --- a/app/Entities/Repos/PageRepo.php +++ b/app/Entities/Repos/PageRepo.php @@ -40,7 +40,7 @@ public function getById(int $id, array $relations = ['book']): Page { $page = Page::visible()->with($relations)->find($id); - if (!$page) { + if (! $page) { throw new NotFoundException(trans('errors.page_not_found')); } @@ -56,7 +56,7 @@ public function getBySlug(string $bookSlug, string $pageSlug): Page { $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first(); - if (!$page) { + if (! $page) { throw new NotFoundException(trans('errors.page_not_found')); } @@ -95,7 +95,7 @@ public function getTemplates(int $count = 10, int $page = 1, string $search = '' ->take($count); if ($search) { - $query->where('name', 'like', '%' . $search . '%'); + $query->where('name', 'like', '%'.$search.'%'); } $paginator = $query->paginate($count, ['*'], 'page', $page); @@ -216,7 +216,7 @@ protected function updateTemplateStatusAndContentFromInput(Page $page, array $in } $pageContent = new PageContent($page); - if (!empty($input['markdown'] ?? '')) { + if (! empty($input['markdown'] ?? '')) { $pageContent->setNewMarkdown($input['markdown']); } elseif (isset($input['html'])) { $pageContent->setNewHTML($input['html']); @@ -297,7 +297,7 @@ public function restoreRevision(Page $page, int $revisionId): Page $page->fill($revision->toArray()); $content = new PageContent($page); - if (!empty($revision->markdown)) { + if (! empty($revision->markdown)) { $content->setNewMarkdown($revision->markdown); } else { $content->setNewHTML($revision->html); @@ -331,7 +331,7 @@ public function move(Page $page, string $parentIdentifier): Entity throw new MoveOperationException('Book or chapter to move page into not found'); } - if (!userCan('page-create', $parent)) { + if (! userCan('page-create', $parent)) { throw new PermissionsException('User does not have permission to create a page within the new parent'); } @@ -358,7 +358,7 @@ public function copy(Page $page, string $parentIdentifier = null, string $newNam throw new MoveOperationException('Book or chapter to move page into not found'); } - if (!userCan('page-create', $parent)) { + if (! userCan('page-create', $parent)) { throw new PermissionsException('User does not have permission to create a page within the new parent'); } @@ -366,7 +366,7 @@ public function copy(Page $page, string $parentIdentifier = null, string $newNam $pageData = $page->getAttributes(); // Update name - if (!empty($newName)) { + if (! empty($newName)) { $pageData['name'] = $newName; } diff --git a/app/Entities/Tools/BookContents.php b/app/Entities/Tools/BookContents.php index 8622d5e1294..30b01c633a6 100644 --- a/app/Entities/Tools/BookContents.php +++ b/app/Entities/Tools/BookContents.php @@ -99,7 +99,7 @@ protected function getPages(bool $showDrafts = false, bool $getPageContent = fal ->select($getPageContent ? Page::$contentAttributes : Page::$listAttributes) ->where('book_id', '=', $this->book->id); - if (!$showDrafts) { + if (! $showDrafts) { $query->where('draft', '=', false); } @@ -174,7 +174,7 @@ protected function applySortUpdates(\stdClass $sortMapItem) protected function loadModelsIntoSortMap(Collection $sortMap): void { $keyMap = $sortMap->keyBy(function (\stdClass $sortMapItem) { - return $sortMapItem->type . ':' . $sortMapItem->id; + return $sortMapItem->type.':'.$sortMapItem->id; }); $pageIds = $sortMap->where('type', '=', 'page')->pluck('id'); $chapterIds = $sortMap->where('type', '=', 'chapter')->pluck('id'); @@ -183,12 +183,12 @@ protected function loadModelsIntoSortMap(Collection $sortMap): void $chapters = Chapter::visible()->whereIn('id', $chapterIds)->get(); foreach ($pages as $page) { - $sortItem = $keyMap->get('page:' . $page->id); + $sortItem = $keyMap->get('page:'.$page->id); $sortItem->model = $page; } foreach ($chapters as $chapter) { - $sortItem = $keyMap->get('chapter:' . $chapter->id); + $sortItem = $keyMap->get('chapter:'.$chapter->id); $sortItem->model = $chapter; } } diff --git a/app/Entities/Tools/ExportFormatter.php b/app/Entities/Tools/ExportFormatter.php index 05d0ff13466..e9d67be03cb 100644 --- a/app/Entities/Tools/ExportFormatter.php +++ b/app/Entities/Tools/ExportFormatter.php @@ -209,7 +209,7 @@ public function pageToPlainText(Page $page): string $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text); $text = html_entity_decode($text); // Add title - $text = $page->name . "\n\n" . $text; + $text = $page->name."\n\n".$text; return $text; } @@ -219,8 +219,8 @@ public function pageToPlainText(Page $page): string */ public function chapterToPlainText(Chapter $chapter): string { - $text = $chapter->name . "\n\n"; - $text .= $chapter->description . "\n\n"; + $text = $chapter->name."\n\n"; + $text .= $chapter->description."\n\n"; foreach ($chapter->getVisiblePages() as $page) { $text .= $this->pageToPlainText($page); } @@ -234,7 +234,7 @@ public function chapterToPlainText(Chapter $chapter): string public function bookToPlainText(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, false); - $text = $book->name . "\n\n"; + $text = $book->name."\n\n"; foreach ($bookTree as $bookChild) { if ($bookChild->isA('chapter')) { $text .= $this->chapterToPlainText($bookChild); @@ -252,10 +252,10 @@ public function bookToPlainText(Book $book): string public function pageToMarkdown(Page $page): string { if ($page->markdown) { - return '# ' . $page->name . "\n\n" . $page->markdown; + return '# '.$page->name."\n\n".$page->markdown; } - return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert(); + return '# '.$page->name."\n\n".(new HtmlToMarkdown($page->html))->convert(); } /** @@ -263,10 +263,10 @@ public function pageToMarkdown(Page $page): string */ public function chapterToMarkdown(Chapter $chapter): string { - $text = '# ' . $chapter->name . "\n\n"; - $text .= $chapter->description . "\n\n"; + $text = '# '.$chapter->name."\n\n"; + $text .= $chapter->description."\n\n"; foreach ($chapter->pages as $page) { - $text .= $this->pageToMarkdown($page) . "\n\n"; + $text .= $this->pageToMarkdown($page)."\n\n"; } return $text; @@ -278,7 +278,7 @@ public function chapterToMarkdown(Chapter $chapter): string public function bookToMarkdown(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); - $text = '# ' . $book->name . "\n\n"; + $text = '# '.$book->name."\n\n"; foreach ($bookTree as $bookChild) { if ($bookChild instanceof Chapter) { $text .= $this->chapterToMarkdown($bookChild); diff --git a/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php b/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php index ca9f434af0f..fb389167f73 100644 --- a/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php +++ b/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php @@ -17,8 +17,8 @@ class CustomStrikethroughRenderer implements InlineRendererInterface { public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer) { - if (!($inline instanceof Strikethrough)) { - throw new \InvalidArgumentException('Incompatible inline type: ' . get_class($inline)); + if (! ($inline instanceof Strikethrough)) { + throw new \InvalidArgumentException('Incompatible inline type: '.get_class($inline)); } return new HtmlElement('s', $inline->getData('attributes', []), $htmlRenderer->renderInlines($inline->children())); diff --git a/app/Entities/Tools/PageContent.php b/app/Entities/Tools/PageContent.php index 9f4ac2893f7..09d322067d0 100644 --- a/app/Entities/Tools/PageContent.php +++ b/app/Entities/Tools/PageContent.php @@ -96,13 +96,13 @@ protected function extractBase64ImagesFromHtml(string $htmlText): string $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png'); // Validate extension - if (!$imageRepo->imageExtensionSupported($extension)) { + if (! $imageRepo->imageExtensionSupported($extension)) { $imageNode->setAttribute('src', ''); continue; } // Save image from data with a random name - $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension; + $imageName = 'embedded-image-'.Str::random(8).'.'.$extension; try { $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id); @@ -135,13 +135,13 @@ protected function extractBase64ImagesFromMarkdown(string $markdown) $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png'); // Validate extension - if (!$imageRepo->imageExtensionSupported($extension)) { + if (! $imageRepo->imageExtensionSupported($extension)) { $markdown = str_replace($base64Match, '', $markdown); continue; } // Save image from data with a random name - $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension; + $imageName = 'embedded-image-'.Str::random(8).'.'.$extension; try { $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id); @@ -174,7 +174,7 @@ protected function formatHtml(string $htmlText): string foreach ($childNodes as $index => $childNode) { [$oldId, $newId] = $this->setUniqueId($childNode, $idMap); if ($newId && $newId !== $oldId) { - $this->updateLinks($xPath, '#' . $oldId, '#' . $newId); + $this->updateLinks($xPath, '#'.$oldId, '#'.$newId); } } @@ -183,7 +183,7 @@ protected function formatHtml(string $htmlText): string foreach ($idElems as $domElem) { [$oldId, $newId] = $this->setUniqueId($domElem, $idMap); if ($newId && $newId !== $oldId) { - $this->updateLinks($xPath, '#' . $oldId, '#' . $newId); + $this->updateLinks($xPath, '#'.$oldId, '#'.$newId); } } @@ -202,7 +202,7 @@ protected function formatHtml(string $htmlText): string protected function updateLinks(DOMXPath $xpath, string $old, string $new) { $old = str_replace('"', '', $old); - $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]'); + $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]'); foreach ($matchingLinks as $domElem) { $domElem->setAttribute('href', $new); } @@ -221,7 +221,7 @@ protected function setUniqueId(\DOMNode $element, array &$idMap): array // Stop if there's an existing valid id that has not already been used. $existingId = $element->getAttribute('id'); - if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) { + if (strpos($existingId, 'bkmrk') === 0 && ! isset($idMap[$existingId])) { $idMap[$existingId] = true; return [$existingId, $existingId]; @@ -230,12 +230,12 @@ protected function setUniqueId(\DOMNode $element, array &$idMap): array // Create an unique id for the element // Uses the content as a basis to ensure output is the same every time // the same content is passed through. - $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20); + $contentId = 'bkmrk-'.mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20); $newId = urlencode($contentId); $loopIndex = 0; while (isset($idMap[$newId])) { - $newId = urlencode($contentId . '-' . $loopIndex); + $newId = urlencode($contentId.'-'.$loopIndex); $loopIndex++; } @@ -262,7 +262,7 @@ public function render(bool $blankIncludes = false): string { $content = $this->page->html ?? ''; - if (!config('app.allow_content_scripts')) { + if (! config('app.allow_content_scripts')) { $content = HtmlContentFilter::removeScripts($content); } @@ -304,7 +304,7 @@ protected function headerNodesToLevelList(DOMNodeList $nodeList): array return [ 'nodeName' => strtolower($header->nodeName), 'level' => intval(str_replace('h', '', $header->nodeName)), - 'link' => '#' . $header->getAttribute('id'), + 'link' => '#'.$header->getAttribute('id'), 'text' => $text, ]; })->filter(function ($header) { @@ -407,7 +407,7 @@ protected function loadDocumentFromHtml(string $html): DOMDocument { libxml_use_internal_errors(true); $doc = new DOMDocument(); - $html = '' . $html . ''; + $html = ''.$html.''; $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); return $doc; diff --git a/app/Entities/Tools/PageEditActivity.php b/app/Entities/Tools/PageEditActivity.php index ef6c085ac72..5fe263b6f72 100644 --- a/app/Entities/Tools/PageEditActivity.php +++ b/app/Entities/Tools/PageEditActivity.php @@ -81,7 +81,7 @@ public function getEditingActiveDraftMessage(PageRevision $draft): string return $message; } - return $message . "\n" . trans('entities.pages_draft_edited_notification'); + return $message."\n".trans('entities.pages_draft_edited_notification'); } /** diff --git a/app/Entities/Tools/PermissionsUpdater.php b/app/Entities/Tools/PermissionsUpdater.php index 4e8351776d8..2a6988d2455 100644 --- a/app/Entities/Tools/PermissionsUpdater.php +++ b/app/Entities/Tools/PermissionsUpdater.php @@ -23,12 +23,12 @@ public function updateFromPermissionsForm(Entity $entity, Request $request) $entity->restricted = $restricted; $entity->permissions()->delete(); - if (!is_null($permissions)) { + if (! is_null($permissions)) { $entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions); $entity->permissions()->createMany($entityPermissionData); } - if (!is_null($ownerId)) { + if (! is_null($ownerId)) { $this->updateOwnerFromId($entity, intval($ownerId)); } @@ -46,7 +46,7 @@ public function updateFromPermissionsForm(Entity $entity, Request $request) protected function updateOwnerFromId(Entity $entity, int $newOwnerId) { $newOwner = User::query()->find($newOwnerId); - if (!is_null($newOwner)) { + if (! is_null($newOwner)) { $entity->owned_by = $newOwner->id; } } diff --git a/app/Entities/Tools/SearchIndex.php b/app/Entities/Tools/SearchIndex.php index cc0b32d6a00..f24d0a61c62 100644 --- a/app/Entities/Tools/SearchIndex.php +++ b/app/Entities/Tools/SearchIndex.php @@ -101,7 +101,7 @@ protected function generateTermArrayFromText(string $text, int $scoreAdjustment $token = strtok($text, $splitChars); while ($token !== false) { - if (!isset($tokenMap[$token])) { + if (! isset($tokenMap[$token])) { $tokenMap[$token] = 0; } $tokenMap[$token]++; diff --git a/app/Entities/Tools/SearchOptions.php b/app/Entities/Tools/SearchOptions.php index 5ce64cc6504..18271051b56 100644 --- a/app/Entities/Tools/SearchOptions.php +++ b/app/Entities/Tools/SearchOptions.php @@ -47,7 +47,7 @@ public static function fromString(string $search): self */ public static function fromRequest(Request $request): self { - if (!$request->has('search') && !$request->has('term')) { + if (! $request->has('search') && ! $request->has('term')) { return static::fromString(''); } @@ -127,7 +127,7 @@ public function toString(): string $string = implode(' ', $this->searches ?? []); foreach ($this->exacts as $term) { - $string .= ' "' . $term . '"'; + $string .= ' "'.$term.'"'; } foreach ($this->tags as $term) { @@ -135,7 +135,7 @@ public function toString(): string } foreach ($this->filters as $filterName => $filterVal) { - $string .= ' {' . $filterName . ($filterVal ? ':' . $filterVal : '') . '}'; + $string .= ' {'.$filterName.($filterVal ? ':'.$filterVal : '').'}'; } return $string; diff --git a/app/Entities/Tools/SearchRunner.php b/app/Entities/Tools/SearchRunner.php index df566eb0b30..3eb421d53d4 100644 --- a/app/Entities/Tools/SearchRunner.php +++ b/app/Entities/Tools/SearchRunner.php @@ -65,7 +65,7 @@ public function searchEntities(SearchOptions $searchOpts, string $entityType = ' $hasMore = false; foreach ($entityTypesToSearch as $entityType) { - if (!in_array($entityType, $entityTypes)) { + if (! in_array($entityType, $entityTypes)) { continue; } $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action); @@ -96,7 +96,7 @@ public function searchBook(int $bookId, string $searchString): Collection $results = collect(); foreach ($entityTypesToSearch as $entityType) { - if (!in_array($entityType, $entityTypes)) { + if (! in_array($entityType, $entityTypes)) { continue; } $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get(); @@ -151,12 +151,12 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent $subQuery->where('entity_type', '=', $entity->getMorphClass()); $subQuery->where(function (Builder $query) use ($searchOpts) { foreach ($searchOpts->searches as $inputTerm) { - $query->orWhere('term', 'like', $inputTerm . '%'); + $query->orWhere('term', 'like', $inputTerm.'%'); } })->groupBy('entity_type', 'entity_id'); - $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) { + $entitySelect->join($this->db->raw('('.$subQuery->toSql().') as s'), function (JoinClause $join) { $join->on('id', '=', 'entity_id'); - })->addSelect($entity->getTable() . '.*') + })->addSelect($entity->getTable().'.*') ->selectRaw('s.score') ->orderBy('score', 'desc'); $entitySelect->mergeBindings($subQuery); @@ -165,8 +165,8 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent // Handle exact term matching foreach ($searchOpts->exacts as $inputTerm) { $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) { - $query->where('name', 'like', '%' . $inputTerm . '%') - ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%'); + $query->where('name', 'like', '%'.$inputTerm.'%') + ->orWhere($entity->textField, 'like', '%'.$inputTerm.'%'); }); } @@ -177,7 +177,7 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent // Handle filters foreach ($searchOpts->filters as $filterTerm => $filterValue) { - $functionName = Str::camel('filter_' . $filterTerm); + $functionName = Str::camel('filter_'.$filterTerm); if (method_exists($this, $functionName)) { $this->$functionName($entitySelect, $entity, $filterValue); } @@ -204,14 +204,14 @@ protected function getRegexEscapedOperators(): string */ protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder { - preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit); + preg_match('/^(.*?)(('.$this->getRegexEscapedOperators().')(.*?))?$/', $tagTerm, $tagSplit); $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) { $tagName = $tagSplit[1]; $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : ''; $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : ''; $validOperator = in_array($tagOperator, $this->queryOperators); - if (!empty($tagOperator) && !empty($tagValue) && $validOperator) { - if (!empty($tagName)) { + if (! empty($tagOperator) && ! empty($tagValue) && $validOperator) { + if (! empty($tagName)) { $query->where('name', '=', $tagName); } if (is_numeric($tagValue) && $tagOperator !== 'like') { @@ -303,7 +303,7 @@ protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input) protected function filterInName(EloquentBuilder $query, Entity $model, $input) { - $query->where('name', 'like', '%' . $input . '%'); + $query->where('name', 'like', '%'.$input.'%'); } protected function filterInTitle(EloquentBuilder $query, Entity $model, $input) @@ -313,7 +313,7 @@ protected function filterInTitle(EloquentBuilder $query, Entity $model, $input) protected function filterInBody(EloquentBuilder $query, Entity $model, $input) { - $query->where($model->textField, 'like', '%' . $input . '%'); + $query->where($model->textField, 'like', '%'.$input.'%'); } protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input) @@ -337,7 +337,7 @@ protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $i protected function filterSortBy(EloquentBuilder $query, Entity $model, $input) { - $functionName = Str::camel('sort_by_' . $input); + $functionName = Str::camel('sort_by_'.$input); if (method_exists($this, $functionName)) { $this->$functionName($query, $model); } @@ -348,10 +348,10 @@ protected function filterSortBy(EloquentBuilder $query, Entity $model, $input) */ protected function sortByLastCommented(EloquentBuilder $query, Entity $model) { - $commentsTable = $this->db->getTablePrefix() . 'comments'; + $commentsTable = $this->db->getTablePrefix().'comments'; $morphClass = str_replace('\\', '\\\\', $model->getMorphClass()); - $commentQuery = $this->db->raw('(SELECT c1.entity_id, c1.entity_type, c1.created_at as last_commented FROM ' . $commentsTable . ' c1 LEFT JOIN ' . $commentsTable . ' c2 ON (c1.entity_id = c2.entity_id AND c1.entity_type = c2.entity_type AND c1.created_at < c2.created_at) WHERE c1.entity_type = \'' . $morphClass . '\' AND c2.created_at IS NULL) as comments'); + $commentQuery = $this->db->raw('(SELECT c1.entity_id, c1.entity_type, c1.created_at as last_commented FROM '.$commentsTable.' c1 LEFT JOIN '.$commentsTable.' c2 ON (c1.entity_id = c2.entity_id AND c1.entity_type = c2.entity_type AND c1.created_at < c2.created_at) WHERE c1.entity_type = \''.$morphClass.'\' AND c2.created_at IS NULL) as comments'); - $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc'); + $query->join($commentQuery, $model->getTable().'.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc'); } } diff --git a/app/Entities/Tools/ShelfContext.php b/app/Entities/Tools/ShelfContext.php index 50d7981716e..f1ad80f5d08 100644 --- a/app/Entities/Tools/ShelfContext.php +++ b/app/Entities/Tools/ShelfContext.php @@ -16,7 +16,7 @@ public function getContextualShelfForBook(Book $book): ?Bookshelf { $contextBookshelfId = session()->get($this->KEY_SHELF_CONTEXT_ID, null); - if (!is_int($contextBookshelfId)) { + if (! is_int($contextBookshelfId)) { return null; } diff --git a/app/Entities/Tools/SiblingFetcher.php b/app/Entities/Tools/SiblingFetcher.php index e9dad0e134f..090b61339ee 100644 --- a/app/Entities/Tools/SiblingFetcher.php +++ b/app/Entities/Tools/SiblingFetcher.php @@ -23,7 +23,7 @@ public function fetch(string $entityType, int $entityId): Collection } // Page in book or chapter - if (($entity->isA('page') && !$entity->chapter) || $entity->isA('chapter')) { + if (($entity->isA('page') && ! $entity->chapter) || $entity->isA('chapter')) { $entities = $entity->book->getDirectChildren(); } diff --git a/app/Entities/Tools/SlugGenerator.php b/app/Entities/Tools/SlugGenerator.php index 52e5700da24..21ddaf70dde 100644 --- a/app/Entities/Tools/SlugGenerator.php +++ b/app/Entities/Tools/SlugGenerator.php @@ -16,7 +16,7 @@ public function generate(Sluggable $model): string { $slug = $this->formatNameAsSlug($model->name); while ($this->slugInUse($slug, $model)) { - $slug .= '-' . Str::random(3); + $slug .= '-'.Str::random(3); } return $slug; diff --git a/app/Exceptions/NotifyException.php b/app/Exceptions/NotifyException.php index 8e748a21dc7..7273ee55f7c 100644 --- a/app/Exceptions/NotifyException.php +++ b/app/Exceptions/NotifyException.php @@ -29,7 +29,7 @@ public function toResponse($request) { $message = $this->getMessage(); - if (!empty($message)) { + if (! empty($message)) { session()->flash('error', $message); } diff --git a/app/Exceptions/PrettyException.php b/app/Exceptions/PrettyException.php index f446442d058..d93b62dd34b 100644 --- a/app/Exceptions/PrettyException.php +++ b/app/Exceptions/PrettyException.php @@ -26,7 +26,7 @@ public function toResponse($request) { $code = ($this->getCode() === 0) ? 500 : $this->getCode(); - return response()->view('errors.' . $code, [ + return response()->view('errors.'.$code, [ 'message' => $this->getMessage(), 'subtitle' => $this->subtitle, 'details' => $this->details, diff --git a/app/Http/Controllers/Api/AttachmentApiController.php b/app/Http/Controllers/Api/AttachmentApiController.php index 06d9f6907ca..47b118964c1 100644 --- a/app/Http/Controllers/Api/AttachmentApiController.php +++ b/app/Http/Controllers/Api/AttachmentApiController.php @@ -102,7 +102,7 @@ public function read(string $id) 'markdown' => $attachment->markdownLink(), ]); - if (!$attachment->external) { + if (! $attachment->external) { $attachmentContents = $this->attachmentService->getAttachmentFromStorage($attachment); $attachment->setAttribute('content', base64_encode($attachmentContents)); } else { diff --git a/app/Http/Controllers/Api/BookExportApiController.php b/app/Http/Controllers/Api/BookExportApiController.php index 028bc3a817e..878a0d9089b 100644 --- a/app/Http/Controllers/Api/BookExportApiController.php +++ b/app/Http/Controllers/Api/BookExportApiController.php @@ -26,7 +26,7 @@ public function exportPdf(int $id) $book = Book::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->bookToPdf($book); - return $this->downloadResponse($pdfContent, $book->slug . '.pdf'); + return $this->downloadResponse($pdfContent, $book->slug.'.pdf'); } /** @@ -39,7 +39,7 @@ public function exportHtml(int $id) $book = Book::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); - return $this->downloadResponse($htmlContent, $book->slug . '.html'); + return $this->downloadResponse($htmlContent, $book->slug.'.html'); } /** @@ -50,7 +50,7 @@ public function exportPlainText(int $id) $book = Book::visible()->findOrFail($id); $textContent = $this->exportFormatter->bookToPlainText($book); - return $this->downloadResponse($textContent, $book->slug . '.txt'); + return $this->downloadResponse($textContent, $book->slug.'.txt'); } /** @@ -61,6 +61,6 @@ public function exportMarkdown(int $id) $book = Book::visible()->findOrFail($id); $markdown = $this->exportFormatter->bookToMarkdown($book); - return $this->downloadResponse($markdown, $book->slug . '.md'); + return $this->downloadResponse($markdown, $book->slug.'.md'); } } diff --git a/app/Http/Controllers/Api/ChapterExportApiController.php b/app/Http/Controllers/Api/ChapterExportApiController.php index 5715ab2e37c..79fc960ad9d 100644 --- a/app/Http/Controllers/Api/ChapterExportApiController.php +++ b/app/Http/Controllers/Api/ChapterExportApiController.php @@ -29,7 +29,7 @@ public function exportPdf(int $id) $chapter = Chapter::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); - return $this->downloadResponse($pdfContent, $chapter->slug . '.pdf'); + return $this->downloadResponse($pdfContent, $chapter->slug.'.pdf'); } /** @@ -42,7 +42,7 @@ public function exportHtml(int $id) $chapter = Chapter::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->chapterToContainedHtml($chapter); - return $this->downloadResponse($htmlContent, $chapter->slug . '.html'); + return $this->downloadResponse($htmlContent, $chapter->slug.'.html'); } /** @@ -53,7 +53,7 @@ public function exportPlainText(int $id) $chapter = Chapter::visible()->findOrFail($id); $textContent = $this->exportFormatter->chapterToPlainText($chapter); - return $this->downloadResponse($textContent, $chapter->slug . '.txt'); + return $this->downloadResponse($textContent, $chapter->slug.'.txt'); } /** @@ -64,6 +64,6 @@ public function exportMarkdown(int $id) $chapter = Chapter::visible()->findOrFail($id); $markdown = $this->exportFormatter->chapterToMarkdown($chapter); - return $this->downloadResponse($markdown, $chapter->slug . '.md'); + return $this->downloadResponse($markdown, $chapter->slug.'.md'); } } diff --git a/app/Http/Controllers/Api/PageApiController.php b/app/Http/Controllers/Api/PageApiController.php index f698627a7e8..bf67c36d955 100644 --- a/app/Http/Controllers/Api/PageApiController.php +++ b/app/Http/Controllers/Api/PageApiController.php @@ -113,11 +113,11 @@ public function update(Request $request, string $id) $parent = Book::visible()->findOrFail($request->get('book_id')); } - if ($parent && !$parent->matches($page->getParent())) { + if ($parent && ! $parent->matches($page->getParent())) { $this->checkOwnablePermission('page-delete', $page); try { - $this->pageRepo->move($page, $parent->getType() . ':' . $parent->id); + $this->pageRepo->move($page, $parent->getType().':'.$parent->id); } catch (Exception $exception) { if ($exception instanceof PermissionsException) { $this->showPermissionError(); diff --git a/app/Http/Controllers/Api/PageExportApiController.php b/app/Http/Controllers/Api/PageExportApiController.php index ce5700c79b9..344766f7cb2 100644 --- a/app/Http/Controllers/Api/PageExportApiController.php +++ b/app/Http/Controllers/Api/PageExportApiController.php @@ -26,7 +26,7 @@ public function exportPdf(int $id) $page = Page::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->pageToPdf($page); - return $this->downloadResponse($pdfContent, $page->slug . '.pdf'); + return $this->downloadResponse($pdfContent, $page->slug.'.pdf'); } /** @@ -39,7 +39,7 @@ public function exportHtml(int $id) $page = Page::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->pageToContainedHtml($page); - return $this->downloadResponse($htmlContent, $page->slug . '.html'); + return $this->downloadResponse($htmlContent, $page->slug.'.html'); } /** @@ -50,7 +50,7 @@ public function exportPlainText(int $id) $page = Page::visible()->findOrFail($id); $textContent = $this->exportFormatter->pageToPlainText($page); - return $this->downloadResponse($textContent, $page->slug . '.txt'); + return $this->downloadResponse($textContent, $page->slug.'.txt'); } /** @@ -61,6 +61,6 @@ public function exportMarkdown(int $id) $page = Page::visible()->findOrFail($id); $markdown = $this->exportFormatter->pageToMarkdown($page); - return $this->downloadResponse($markdown, $page->slug . '.md'); + return $this->downloadResponse($markdown, $page->slug.'.md'); } } diff --git a/app/Http/Controllers/Auth/HandlesPartialLogins.php b/app/Http/Controllers/Auth/HandlesPartialLogins.php index c7f3621517f..e66841e1ad6 100644 --- a/app/Http/Controllers/Auth/HandlesPartialLogins.php +++ b/app/Http/Controllers/Auth/HandlesPartialLogins.php @@ -16,7 +16,7 @@ protected function currentOrLastAttemptedUser(): User $loginService = app()->make(LoginService::class); $user = auth()->user() ?? $loginService->getLastLoginAttemptUser(); - if (!$user) { + if (! $user) { throw new NotFoundException('A user for this action could not be found'); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index d12d7c9bc48..f4f22621479 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -234,7 +234,7 @@ protected function updateIntendedFromPrevious(): void // Store the previous location for redirect after login $previous = url()->previous(''); $isPreviousFromInstance = (strpos($previous, url('/')) === 0); - if (!$previous || !setting('app-public') || !$isPreviousFromInstance) { + if (! $previous || ! setting('app-public') || ! $isPreviousFromInstance) { return; } diff --git a/app/Http/Controllers/Auth/MfaBackupCodesController.php b/app/Http/Controllers/Auth/MfaBackupCodesController.php index d92029bf1b7..9e3cbad2760 100644 --- a/app/Http/Controllers/Auth/MfaBackupCodesController.php +++ b/app/Http/Controllers/Auth/MfaBackupCodesController.php @@ -27,7 +27,7 @@ public function generate(BackupCodeService $codeService) $codes = $codeService->generateNewSet(); session()->put(self::SETUP_SECRET_SESSION_KEY, encrypt($codes)); - $downloadUrl = 'data:application/octet-stream;base64,' . base64_encode(implode("\n\n", $codes)); + $downloadUrl = 'data:application/octet-stream;base64,'.base64_encode(implode("\n\n", $codes)); return view('mfa.backup-codes-generate', [ 'codes' => $codes, @@ -42,7 +42,7 @@ public function generate(BackupCodeService $codeService) */ public function confirm() { - if (!session()->has(self::SETUP_SECRET_SESSION_KEY)) { + if (! session()->has(self::SETUP_SECRET_SESSION_KEY)) { return response('No generated codes found in the session', 500); } @@ -51,7 +51,7 @@ public function confirm() $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'backup-codes'); - if (!auth()->check()) { + if (! auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); @@ -76,7 +76,7 @@ public function verify(Request $request, BackupCodeService $codeService, MfaSess 'required', 'max:12', 'min:8', function ($attribute, $value, $fail) use ($codeService, $codes) { - if (!$codeService->inputCodeExistsInSet($value, $codes)) { + if (! $codeService->inputCodeExistsInSet($value, $codes)) { $fail(trans('validation.backup_codes')); } }, diff --git a/app/Http/Controllers/Auth/MfaTotpController.php b/app/Http/Controllers/Auth/MfaTotpController.php index 5644f02688e..553034bd8b4 100644 --- a/app/Http/Controllers/Auth/MfaTotpController.php +++ b/app/Http/Controllers/Auth/MfaTotpController.php @@ -62,7 +62,7 @@ public function confirm(Request $request) session()->remove(static::SETUP_SECRET_SESSION_KEY); $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp'); - if (!auth()->check()) { + if (! auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); diff --git a/app/Http/Controllers/Auth/Saml2Controller.php b/app/Http/Controllers/Auth/Saml2Controller.php index bd3b25da770..89ff80cb56a 100644 --- a/app/Http/Controllers/Auth/Saml2Controller.php +++ b/app/Http/Controllers/Auth/Saml2Controller.php @@ -93,10 +93,10 @@ public function startAcs(Request $request) } $acsId = Str::random(16); - $cacheKey = 'saml2_acs:' . $acsId; + $cacheKey = 'saml2_acs:'.$acsId; cache()->set($cacheKey, encrypt($samlResponse), 10); - return redirect()->guest('/saml2/acs?id=' . $acsId); + return redirect()->guest('/saml2/acs?id='.$acsId); } /** @@ -107,7 +107,7 @@ public function startAcs(Request $request) public function processAcs(Request $request) { $acsId = $request->get('id', null); - $cacheKey = 'saml2_acs:' . $acsId; + $cacheKey = 'saml2_acs:'.$acsId; $samlResponse = null; try { diff --git a/app/Http/Controllers/Auth/SocialController.php b/app/Http/Controllers/Auth/SocialController.php index 1691668a2bb..40557938c80 100644 --- a/app/Http/Controllers/Auth/SocialController.php +++ b/app/Http/Controllers/Auth/SocialController.php @@ -69,7 +69,7 @@ public function register(string $socialDriver) */ public function callback(Request $request, string $socialDriver) { - if (!session()->has('social-callback')) { + if (! session()->has('social-callback')) { throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login'); } @@ -134,7 +134,7 @@ protected function socialRegisterCallback(string $socialDriver, SocialUser $soci ]; // Take name from email address if empty - if (!$userData['name']) { + if (! $userData['name']) { $userData['name'] = explode('@', $userData['email'])[0]; } diff --git a/app/Http/Controllers/BookController.php b/app/Http/Controllers/BookController.php index 7c099377cb6..57befe7408c 100644 --- a/app/Http/Controllers/BookController.php +++ b/app/Http/Controllers/BookController.php @@ -87,7 +87,7 @@ public function store(Request $request, string $shelfSlug = null) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|' . $this->getImageValidationRules(), + 'image' => 'nullable|'.$this->getImageValidationRules(), ]); $bookshelf = null; @@ -158,7 +158,7 @@ public function update(Request $request, string $slug) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|' . $this->getImageValidationRules(), + 'image' => 'nullable|'.$this->getImageValidationRules(), ]); $book = $this->bookRepo->update($book, $request->all()); diff --git a/app/Http/Controllers/BookExportController.php b/app/Http/Controllers/BookExportController.php index 7f6dd801752..6038e0a6b67 100644 --- a/app/Http/Controllers/BookExportController.php +++ b/app/Http/Controllers/BookExportController.php @@ -31,7 +31,7 @@ public function pdf(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $pdfContent = $this->exportFormatter->bookToPdf($book); - return $this->downloadResponse($pdfContent, $bookSlug . '.pdf'); + return $this->downloadResponse($pdfContent, $bookSlug.'.pdf'); } /** @@ -44,7 +44,7 @@ public function html(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); - return $this->downloadResponse($htmlContent, $bookSlug . '.html'); + return $this->downloadResponse($htmlContent, $bookSlug.'.html'); } /** @@ -55,7 +55,7 @@ public function plainText(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $textContent = $this->exportFormatter->bookToPlainText($book); - return $this->downloadResponse($textContent, $bookSlug . '.txt'); + return $this->downloadResponse($textContent, $bookSlug.'.txt'); } /** @@ -66,6 +66,6 @@ public function markdown(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $textContent = $this->exportFormatter->bookToMarkdown($book); - return $this->downloadResponse($textContent, $bookSlug . '.md'); + return $this->downloadResponse($textContent, $bookSlug.'.md'); } } diff --git a/app/Http/Controllers/BookSortController.php b/app/Http/Controllers/BookSortController.php index 0bd39477801..870e33eea93 100644 --- a/app/Http/Controllers/BookSortController.php +++ b/app/Http/Controllers/BookSortController.php @@ -55,7 +55,7 @@ public function update(Request $request, string $bookSlug) $this->checkOwnablePermission('book-update', $book); // Return if no map sent - if (!$request->filled('sort-tree')) { + if (! $request->filled('sort-tree')) { return redirect($book->getUrl()); } diff --git a/app/Http/Controllers/BookshelfController.php b/app/Http/Controllers/BookshelfController.php index da16d782281..80bdecc61ff 100644 --- a/app/Http/Controllers/BookshelfController.php +++ b/app/Http/Controllers/BookshelfController.php @@ -86,7 +86,7 @@ public function store(Request $request) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|' . $this->getImageValidationRules(), + 'image' => 'nullable|'.$this->getImageValidationRules(), ]); $bookIds = explode(',', $request->get('books', '')); @@ -163,7 +163,7 @@ public function update(Request $request, string $slug) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|' . $this->getImageValidationRules(), + 'image' => 'nullable|'.$this->getImageValidationRules(), ]); $bookIds = explode(',', $request->get('books', '')); diff --git a/app/Http/Controllers/ChapterExportController.php b/app/Http/Controllers/ChapterExportController.php index 480280c99ef..b6ec1a96b64 100644 --- a/app/Http/Controllers/ChapterExportController.php +++ b/app/Http/Controllers/ChapterExportController.php @@ -33,7 +33,7 @@ public function pdf(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); - return $this->downloadResponse($pdfContent, $chapterSlug . '.pdf'); + return $this->downloadResponse($pdfContent, $chapterSlug.'.pdf'); } /** @@ -47,7 +47,7 @@ public function html(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $containedHtml = $this->exportFormatter->chapterToContainedHtml($chapter); - return $this->downloadResponse($containedHtml, $chapterSlug . '.html'); + return $this->downloadResponse($containedHtml, $chapterSlug.'.html'); } /** @@ -60,7 +60,7 @@ public function plainText(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToPlainText($chapter); - return $this->downloadResponse($chapterText, $chapterSlug . '.txt'); + return $this->downloadResponse($chapterText, $chapterSlug.'.txt'); } /** @@ -74,6 +74,6 @@ public function markdown(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToMarkdown($chapter); - return $this->downloadResponse($chapterText, $chapterSlug . '.md'); + return $this->downloadResponse($chapterText, $chapterSlug.'.md'); } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 283a01cfb6a..49561eaf6d3 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -66,7 +66,7 @@ protected function showPermissionError() */ protected function checkPermission(string $permission): void { - if (!user() || !user()->can($permission)) { + if (! user() || ! user()->can($permission)) { $this->showPermissionError(); } } @@ -76,7 +76,7 @@ protected function checkPermission(string $permission): void */ protected function checkOwnablePermission(string $permission, Model $ownable): void { - if (!userCan($permission, $ownable)) { + if (! userCan($permission, $ownable)) { $this->showPermissionError(); } } @@ -118,7 +118,7 @@ protected function downloadResponse(string $content, string $fileName): Response { return response()->make($content, 200, [ 'Content-Type' => 'application/octet-stream', - 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Disposition' => 'attachment; filename="'.$fileName.'"', ]); } @@ -133,7 +133,7 @@ protected function inlineDownloadResponse(string $content, string $fileName): Re return response()->make($content, 200, [ 'Content-Type' => $mime, - 'Content-Disposition' => 'inline; filename="' . $fileName . '"', + 'Content-Disposition' => 'inline; filename="'.$fileName.'"', ]); } diff --git a/app/Http/Controllers/FavouriteController.php b/app/Http/Controllers/FavouriteController.php index a990ff82578..899c9f43326 100644 --- a/app/Http/Controllers/FavouriteController.php +++ b/app/Http/Controllers/FavouriteController.php @@ -19,7 +19,7 @@ public function index(Request $request) $page = intval($request->get('page', 1)); $favourites = (new TopFavourites())->run($viewCount + 1, (($page - 1) * $viewCount)); - $hasMoreLink = ($favourites->count() > $viewCount) ? url('/favourites?page=' . ($page + 1)) : null; + $hasMoreLink = ($favourites->count() > $viewCount) ? url('/favourites?page='.($page + 1)) : null; return view('common.detailed-listing-with-more', [ 'title' => trans('entities.my_favourites'), @@ -73,13 +73,13 @@ protected function getValidatedModelFromRequest(Request $request): Favouritable 'id' => 'required|integer', ]); - if (!class_exists($modelInfo['type'])) { + if (! class_exists($modelInfo['type'])) { throw new \Exception('Model not found'); } /** @var Model $model */ $model = new $modelInfo['type'](); - if (!$model instanceof Favouritable) { + if (! $model instanceof Favouritable) { throw new \Exception('Model not favouritable'); } @@ -87,7 +87,7 @@ protected function getValidatedModelFromRequest(Request $request): Favouritable ->where('id', '=', $modelInfo['id']) ->first(['id', 'name']); - $inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance)); + $inaccessibleEntity = ($modelInstance instanceof Entity && ! userCan('view', $modelInstance)); if (is_null($modelInstance) || $inaccessibleEntity) { throw new \Exception('Model instance not found'); } diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 5451c0abfe8..bc829409c1d 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -45,7 +45,7 @@ public function index() $homepageOptions = ['default', 'books', 'bookshelves', 'page']; $homepageOption = setting('app-homepage-type', 'default'); - if (!in_array($homepageOption, $homepageOptions)) { + if (! in_array($homepageOption, $homepageOptions)) { $homepageOption = 'default'; } @@ -60,9 +60,9 @@ public function index() // Add required list ordering & sorting for books & shelves views. if ($homepageOption === 'bookshelves' || $homepageOption === 'books') { $key = $homepageOption; - $view = setting()->getForCurrentUser($key . '_view_type'); - $sort = setting()->getForCurrentUser($key . '_sort', 'name'); - $order = setting()->getForCurrentUser($key . '_sort_order', 'asc'); + $view = setting()->getForCurrentUser($key.'_view_type'); + $sort = setting()->getForCurrentUser($key.'_sort', 'name'); + $order = setting()->getForCurrentUser($key.'_sort_order', 'asc'); $sortOptions = [ 'name' => trans('common.sort_name'), diff --git a/app/Http/Controllers/Images/DrawioImageController.php b/app/Http/Controllers/Images/DrawioImageController.php index d99bb8e6f6a..1a0ec87dc92 100644 --- a/app/Http/Controllers/Images/DrawioImageController.php +++ b/app/Http/Controllers/Images/DrawioImageController.php @@ -68,7 +68,7 @@ public function getAsBase64($id) { $image = $this->imageRepo->getById($id); $page = $image->getPage(); - if ($image === null || $image->type !== 'drawio' || !userCan('page-view', $page)) { + if ($image === null || $image->type !== 'drawio' || ! userCan('page-view', $page)) { return $this->jsonError('Image data could not be found'); } diff --git a/app/Http/Controllers/Images/ImageController.php b/app/Http/Controllers/Images/ImageController.php index 4070a0e2fe6..c0ed23b3817 100644 --- a/app/Http/Controllers/Images/ImageController.php +++ b/app/Http/Controllers/Images/ImageController.php @@ -35,8 +35,8 @@ public function __construct(Image $image, File $file, ImageRepo $imageRepo) */ public function showImage(string $path) { - $path = storage_path('uploads/images/' . $path); - if (!file_exists($path)) { + $path = storage_path('uploads/images/'.$path); + if (! file_exists($path)) { throw (new NotFoundException(trans('errors.image_not_found'))) ->setSubtitle(trans('errors.image_not_found_subtitle')) ->setDetails(trans('errors.image_not_found_details')); diff --git a/app/Http/Controllers/MaintenanceController.php b/app/Http/Controllers/MaintenanceController.php index d6abe468298..a1649bf1cbe 100644 --- a/app/Http/Controllers/MaintenanceController.php +++ b/app/Http/Controllers/MaintenanceController.php @@ -38,8 +38,8 @@ public function cleanupImages(Request $request, ImageService $imageService) $this->checkPermission('settings-manage'); $this->logActivity(ActivityType::MAINTENANCE_ACTION_RUN, 'cleanup-images'); - $checkRevisions = !($request->get('ignore_revisions', 'false') === 'true'); - $dryRun = !($request->has('confirm')); + $checkRevisions = ! ($request->get('ignore_revisions', 'false') === 'true'); + $dryRun = ! ($request->has('confirm')); $imagesToDelete = $imageService->deleteUnusedImages($checkRevisions, $dryRun); $deleteCount = count($imagesToDelete); @@ -70,7 +70,7 @@ public function sendTestEmail() user()->notify(new TestEmail()); $this->showSuccessNotification(trans('settings.maint_send_test_email_success', ['address' => user()->email])); } catch (\Exception $exception) { - $errorMessage = trans('errors.maintenance_test_email_failure') . "\n" . $exception->getMessage(); + $errorMessage = trans('errors.maintenance_test_email_failure')."\n".$exception->getMessage(); $this->showErrorNotification($errorMessage); } diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index ddb15a7aadc..aa306761315 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -145,7 +145,7 @@ public function show(string $bookSlug, string $pageSlug) $pageNav = $pageContent->getNavigation($page->html); // Check if page comments are enabled - $commentsEnabled = !setting('app-disable-comments'); + $commentsEnabled = ! setting('app-disable-comments'); if ($commentsEnabled) { $page->load(['comments.createdBy']); } @@ -254,7 +254,7 @@ public function saveDraft(Request $request, int $pageId) $page = $this->pageRepo->getById($pageId); $this->checkOwnablePermission('page-update', $page); - if (!$this->isSignedIn()) { + if (! $this->isSignedIn()) { return $this->jsonError(trans('errors.guests_cannot_save_drafts'), 500); } diff --git a/app/Http/Controllers/PageExportController.php b/app/Http/Controllers/PageExportController.php index 0287916de28..9516aeb3970 100644 --- a/app/Http/Controllers/PageExportController.php +++ b/app/Http/Controllers/PageExportController.php @@ -36,7 +36,7 @@ public function pdf(string $bookSlug, string $pageSlug) $page->html = (new PageContent($page))->render(); $pdfContent = $this->exportFormatter->pageToPdf($page); - return $this->downloadResponse($pdfContent, $pageSlug . '.pdf'); + return $this->downloadResponse($pdfContent, $pageSlug.'.pdf'); } /** @@ -51,7 +51,7 @@ public function html(string $bookSlug, string $pageSlug) $page->html = (new PageContent($page))->render(); $containedHtml = $this->exportFormatter->pageToContainedHtml($page); - return $this->downloadResponse($containedHtml, $pageSlug . '.html'); + return $this->downloadResponse($containedHtml, $pageSlug.'.html'); } /** @@ -64,7 +64,7 @@ public function plainText(string $bookSlug, string $pageSlug) $page = $this->pageRepo->getBySlug($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToPlainText($page); - return $this->downloadResponse($pageText, $pageSlug . '.txt'); + return $this->downloadResponse($pageText, $pageSlug.'.txt'); } /** @@ -77,6 +77,6 @@ public function markdown(string $bookSlug, string $pageSlug) $page = $this->pageRepo->getBySlug($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToMarkdown($page); - return $this->downloadResponse($pageText, $pageSlug . '.md'); + return $this->downloadResponse($pageText, $pageSlug.'.md'); } } diff --git a/app/Http/Controllers/PageTemplateController.php b/app/Http/Controllers/PageTemplateController.php index 1e24c29eeff..4029e1ed26e 100644 --- a/app/Http/Controllers/PageTemplateController.php +++ b/app/Http/Controllers/PageTemplateController.php @@ -45,7 +45,7 @@ public function get(int $templateId) { $page = $this->pageRepo->getById($templateId); - if (!$page->template) { + if (! $page->template) { throw new NotFoundException(); } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index d12c23b5a2c..8908719ef32 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -32,7 +32,7 @@ public function search(Request $request) $this->setPageTitle(trans('entities.search_for_term', ['term' => $fullSearchString])); $page = intval($request->get('page', '0')) ?: 1; - $nextPageLink = url('/search?term=' . urlencode($fullSearchString) . '&page=' . ($page + 1)); + $nextPageLink = url('/search?term='.urlencode($fullSearchString).'&page='.($page + 1)); $results = $this->searchRunner->searchEntities($searchOpts, 'all', $page, 20); @@ -80,7 +80,7 @@ public function searchEntitiesAjax(Request $request) // Search for entities otherwise show most popular if ($searchTerm !== false) { - $searchTerm .= ' {type:' . implode('|', $entityTypes) . '}'; + $searchTerm .= ' {type:'.implode('|', $entityTypes).'}'; $entities = $this->searchRunner->searchEntities(SearchOptions::fromString($searchTerm), 'all', 1, 20, $permission)['results']; } else { $entities = (new Popular())->run(20, 0, $entityTypes, $permission); diff --git a/app/Http/Controllers/SettingController.php b/app/Http/Controllers/SettingController.php index d9f172081ef..61256e338d9 100644 --- a/app/Http/Controllers/SettingController.php +++ b/app/Http/Controllers/SettingController.php @@ -44,7 +44,7 @@ public function update(Request $request) $this->preventAccessInDemoMode(); $this->checkPermission('settings-manage'); $this->validate($request, [ - 'app_logo' => 'nullable|' . $this->getImageValidationRules(), + 'app_logo' => 'nullable|'.$this->getImageValidationRules(), ]); // Cycles through posted settings and update them @@ -73,7 +73,7 @@ public function update(Request $request) $section = $request->get('section', ''); $this->logActivity(ActivityType::SETTINGS_UPDATE, $section); $this->showSuccessNotification(trans('settings.settings_save_success')); - $redirectLocation = '/settings#' . $section; + $redirectLocation = '/settings#'.$section; return redirect(rtrim($redirectLocation, '#')); } diff --git a/app/Http/Controllers/UserApiTokenController.php b/app/Http/Controllers/UserApiTokenController.php index bdc25f79dc7..fbc38f7f918 100644 --- a/app/Http/Controllers/UserApiTokenController.php +++ b/app/Http/Controllers/UserApiTokenController.php @@ -57,11 +57,11 @@ public function store(Request $request, int $userId) $token->save(); - session()->flash('api-token-secret:' . $token->id, $secret); + session()->flash('api-token-secret:'.$token->id, $secret); $this->showSuccessNotification(trans('settings.user_api_token_create_success')); $this->logActivity(ActivityType::API_TOKEN_CREATE, $token); - return redirect($user->getEditUrl('/api-tokens/' . $token->id)); + return redirect($user->getEditUrl('/api-tokens/'.$token->id)); } /** @@ -70,7 +70,7 @@ public function store(Request $request, int $userId) public function edit(int $userId, int $tokenId) { [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); - $secret = session()->pull('api-token-secret:' . $token->id, null); + $secret = session()->pull('api-token-secret:'.$token->id, null); return view('users.api-tokens.edit', [ 'user' => $user, @@ -99,7 +99,7 @@ public function update(Request $request, int $userId, int $tokenId) $this->showSuccessNotification(trans('settings.user_api_token_update_success')); $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token); - return redirect($user->getEditUrl('/api-tokens/' . $token->id)); + return redirect($user->getEditUrl('/api-tokens/'.$token->id)); } /** diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 2ee303f3fee..c7f44d106b2 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -81,7 +81,7 @@ public function store(Request $request) $authMethod = config('auth.method'); $sendInvite = ($request->get('send_invite', 'false') === 'true'); - if ($authMethod === 'standard' && !$sendInvite) { + if ($authMethod === 'standard' && ! $sendInvite) { $validationRules['password'] = 'required|min:6'; $validationRules['password-confirm'] = 'required|same:password'; } elseif ($authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'openid') { @@ -156,11 +156,11 @@ public function update(Request $request, int $id) $this->validate($request, [ 'name' => 'min:2', - 'email' => 'min:2|email|unique:users,email,' . $id, + 'email' => 'min:2|email|unique:users,email,'.$id, 'password' => 'min:6|required_with:password_confirm', 'password-confirm' => 'same:password|required_with:password', 'setting' => 'array', - 'profile_image' => 'nullable|' . $this->getImageValidationRules(), + 'profile_image' => 'nullable|'.$this->getImageValidationRules(), ]); $user = $this->userRepo->getById($id); @@ -217,7 +217,7 @@ public function update(Request $request, int $id) $this->showSuccessNotification(trans('settings.users_edit_success')); $this->logActivity(ActivityType::USER_UPDATE, $user); - $redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/' . $user->id); + $redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/'.$user->id); return redirect($redirectUrl); } @@ -299,12 +299,12 @@ protected function switchViewType(int $userId, Request $request, string $listNam $this->checkPermissionOrCurrentUser('users-manage', $userId); $viewType = $request->get('view_type'); - if (!in_array($viewType, ['grid', 'list'])) { + if (! in_array($viewType, ['grid', 'list'])) { $viewType = 'list'; } $user = $this->userRepo->getById($userId); - $key = $listName . '_view_type'; + $key = $listName.'_view_type'; setting()->putUser($user, $key, $viewType); return redirect()->back(302, [], "/settings/users/$userId"); @@ -316,7 +316,7 @@ protected function switchViewType(int $userId, Request $request, string $listNam public function changeSort(Request $request, string $id, string $type) { $validSortTypes = ['books', 'bookshelves', 'shelf_books']; - if (!in_array($type, $validSortTypes)) { + if (! in_array($type, $validSortTypes)) { return redirect()->back(500); } @@ -341,14 +341,14 @@ public function updateExpansionPreference(Request $request, string $id, string $ { $this->checkPermissionOrCurrentUser('users-manage', $id); $keyWhitelist = ['home-details']; - if (!in_array($key, $keyWhitelist)) { + if (! in_array($key, $keyWhitelist)) { return response('Invalid key', 500); } $newState = $request->get('expand', 'false'); $user = $this->user->findOrFail($id); - setting()->putUser($user, 'section_expansion#' . $key, $newState); + setting()->putUser($user, 'section_expansion#'.$key, $newState); return response('', 204); } @@ -361,18 +361,18 @@ protected function changeListSort(int $userId, Request $request, string $listNam $this->checkPermissionOrCurrentUser('users-manage', $userId); $sort = $request->get('sort'); - if (!in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) { + if (! in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) { $sort = 'name'; } $order = $request->get('order'); - if (!in_array($order, ['asc', 'desc'])) { + if (! in_array($order, ['asc', 'desc'])) { $order = 'asc'; } $user = $this->user->findOrFail($userId); - $sortKey = $listName . '_sort'; - $orderKey = $listName . '_sort_order'; + $sortKey = $listName.'_sort'; + $orderKey = $listName.'_sort_order'; setting()->putUser($user, $sortKey, $sort); setting()->putUser($user, $orderKey, $order); diff --git a/app/Http/Controllers/UserSearchController.php b/app/Http/Controllers/UserSearchController.php index f7ed9e57a94..a4b37332d85 100644 --- a/app/Http/Controllers/UserSearchController.php +++ b/app/Http/Controllers/UserSearchController.php @@ -18,10 +18,10 @@ public function forSelect(Request $request) $query = User::query()->orderBy('name', 'desc') ->take(20); - if (!empty($search)) { + if (! empty($search)) { $query->where(function (Builder $query) use ($search) { - $query->where('email', 'like', '%' . $search . '%') - ->orWhere('name', 'like', '%' . $search . '%'); + $query->where('email', 'like', '%'.$search.'%') + ->orWhere('name', 'like', '%'.$search.'%'); }); } diff --git a/app/Http/Middleware/ApiAuthenticate.php b/app/Http/Middleware/ApiAuthenticate.php index bc584d3c5a4..66de6230f95 100644 --- a/app/Http/Middleware/ApiAuthenticate.php +++ b/app/Http/Middleware/ApiAuthenticate.php @@ -35,7 +35,7 @@ protected function ensureAuthorizedBySessionOrToken(): void // Return if the user is already found to be signed in via session-based auth. // This is to make it easy to browser the API via browser after just logging into the system. if (signedInUser() || session()->isStarted()) { - if (!user()->can('access-api')) { + if (! user()->can('access-api')) { throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index a320291122b..df47528e3eb 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -12,7 +12,7 @@ class Authenticate */ public function handle(Request $request, Closure $next) { - if (!hasAppAccess()) { + if (! hasAppAccess()) { if ($request->ajax()) { return response('Unauthorized.', 401); } diff --git a/app/Http/Middleware/CheckEmailConfirmed.php b/app/Http/Middleware/CheckEmailConfirmed.php index 7dd970ade11..9b88407944b 100644 --- a/app/Http/Middleware/CheckEmailConfirmed.php +++ b/app/Http/Middleware/CheckEmailConfirmed.php @@ -38,7 +38,7 @@ public function handle($request, Closure $next) { /** @var User $user */ $user = auth()->user(); - if (auth()->check() && !$user->email_confirmed && $this->confirmationService->confirmationRequired()) { + if (auth()->check() && ! $user->email_confirmed && $this->confirmationService->confirmationRequired()) { auth()->logout(); return redirect()->to('/'); diff --git a/app/Http/Middleware/CheckGuard.php b/app/Http/Middleware/CheckGuard.php index adc1d1f3ec0..769f18f7436 100644 --- a/app/Http/Middleware/CheckGuard.php +++ b/app/Http/Middleware/CheckGuard.php @@ -18,7 +18,7 @@ class CheckGuard public function handle($request, Closure $next, ...$allowedGuards) { $activeGuard = config('auth.method'); - if (!in_array($activeGuard, $allowedGuards)) { + if (! in_array($activeGuard, $allowedGuards)) { session()->flash('error', trans('errors.permission')); return redirect('/'); diff --git a/app/Http/Middleware/CheckUserHasPermission.php b/app/Http/Middleware/CheckUserHasPermission.php index 4a6a06468d1..edd83f4f9b5 100644 --- a/app/Http/Middleware/CheckUserHasPermission.php +++ b/app/Http/Middleware/CheckUserHasPermission.php @@ -18,7 +18,7 @@ class CheckUserHasPermission */ public function handle($request, Closure $next, $permission) { - if (!user()->can($permission)) { + if (! user()->can($permission)) { return $this->errorResponse($request); } diff --git a/app/Http/Middleware/Localization.php b/app/Http/Middleware/Localization.php index d8e1253e5ed..0f7fa061495 100644 --- a/app/Http/Middleware/Localization.php +++ b/app/Http/Middleware/Localization.php @@ -133,7 +133,7 @@ protected function setSystemDateLocale(string $locale) $systemLocale = $this->getLocaleIso($locale); $set = setlocale(LC_TIME, $systemLocale); if ($set === false) { - setlocale(LC_TIME, $systemLocale . '.utf8'); + setlocale(LC_TIME, $systemLocale.'.utf8'); } } } diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 6853809ea9d..a0fa075afa0 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -37,7 +37,7 @@ public function __construct(Guard $auth) public function handle($request, Closure $next) { $requireConfirmation = setting('registration-confirmation'); - if ($this->auth->check() && (!$requireConfirmation || ($requireConfirmation && $this->auth->user()->email_confirmed))) { + if ($this->auth->check() && (! $requireConfirmation || ($requireConfirmation && $this->auth->user()->email_confirmed))) { return redirect('/'); } diff --git a/app/Http/Middleware/RunThemeActions.php b/app/Http/Middleware/RunThemeActions.php index 5e727daae5e..a34ea776906 100644 --- a/app/Http/Middleware/RunThemeActions.php +++ b/app/Http/Middleware/RunThemeActions.php @@ -19,7 +19,7 @@ class RunThemeActions public function handle($request, Closure $next) { $earlyResponse = Theme::dispatch(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $request); - if (!is_null($earlyResponse)) { + if (! is_null($earlyResponse)) { return $earlyResponse; } diff --git a/app/Http/Request.php b/app/Http/Request.php index c5b38f1c1bb..f90128779f8 100644 --- a/app/Http/Request.php +++ b/app/Http/Request.php @@ -19,7 +19,7 @@ public function getSchemeAndHttpHost() if ($base) { $base = trim($base, '/'); } else { - $base = $this->getScheme() . '://' . $this->getHttpHost(); + $base = $this->getScheme().'://'.$this->getHttpHost(); } return $base; diff --git a/app/Notifications/ConfirmEmail.php b/app/Notifications/ConfirmEmail.php index 5399c25a849..75164018aa3 100644 --- a/app/Notifications/ConfirmEmail.php +++ b/app/Notifications/ConfirmEmail.php @@ -31,6 +31,6 @@ public function toMail($notifiable) ->subject(trans('auth.email_confirm_subject', $appName)) ->greeting(trans('auth.email_confirm_greeting', $appName)) ->line(trans('auth.email_confirm_text')) - ->action(trans('auth.email_confirm_action'), url('/register/confirm/' . $this->token)); + ->action(trans('auth.email_confirm_action'), url('/register/confirm/'.$this->token)); } } diff --git a/app/Notifications/ResetPassword.php b/app/Notifications/ResetPassword.php index 7fa14659604..94f8f0d4a2d 100644 --- a/app/Notifications/ResetPassword.php +++ b/app/Notifications/ResetPassword.php @@ -31,7 +31,7 @@ public function toMail() return $this->newMailMessage() ->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')])) ->line(trans('auth.email_reset_text')) - ->action(trans('auth.reset_password'), url('password/reset/' . $this->token)) + ->action(trans('auth.reset_password'), url('password/reset/'.$this->token)) ->line(trans('auth.email_reset_not_requested')); } } diff --git a/app/Notifications/UserInvite.php b/app/Notifications/UserInvite.php index b0dc9afac3f..da7066ca638 100644 --- a/app/Notifications/UserInvite.php +++ b/app/Notifications/UserInvite.php @@ -31,6 +31,6 @@ public function toMail($notifiable) ->subject(trans('auth.user_invite_email_subject', $appName)) ->greeting(trans('auth.user_invite_email_greeting', $appName)) ->line(trans('auth.user_invite_email_text')) - ->action(trans('auth.user_invite_email_action'), url('/register/invite/' . $this->token)); + ->action(trans('auth.user_invite_email_action'), url('/register/invite/'.$this->token)); } } diff --git a/app/Providers/CustomValidationServiceProvider.php b/app/Providers/CustomValidationServiceProvider.php index c54f48ca313..b005b89c404 100644 --- a/app/Providers/CustomValidationServiceProvider.php +++ b/app/Providers/CustomValidationServiceProvider.php @@ -23,7 +23,7 @@ public function boot(): void $isJs = strpos($cleanLinkName, 'javascript:') === 0; $isData = strpos($cleanLinkName, 'data:') === 0; - return !$isJs && !$isData; + return ! $isJs && ! $isData; }); } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index b60443a4528..e57aad5b2d5 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -65,7 +65,7 @@ protected function mapApiRoutes() { Route::group([ 'middleware' => 'api', - 'namespace' => $this->namespace . '\Api', + 'namespace' => $this->namespace.'\Api', 'prefix' => 'api', ], function ($router) { require base_path('routes/api.php'); diff --git a/app/Settings/SettingService.php b/app/Settings/SettingService.php index f2c4c8305c4..174b98329cc 100644 --- a/app/Settings/SettingService.php +++ b/app/Settings/SettingService.php @@ -34,7 +34,7 @@ public function __construct(Setting $setting, Cache $cache) public function get(string $key, $default = null) { if (is_null($default)) { - $default = config('setting-defaults.' . $key, false); + $default = config('setting-defaults.'.$key, false); } if (isset($this->localCache[$key])) { @@ -64,7 +64,7 @@ protected function getFromSession(string $key, $default = false) public function getUser(User $user, string $key, $default = null) { if (is_null($default)) { - $default = config('setting-defaults.user.' . $key, false); + $default = config('setting-defaults.user.'.$key, false); } if ($user->isDefault()) { @@ -90,7 +90,7 @@ public function getForCurrentUser(string $key, $default = null) protected function getValueFromStore(string $key) { // Check the cache - $cacheKey = $this->cachePrefix . $key; + $cacheKey = $this->cachePrefix.$key; $cacheVal = $this->cache->get($cacheKey, null); if ($cacheVal !== null) { return $cacheVal; @@ -118,7 +118,7 @@ protected function getValueFromStore(string $key) */ protected function clearFromCache(string $key) { - $cacheKey = $this->cachePrefix . $key; + $cacheKey = $this->cachePrefix.$key; $this->cache->forget($cacheKey); if (isset($this->localCache[$key])) { unset($this->localCache[$key]); @@ -211,7 +211,7 @@ public function putUser(User $user, string $key, string $value): bool */ protected function userKey(string $userId, string $key = ''): string { - return 'user:' . $userId . ':' . $key; + return 'user:'.$userId.':'.$key; } /** @@ -232,7 +232,7 @@ public function remove(string $key): void public function deleteUserSettings(string $userId) { return $this->setting->newQuery() - ->where('setting_key', 'like', $this->userKey($userId) . '%') + ->where('setting_key', 'like', $this->userKey($userId).'%') ->delete(); } diff --git a/app/Theming/CustomHtmlHeadContentProvider.php b/app/Theming/CustomHtmlHeadContentProvider.php index 041e5d025bd..8a6f1a0ee4e 100644 --- a/app/Theming/CustomHtmlHeadContentProvider.php +++ b/app/Theming/CustomHtmlHeadContentProvider.php @@ -33,7 +33,7 @@ public function forWeb(): string { $content = $this->getSourceContent(); $hash = md5($content); - $html = $this->cache->remember('custom-head-web:' . $hash, 86400, function () use ($content) { + $html = $this->cache->remember('custom-head-web:'.$hash, 86400, function () use ($content) { return HtmlNonceApplicator::prepare($content); }); @@ -49,7 +49,7 @@ public function forExport(): string $content = $this->getSourceContent(); $hash = md5($content); - return $this->cache->remember('custom-head-export:' . $hash, 86400, function () use ($content) { + return $this->cache->remember('custom-head-export:'.$hash, 86400, function () use ($content) { return HtmlContentFilter::removeScripts($content); }); } diff --git a/app/Theming/ThemeService.php b/app/Theming/ThemeService.php index 602abaf1c5a..b18ecaa5850 100644 --- a/app/Theming/ThemeService.php +++ b/app/Theming/ThemeService.php @@ -14,7 +14,7 @@ class ThemeService */ public function listen(string $event, callable $action) { - if (!isset($this->listeners[$event])) { + if (! isset($this->listeners[$event])) { $this->listeners[$event] = []; } @@ -35,7 +35,7 @@ public function dispatch(string $event, ...$args) { foreach ($this->listeners[$event] ?? [] as $action) { $result = call_user_func_array($action, $args); - if (!is_null($result)) { + if (! is_null($result)) { return $result; } } diff --git a/app/Uploads/Attachment.php b/app/Uploads/Attachment.php index 5e637246a66..1c644ebbbd1 100644 --- a/app/Uploads/Attachment.php +++ b/app/Uploads/Attachment.php @@ -45,7 +45,7 @@ public function getFileName() return $this->name; } - return $this->name . '.' . $this->extension; + return $this->name.'.'.$this->extension; } /** @@ -65,7 +65,7 @@ public function getUrl($openInline = false): string return $this->path; } - return url('/attachments/' . $this->id . ($openInline ? '?open=true' : '')); + return url('/attachments/'.$this->id.($openInline ? '?open=true' : '')); } /** @@ -73,7 +73,7 @@ public function getUrl($openInline = false): string */ public function htmlLink(): string { - return '' . e($this->name) . ''; + return ''.e($this->name).''; } /** @@ -81,7 +81,7 @@ public function htmlLink(): string */ public function markdownLink(): string { - return '[' . $this->name . '](' . $this->getUrl() . ')'; + return '['.$this->name.']('.$this->getUrl().')'; } /** diff --git a/app/Uploads/AttachmentService.php b/app/Uploads/AttachmentService.php index f7a0918c609..e13772f1803 100644 --- a/app/Uploads/AttachmentService.php +++ b/app/Uploads/AttachmentService.php @@ -60,7 +60,7 @@ protected function adjustPathForStorageDisk(string $path): string return $path; } - return 'uploads/files/' . $path; + return 'uploads/files/'.$path; } /** @@ -106,7 +106,7 @@ public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachme */ public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment { - if (!$attachment->external) { + if (! $attachment->external) { $this->deleteFileInStorage($attachment); } @@ -161,8 +161,8 @@ public function updateFile(Attachment $attachment, array $requestData): Attachme $attachment->name = $requestData['name']; $link = trim($requestData['link'] ?? ''); - if (!empty($link)) { - if (!$attachment->external) { + if (! empty($link)) { + if (! $attachment->external) { $this->deleteFileInStorage($attachment); $attachment->external = true; $attachment->extension = ''; @@ -182,7 +182,7 @@ public function updateFile(Attachment $attachment, array $requestData): Attachme */ public function deleteFile(Attachment $attachment) { - if (!$attachment->external) { + if (! $attachment->external) { $this->deleteFileInStorage($attachment); } @@ -214,19 +214,19 @@ protected function putFileInStorage(UploadedFile $uploadedFile): string $attachmentData = file_get_contents($uploadedFile->getRealPath()); $storage = $this->getStorage(); - $basePath = 'uploads/files/' . date('Y-m-M') . '/'; + $basePath = 'uploads/files/'.date('Y-m-M').'/'; - $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension(); - while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) { - $uploadFileName = Str::random(3) . $uploadFileName; + $uploadFileName = Str::random(16).'.'.$uploadedFile->getClientOriginalExtension(); + while ($storage->exists($this->adjustPathForStorageDisk($basePath.$uploadFileName))) { + $uploadFileName = Str::random(3).$uploadFileName; } - $attachmentPath = $basePath . $uploadFileName; + $attachmentPath = $basePath.$uploadFileName; try { $storage->put($this->adjustPathForStorageDisk($attachmentPath), $attachmentData); } catch (Exception $e) { - Log::error('Error when attempting file upload:' . $e->getMessage()); + Log::error('Error when attempting file upload:'.$e->getMessage()); throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath])); } diff --git a/app/Uploads/ImageRepo.php b/app/Uploads/ImageRepo.php index c4205e35740..1ff6a1e9cd7 100644 --- a/app/Uploads/ImageRepo.php +++ b/app/Uploads/ImageRepo.php @@ -88,7 +88,7 @@ public function getPaginatedByType( } if ($search !== null) { - $imageQuery = $imageQuery->where('name', 'LIKE', '%' . $search . '%'); + $imageQuery = $imageQuery->where('name', 'LIKE', '%'.$search.'%'); } // Filter by page access @@ -162,7 +162,7 @@ public function saveNewFromData(string $imageName, string $imageData, string $ty */ public function saveDrawing(string $base64Uri, int $uploadedTo): Image { - $name = 'Drawing-' . strval(user()->id) . '-' . strval(time()) . '.png'; + $name = 'Drawing-'.strval(user()->id).'-'.strval(time()).'.png'; return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo); } @@ -256,7 +256,7 @@ public function getImageData(Image $image): ?string public function getPagesUsingImage(Image $image): array { $pages = Page::visible() - ->where('html', 'like', '%' . $image->url . '%') + ->where('html', 'like', '%'.$image->url.'%') ->get(['id', 'name', 'slug', 'book_id']); foreach ($pages as $page) { diff --git a/app/Uploads/ImageService.php b/app/Uploads/ImageService.php index d6c74c751c7..48ad0f6b223 100644 --- a/app/Uploads/ImageService.php +++ b/app/Uploads/ImageService.php @@ -56,7 +56,7 @@ protected function adjustPathForStorageDisk(string $path, string $imageType = '' return $path; } - return 'uploads/images/' . $path; + return 'uploads/images/'.$path; } /** @@ -130,21 +130,21 @@ public function saveNew(string $imageName, string $imageData, string $type, int $secureUploads = setting('app-secure-images'); $fileName = $this->cleanImageFileName($imageName); - $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/'; + $imagePath = '/uploads/images/'.$type.'/'.date('Y-m').'/'; - while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) { - $fileName = Str::random(3) . $fileName; + while ($storage->exists($this->adjustPathForStorageDisk($imagePath.$fileName, $type))) { + $fileName = Str::random(3).$fileName; } - $fullPath = $imagePath . $fileName; + $fullPath = $imagePath.$fileName; if ($secureUploads) { - $fullPath = $imagePath . Str::random(16) . '-' . $fileName; + $fullPath = $imagePath.Str::random(16).'-'.$fileName; } try { $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData); } catch (Exception $e) { - \Log::error('Error when attempting image upload:' . $e->getMessage()); + \Log::error('Error when attempting image upload:'.$e->getMessage()); throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath])); } @@ -182,8 +182,8 @@ protected function saveImageDataInPublicSpace(Storage $storage, string $path, st // Attempting to set ACL during above put request requires different permissions // hence would technically be a breaking change for actual s3 usage. $usingS3 = strtolower(config('filesystems.images')) === 's3'; - $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint')); - if (!$usingS3Like) { + $usingS3Like = $usingS3 && ! is_null(config('filesystems.disks.s3.endpoint')); + if (! $usingS3Like) { $storage->setVisibility($path, 'public'); } } @@ -203,7 +203,7 @@ protected function cleanImageFileName(string $name): string $name = Str::random(10); } - return $name . '.' . $extension; + return $name.'.'.$extension; } /** @@ -235,11 +235,11 @@ public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRat return $this->getPublicUrl($image->path); } - $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/'; + $thumbDirName = '/'.($keepRatio ? 'scaled-' : 'thumbs-').$width.'-'.$height.'/'; $imagePath = $image->path; - $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath); + $thumbFilePath = dirname($imagePath).$thumbDirName.basename($imagePath); - if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) { + if ($this->cache->has('images-'.$image->id.'-'.$thumbFilePath) && $this->cache->get('images-'.$thumbFilePath)) { return $this->getPublicUrl($thumbFilePath); } @@ -251,7 +251,7 @@ public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRat $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio); $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData); - $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72); + $this->cache->put('images-'.$image->id.'-'.$thumbFilePath, $thumbFilePath, 60 * 60 * 72); return $this->getPublicUrl($thumbFilePath); } @@ -379,7 +379,7 @@ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = t $this->image->newQuery()->whereIn('type', $types) ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) { foreach ($images as $image) { - $searchQuery = '%' . basename($image->path) . '%'; + $searchQuery = '%'.basename($image->path).'%'; $inPage = DB::table('pages') ->where('html', 'like', $searchQuery)->count() > 0; @@ -389,9 +389,9 @@ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = t ->where('html', 'like', $searchQuery)->count() > 0; } - if (!$inPage && !$inRevision) { + if (! $inPage && ! $inRevision) { $deletedPaths[] = $image->path; - if (!$dryRun) { + if (! $dryRun) { $this->destroy($image); } } @@ -432,7 +432,7 @@ public function imageUriToBase64(string $uri): ?string $extension = 'svg+xml'; } - return 'data:image/' . $extension . ';base64,' . base64_encode($imageData); + return 'data:image/'.$extension.';base64,'.base64_encode($imageData); } /** @@ -463,7 +463,7 @@ private function imageUrlToStoragePath(string $url): ?string foreach ($potentialHostPaths as $potentialBasePath) { $potentialBasePath = strtolower($potentialBasePath); if (strpos(strtolower($url), $potentialBasePath) === 0) { - return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/'); + return 'uploads/images/'.trim(substr($url, strlen($potentialBasePath)), '/'); } } @@ -485,9 +485,9 @@ private function getPublicUrl(string $filePath): string if ($storageUrl == false && config('filesystems.images') === 's3') { $storageDetails = config('filesystems.disks.s3'); if (strpos($storageDetails['bucket'], '.') === false) { - $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com'; + $storageUrl = 'https://'.$storageDetails['bucket'].'.s3.amazonaws.com'; } else { - $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket']; + $storageUrl = 'https://s3-'.$storageDetails['region'].'.amazonaws.com/'.$storageDetails['bucket']; } } $this->storageUrl = $storageUrl; @@ -495,6 +495,6 @@ private function getPublicUrl(string $filePath): string $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl; - return rtrim($basePath, '/') . $filePath; + return rtrim($basePath, '/').$filePath; } } diff --git a/app/Uploads/UserAvatars.php b/app/Uploads/UserAvatars.php index f5b085a35d5..e317ee74af0 100644 --- a/app/Uploads/UserAvatars.php +++ b/app/Uploads/UserAvatars.php @@ -23,7 +23,7 @@ public function __construct(ImageService $imageService, HttpFetcher $http) */ public function fetchAndAssignToUser(User $user): void { - if (!$this->avatarFetchEnabled()) { + if (! $this->avatarFetchEnabled()) { return; } @@ -93,7 +93,7 @@ protected function saveAvatarImage(User $user, int $size = 500): Image */ protected function createAvatarImageFromData(User $user, string $imageData, string $extension): Image { - $imageName = str_replace(' ', '-', $user->id . '-avatar.' . $extension); + $imageName = str_replace(' ', '-', $user->id.'-avatar.'.$extension); $image = $this->imageService->saveNew($imageName, $imageData, 'user', $user->id); $image->created_by = $user->id; @@ -136,7 +136,7 @@ protected function getAvatarUrl(): string { $url = trim(config('services.avatar_url')); - if (empty($url) && !config('services.disable_services')) { + if (empty($url) && ! config('services.disable_services')) { $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon'; } diff --git a/app/Util/CspService.php b/app/Util/CspService.php index 812e1a4bed1..520344a2fd0 100644 --- a/app/Util/CspService.php +++ b/app/Util/CspService.php @@ -36,11 +36,11 @@ public function setScriptSrc(Response $response) $parts = [ 'http:', 'https:', - '\'nonce-' . $this->nonce . '\'', + '\'nonce-'.$this->nonce.'\'', '\'strict-dynamic\'', ]; - $value = 'script-src ' . implode(' ', $parts); + $value = 'script-src '.implode(' ', $parts); $response->headers->set('Content-Security-Policy', $value, false); } @@ -53,7 +53,7 @@ public function setFrameAncestors(Response $response) { $iframeHosts = $this->getAllowedIframeHosts(); array_unshift($iframeHosts, "'self'"); - $cspValue = 'frame-ancestors ' . implode(' ', $iframeHosts); + $cspValue = 'frame-ancestors '.implode(' ', $iframeHosts); $response->headers->set('Content-Security-Policy', $cspValue, false); } diff --git a/app/Util/HtmlContentFilter.php b/app/Util/HtmlContentFilter.php index 1943aa7802c..ffde21ba36d 100644 --- a/app/Util/HtmlContentFilter.php +++ b/app/Util/HtmlContentFilter.php @@ -18,7 +18,7 @@ public static function removeScripts(string $html): string return $html; } - $html = '' . $html . ''; + $html = ''.$html.''; libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); @@ -29,19 +29,19 @@ public static function removeScripts(string $html): string static::removeNodes($scriptElems); // Remove clickable links to JavaScript URI - $badLinks = $xPath->query('//*[' . static::xpathContains('@href', 'javascript:') . ']'); + $badLinks = $xPath->query('//*['.static::xpathContains('@href', 'javascript:').']'); static::removeNodes($badLinks); // Remove forms with calls to JavaScript URI - $badForms = $xPath->query('//*[' . static::xpathContains('@action', 'javascript:') . '] | //*[' . static::xpathContains('@formaction', 'javascript:') . ']'); + $badForms = $xPath->query('//*['.static::xpathContains('@action', 'javascript:').'] | //*['.static::xpathContains('@formaction', 'javascript:').']'); static::removeNodes($badForms); // Remove meta tag to prevent external redirects - $metaTags = $xPath->query('//meta[' . static::xpathContains('@content', 'url') . ']'); + $metaTags = $xPath->query('//meta['.static::xpathContains('@content', 'url').']'); static::removeNodes($metaTags); // Remove data or JavaScript iFrames - $badIframes = $xPath->query('//*[' . static::xpathContains('@src', 'data:') . '] | //*[' . static::xpathContains('@src', 'javascript:') . '] | //*[@srcdoc]'); + $badIframes = $xPath->query('//*['.static::xpathContains('@src', 'data:').'] | //*['.static::xpathContains('@src', 'javascript:').'] | //*[@srcdoc]'); static::removeNodes($badIframes); // Remove elements with a xlink:href attribute @@ -71,7 +71,7 @@ protected static function xpathContains(string $property, string $value): string $value = strtolower($value); $upperVal = strtoupper($value); - return 'contains(translate(' . $property . ', \'' . $upperVal . '\', \'' . $value . '\'), \'' . $value . '\')'; + return 'contains(translate('.$property.', \''.$upperVal.'\', \''.$value.'\'), \''.$value.'\')'; } /** diff --git a/app/Util/HtmlNonceApplicator.php b/app/Util/HtmlNonceApplicator.php index 07298577cf5..d6afb53e3ce 100644 --- a/app/Util/HtmlNonceApplicator.php +++ b/app/Util/HtmlNonceApplicator.php @@ -21,7 +21,7 @@ public static function prepare(string $html): string return $html; } - $html = '' . $html . ''; + $html = ''.$html.''; libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML($html, LIBXML_SCHEMA_CREATE); diff --git a/app/helpers.php b/app/helpers.php index 9edc22c403d..860fddd1d44 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -24,7 +24,7 @@ function versioned_asset(string $file = ''): string $additional = sha1_file(public_path($file)); } - $path = $file . '?version=' . urlencode($version) . $additional; + $path = $file.'?version='.urlencode($version).$additional; return url($path); } @@ -43,7 +43,7 @@ function user(): User */ function signedInUser(): bool { - return auth()->user() && !auth()->user()->isDefault(); + return auth()->user() && ! auth()->user()->isDefault(); } /** @@ -51,7 +51,7 @@ function signedInUser(): bool */ function hasAppAccess(): bool { - return !auth()->guest() || setting('app-public'); + return ! auth()->guest() || setting('app-public'); } /** @@ -106,11 +106,11 @@ function theme_path(string $path = ''): ?string { $theme = config('view.theme'); - if (!$theme) { + if (! $theme) { return null; } - return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path)); + return base_path('themes/'.$theme.($path ? DIRECTORY_SEPARATOR.$path : $path)); } /** @@ -129,21 +129,21 @@ function icon(string $name, array $attrs = []): string ], $attrs); $attrString = ' '; foreach ($attrs as $attrName => $attr) { - $attrString .= $attrName . '="' . $attr . '" '; + $attrString .= $attrName.'="'.$attr.'" '; } - $iconPath = resource_path('icons/' . $name . '.svg'); - $themeIconPath = theme_path('icons/' . $name . '.svg'); + $iconPath = resource_path('icons/'.$name.'.svg'); + $themeIconPath = theme_path('icons/'.$name.'.svg'); if ($themeIconPath && file_exists($themeIconPath)) { $iconPath = $themeIconPath; - } elseif (!file_exists($iconPath)) { + } elseif (! file_exists($iconPath)) { return ''; } $fileContents = file_get_contents($iconPath); - return str_replace(' env('DISABLE_EXTERNAL_SERVICES', false), // Draw.io integration active - 'drawio' => env('DRAWIO', !env('DISABLE_EXTERNAL_SERVICES', false)), + 'drawio' => env('DRAWIO', ! env('DISABLE_EXTERNAL_SERVICES', false)), // URL for fetching avatars 'avatar_url' => env('AVATAR_URL', ''), @@ -25,7 +25,7 @@ 'github' => [ 'client_id' => env('GITHUB_APP_ID', false), 'client_secret' => env('GITHUB_APP_SECRET', false), - 'redirect' => env('APP_URL') . '/login/service/github/callback', + 'redirect' => env('APP_URL').'/login/service/github/callback', 'name' => 'GitHub', 'auto_register' => env('GITHUB_AUTO_REGISTER', false), 'auto_confirm' => env('GITHUB_AUTO_CONFIRM_EMAIL', false), @@ -34,7 +34,7 @@ 'google' => [ 'client_id' => env('GOOGLE_APP_ID', false), 'client_secret' => env('GOOGLE_APP_SECRET', false), - 'redirect' => env('APP_URL') . '/login/service/google/callback', + 'redirect' => env('APP_URL').'/login/service/google/callback', 'name' => 'Google', 'auto_register' => env('GOOGLE_AUTO_REGISTER', false), 'auto_confirm' => env('GOOGLE_AUTO_CONFIRM_EMAIL', false), @@ -44,7 +44,7 @@ 'slack' => [ 'client_id' => env('SLACK_APP_ID', false), 'client_secret' => env('SLACK_APP_SECRET', false), - 'redirect' => env('APP_URL') . '/login/service/slack/callback', + 'redirect' => env('APP_URL').'/login/service/slack/callback', 'name' => 'Slack', 'auto_register' => env('SLACK_AUTO_REGISTER', false), 'auto_confirm' => env('SLACK_AUTO_CONFIRM_EMAIL', false), @@ -53,7 +53,7 @@ 'facebook' => [ 'client_id' => env('FACEBOOK_APP_ID', false), 'client_secret' => env('FACEBOOK_APP_SECRET', false), - 'redirect' => env('APP_URL') . '/login/service/facebook/callback', + 'redirect' => env('APP_URL').'/login/service/facebook/callback', 'name' => 'Facebook', 'auto_register' => env('FACEBOOK_AUTO_REGISTER', false), 'auto_confirm' => env('FACEBOOK_AUTO_CONFIRM_EMAIL', false), @@ -62,7 +62,7 @@ 'twitter' => [ 'client_id' => env('TWITTER_APP_ID', false), 'client_secret' => env('TWITTER_APP_SECRET', false), - 'redirect' => env('APP_URL') . '/login/service/twitter/callback', + 'redirect' => env('APP_URL').'/login/service/twitter/callback', 'name' => 'Twitter', 'auto_register' => env('TWITTER_AUTO_REGISTER', false), 'auto_confirm' => env('TWITTER_AUTO_CONFIRM_EMAIL', false), @@ -72,7 +72,7 @@ 'client_id' => env('AZURE_APP_ID', false), 'client_secret' => env('AZURE_APP_SECRET', false), 'tenant' => env('AZURE_TENANT', false), - 'redirect' => env('APP_URL') . '/login/service/azure/callback', + 'redirect' => env('APP_URL').'/login/service/azure/callback', 'name' => 'Microsoft Azure', 'auto_register' => env('AZURE_AUTO_REGISTER', false), 'auto_confirm' => env('AZURE_AUTO_CONFIRM_EMAIL', false), @@ -81,7 +81,7 @@ 'okta' => [ 'client_id' => env('OKTA_APP_ID'), 'client_secret' => env('OKTA_APP_SECRET'), - 'redirect' => env('APP_URL') . '/login/service/okta/callback', + 'redirect' => env('APP_URL').'/login/service/okta/callback', 'base_url' => env('OKTA_BASE_URL'), 'name' => 'Okta', 'auto_register' => env('OKTA_AUTO_REGISTER', false), @@ -91,7 +91,7 @@ 'gitlab' => [ 'client_id' => env('GITLAB_APP_ID'), 'client_secret' => env('GITLAB_APP_SECRET'), - 'redirect' => env('APP_URL') . '/login/service/gitlab/callback', + 'redirect' => env('APP_URL').'/login/service/gitlab/callback', 'instance_uri' => env('GITLAB_BASE_URI'), // Needed only for self hosted instances 'name' => 'GitLab', 'auto_register' => env('GITLAB_AUTO_REGISTER', false), @@ -101,7 +101,7 @@ 'twitch' => [ 'client_id' => env('TWITCH_APP_ID'), 'client_secret' => env('TWITCH_APP_SECRET'), - 'redirect' => env('APP_URL') . '/login/service/twitch/callback', + 'redirect' => env('APP_URL').'/login/service/twitch/callback', 'name' => 'Twitch', 'auto_register' => env('TWITCH_AUTO_REGISTER', false), 'auto_confirm' => env('TWITCH_AUTO_CONFIRM_EMAIL', false), @@ -110,7 +110,7 @@ 'discord' => [ 'client_id' => env('DISCORD_APP_ID'), 'client_secret' => env('DISCORD_APP_SECRET'), - 'redirect' => env('APP_URL') . '/login/service/discord/callback', + 'redirect' => env('APP_URL').'/login/service/discord/callback', 'name' => 'Discord', 'auto_register' => env('DISCORD_AUTO_REGISTER', false), 'auto_confirm' => env('DISCORD_AUTO_CONFIRM_EMAIL', false), diff --git a/config/session.php b/config/session.php index 4bbb789010f..321530df397 100644 --- a/config/session.php +++ b/config/session.php @@ -59,7 +59,7 @@ // The session cookie path determines the path for which the cookie will // be regarded as available. Typically, this will be the root path of // your application but you are free to change this when necessary. - 'path' => '/' . (explode('/', env('APP_URL', ''), 4)[3] ?? ''), + 'path' => '/'.(explode('/', env('APP_URL', ''), 4)[3] ?? ''), // Session Cookie Domain // Here you may change the domain of the cookie used to identify a session diff --git a/config/view.php b/config/view.php index 80bc9ef8fe8..811cedc7f95 100644 --- a/config/view.php +++ b/config/view.php @@ -11,7 +11,7 @@ // Join up possible view locations $viewPaths = [realpath(base_path('resources/views'))]; if ($theme = env('APP_THEME', false)) { - array_unshift($viewPaths, base_path('themes/' . $theme)); + array_unshift($viewPaths, base_path('themes/'.$theme)); } return [ diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index dc06455402a..4771f56fb88 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -17,7 +17,7 @@ return [ 'name' => $name, 'email' => $faker->email, - 'slug' => \Illuminate\Support\Str::slug($name . '-' . \Illuminate\Support\Str::random(5)), + 'slug' => \Illuminate\Support\Str::slug($name.'-'.\Illuminate\Support\Str::random(5)), 'password' => Str::random(10), 'remember_token' => Str::random(10), 'email_confirmed' => 1, @@ -49,7 +49,7 @@ }); $factory->define(\BookStack\Entities\Models\Page::class, function ($faker) { - $html = '

' . implode('

', $faker->paragraphs(5)) . '

'; + $html = '

'.implode('

', $faker->paragraphs(5)).'

'; return [ 'name' => $faker->sentence, @@ -76,7 +76,7 @@ $factory->define(\BookStack\Uploads\Image::class, function ($faker) { return [ - 'name' => $faker->slug . '.jpg', + 'name' => $faker->slug.'.jpg', 'url' => $faker->url, 'path' => $faker->url, 'type' => 'gallery', @@ -86,7 +86,7 @@ $factory->define(\BookStack\Actions\Comment::class, function ($faker) { $text = $faker->paragraph(1); - $html = '

' . $text . '

'; + $html = '

'.$text.'

'; return [ 'html' => $html, diff --git a/database/migrations/2015_08_29_105422_add_roles_and_permissions.php b/database/migrations/2015_08_29_105422_add_roles_and_permissions.php index c17f72e2fed..19e5a76e67c 100644 --- a/database/migrations/2015_08_29_105422_add_roles_and_permissions.php +++ b/database/migrations/2015_08_29_105422_add_roles_and_permissions.php @@ -94,8 +94,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $newPermId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower($op), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower($op), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -112,8 +112,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $newPermId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower($op), - 'display_name' => $op . ' ' . $entity, + 'name' => strtolower($entity).'-'.strtolower($op), + 'display_name' => $op.' '.$entity, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); diff --git a/database/migrations/2016_02_27_120329_update_permissions_and_roles.php b/database/migrations/2016_02_27_120329_update_permissions_and_roles.php index 1bab5a873b1..c5f202c7364 100644 --- a/database/migrations/2016_02_27_120329_update_permissions_and_roles.php +++ b/database/migrations/2016_02_27_120329_update_permissions_and_roles.php @@ -45,8 +45,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -83,8 +83,8 @@ public function down() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower($op), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower($op), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -101,8 +101,8 @@ public function down() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower($op), - 'display_name' => $op . ' ' . $entity, + 'name' => strtolower($entity).'-'.strtolower($op), + 'display_name' => $op.' '.$entity, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); diff --git a/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php b/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php index 48a913f8201..2459284a415 100644 --- a/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php +++ b/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php @@ -19,8 +19,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $permId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -47,7 +47,7 @@ public function down() $ops = ['View All', 'View Own']; foreach ($entities as $entity) { foreach ($ops as $op) { - $permissionName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); + $permissionName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); $permission = DB::table('permissions')->where('name', '=', $permissionName)->first(); DB::table('permission_role')->where('permission_id', '=', $permission->id)->delete(); DB::table('permissions')->where('name', '=', $permissionName)->delete(); diff --git a/database/migrations/2016_04_20_192649_create_joint_permissions_table.php b/database/migrations/2016_04_20_192649_create_joint_permissions_table.php index 8c3d9124c75..31e050696de 100644 --- a/database/migrations/2016_04_20_192649_create_joint_permissions_table.php +++ b/database/migrations/2016_04_20_192649_create_joint_permissions_table.php @@ -54,7 +54,7 @@ public function up() // Ensure unique name while (DB::table('roles')->where('name', '=', $publicRoleData['display_name'])->count() > 0) { - $publicRoleData['display_name'] = $publicRoleData['display_name'] . Str::random(2); + $publicRoleData['display_name'] = $publicRoleData['display_name'].Str::random(2); } $publicRoleId = DB::table('roles')->insertGetId($publicRoleData); @@ -63,7 +63,7 @@ public function up() $ops = ['View All', 'View Own']; foreach ($entities as $entity) { foreach ($ops as $op) { - $name = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); + $name = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); $permission = DB::table('role_permissions')->where('name', '=', $name)->first(); // Assign view permission to public DB::table('permission_role')->insert([ diff --git a/database/migrations/2016_10_09_142037_create_attachments_table.php b/database/migrations/2016_10_09_142037_create_attachments_table.php index 9c5422f0899..f175a41405b 100644 --- a/database/migrations/2016_10_09_142037_create_attachments_table.php +++ b/database/migrations/2016_10_09_142037_create_attachments_table.php @@ -38,8 +38,8 @@ public function up() $entity = 'Attachment'; foreach ($ops as $op) { $permissionId = DB::table('role_permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -63,7 +63,7 @@ public function down() $ops = ['Create All', 'Create Own', 'Update All', 'Update Own', 'Delete All', 'Delete Own']; $entity = 'Attachment'; foreach ($ops as $op) { - $permName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); + $permName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); DB::table('role_permissions')->where('name', '=', $permName)->delete(); } } diff --git a/database/migrations/2017_04_20_185112_add_revision_counts.php b/database/migrations/2017_04_20_185112_add_revision_counts.php index 8c6d75e778c..922e0d9c3df 100644 --- a/database/migrations/2017_04_20_185112_add_revision_counts.php +++ b/database/migrations/2017_04_20_185112_add_revision_counts.php @@ -22,8 +22,8 @@ public function up() }); // Update revision count - $pTable = DB::getTablePrefix() . 'pages'; - $rTable = DB::getTablePrefix() . 'page_revisions'; + $pTable = DB::getTablePrefix().'pages'; + $rTable = DB::getTablePrefix().'page_revisions'; DB::statement("UPDATE ${pTable} SET ${pTable}.revision_count=(SELECT count(*) FROM ${rTable} WHERE ${rTable}.page_id=${pTable}.id)"); } diff --git a/database/migrations/2017_08_01_130541_create_comments_table.php b/database/migrations/2017_08_01_130541_create_comments_table.php index 7e64d347b4c..9b0b38651c0 100644 --- a/database/migrations/2017_08_01_130541_create_comments_table.php +++ b/database/migrations/2017_08_01_130541_create_comments_table.php @@ -35,8 +35,8 @@ public function up() $entity = 'Comment'; foreach ($ops as $op) { $permissionId = DB::table('role_permissions')->insertGetId([ - 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op . ' ' . $entity . 's', + 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op.' '.$entity.'s', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -60,7 +60,7 @@ public function down() $ops = ['Create All', 'Create Own', 'Update All', 'Update Own', 'Delete All', 'Delete Own']; $entity = 'Comment'; foreach ($ops as $op) { - $permName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); + $permName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); DB::table('role_permissions')->where('name', '=', $permName)->delete(); } } diff --git a/database/migrations/2018_08_04_115700_create_bookshelves_table.php b/database/migrations/2018_08_04_115700_create_bookshelves_table.php index 8dc2a72e9b9..51f6587cb6a 100644 --- a/database/migrations/2018_08_04_115700_create_bookshelves_table.php +++ b/database/migrations/2018_08_04_115700_create_bookshelves_table.php @@ -77,17 +77,17 @@ public function up() $roleIdsWithBookPermission = DB::table('role_permissions') ->leftJoin('permission_role', 'role_permissions.id', '=', 'permission_role.permission_id') ->leftJoin('roles', 'roles.id', '=', 'permission_role.role_id') - ->where('role_permissions.name', '=', 'book-' . $dbOpName)->get(['roles.id'])->pluck('id'); + ->where('role_permissions.name', '=', 'book-'.$dbOpName)->get(['roles.id'])->pluck('id'); $permId = DB::table('role_permissions')->insertGetId([ - 'name' => 'bookshelf-' . $dbOpName, - 'display_name' => $op . ' ' . 'BookShelves', + 'name' => 'bookshelf-'.$dbOpName, + 'display_name' => $op.' '.'BookShelves', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); $rowsToInsert = $roleIdsWithBookPermission->filter(function ($roleId) { - return !is_null($roleId); + return ! is_null($roleId); })->map(function ($roleId) use ($permId) { return [ 'role_id' => $roleId, diff --git a/database/migrations/2021_03_08_215138_add_user_slug.php b/database/migrations/2021_03_08_215138_add_user_slug.php index dad1e42273c..e4f7c9e1137 100644 --- a/database/migrations/2021_03_08_215138_add_user_slug.php +++ b/database/migrations/2021_03_08_215138_add_user_slug.php @@ -22,7 +22,7 @@ public function up() DB::table('users')->cursor()->each(function ($user) use (&$slugMap) { $userSlug = Str::slug($user->name); while (isset($slugMap[$userSlug])) { - $userSlug = Str::slug($user->name . Str::random(4)); + $userSlug = Str::slug($user->name.Str::random(4)); } $slugMap[$userSlug] = true; diff --git a/database/seeds/DummyContentSeeder.php b/database/seeds/DummyContentSeeder.php index 7463a3b3760..d3431e14a33 100644 --- a/database/seeds/DummyContentSeeder.php +++ b/database/seeds/DummyContentSeeder.php @@ -45,7 +45,7 @@ public function run() $book->pages()->saveMany($pages); }); - $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(array_merge($byData, ['name' => 'Large book' . Str::random(10)])); + $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(array_merge($byData, ['name' => 'Large book'.Str::random(10)])); $pages = factory(Page::class, 200)->make($byData); $chapters = factory(Chapter::class, 50)->make($byData); $largeBook->pages()->saveMany($pages); diff --git a/database/seeds/LargeContentSeeder.php b/database/seeds/LargeContentSeeder.php index 535626b8f79..89c0b0aef6a 100644 --- a/database/seeds/LargeContentSeeder.php +++ b/database/seeds/LargeContentSeeder.php @@ -23,7 +23,7 @@ public function run() $editorRole = Role::getRole('editor'); $editorUser->attachRole($editorRole); - $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(['name' => 'Large book' . Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); + $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(['name' => 'Large book'.Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $pages = factory(Page::class, 200)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $chapters = factory(Chapter::class, 50)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $largeBook->pages()->saveMany($pages); diff --git a/tests/Api/ApiConfigTest.php b/tests/Api/ApiConfigTest.php index af808a76ca3..7a5b701ee9c 100644 --- a/tests/Api/ApiConfigTest.php +++ b/tests/Api/ApiConfigTest.php @@ -27,7 +27,7 @@ public function test_default_item_count_does_not_limit_count_param() { $this->actingAsApiEditor(); config()->set(['api.default_item_count' => 1]); - $resp = $this->get($this->endpoint . '?count=5'); + $resp = $this->get($this->endpoint.'?count=5'); $resp->assertJsonCount(5, 'data'); } @@ -39,7 +39,7 @@ public function test_max_item_count_limits_listing_requests() $resp = $this->get($this->endpoint); $resp->assertJsonCount(2, 'data'); - $resp = $this->get($this->endpoint . '?count=5'); + $resp = $this->get($this->endpoint.'?count=5'); $resp->assertJsonCount(2, 'data'); } diff --git a/tests/Api/ApiDocsTest.php b/tests/Api/ApiDocsTest.php index 062adce5376..1aabaccfc30 100644 --- a/tests/Api/ApiDocsTest.php +++ b/tests/Api/ApiDocsTest.php @@ -21,7 +21,7 @@ public function test_docs_page_returns_view_with_docs_content() public function test_docs_json_endpoint_returns_json() { - $resp = $this->actingAsApiEditor()->get($this->endpoint . '.json'); + $resp = $this->actingAsApiEditor()->get($this->endpoint.'.json'); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'application/json'); $resp->assertJson([ diff --git a/tests/Api/ApiListingTest.php b/tests/Api/ApiListingTest.php index f90ec5a3dd2..45d06b5dca2 100644 --- a/tests/Api/ApiListingTest.php +++ b/tests/Api/ApiListingTest.php @@ -19,7 +19,7 @@ public function test_count_parameter_limits_responses() $resp = $this->get($this->endpoint); $resp->assertJsonCount($bookCount, 'data'); - $resp = $this->get($this->endpoint . '?count=1'); + $resp = $this->get($this->endpoint.'?count=1'); $resp->assertJsonCount(1, 'data'); } @@ -28,10 +28,10 @@ public function test_offset_parameter() $this->actingAsApiEditor(); $books = Book::visible()->orderBy('id')->take(3)->get(); - $resp = $this->get($this->endpoint . '?count=1'); + $resp = $this->get($this->endpoint.'?count=1'); $resp->assertJsonMissing(['name' => $books[1]->name]); - $resp = $this->get($this->endpoint . '?count=1&offset=1000'); + $resp = $this->get($this->endpoint.'?count=1&offset=1000'); $resp->assertJsonCount(0, 'data'); } @@ -47,7 +47,7 @@ public function test_sort_parameter() ]; foreach ($sortChecks as $sortOption => $result) { - $resp = $this->get($this->endpoint . '?count=1&sort=' . $sortOption); + $resp = $this->get($this->endpoint.'?count=1&sort='.$sortOption); $resp->assertJson(['data' => [ [ 'id' => $result->id, @@ -71,14 +71,14 @@ public function test_filter_parameter() "filter[id:gt]={$book->id}" => Book::visible()->where('id', '>', $book->id)->count(), "filter[id:gte]={$book->id}" => Book::visible()->where('id', '>=', $book->id)->count(), "filter[id:lt]={$book->id}" => Book::visible()->where('id', '<', $book->id)->count(), - "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr . '%')->count(), + "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr.'%')->count(), // Test mulitple filters 'and' together "filter[id]={$book->id}&filter[name]=random_non_existing_string" => 0, ]; foreach ($filterChecks as $filterOption => $resultCount) { - $resp = $this->get($this->endpoint . '?count=1&' . $filterOption); + $resp = $this->get($this->endpoint.'?count=1&'.$filterOption); $resp->assertJson(['total' => $resultCount]); } } @@ -87,7 +87,7 @@ public function test_total_on_results_shows_correctly() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); - $resp = $this->get($this->endpoint . '?count=1'); + $resp = $this->get($this->endpoint.'?count=1'); $resp->assertJson(['total' => $bookCount]); } @@ -95,7 +95,7 @@ public function test_total_on_results_shows_correctly_when_offset_provided() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); - $resp = $this->get($this->endpoint . '?count=1&offset=1'); + $resp = $this->get($this->endpoint.'?count=1&offset=1'); $resp->assertJson(['total' => $bookCount]); } } diff --git a/tests/Api/AttachmentsApiTest.php b/tests/Api/AttachmentsApiTest.php index ceab5d49afa..a9ff9d80389 100644 --- a/tests/Api/AttachmentsApiTest.php +++ b/tests/Api/AttachmentsApiTest.php @@ -22,7 +22,7 @@ public function test_index_endpoint_returns_expected_book() 'external' => true, ]); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, @@ -43,7 +43,7 @@ public function test_attachments_listing_based_upon_page_visibility() 'external' => true, ]); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, @@ -54,7 +54,7 @@ public function test_attachments_listing_based_upon_page_visibility() $page->save(); $this->regenEntityPermissions($page); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJsonMissing(['data' => [ [ 'id' => $attachment->id, diff --git a/tests/Api/BooksApiTest.php b/tests/Api/BooksApiTest.php index 91e2db9e52d..df59546fe48 100644 --- a/tests/Api/BooksApiTest.php +++ b/tests/Api/BooksApiTest.php @@ -16,7 +16,7 @@ public function test_index_endpoint_returns_expected_book() $this->actingAsApiEditor(); $firstBook = Book::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBook->id, @@ -66,7 +66,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->getJson($this->baseEndpoint . "/{$book->id}"); + $resp = $this->getJson($this->baseEndpoint."/{$book->id}"); $resp->assertStatus(200); $resp->assertJson([ @@ -93,7 +93,7 @@ public function test_update_endpoint() 'description' => 'A book created via the API', ]; - $resp = $this->putJson($this->baseEndpoint . "/{$book->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$book->id}", $details); $book->refresh(); $resp->assertStatus(200); @@ -105,7 +105,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint . "/{$book->id}"); + $resp = $this->deleteJson($this->baseEndpoint."/{$book->id}"); $resp->assertStatus(204); $this->assertActivityExists('book_delete'); @@ -116,10 +116,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/html"); + $resp = $this->get($this->baseEndpoint."/{$book->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($book->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.html"'); } public function test_export_plain_text_endpoint() @@ -127,10 +127,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint."/{$book->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($book->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.txt"'); } public function test_export_pdf_endpoint() @@ -138,9 +138,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint."/{$book->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.pdf"'); } public function test_export_markdown_endpoint() @@ -148,12 +148,12 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->has('pages')->has('chapters')->first(); - $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint."/{$book->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.md"'); - $resp->assertSee('# ' . $book->name); - $resp->assertSee('# ' . $book->pages()->first()->name); - $resp->assertSee('# ' . $book->chapters()->first()->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.md"'); + $resp->assertSee('# '.$book->name); + $resp->assertSee('# '.$book->pages()->first()->name); + $resp->assertSee('# '.$book->chapters()->first()->name); } public function test_cant_export_when_not_have_permission() @@ -164,7 +164,7 @@ public function test_cant_export_when_not_have_permission() $book = Book::visible()->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint."/{$book->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/ChaptersApiTest.php b/tests/Api/ChaptersApiTest.php index c9ed1a2892e..8660ca518ba 100644 --- a/tests/Api/ChaptersApiTest.php +++ b/tests/Api/ChaptersApiTest.php @@ -17,7 +17,7 @@ public function test_index_endpoint_returns_expected_chapter() $this->actingAsApiEditor(); $firstChapter = Chapter::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstChapter->id, @@ -96,7 +96,7 @@ public function test_read_endpoint() $chapter = Chapter::visible()->first(); $page = $chapter->pages()->first(); - $resp = $this->getJson($this->baseEndpoint . "/{$chapter->id}"); + $resp = $this->getJson($this->baseEndpoint."/{$chapter->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $chapter->id, @@ -137,7 +137,7 @@ public function test_update_endpoint() ], ]; - $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$chapter->id}", $details); $chapter->refresh(); $resp->assertStatus(200); @@ -151,7 +151,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint . "/{$chapter->id}"); + $resp = $this->deleteJson($this->baseEndpoint."/{$chapter->id}"); $resp->assertStatus(204); $this->assertActivityExists('chapter_delete'); @@ -162,10 +162,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/html"); + $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($chapter->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.html"'); } public function test_export_plain_text_endpoint() @@ -173,10 +173,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($chapter->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.txt"'); } public function test_export_pdf_endpoint() @@ -184,9 +184,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.pdf"'); } public function test_export_markdown_endpoint() @@ -194,11 +194,11 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->has('pages')->first(); - $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.md"'); - $resp->assertSee('# ' . $chapter->name); - $resp->assertSee('# ' . $chapter->pages()->first()->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.md"'); + $resp->assertSee('# '.$chapter->name); + $resp->assertSee('# '.$chapter->pages()->first()->name); } public function test_cant_export_when_not_have_permission() @@ -209,7 +209,7 @@ public function test_cant_export_when_not_have_permission() $chapter = Chapter::visible()->has('pages')->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/PagesApiTest.php b/tests/Api/PagesApiTest.php index 4eb109d9dec..1f4bd11823b 100644 --- a/tests/Api/PagesApiTest.php +++ b/tests/Api/PagesApiTest.php @@ -18,7 +18,7 @@ public function test_index_endpoint_returns_expected_page() $this->actingAsApiEditor(); $firstPage = Page::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstPage->id, @@ -126,7 +126,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); + $resp = $this->getJson($this->baseEndpoint."/{$page->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $page->id, @@ -151,7 +151,7 @@ public function test_read_endpoint_provides_rendered_html() $page->html = "

testing

Hello

"; $page->save(); - $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); + $resp = $this->getJson($this->baseEndpoint."/{$page->id}"); $html = $resp->json('html'); $this->assertStringNotContainsString('script', $html); $this->assertStringContainsString('Hello', $html); @@ -173,7 +173,7 @@ public function test_update_endpoint() ], ]; - $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); $page->refresh(); $resp->assertStatus(200); @@ -195,7 +195,7 @@ public function test_providing_new_chapter_id_on_update_will_move_page() 'html' => '

A page created via the API

', ]; - $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); $resp->assertStatus(200); $resp->assertJson([ 'chapter_id' => $chapter->id, @@ -215,7 +215,7 @@ public function test_providing_move_via_update_requires_page_create_permission_o 'html' => '

A page created via the API

', ]; - $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); $resp->assertStatus(403); } @@ -234,7 +234,7 @@ public function test_update_endpoint_does_not_wipe_content_if_no_html_or_md_prov ], ]; - $this->putJson($this->baseEndpoint . "/{$page->id}", $details); + $this->putJson($this->baseEndpoint."/{$page->id}", $details); $page->refresh(); $this->assertEquals($originalContent, $page->html); @@ -244,7 +244,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint . "/{$page->id}"); + $resp = $this->deleteJson($this->baseEndpoint."/{$page->id}"); $resp->assertStatus(204); $this->assertActivityExists('page_delete', $page); @@ -255,10 +255,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/html"); + $resp = $this->get($this->baseEndpoint."/{$page->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.html"'); } public function test_export_plain_text_endpoint() @@ -266,10 +266,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint."/{$page->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.txt"'); } public function test_export_pdf_endpoint() @@ -277,9 +277,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint."/{$page->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.pdf"'); } public function test_export_markdown_endpoint() @@ -287,10 +287,10 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint."/{$page->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertSee('# ' . $page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); + $resp->assertSee('# '.$page->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.md"'); } public function test_cant_export_when_not_have_permission() @@ -301,7 +301,7 @@ public function test_cant_export_when_not_have_permission() $page = Page::visible()->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint."/{$page->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/ShelvesApiTest.php b/tests/Api/ShelvesApiTest.php index 8868c686e50..2a709af12fc 100644 --- a/tests/Api/ShelvesApiTest.php +++ b/tests/Api/ShelvesApiTest.php @@ -17,7 +17,7 @@ public function test_index_endpoint_returns_expected_shelf() $this->actingAsApiEditor(); $firstBookshelf = Bookshelf::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBookshelf->id, @@ -76,7 +76,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); - $resp = $this->getJson($this->baseEndpoint . "/{$shelf->id}"); + $resp = $this->getJson($this->baseEndpoint."/{$shelf->id}"); $resp->assertStatus(200); $resp->assertJson([ @@ -103,7 +103,7 @@ public function test_update_endpoint() 'description' => 'A shelf created via the API', ]; - $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", $details); $shelf->refresh(); $resp->assertStatus(200); @@ -120,11 +120,11 @@ public function test_update_only_assigns_books_if_param_provided() 'name' => 'My updated API shelf', ]; - $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); + $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", $details); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() > 0); - $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", ['books' => []]); + $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", ['books' => []]); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() === 0); } @@ -133,7 +133,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint . "/{$shelf->id}"); + $resp = $this->deleteJson($this->baseEndpoint."/{$shelf->id}"); $resp->assertStatus(204); $this->assertActivityExists('bookshelf_delete'); diff --git a/tests/AuditLogTest.php b/tests/AuditLogTest.php index 8d13670ca95..90590a6fd48 100644 --- a/tests/AuditLogTest.php +++ b/tests/AuditLogTest.php @@ -68,7 +68,7 @@ public function test_shows_name_for_deleted_items() $resp = $this->get('settings/audit'); $resp->assertSeeText('Deleted Item'); - $resp->assertSeeText('Name: ' . $pageName); + $resp->assertSeeText('Name: '.$pageName); } public function test_shows_activity_for_deleted_users() @@ -107,16 +107,16 @@ public function test_date_filters() $yesterday = (Carbon::now()->subDay()->format('Y-m-d')); $tomorrow = (Carbon::now()->addDay()->format('Y-m-d')); - $resp = $this->get('settings/audit?date_from=' . $yesterday); + $resp = $this->get('settings/audit?date_from='.$yesterday); $resp->assertSeeText($page->name); - $resp = $this->get('settings/audit?date_from=' . $tomorrow); + $resp = $this->get('settings/audit?date_from='.$tomorrow); $resp->assertDontSeeText($page->name); - $resp = $this->get('settings/audit?date_to=' . $tomorrow); + $resp = $this->get('settings/audit?date_to='.$tomorrow); $resp->assertSeeText($page->name); - $resp = $this->get('settings/audit?date_to=' . $yesterday); + $resp = $this->get('settings/audit?date_to='.$yesterday); $resp->assertDontSeeText($page->name); } @@ -132,11 +132,11 @@ public function test_user_filter() $chapter = Chapter::query()->first(); $this->activityService->addForEntity($chapter, ActivityType::CHAPTER_UPDATE); - $resp = $this->actingAs($admin)->get('settings/audit?user=' . $admin->id); + $resp = $this->actingAs($admin)->get('settings/audit?user='.$admin->id); $resp->assertSeeText($page->name); $resp->assertDontSeeText($chapter->name); - $resp = $this->actingAs($admin)->get('settings/audit?user=' . $editor->id); + $resp = $this->actingAs($admin)->get('settings/audit?user='.$editor->id); $resp->assertSeeText($chapter->name); $resp->assertDontSeeText($page->name); } diff --git a/tests/Auth/AuthTest.php b/tests/Auth/AuthTest.php index 79f00bed093..4d318cd9eb8 100644 --- a/tests/Auth/AuthTest.php +++ b/tests/Auth/AuthTest.php @@ -37,7 +37,7 @@ public function test_registration_showing() // Ensure registration form is showing $this->setSettings(['registration-enabled' => 'true']); $this->get('/login') - ->assertElementContains('a[href="' . url('/register') . '"]', 'Sign up'); + ->assertElementContains('a[href="'.url('/register').'"]', 'Sign up'); } public function test_normal_registration() @@ -49,7 +49,7 @@ public function test_normal_registration() // Test form and ensure user is created $this->get('/register') ->assertSee('Sign Up') - ->assertElementContains('form[action="' . url('/register') . '"]', 'Create Account'); + ->assertElementContains('form[action="'.url('/register').'"]', 'Create Account'); $resp = $this->post('/register', $user->only('password', 'name', 'email')); $resp->assertRedirect('/'); @@ -119,7 +119,7 @@ public function test_confirmed_registration() $resp->assertRedirect('/register/confirm/awaiting'); $resp = $this->get('/register/confirm/awaiting'); - $resp->assertElementContains('form[action="' . url('/register/confirm/resend') . '"]', 'Resend'); + $resp->assertElementContains('form[action="'.url('/register/confirm/resend').'"]', 'Resend'); $this->get('/books')->assertRedirect('/login'); $this->post('/register/confirm/resend', $user->only('email')); @@ -131,7 +131,7 @@ public function test_confirmed_registration() }); // Check confirmation email confirmation activation. - $this->get('/register/confirm/' . $emailConfirmation->token)->assertRedirect('/'); + $this->get('/register/confirm/'.$emailConfirmation->token)->assertRedirect('/'); $this->get('/')->assertSee($user->name); $this->assertDatabaseMissing('email_confirmations', ['token' => $emailConfirmation->token]); $this->assertDatabaseHas('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]); @@ -213,10 +213,10 @@ public function test_reset_password_flow() Notification::fake(); $this->get('/login') - ->assertElementContains('a[href="' . url('/password/email') . '"]', 'Forgot Password?'); + ->assertElementContains('a[href="'.url('/password/email').'"]', 'Forgot Password?'); $this->get('/password/email') - ->assertElementContains('form[action="' . url('/password/email') . '"]', 'Send Reset Link'); + ->assertElementContains('form[action="'.url('/password/email').'"]', 'Send Reset Link'); $resp = $this->post('/password/email', [ 'email' => 'admin@admin.com', @@ -236,7 +236,7 @@ public function test_reset_password_flow() Notification::assertSentTo($user, ResetPassword::class); $n = Notification::sent($user, ResetPassword::class); - $this->get('/password/reset/' . $n->first()->token) + $this->get('/password/reset/'.$n->first()->token) ->assertOk() ->assertSee('Reset Password'); @@ -295,7 +295,7 @@ public function test_reset_password_request_is_throttled() 'email' => $editor->email, ]); Notification::assertTimesSent(1, ResetPassword::class); - $resp->assertSee('A password reset link will be sent to ' . $editor->email . ' if that email address is found in the system.'); + $resp->assertSee('A password reset link will be sent to '.$editor->email.' if that email address is found in the system.'); } public function test_login_redirects_to_initially_requested_url_correctly() diff --git a/tests/Auth/LdapTest.php b/tests/Auth/LdapTest.php index 9e0729a8e9f..1b0fe99750f 100644 --- a/tests/Auth/LdapTest.php +++ b/tests/Auth/LdapTest.php @@ -23,7 +23,7 @@ class LdapTest extends TestCase public function setUp(): void { parent::setUp(); - if (!defined('LDAP_OPT_REFERRALS')) { + if (! defined('LDAP_OPT_REFERRALS')) { define('LDAP_OPT_REFERRALS', 1); } config()->set([ @@ -96,7 +96,7 @@ public function test_login() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $resp = $this->mockUserLogin(); @@ -127,7 +127,7 @@ public function test_email_domain_restriction_active_on_new_ldap_login() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $resp = $this->mockUserLogin(); @@ -144,7 +144,7 @@ public function test_email_domain_restriction_active_on_new_ldap_login() public function test_login_works_when_no_uid_provided_by_ldap_server() { - $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); $this->commonLdapMocks(1, 1, 1, 2, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) @@ -166,7 +166,7 @@ public function test_a_custom_uid_attribute_can_be_specified_and_is_used_properl config()->set(['services.ldap.id_attribute' => 'my_custom_id']); $this->commonLdapMocks(1, 1, 1, 2, 1); - $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ @@ -190,7 +190,7 @@ public function test_initial_incorrect_credentials() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $this->mockLdap->shouldReceive('bind')->times(2)->andReturn(true, false); @@ -258,7 +258,7 @@ public function test_non_admins_cannot_change_auth_id() { $testUser = $this->getNormalUser(); $this->actingAs($testUser) - ->get('/settings/users/' . $testUser->id) + ->get('/settings/users/'.$testUser->id) ->assertDontSee('External Authentication'); } @@ -282,7 +282,7 @@ public function test_login_maps_roles_and_retains_existing_roles() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, @@ -327,7 +327,7 @@ public function test_login_maps_roles_and_removes_old_roles_if_set() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, @@ -351,7 +351,7 @@ public function test_login_maps_roles_and_removes_old_roles_if_set() public function test_external_auth_id_visible_in_roles_page_when_ldap_active() { $role = factory(Role::class)->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']); - $this->asAdmin()->get('/settings/roles/' . $role->id) + $this->asAdmin()->get('/settings/roles/'.$role->id) ->assertSee('ex-auth-a'); } @@ -372,7 +372,7 @@ public function test_login_maps_roles_using_external_auth_ids_if_set() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, @@ -413,7 +413,7 @@ public function test_login_group_mapping_does_not_conflict_with_default_role() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, @@ -447,7 +447,7 @@ public function test_login_uses_specified_display_name_attribute() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'displayname' => 'displayNameAttribute', ]]); @@ -472,7 +472,7 @@ public function test_login_uses_default_display_name_attribute_if_specified_not_ ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $this->mockUserLogin()->assertRedirect('/login'); @@ -500,7 +500,7 @@ protected function checkLdapReceivesCorrectDetails($serverString, $expectedHost, $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $this->mockLdap->shouldReceive('connect')->once() @@ -567,7 +567,7 @@ public function test_dump_user_details_option_works() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $resp = $this->post('/login', [ @@ -606,7 +606,7 @@ public function test_ldap_attributes_can_be_binary_decoded_if_marked() ->andReturn(['count' => 1, 0 => [ 'uid' => [hex2bin('FFF8F7')], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], ]]); $details = $ldapService->getUserDetails('test'); @@ -621,12 +621,12 @@ public function test_new_ldap_user_login_with_already_used_email_address_shows_e ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => 'tester@example.com', ]], ['count' => 1, 0 => [ 'uid' => ['Barry'], 'cn' => ['Scott'], - 'dn' => ['dc=bscott' . config('services.ldap.base_dn')], + 'dn' => ['dc=bscott'.config('services.ldap.base_dn')], 'mail' => 'tester@example.com', ]]); @@ -657,7 +657,7 @@ public function test_login_with_email_confirmation_required_maps_groups_but_show ->andReturn(['count' => 1, 0 => [ 'uid' => [$user->name], 'cn' => [$user->name], - 'dn' => ['dc=test' . config('services.ldap.base_dn')], + 'dn' => ['dc=test'.config('services.ldap.base_dn')], 'mail' => [$user->email], 'memberof' => [ 'count' => 1, @@ -700,7 +700,7 @@ public function test_thumbnail_attribute_used_as_user_avatar_if_configured() config()->set(['services.ldap.thumbnail_attribute' => 'jpegPhoto']); $this->commonLdapMocks(1, 1, 1, 2, 1); - $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ diff --git a/tests/Auth/OidcTest.php b/tests/Auth/OidcTest.php index 6c806aa8ed4..cbe8762be42 100644 --- a/tests/Auth/OidcTest.php +++ b/tests/Auth/OidcTest.php @@ -22,7 +22,7 @@ public function setUp(): void // Set default config for OpenID Connect $this->keyFile = tmpfile(); - $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri']; + $this->keyFilePath = 'file://'.stream_get_meta_data($this->keyFile)['uri']; file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey()); config()->set([ @@ -61,7 +61,7 @@ public function test_oidc_routes_are_only_active_if_oidc_enabled() config()->set(['auth.method' => 'standard']); $routes = ['/login' => 'post', '/callback' => 'get']; foreach ($routes as $uri => $method) { - $req = $this->call($method, '/oidc' . $uri); + $req = $this->call($method, '/oidc'.$uri); $this->assertPermissionError($req); } } @@ -120,8 +120,8 @@ public function test_login() $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location'); $this->assertFalse($this->isAuthenticated()); $this->assertStringContainsString('scope=openid%20profile%20email', $redirect); - $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect); - $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect); + $this->assertStringContainsString('client_id='.OidcJwtHelper::defaultClientId(), $redirect); + $this->assertStringContainsString('redirect_uri='.urlencode(url('/oidc/callback')), $redirect); } public function test_login_success_flow() @@ -137,17 +137,17 @@ public function test_login_success_flow() // Callback from auth provider // App calls token endpoint to get id token - $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); + $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state='.$state); $resp->assertRedirect('/'); $this->assertCount(1, $transactions); /** @var Request $tokenRequest */ $tokenRequest = $transactions[0]['request']; $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri()); $this->assertEquals('POST', $tokenRequest->getMethod()); - $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]); + $this->assertEquals('Basic '.base64_encode(OidcJwtHelper::defaultClientId().':testpass'), $tokenRequest->getHeader('Authorization')[0]); $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody()); $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody()); - $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody()); + $this->assertStringContainsString('redirect_uri='.urlencode(url('/oidc/callback')), $tokenRequest->getBody()); $this->assertTrue(auth()->check()); $this->assertDatabaseHas('users', [ @@ -241,7 +241,7 @@ public function test_auth_login_as_existing_user_email_with_different_auth_id_fa 'sub' => 'benny505', ]); - $this->assertSessionError('A user with the email ' . $editor->email . ' already exists but with different credentials.'); + $this->assertSessionError('A user with the email '.$editor->email.' already exists but with different credentials.'); $this->assertFalse(auth()->check()); } @@ -276,8 +276,8 @@ public function test_auth_login_with_autodiscovery() $this->assertEquals('GET', $keysRequest->getMethod()); $this->assertEquals('GET', $discoverRequest->getMethod()); - $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri()); - $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri()); + $this->assertEquals(OidcJwtHelper::defaultIssuer().'/.well-known/openid-configuration', $discoverRequest->getUri()); + $this->assertEquals(OidcJwtHelper::defaultIssuer().'/oidc/keys', $keysRequest->getUri()); } public function test_auth_fails_if_autodiscovery_fails() @@ -335,7 +335,7 @@ protected function runLogin($claimOverrides = []): TestResponse $state = session()->get('oidc_state'); $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]); - return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); + return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state='.$state); } protected function getAutoDiscoveryResponse($responseOverrides = []): Response @@ -345,9 +345,9 @@ protected function getAutoDiscoveryResponse($responseOverrides = []): Response 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache', ], json_encode(array_merge([ - 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token', - 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize', - 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys', + 'token_endpoint' => OidcJwtHelper::defaultIssuer().'/oidc/token', + 'authorization_endpoint' => OidcJwtHelper::defaultIssuer().'/oidc/authorize', + 'jwks_uri' => OidcJwtHelper::defaultIssuer().'/oidc/keys', 'issuer' => OidcJwtHelper::defaultIssuer(), ], $responseOverrides))); } diff --git a/tests/Auth/Saml2Test.php b/tests/Auth/Saml2Test.php index c534b2d7863..bedda0520cc 100644 --- a/tests/Auth/Saml2Test.php +++ b/tests/Auth/Saml2Test.php @@ -74,11 +74,11 @@ public function test_login() $this->assertTrue(strlen($acsId) > 12); $this->assertStringContainsString('/saml2/acs?id=', $redirect); - $this->assertTrue(cache()->has('saml2_acs:' . $acsId)); + $this->assertTrue(cache()->has('saml2_acs:'.$acsId)); $acsGet = $this->get($redirect); $acsGet->assertRedirect('/'); - $this->assertFalse(cache()->has('saml2_acs:' . $acsId)); + $this->assertFalse(cache()->has('saml2_acs:'.$acsId)); $this->assertTrue($this->isAuthenticated()); $this->assertDatabaseHas('users', [ @@ -218,13 +218,13 @@ public function test_saml_routes_are_only_active_if_saml_enabled() config()->set(['auth.method' => 'standard']); $getRoutes = ['/logout', '/metadata', '/sls']; foreach ($getRoutes as $route) { - $req = $this->get('/saml2' . $route); + $req = $this->get('/saml2'.$route); $this->assertPermissionError($req); } $postRoutes = ['/login', '/acs']; foreach ($postRoutes as $route) { - $req = $this->post('/saml2' . $route); + $req = $this->post('/saml2'.$route); $this->assertPermissionError($req); } } diff --git a/tests/Auth/SocialAuthTest.php b/tests/Auth/SocialAuthTest.php index f70263dd278..3a3fe23f944 100644 --- a/tests/Auth/SocialAuthTest.php +++ b/tests/Auth/SocialAuthTest.php @@ -83,7 +83,7 @@ public function test_social_login() ]); $resp = $this->followingRedirects()->get('/login/service/github/callback'); $resp->assertDontSee('login-form'); - $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, 'github; (' . $this->getAdmin()->id . ') ' . $this->getAdmin()->name); + $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, 'github; ('.$this->getAdmin()->id.') '.$this->getAdmin()->name); } public function test_social_account_detach() diff --git a/tests/Auth/UserInviteTest.php b/tests/Auth/UserInviteTest.php index dcf9e23df9b..39c9f415bee 100644 --- a/tests/Auth/UserInviteTest.php +++ b/tests/Auth/UserInviteTest.php @@ -18,7 +18,7 @@ public function test_user_creation_creates_invite() Notification::fake(); $admin = $this->getAdmin(); - $email = Str::random(16) . '@example.com'; + $email = Str::random(16).'@example.com'; $resp = $this->actingAs($admin)->post('/settings/users/create', [ 'name' => 'Barry', 'email' => $email, @@ -43,13 +43,13 @@ public function test_invite_set_password() $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; - $setPasswordPageResp = $this->get('/register/invite/' . $token); + $setPasswordPageResp = $this->get('/register/invite/'.$token); $setPasswordPageResp->assertSuccessful(); $setPasswordPageResp->assertSee('Welcome to BookStack!'); $setPasswordPageResp->assertSee('Password'); $setPasswordPageResp->assertSee('Confirm Password'); - $setPasswordResp = $this->followingRedirects()->post('/register/invite/' . $token, [ + $setPasswordResp = $this->followingRedirects()->post('/register/invite/'.$token, [ 'password' => 'my test password', ]); $setPasswordResp->assertSee('Password set, you now have access to BookStack!'); @@ -72,14 +72,14 @@ public function test_invite_set_has_password_validation() $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; - $this->get('/register/invite/' . $token); - $shortPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ + $this->get('/register/invite/'.$token); + $shortPassword = $this->followingRedirects()->post('/register/invite/'.$token, [ 'password' => 'mypassw', ]); $shortPassword->assertSee('The password must be at least 8 characters.'); - $this->get('/register/invite/' . $token); - $noPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ + $this->get('/register/invite/'.$token); + $noPassword = $this->followingRedirects()->post('/register/invite/'.$token, [ 'password' => '', ]); $noPassword->assertSee('The password field is required.'); @@ -91,10 +91,10 @@ public function test_invite_set_has_password_validation() public function test_non_existent_invite_token_redirects_to_home() { - $setPasswordPageResp = $this->get('/register/invite/' . Str::random(12)); + $setPasswordPageResp = $this->get('/register/invite/'.Str::random(12)); $setPasswordPageResp->assertRedirect('/'); - $setPasswordResp = $this->post('/register/invite/' . Str::random(12), ['password' => 'Password Test']); + $setPasswordResp = $this->post('/register/invite/'.Str::random(12), ['password' => 'Password Test']); $setPasswordResp->assertRedirect('/'); } @@ -108,7 +108,7 @@ public function test_token_expires_after_two_weeks() $tokenEntry = DB::table('user_invites')->where('user_id', '=', $user->id)->first(); DB::table('user_invites')->update(['created_at' => Carbon::now()->subDays(14)->subHour(1)]); - $setPasswordPageResp = $this->get('/register/invite/' . $tokenEntry->token); + $setPasswordPageResp = $this->get('/register/invite/'.$tokenEntry->token); $setPasswordPageResp->assertRedirect('/password/email'); $setPasswordPageResp->assertSessionHas('error', 'This invitation link has expired. You can instead try to reset your account password.'); } diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index b1cefbb6584..f27337b0a98 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -13,7 +13,7 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__ . '/../bootstrap/app.php'; + $app = require __DIR__.'/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; diff --git a/tests/DebugViewTest.php b/tests/DebugViewTest.php index 63d6472b982..e780c4cb6e8 100644 --- a/tests/DebugViewTest.php +++ b/tests/DebugViewTest.php @@ -21,12 +21,12 @@ public function test_debug_view_shows_expected_details() // Warning message $resp->assertSeeText('WARNING: Application is in debug mode. This mode has the potential to leak'); // PHP version - $resp->assertSeeText('PHP Version: ' . phpversion()); + $resp->assertSeeText('PHP Version: '.phpversion()); // BookStack version - $resp->assertSeeText('BookStack Version: ' . trim(file_get_contents(base_path('version')))); + $resp->assertSeeText('BookStack Version: '.trim(file_get_contents(base_path('version')))); // Dynamic help links - $resp->assertElementExists('a[href*="q=' . urlencode('BookStack An error occurred during testing') . '"]'); - $resp->assertElementExists('a[href*="?q=is%3Aissue+' . urlencode('An error occurred during testing') . '"]'); + $resp->assertElementExists('a[href*="q='.urlencode('BookStack An error occurred during testing').'"]'); + $resp->assertElementExists('a[href*="?q=is%3Aissue+'.urlencode('An error occurred during testing').'"]'); } public function test_debug_view_only_shows_when_debug_mode_is_enabled() diff --git a/tests/Entity/BookShelfTest.php b/tests/Entity/BookShelfTest.php index afd6a1a0656..f799f7672a9 100644 --- a/tests/Entity/BookShelfTest.php +++ b/tests/Entity/BookShelfTest.php @@ -80,8 +80,8 @@ public function test_shelves_create() { $booksToInclude = Book::take(2)->get(); $shelfInfo = [ - 'name' => 'My test book' . Str::random(4), - 'description' => 'Test book description ' . Str::random(10), + 'name' => 'My test book'.Str::random(4), + 'description' => 'Test book description '.Str::random(10), ]; $resp = $this->asEditor()->post('/shelves', array_merge($shelfInfo, [ 'books' => $booksToInclude->implode('id', ','), @@ -110,8 +110,8 @@ public function test_shelves_create() public function test_shelves_create_sets_cover_image() { $shelfInfo = [ - 'name' => 'My test book' . Str::random(4), - 'description' => 'Test book description ' . Str::random(10), + 'name' => 'My test book'.Str::random(4), + 'description' => 'Test book description '.Str::random(10), ]; $imageFile = $this->getTestImage('shelf-test.png'); @@ -206,8 +206,8 @@ public function test_shelf_edit() $booksToInclude = Book::take(2)->get(); $shelfInfo = [ - 'name' => 'My test book' . Str::random(4), - 'description' => 'Test book description ' . Str::random(10), + 'name' => 'My test book'.Str::random(4), + 'description' => 'Test book description '.Str::random(10), ]; $resp = $this->asEditor()->put($shelf->getUrl(), array_merge($shelfInfo, [ @@ -345,8 +345,8 @@ public function test_bookshelves_show_on_book() { // Create shelf $shelfInfo = [ - 'name' => 'My test shelf' . Str::random(4), - 'description' => 'Test shelf description ' . Str::random(10), + 'name' => 'My test shelf'.Str::random(4), + 'description' => 'Test shelf description '.Str::random(10), ]; $this->asEditor()->post('/shelves', $shelfInfo); @@ -375,6 +375,6 @@ public function test_cancel_on_child_book_creation_returns_to_original_shelf() /** @var Bookshelf $shelf */ $shelf = Bookshelf::query()->first(); $resp = $this->asEditor()->get($shelf->getUrl('/create-book')); - $resp->assertElementContains('form a[href="' . $shelf->getUrl() . '"]', 'Cancel'); + $resp->assertElementContains('form a[href="'.$shelf->getUrl().'"]', 'Cancel'); } } diff --git a/tests/Entity/BookTest.php b/tests/Entity/BookTest.php index 53ee6faf98b..f232ebf3fa4 100644 --- a/tests/Entity/BookTest.php +++ b/tests/Entity/BookTest.php @@ -14,10 +14,10 @@ public function test_create() ]); $resp = $this->asEditor()->get('/books'); - $resp->assertElementContains('a[href="' . url('/create-book') . '"]', 'Create New Book'); + $resp->assertElementContains('a[href="'.url('/create-book').'"]', 'Create New Book'); $resp = $this->get('/create-book'); - $resp->assertElementContains('form[action="' . url('/books') . '"][method="POST"]', 'Save Book'); + $resp->assertElementContains('form[action="'.url('/books').'"][method="POST"]', 'Save Book'); $resp = $this->post('/books', $book->only('name', 'description')); $resp->assertRedirect('/books/my-first-book'); @@ -50,21 +50,21 @@ public function test_update() /** @var Book $book */ $book = Book::query()->first(); // Cheeky initial update to refresh slug - $this->asEditor()->put($book->getUrl(), ['name' => $book->name . '5', 'description' => $book->description]); + $this->asEditor()->put($book->getUrl(), ['name' => $book->name.'5', 'description' => $book->description]); $book->refresh(); - $newName = $book->name . ' Updated'; - $newDesc = $book->description . ' with more content'; + $newName = $book->name.' Updated'; + $newDesc = $book->description.' with more content'; $resp = $this->get($book->getUrl('/edit')); $resp->assertSee($book->name); $resp->assertSee($book->description); - $resp->assertElementContains('form[action="' . $book->getUrl() . '"]', 'Save Book'); + $resp->assertElementContains('form[action="'.$book->getUrl().'"]', 'Save Book'); $resp = $this->put($book->getUrl(), ['name' => $newName, 'description' => $newDesc]); - $resp->assertRedirect($book->getUrl() . '-updated'); + $resp->assertRedirect($book->getUrl().'-updated'); - $resp = $this->get($book->getUrl() . '-updated'); + $resp = $this->get($book->getUrl().'-updated'); $resp->assertSee($newName); $resp->assertSee($newDesc); } @@ -99,7 +99,7 @@ public function test_delete() public function test_cancel_on_create_page_leads_back_to_books_listing() { $resp = $this->asEditor()->get('/create-book'); - $resp->assertElementContains('form a[href="' . url('/books') . '"]', 'Cancel'); + $resp->assertElementContains('form a[href="'.url('/books').'"]', 'Cancel'); } public function test_cancel_on_edit_book_page_leads_back_to_book() @@ -107,7 +107,7 @@ public function test_cancel_on_edit_book_page_leads_back_to_book() /** @var Book $book */ $book = Book::query()->first(); $resp = $this->asEditor()->get($book->getUrl('/edit')); - $resp->assertElementContains('form a[href="' . $book->getUrl() . '"]', 'Cancel'); + $resp->assertElementContains('form a[href="'.$book->getUrl().'"]', 'Cancel'); } public function test_next_previous_navigation_controls_show_within_book_content() @@ -165,7 +165,7 @@ public function test_books_view_shows_view_toggle_option() setting()->putUser($editor, 'books_view_type', 'list'); $resp = $this->actingAs($editor)->get('/books'); - $resp->assertElementContains('form[action$="/settings/users/' . $editor->id . '/switch-books-view"]', 'Grid View'); + $resp->assertElementContains('form[action$="/settings/users/'.$editor->id.'/switch-books-view"]', 'Grid View'); $resp->assertElementExists('input[name="view_type"][value="grid"]'); $resp = $this->patch("/settings/users/{$editor->id}/switch-books-view", ['view_type' => 'grid']); @@ -173,7 +173,7 @@ public function test_books_view_shows_view_toggle_option() $this->assertEquals('grid', setting()->getUser($editor, 'books_view_type')); $resp = $this->actingAs($editor)->get('/books'); - $resp->assertElementContains('form[action$="/settings/users/' . $editor->id . '/switch-books-view"]', 'List View'); + $resp->assertElementContains('form[action$="/settings/users/'.$editor->id.'/switch-books-view"]', 'List View'); $resp->assertElementExists('input[name="view_type"][value="list"]'); $resp = $this->patch("/settings/users/{$editor->id}/switch-books-view", ['view_type' => 'list']); diff --git a/tests/Entity/ChapterTest.php b/tests/Entity/ChapterTest.php index ea29ece5d2c..3f0fe0effbf 100644 --- a/tests/Entity/ChapterTest.php +++ b/tests/Entity/ChapterTest.php @@ -18,10 +18,10 @@ public function test_create() ]); $resp = $this->asEditor()->get($book->getUrl()); - $resp->assertElementContains('a[href="' . $book->getUrl('/create-chapter') . '"]', 'New Chapter'); + $resp->assertElementContains('a[href="'.$book->getUrl('/create-chapter').'"]', 'New Chapter'); $resp = $this->get($book->getUrl('/create-chapter')); - $resp->assertElementContains('form[action="' . $book->getUrl('/create-chapter') . '"][method="POST"]', 'Save Chapter'); + $resp->assertElementContains('form[action="'.$book->getUrl('/create-chapter').'"][method="POST"]', 'Save Chapter'); $resp = $this->post($book->getUrl('/create-chapter'), $chapter->only('name', 'description')); $resp->assertRedirect($book->getUrl('/chapter/my-first-chapter')); diff --git a/tests/Entity/CommentTest.php b/tests/Entity/CommentTest.php index b613f80a1d3..f150f6e6702 100644 --- a/tests/Entity/CommentTest.php +++ b/tests/Entity/CommentTest.php @@ -107,7 +107,7 @@ public function test_html_cannot_be_injected_via_comment_content() $comment = $page->comments()->first(); $this->putJson("/comment/$comment->id", [ - 'text' => $script . 'updated', + 'text' => $script.'updated', ]); $pageView = $this->get($page->getUrl()); diff --git a/tests/Entity/EntitySearchTest.php b/tests/Entity/EntitySearchTest.php index 8d2ef0fded2..83b16ecf375 100644 --- a/tests/Entity/EntitySearchTest.php +++ b/tests/Entity/EntitySearchTest.php @@ -16,7 +16,7 @@ public function test_page_search() $book = Book::all()->first(); $page = $book->pages->first(); - $search = $this->asEditor()->get('/search?term=' . urlencode($page->name)); + $search = $this->asEditor()->get('/search?term='.urlencode($page->name)); $search->assertSee('Search Results'); $search->assertSee($page->name); } @@ -24,14 +24,14 @@ public function test_page_search() public function test_bookshelf_search() { $shelf = Bookshelf::first(); - $search = $this->asEditor()->get('/search?term=' . urlencode(mb_substr($shelf->name, 0, 3)) . ' {type:bookshelf}'); + $search = $this->asEditor()->get('/search?term='.urlencode(mb_substr($shelf->name, 0, 3)).' {type:bookshelf}'); $search->assertStatus(200); $search->assertSee($shelf->name); } public function test_invalid_page_search() { - $resp = $this->asEditor()->get('/search?term=' . urlencode('

test

')); + $resp = $this->asEditor()->get('/search?term='.urlencode('

test

')); $resp->assertSee('Search Results'); $resp->assertStatus(200); $this->get('/search?term=cat+-')->assertStatus(200); @@ -48,10 +48,10 @@ public function test_searching_accents_and_small_terms() $page = $this->newPage(['name' => 'My new test quaffleachits', 'html' => 'some áéííúü¿¡ test content a2 orange dog']); $this->asEditor(); - $accentSearch = $this->get('/search?term=' . urlencode('áéíí')); + $accentSearch = $this->get('/search?term='.urlencode('áéíí')); $accentSearch->assertStatus(200)->assertSee($page->name); - $smallSearch = $this->get('/search?term=' . urlencode('a2')); + $smallSearch = $this->get('/search?term='.urlencode('a2')); $smallSearch->assertStatus(200)->assertSee($page->name); } @@ -61,10 +61,10 @@ public function test_book_search() $page = $book->pages->last(); $chapter = $book->chapters->last(); - $pageTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($page->name)); + $pageTestResp = $this->asEditor()->get('/search/book/'.$book->id.'?term='.urlencode($page->name)); $pageTestResp->assertSee($page->name); - $chapterTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($chapter->name)); + $chapterTestResp = $this->asEditor()->get('/search/book/'.$book->id.'?term='.urlencode($chapter->name)); $chapterTestResp->assertSee($chapter->name); } @@ -73,7 +73,7 @@ public function test_chapter_search() $chapter = Chapter::has('pages')->first(); $page = $chapter->pages[0]; - $pageTestResp = $this->asEditor()->get('/search/chapter/' . $chapter->id . '?term=' . urlencode($page->name)); + $pageTestResp = $this->asEditor()->get('/search/chapter/'.$chapter->id.'?term='.urlencode($page->name)); $pageTestResp->assertSee($page->name); } @@ -111,10 +111,10 @@ public function test_exact_searches() { $page = $this->newPage(['name' => 'My new test page', 'html' => 'this is a story about an orange donkey']); - $exactSearchA = $this->asEditor()->get('/search?term=' . urlencode('"story about an orange"')); + $exactSearchA = $this->asEditor()->get('/search?term='.urlencode('"story about an orange"')); $exactSearchA->assertStatus(200)->assertSee($page->name); - $exactSearchB = $this->asEditor()->get('/search?term=' . urlencode('"story not about an orange"')); + $exactSearchB = $this->asEditor()->get('/search?term='.urlencode('"story not about an orange"')); $exactSearchB->assertStatus(200)->assertDontSee($page->name); } @@ -126,59 +126,59 @@ public function test_search_filters() $editorSlug = $this->getEditor()->slug; // Viewed filter searches - $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {not_viewed_by_me}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {viewed_by_me}'))->assertDontSee($page->name); $this->get($page->getUrl()); - $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {not_viewed_by_me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {viewed_by_me}'))->assertSee($page->name); // User filters - $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editorSlug . '}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_by:'.$editorSlug.'}'))->assertDontSee($page->name); $page->created_by = $editorId; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {created_by: ' . $editorSlug . '}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_by:me}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_by: '.$editorSlug.'}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->updated_by = $editorId; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editorSlug . '}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_by:'.$editorSlug.'}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->owned_by = $editorId; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:' . $editorSlug . '}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {owned_by:'.$editorSlug.'}'))->assertSee($page->name); // Content filters - $this->get('/search?term=' . urlencode('{in_name:danzorbhsing}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('{in_body:danzorbhsing}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('{in_name:test quaffleachits}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('{in_body:test quaffleachits}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('{in_name:danzorbhsing}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('{in_body:danzorbhsing}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('{in_name:test quaffleachits}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('{in_body:test quaffleachits}'))->assertDontSee($page->name); // Restricted filter - $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {is_restricted}'))->assertDontSee($page->name); $page->restricted = true; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {is_restricted}'))->assertSee($page->name); // Date filters - $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertSee($page->name); $page->updated_at = '2037-02-01'; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_after:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_before:2037-01-01}'))->assertSee($page->name); $page->created_at = '2037-02-01'; $page->save(); - $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertSee($page->name); - $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_after:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term='.urlencode('danzorbhsing {created_before:2037-01-01}'))->assertDontSee($page->name); } public function test_ajax_entity_search() @@ -189,10 +189,10 @@ public function test_ajax_entity_search() // Visit the page to make popular $this->asEditor()->get($page->getUrl()); - $normalSearch = $this->get('/ajax/search/entities?term=' . urlencode($page->name)); + $normalSearch = $this->get('/ajax/search/entities?term='.urlencode($page->name)); $normalSearch->assertSee($page->name); - $bookSearch = $this->get('/ajax/search/entities?types=book&term=' . urlencode($page->name)); + $bookSearch = $this->get('/ajax/search/entities?types=book&term='.urlencode($page->name)); $bookSearch->assertDontSee($page->name); $defaultListTest = $this->get('/ajax/search/entities'); @@ -206,12 +206,12 @@ public function test_ajax_entity_serach_shows_breadcrumbs() $page = $chapter->pages->first(); $this->asEditor(); - $pageSearch = $this->get('/ajax/search/entities?term=' . urlencode($page->name)); + $pageSearch = $this->get('/ajax/search/entities?term='.urlencode($page->name)); $pageSearch->assertSee($page->name); $pageSearch->assertSee($chapter->getShortName(42)); $pageSearch->assertSee($page->book->getShortName(42)); - $chapterSearch = $this->get('/ajax/search/entities?term=' . urlencode($chapter->name)); + $chapterSearch = $this->get('/ajax/search/entities?term='.urlencode($chapter->name)); $chapterSearch->assertSee($chapter->name); $chapterSearch->assertSee($chapter->book->getShortName(42)); } diff --git a/tests/Entity/ExportTest.php b/tests/Entity/ExportTest.php index 9ea336db8ff..38db7ade092 100644 --- a/tests/Entity/ExportTest.php +++ b/tests/Entity/ExportTest.php @@ -20,7 +20,7 @@ public function test_page_text_export() $resp = $this->get($page->getUrl('/export/plaintext')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.txt"'); } public function test_page_pdf_export() @@ -30,7 +30,7 @@ public function test_page_pdf_export() $resp = $this->get($page->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.pdf"'); } public function test_page_html_export() @@ -41,7 +41,7 @@ public function test_page_html_export() $resp = $this->get($page->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.html"'); } public function test_book_text_export() @@ -54,7 +54,7 @@ public function test_book_text_export() $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.txt"'); } public function test_book_pdf_export() @@ -65,7 +65,7 @@ public function test_book_pdf_export() $resp = $this->get($book->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.pdf"'); } public function test_book_html_export() @@ -78,12 +78,12 @@ public function test_book_html_export() $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.html"'); } public function test_book_html_export_shows_chapter_descriptions() { - $chapterDesc = 'My custom test chapter description ' . Str::random(12); + $chapterDesc = 'My custom test chapter description '.Str::random(12); $chapter = Chapter::query()->first(); $chapter->description = $chapterDesc; $chapter->save(); @@ -105,7 +105,7 @@ public function test_chapter_text_export() $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.txt"'); } public function test_chapter_pdf_export() @@ -115,7 +115,7 @@ public function test_chapter_pdf_export() $resp = $this->get($chapter->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.pdf"'); } public function test_chapter_html_export() @@ -128,7 +128,7 @@ public function test_chapter_html_export() $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.html"'); } public function test_page_html_export_contains_custom_head_if_set() @@ -211,8 +211,8 @@ public function test_page_export_contained_html_image_fetches_only_run_when_url_ { $page = Page::query()->first(); $page->html = '' - . '' - . ''; + .'' + .''; $storageDisk = Storage::disk('local'); $storageDisk->makeDirectory('uploads/images/gallery'); $storageDisk->put('uploads/images/gallery/svg_test.svg', 'good'); @@ -296,7 +296,7 @@ public function test_page_markdown_export() $resp = $this->asEditor()->get($page->getUrl('/export/markdown')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.md"'); } public function test_page_markdown_export_uses_existing_markdown_if_apparent() @@ -340,7 +340,7 @@ public function test_page_markdown_export_handles_bookstacks_wysiwyg_codeblock_f { $page = Page::query()->first()->forceFill([ 'markdown' => '', - 'html' => '

Dogcat

' . "\r\n" . '
var a = \'cat\';

Another line

', + 'html' => '

Dogcat

'."\r\n".'
var a = \'cat\';

Another line

', ]); $page->save(); @@ -354,8 +354,8 @@ public function test_chapter_markdown_export() $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($chapter->getUrl('/export/markdown')); - $resp->assertSee('# ' . $chapter->name); - $resp->assertSee('# ' . $page->name); + $resp->assertSee('# '.$chapter->name); + $resp->assertSee('# '.$page->name); } public function test_book_markdown_export() @@ -365,9 +365,9 @@ public function test_book_markdown_export() $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($book->getUrl('/export/markdown')); - $resp->assertSee('# ' . $book->name); - $resp->assertSee('# ' . $chapter->name); - $resp->assertSee('# ' . $page->name); + $resp->assertSee('# '.$book->name); + $resp->assertSee('# '.$chapter->name); + $resp->assertSee('# '.$page->name); } public function test_export_option_only_visible_and_accessible_with_permission() diff --git a/tests/Entity/PageContentTest.php b/tests/Entity/PageContentTest.php index dd996b92633..e1ecd6a1189 100644 --- a/tests/Entity/PageContentTest.php +++ b/tests/Entity/PageContentTest.php @@ -34,7 +34,7 @@ public function test_page_includes() $pageContent->assertSee('Hello, This is a test'); $pageContent->assertSee('This is a second block of content'); - $page->html = $originalHtml . " Well {{@{$secondPage->id}#section2}}"; + $page->html = $originalHtml." Well {{@{$secondPage->id}#section2}}"; $page->save(); $pageContent = $this->get($page->getUrl()); @@ -48,8 +48,8 @@ public function test_saving_page_with_includes() $secondPage = Page::query()->where('id', '!=', $page->id)->first(); $this->asEditor(); - $includeTag = '{{@' . $secondPage->id . '}}'; - $page->html = '

' . $includeTag . '

'; + $includeTag = '{{@'.$secondPage->id.'}}'; + $page->html = '

'.$includeTag.'

'; $resp = $this->put($page->getUrl(), ['name' => $page->name, 'html' => $page->html, 'summary' => '']); @@ -352,7 +352,7 @@ public function test_duplicate_ids_does_not_break_page_render() $pageA->html = $content; $pageA->save(); - $pageB->html = '

    {{@' . $pageA->id . '#test}}

    '; + $pageB->html = '

      {{@'.$pageA->id.'#test}}

      '; $pageB->save(); $pageView = $this->get($pageB->getUrl()); @@ -555,7 +555,7 @@ public function test_base64_images_get_extracted_from_page_content() $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

      test

      ', + 'html' => '

      test

      ', ]); $page->refresh(); @@ -579,7 +579,7 @@ public function test_base64_images_get_extracted_when_containing_whitespace() $base64PngWithoutWhitespace = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQAB'; $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

      test

      ', + 'html' => '

      test

      ', ]); $page->refresh(); @@ -601,7 +601,7 @@ public function test_base64_images_within_html_blanked_if_not_supported_extensio $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

      test

      ', + 'html' => '

      test

      ', ]); $page->refresh(); @@ -615,7 +615,7 @@ public function test_base64_images_get_extracted_from_markdown_page_content() $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')', + 'markdown' => 'test ![test](data:image/jpeg;base64,'.$this->base64Jpeg.')', ]); $page->refresh(); @@ -637,7 +637,7 @@ public function test_base64_images_within_markdown_blanked_if_not_supported_exte $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'markdown' => 'test ![test](data:image/jiff;base64,' . $this->base64Jpeg . ')', + 'markdown' => 'test ![test](data:image/jiff;base64,'.$this->base64Jpeg.')', ]); $page->refresh(); diff --git a/tests/Entity/PageDraftTest.php b/tests/Entity/PageDraftTest.php index 4fb7d7ab6e5..14865fb7853 100644 --- a/tests/Entity/PageDraftTest.php +++ b/tests/Entity/PageDraftTest.php @@ -34,7 +34,7 @@ public function test_draft_content_shows_if_available() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html . $addedContent; + $newContent = $this->page->html.$addedContent; $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementContains('[name="html"]', $newContent); @@ -46,7 +46,7 @@ public function test_draft_not_visible_by_others() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html . $addedContent; + $newContent = $this->page->html.$addedContent; $newUser = $this->getEditor(); $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); @@ -69,7 +69,7 @@ public function test_alert_message_shows_if_someone_else_editing() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html . $addedContent; + $newContent = $this->page->html.$addedContent; $newUser = $this->getEditor(); $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); @@ -77,7 +77,7 @@ public function test_alert_message_shows_if_someone_else_editing() ->get($this->page->getUrl('/edit')) ->assertSee('Admin has started editing this page'); $this->flushSession(); - $this->get($nonEditedPage->getUrl() . '/edit') + $this->get($nonEditedPage->getUrl().'/edit') ->assertElementNotContains('.notification', 'Admin has started editing this page'); } @@ -88,7 +88,7 @@ public function test_draft_save_shows_alert_if_draft_older_than_last_page_update /** @var Page $page */ $page = Page::query()->first(); - $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ + $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ 'name' => $page->name, 'html' => '

      updated draft

      ', ]); @@ -106,7 +106,7 @@ public function test_draft_save_shows_alert_if_draft_older_than_last_page_update 'html' => '

      admin update

      ', ]); - $resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ + $resp = $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ 'name' => $page->name, 'html' => '

      updated draft again

      ', ]); @@ -123,12 +123,12 @@ public function test_draft_save_shows_alert_if_draft_edit_started_by_someone_els /** @var Page $page */ $page = Page::query()->first(); - $this->actingAs($admin)->put('/ajax/page/' . $page->id . '/save-draft', [ + $this->actingAs($admin)->put('/ajax/page/'.$page->id.'/save-draft', [ 'name' => $page->name, 'html' => '

      updated draft

      ', ]); - $resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ + $resp = $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ 'name' => $page->name, 'html' => '

      updated draft again

      ', ]); @@ -145,7 +145,7 @@ public function test_draft_pages_show_on_homepage() $this->asAdmin()->get('/') ->assertElementNotContains('#recent-drafts', 'New Page'); - $this->get($book->getUrl() . '/create-page'); + $this->get($book->getUrl().'/create-page'); $this->get('/')->assertElementContains('#recent-drafts', 'New Page'); } @@ -174,7 +174,7 @@ public function test_page_html_in_ajax_fetch_response() /** @var Page $page */ $page = Page::query()->first(); - $this->getJson('/ajax/page/' . $page->id)->assertJson([ + $this->getJson('/ajax/page/'.$page->id)->assertJson([ 'html' => $page->html, ]); } diff --git a/tests/Entity/PageEditorTest.php b/tests/Entity/PageEditorTest.php index 9b0a8f18810..df08f415c5e 100644 --- a/tests/Entity/PageEditorTest.php +++ b/tests/Entity/PageEditorTest.php @@ -20,14 +20,14 @@ public function setUp(): void public function test_default_editor_is_wysiwyg() { $this->assertEquals('wysiwyg', setting('app-editor')); - $this->asAdmin()->get($this->page->getUrl() . '/edit') + $this->asAdmin()->get($this->page->getUrl().'/edit') ->assertElementExists('#html-editor'); } public function test_markdown_setting_shows_markdown_editor() { $this->setSettings(['app-editor' => 'markdown']); - $this->asAdmin()->get($this->page->getUrl() . '/edit') + $this->asAdmin()->get($this->page->getUrl().'/edit') ->assertElementNotExists('#html-editor') ->assertElementExists('#markdown-editor'); } @@ -40,14 +40,14 @@ public function test_markdown_content_given_to_editor() $this->page->markdown = $mdContent; $this->page->save(); - $this->asAdmin()->get($this->page->getUrl() . '/edit') + $this->asAdmin()->get($this->page->getUrl().'/edit') ->assertElementContains('[name="markdown"]', $mdContent); } public function test_html_content_given_to_editor_if_no_markdown() { $this->setSettings(['app-editor' => 'markdown']); - $this->asAdmin()->get($this->page->getUrl() . '/edit') + $this->asAdmin()->get($this->page->getUrl().'/edit') ->assertElementContains('[name="markdown"]', $this->page->html); } diff --git a/tests/Entity/PageRevisionTest.php b/tests/Entity/PageRevisionTest.php index 2ed7d3b411e..d16640a3505 100644 --- a/tests/Entity/PageRevisionTest.php +++ b/tests/Entity/PageRevisionTest.php @@ -17,11 +17,11 @@ public function test_page_revision_views_viewable() $pageRepo->update($page, ['name' => 'updated page', 'html' => '

      new content

      ', 'summary' => 'page revision testing']); $pageRevision = $page->revisions->last(); - $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); + $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id); $revisionView->assertStatus(200); $revisionView->assertSee('new content'); - $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id . '/changes'); + $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id.'/changes'); $revisionView->assertStatus(200); $revisionView->assertSee('new content'); } @@ -36,7 +36,7 @@ public function test_page_revision_preview_shows_content_of_revision() $pageRevision = $page->revisions->last(); $pageRepo->update($page, ['name' => 'updated page', 'html' => '

      Updated content

      ', 'summary' => 'page revision testing 2']); - $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); + $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id); $revisionView->assertStatus(200); $revisionView->assertSee('new revision content'); } @@ -56,7 +56,7 @@ public function test_page_revision_restore_updates_content() $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); + $restoreReq = $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); @@ -82,7 +82,7 @@ public function test_page_revision_restore_with_markdown_retains_markdown_conten $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); + $restoreReq = $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); @@ -108,7 +108,7 @@ public function test_page_revision_restore_sets_new_revision_with_summary() $page->refresh(); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); + $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); $page->refresh(); $this->assertDatabaseHas('page_revisions', [ @@ -139,7 +139,7 @@ public function test_revision_count_shown_in_page_meta() $page = Page::find($page->id); $pageView = $this->get($page->getUrl()); - $pageView->assertSee('Revision #' . $page->revision_count); + $pageView->assertSee('Revision #'.$page->revision_count); } public function test_revision_deletion() diff --git a/tests/Entity/PageTemplateTest.php b/tests/Entity/PageTemplateTest.php index 3d16895102f..fa93df08bb2 100644 --- a/tests/Entity/PageTemplateTest.php +++ b/tests/Entity/PageTemplateTest.php @@ -56,14 +56,14 @@ public function test_templates_content_should_be_fetchable_only_if_page_marked_a $editor = $this->getEditor(); $this->actingAs($editor); - $templateFetch = $this->get('/templates/' . $page->id); + $templateFetch = $this->get('/templates/'.$page->id); $templateFetch->assertStatus(404); $page->html = $content; $page->template = true; $page->save(); - $templateFetch = $this->get('/templates/' . $page->id); + $templateFetch = $this->get('/templates/'.$page->id); $templateFetch->assertStatus(200); $templateFetch->assertJson([ 'html' => $content, diff --git a/tests/Entity/PageTest.php b/tests/Entity/PageTest.php index 313fc77f060..48749420cac 100644 --- a/tests/Entity/PageTest.php +++ b/tests/Entity/PageTest.php @@ -19,7 +19,7 @@ public function test_create() ]); $resp = $this->asEditor()->get($chapter->getUrl()); - $resp->assertElementContains('a[href="' . $chapter->getUrl('/create-page') . '"]', 'New Page'); + $resp->assertElementContains('a[href="'.$chapter->getUrl('/create-page').'"]', 'New Page'); $resp = $this->get($chapter->getUrl('/create-page')); /** @var Page $draftPage */ @@ -30,7 +30,7 @@ public function test_create() $resp->assertRedirect($draftPage->getUrl()); $resp = $this->get($draftPage->getUrl()); - $resp->assertElementContains('form[action="' . $draftPage->getUrl() . '"][method="POST"]', 'Save Page'); + $resp->assertElementContains('form[action="'.$draftPage->getUrl().'"][method="POST"]', 'Save Page'); $resp = $this->post($draftPage->getUrl(), $draftPage->only('name', 'html')); $draftPage->refresh(); @@ -49,7 +49,7 @@ public function test_page_view_when_creator_is_deleted_but_owner_exists() $resp = $this->asAdmin()->get($page->getUrl()); $resp->assertStatus(200); - $resp->assertSeeText('Owned by ' . $owner->name); + $resp->assertSeeText('Owned by '.$owner->name); } public function test_page_creation_with_markdown_content() @@ -141,7 +141,7 @@ public function test_page_copy() $resp->assertSee('Copy Page'); $movePageResp = $this->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); @@ -160,7 +160,7 @@ public function test_page_copy_with_markdown_has_both_html_and_markdown() $newBook = Book::where('id', '!=', $page->book->id)->first(); $this->asEditor()->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); @@ -207,7 +207,7 @@ public function test_page_can_be_copied_without_edit_permission() $resp->assertSee($page->getUrl('/copy')); $movePageResp = $this->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, 'name' => 'My copied test page', ]); $movePageResp->assertRedirect(); diff --git a/tests/Entity/SortTest.php b/tests/Entity/SortTest.php index 5cfc5c3c5b9..1f47cd8e280 100644 --- a/tests/Entity/SortTest.php +++ b/tests/Entity/SortTest.php @@ -27,7 +27,7 @@ public function test_drafts_do_not_show_up() $resp = $this->get($this->book->getUrl()); $resp->assertSee($draft->name); - $resp = $this->get($this->book->getUrl() . '/sort'); + $resp = $this->get($this->book->getUrl().'/sort'); $resp->assertDontSee($draft->name); } @@ -41,7 +41,7 @@ public function test_page_move_into_book() $resp->assertSee('Move Page'); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $page = Page::find($page->id); @@ -61,7 +61,7 @@ public function test_page_move_into_chapter() $newChapter = $newBook->chapters()->first(); $movePageResp = $this->actingAs($this->getEditor())->put($page->getUrl('/move'), [ - 'entity_selection' => 'chapter:' . $newChapter->id, + 'entity_selection' => 'chapter:'.$newChapter->id, ]); $page = Page::find($page->id); @@ -79,7 +79,7 @@ public function test_page_move_from_chapter_to_book() $newBook = Book::where('id', '!=', $oldChapter->book_id)->first(); $movePageResp = $this->actingAs($this->getEditor())->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $page->refresh(); @@ -101,13 +101,13 @@ public function test_page_move_requires_create_permissions_on_parent() $this->setEntityRestrictions($newBook, ['view', 'update', 'delete'], $editor->roles->all()); $movePageResp = $this->actingAs($editor)->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $this->assertPermissionError($movePageResp); $this->setEntityRestrictions($newBook, ['view', 'update', 'delete', 'create'], $editor->roles->all()); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $page = Page::find($page->id); @@ -127,7 +127,7 @@ public function test_page_move_requires_delete_permissions() $this->setEntityRestrictions($page, ['view', 'update', 'create'], $editor->roles->all()); $movePageResp = $this->actingAs($editor)->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $this->assertPermissionError($movePageResp); $pageView = $this->get($page->getUrl()); @@ -135,7 +135,7 @@ public function test_page_move_requires_delete_permissions() $this->setEntityRestrictions($page, ['view', 'update', 'create', 'delete'], $editor->roles->all()); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $page = Page::find($page->id); @@ -154,7 +154,7 @@ public function test_chapter_move() $chapterMoveResp->assertSee('Move Chapter'); $moveChapterResp = $this->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $chapter = Chapter::find($chapter->id); @@ -182,7 +182,7 @@ public function test_chapter_move_requires_delete_permissions() $this->setEntityRestrictions($chapter, ['view', 'update', 'create'], $editor->roles->all()); $moveChapterResp = $this->actingAs($editor)->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $this->assertPermissionError($moveChapterResp); $pageView = $this->get($chapter->getUrl()); @@ -190,7 +190,7 @@ public function test_chapter_move_requires_delete_permissions() $this->setEntityRestrictions($chapter, ['view', 'update', 'create', 'delete'], $editor->roles->all()); $moveChapterResp = $this->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $chapter = Chapter::find($chapter->id); @@ -209,7 +209,7 @@ public function test_chapter_move_changes_book_for_deleted_pages_within() $pageToCheck->delete(); $this->asEditor()->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:' . $newBook->id, + 'entity_selection' => 'book:'.$newBook->id, ]); $pageToCheck->refresh(); @@ -222,7 +222,7 @@ public function test_book_sort_page_shows() $bookToSort = Book::query()->first(); $resp = $this->asAdmin()->get($bookToSort->getUrl()); - $resp->assertElementExists('a[href="' . $bookToSort->getUrl('/sort') . '"]'); + $resp->assertElementExists('a[href="'.$bookToSort->getUrl('/sort').'"]'); $resp = $this->get($bookToSort->getUrl('/sort')); $resp->assertStatus(200); @@ -256,7 +256,7 @@ public function test_book_sort() ]; } - $sortResp = $this->asEditor()->put($newBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]); + $sortResp = $this->asEditor()->put($newBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]); $sortResp->assertRedirect($newBook->getUrl()); $sortResp->assertStatus(302); $this->assertDatabaseHas('chapters', [ @@ -279,7 +279,7 @@ public function test_book_sort_item_returns_book_content() $firstPage = $bookToSort->pages[0]; $firstChapter = $bookToSort->chapters[0]; - $resp = $this->asAdmin()->get($bookToSort->getUrl() . '/sort-item'); + $resp = $this->asAdmin()->get($bookToSort->getUrl().'/sort-item'); // Ensure book details are returned $resp->assertSee($bookToSort->name); diff --git a/tests/Entity/TagTest.php b/tests/Entity/TagTest.php index 74da37f4a86..2823aaf890b 100644 --- a/tests/Entity/TagTest.php +++ b/tests/Entity/TagTest.php @@ -93,9 +93,9 @@ public function test_tags_shown_on_search_listing() $page = $this->getEntityWithTags(Page::class, $tags); $resp = $this->asEditor()->get('/search?term=[category]'); $resp->assertSee($page->name); - $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'category'); - $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'buckets'); - $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'color'); - $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'red'); + $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'category'); + $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'buckets'); + $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'color'); + $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'red'); } } diff --git a/tests/Helpers/OidcJwtHelper.php b/tests/Helpers/OidcJwtHelper.php index 55a34d4dc96..fd5a4852bce 100644 --- a/tests/Helpers/OidcJwtHelper.php +++ b/tests/Helpers/OidcJwtHelper.php @@ -56,7 +56,7 @@ public static function idToken($payloadOverrides = [], $headerOverrides = []): s $privateKey = static::privateKeyInstance(); $signature = $privateKey->sign($top); - return $top . '.' . static::base64UrlEncode($signature); + return $top.'.'.static::base64UrlEncode($signature); } public static function privateKeyInstance() diff --git a/tests/HomepageTest.php b/tests/HomepageTest.php index e27b787745f..466c36a0e33 100644 --- a/tests/HomepageTest.php +++ b/tests/HomepageTest.php @@ -89,7 +89,7 @@ public function test_custom_homepage_renders_includes() $included->save(); $name = 'My custom homepage'; - $customPage = $this->newPage(['name' => $name, 'html' => '{{@' . $included->id . '}}']); + $customPage = $this->newPage(['name' => $name, 'html' => '{{@'.$included->id.'}}']); $this->setSettings(['app-homepage' => $customPage->id]); $this->setSettings(['app-homepage-type' => 'page']); diff --git a/tests/OpenGraphTest.php b/tests/OpenGraphTest.php index 17a5aa2c56f..b9066c41e82 100644 --- a/tests/OpenGraphTest.php +++ b/tests/OpenGraphTest.php @@ -21,7 +21,7 @@ public function test_page_tags() $resp = $this->asEditor()->get($page->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($page->getShortName() . ' | BookStack', $tags['title']); + $this->assertEquals($page->getShortName().' | BookStack', $tags['title']); $this->assertEquals($page->getUrl(), $tags['url']); $this->assertEquals(Str::limit($page->text, 100, '...'), $tags['description']); } @@ -32,7 +32,7 @@ public function test_chapter_tags() $resp = $this->asEditor()->get($chapter->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($chapter->getShortName() . ' | BookStack', $tags['title']); + $this->assertEquals($chapter->getShortName().' | BookStack', $tags['title']); $this->assertEquals($chapter->getUrl(), $tags['url']); $this->assertEquals(Str::limit($chapter->description, 100, '...'), $tags['description']); } @@ -43,7 +43,7 @@ public function test_book_tags() $resp = $this->asEditor()->get($book->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($book->getShortName() . ' | BookStack', $tags['title']); + $this->assertEquals($book->getShortName().' | BookStack', $tags['title']); $this->assertEquals($book->getUrl(), $tags['url']); $this->assertEquals(Str::limit($book->description, 100, '...'), $tags['description']); $this->assertArrayNotHasKey('image', $tags); @@ -63,7 +63,7 @@ public function test_shelf_tags() $resp = $this->asEditor()->get($shelf->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($shelf->getShortName() . ' | BookStack', $tags['title']); + $this->assertEquals($shelf->getShortName().' | BookStack', $tags['title']); $this->assertEquals($shelf->getUrl(), $tags['url']); $this->assertEquals(Str::limit($shelf->description, 100, '...'), $tags['description']); $this->assertArrayNotHasKey('image', $tags); diff --git a/tests/Permissions/EntityPermissionsTest.php b/tests/Permissions/EntityPermissionsTest.php index bb011cfc6f5..3e20694f075 100644 --- a/tests/Permissions/EntityPermissionsTest.php +++ b/tests/Permissions/EntityPermissionsTest.php @@ -149,10 +149,10 @@ public function test_book_create_restriction() $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); - $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); + $this->get($bookUrl.'/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookUrl . '/create-page')->assertRedirect('/'); + $this->get($bookUrl.'/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl) @@ -190,23 +190,23 @@ public function test_book_update_restriction() $bookUrl = $book->getUrl(); $this->actingAs($this->user) - ->get($bookUrl . '/edit') + ->get($bookUrl.'/edit') ->assertSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl . '/edit')->assertRedirect('/'); + $this->get($bookUrl.'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl() . '/edit')->assertRedirect('/'); + $this->get($bookPage->getUrl().'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); + $this->get($bookChapter->getUrl().'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl . '/edit')->assertOk(); - $this->get($bookPage->getUrl() . '/edit')->assertOk(); - $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); + $this->get($bookUrl.'/edit')->assertOk(); + $this->get($bookPage->getUrl().'/edit')->assertOk(); + $this->get($bookChapter->getUrl().'/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction() @@ -217,21 +217,21 @@ public function test_book_delete_restriction() $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); - $this->actingAs($this->user)->get($bookUrl . '/delete') + $this->actingAs($this->user)->get($bookUrl.'/delete') ->assertSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl . '/delete')->assertRedirect('/'); + $this->get($bookUrl.'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); + $this->get($bookPage->getUrl().'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); + $this->get($bookChapter->getUrl().'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); + $this->get($bookUrl.'/delete')->assertOk()->assertSee('Delete Book'); $this->get($bookPage->getUrl('/delete'))->assertOk()->assertSee('Delete Page'); $this->get($bookChapter->getUrl('/delete'))->assertSee('Delete Chapter'); } @@ -268,7 +268,7 @@ public function test_chapter_create_restriction() $this->setRestrictionsForTestRoles($chapter, ['view', 'delete', 'update']); - $this->get($chapterUrl . '/create-page')->assertRedirect('/'); + $this->get($chapterUrl.'/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($chapterUrl)->assertElementNotContains('.actions', 'New Page'); @@ -293,20 +293,20 @@ public function test_chapter_update_restriction() $chapterPage = $chapter->pages->first(); $chapterUrl = $chapter->getUrl(); - $this->actingAs($this->user)->get($chapterUrl . '/edit') + $this->actingAs($this->user)->get($chapterUrl.'/edit') ->assertSee('Edit Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); - $this->get($chapterUrl . '/edit')->assertRedirect('/'); + $this->get($chapterUrl.'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($chapterPage->getUrl() . '/edit')->assertRedirect('/'); + $this->get($chapterPage->getUrl().'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); - $this->get($chapterUrl . '/edit')->assertOk()->assertSee('Edit Chapter'); - $this->get($chapterPage->getUrl() . '/edit')->assertOk(); + $this->get($chapterUrl.'/edit')->assertOk()->assertSee('Edit Chapter'); + $this->get($chapterPage->getUrl().'/edit')->assertOk(); } public function test_chapter_delete_restriction() @@ -317,20 +317,20 @@ public function test_chapter_delete_restriction() $chapterUrl = $chapter->getUrl(); $this->actingAs($this->user) - ->get($chapterUrl . '/delete') + ->get($chapterUrl.'/delete') ->assertSee('Delete Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); - $this->get($chapterUrl . '/delete')->assertRedirect('/'); + $this->get($chapterUrl.'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($chapterPage->getUrl() . '/delete')->assertRedirect('/'); + $this->get($chapterPage->getUrl().'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); - $this->get($chapterUrl . '/delete')->assertOk()->assertSee('Delete Chapter'); - $this->get($chapterPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); + $this->get($chapterUrl.'/delete')->assertOk()->assertSee('Delete Chapter'); + $this->get($chapterPage->getUrl().'/delete')->assertOk()->assertSee('Delete Page'); } public function test_page_view_restriction() @@ -357,19 +357,19 @@ public function test_page_update_restriction() $pageUrl = $page->getUrl(); $this->actingAs($this->user) - ->get($pageUrl . '/edit') - ->assertElementExists('input[name="name"][value="' . $page->name . '"]'); + ->get($pageUrl.'/edit') + ->assertElementExists('input[name="name"][value="'.$page->name.'"]'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); - $this->get($pageUrl . '/edit')->assertRedirect('/'); + $this->get($pageUrl.'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); - $this->get($pageUrl . '/edit') + $this->get($pageUrl.'/edit') ->assertOk() - ->assertElementExists('input[name="name"][value="' . $page->name . '"]'); + ->assertElementExists('input[name="name"][value="'.$page->name.'"]'); } public function test_page_delete_restriction() @@ -379,17 +379,17 @@ public function test_page_delete_restriction() $pageUrl = $page->getUrl(); $this->actingAs($this->user) - ->get($pageUrl . '/delete') + ->get($pageUrl.'/delete') ->assertSee('Delete Page'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); - $this->get($pageUrl . '/delete')->assertRedirect('/'); + $this->get($pageUrl.'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); - $this->get($pageUrl . '/delete')->assertOk()->assertSee('Delete Page'); + $this->get($pageUrl.'/delete')->assertOk()->assertSee('Delete Page'); } protected function entityRestrictionFormTest(string $model, string $title, string $permission, string $roleId) @@ -545,9 +545,9 @@ public function test_book_create_restriction_override() $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); - $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); + $this->get($bookUrl.'/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookUrl . '/create-page')->assertRedirect('/'); + $this->get($bookUrl.'/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); @@ -582,23 +582,23 @@ public function test_book_update_restriction_override() $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); - $this->actingAs($this->viewer)->get($bookUrl . '/edit') + $this->actingAs($this->viewer)->get($bookUrl.'/edit') ->assertDontSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl . '/edit')->assertRedirect('/'); + $this->get($bookUrl.'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl() . '/edit')->assertRedirect('/'); + $this->get($bookPage->getUrl().'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); + $this->get($bookChapter->getUrl().'/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl . '/edit')->assertOk(); - $this->get($bookPage->getUrl() . '/edit')->assertOk(); - $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); + $this->get($bookUrl.'/edit')->assertOk(); + $this->get($bookPage->getUrl().'/edit')->assertOk(); + $this->get($bookChapter->getUrl().'/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction_override() @@ -610,23 +610,23 @@ public function test_book_delete_restriction_override() $bookUrl = $book->getUrl(); $this->actingAs($this->viewer) - ->get($bookUrl . '/delete') + ->get($bookUrl.'/delete') ->assertDontSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl . '/delete')->assertRedirect('/'); + $this->get($bookUrl.'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); + $this->get($bookPage->getUrl().'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); + $this->get($bookChapter->getUrl().'/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); - $this->get($bookPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); - $this->get($bookChapter->getUrl() . '/delete')->assertSee('Delete Chapter'); + $this->get($bookUrl.'/delete')->assertOk()->assertSee('Delete Book'); + $this->get($bookPage->getUrl().'/delete')->assertOk()->assertSee('Delete Page'); + $this->get($bookChapter->getUrl().'/delete')->assertSee('Delete Chapter'); } public function test_page_visible_if_has_permissions_when_book_not_visible() @@ -695,7 +695,7 @@ public function test_book_sort_permission() ]; // Move chapter from first book to a second book - $this->actingAs($this->user)->put($firstBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]) + $this->actingAs($this->user)->put($firstBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]) ->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); @@ -710,7 +710,7 @@ public function test_book_sort_permission() ]; // Move chapter from second book to first book - $this->actingAs($this->user)->put($firstBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]) + $this->actingAs($this->user)->put($firstBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]) ->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); } diff --git a/tests/Permissions/ExportPermissionsTest.php b/tests/Permissions/ExportPermissionsTest.php index 2e3d84fa13e..076021edc31 100644 --- a/tests/Permissions/ExportPermissionsTest.php +++ b/tests/Permissions/ExportPermissionsTest.php @@ -14,7 +14,7 @@ public function test_page_content_without_view_access_hidden_on_chapter_export() $chapter = Chapter::query()->first(); $page = $chapter->pages()->firstOrFail(); $pageContent = Str::random(48); - $page->html = '

      ' . $pageContent . '

      '; + $page->html = '

      '.$pageContent.'

      '; $page->save(); $viewer = $this->getViewer(); $this->actingAs($viewer); @@ -42,7 +42,7 @@ public function test_page_content_without_view_access_hidden_on_book_export() $book = Book::query()->first(); $page = $book->pages()->firstOrFail(); $pageContent = Str::random(48); - $page->html = '

      ' . $pageContent . '

      '; + $page->html = '

      '.$pageContent.'

      '; $page->save(); $viewer = $this->getViewer(); $this->actingAs($viewer); diff --git a/tests/Permissions/RolesTest.php b/tests/Permissions/RolesTest.php index 3178bd8ce7b..6aa1e09a950 100644 --- a/tests/Permissions/RolesTest.php +++ b/tests/Permissions/RolesTest.php @@ -33,7 +33,7 @@ public function test_admin_can_see_settings() public function test_cannot_delete_admin_role() { $adminRole = Role::getRole('admin'); - $deletePageUrl = '/settings/roles/delete/' . $adminRole->id; + $deletePageUrl = '/settings/roles/delete/'.$adminRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); @@ -45,7 +45,7 @@ public function test_role_cannot_be_deleted_if_default() $newRole = $this->createNewRole(); $this->setSettings(['registration-role' => $newRole->id]); - $deletePageUrl = '/settings/roles/delete/' . $newRole->id; + $deletePageUrl = '/settings/roles/delete/'.$newRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); $this->get($deletePageUrl)->assertSee('cannot be deleted'); @@ -59,13 +59,13 @@ public function test_role_create_update_delete_flow() // Creation $resp = $this->asAdmin()->get('/settings'); - $resp->assertElementContains('a[href="' . url('/settings/roles') . '"]', 'Roles'); + $resp->assertElementContains('a[href="'.url('/settings/roles').'"]', 'Roles'); $resp = $this->get('/settings/roles'); - $resp->assertElementContains('a[href="' . url('/settings/roles/new') . '"]', 'Create New Role'); + $resp->assertElementContains('a[href="'.url('/settings/roles/new').'"]', 'Create New Role'); $resp = $this->get('/settings/roles/new'); - $resp->assertElementContains('form[action="' . url('/settings/roles/new') . '"]', 'Save Role'); + $resp->assertElementContains('form[action="'.url('/settings/roles/new').'"]', 'Save Role'); $resp = $this->post('/settings/roles/new', [ 'display_name' => $testRoleName, @@ -86,12 +86,12 @@ public function test_role_create_update_delete_flow() $role = Role::query()->where('display_name', '=', $testRoleName)->first(); // Updating - $resp = $this->get('/settings/roles/' . $role->id); + $resp = $this->get('/settings/roles/'.$role->id); $resp->assertSee($testRoleName); $resp->assertSee($testRoleDesc); - $resp->assertElementContains('form[action="' . url('/settings/roles/' . $role->id) . '"]', 'Save Role'); + $resp->assertElementContains('form[action="'.url('/settings/roles/'.$role->id).'"]', 'Save Role'); - $resp = $this->put('/settings/roles/' . $role->id, [ + $resp = $this->put('/settings/roles/'.$role->id, [ 'display_name' => $testRoleUpdateName, 'description' => $testRoleDesc, 'mfa_enforced' => 'true', @@ -104,12 +104,12 @@ public function test_role_create_update_delete_flow() ]); // Deleting - $resp = $this->get('/settings/roles/' . $role->id); - $resp->assertElementContains('a[href="' . url("/settings/roles/delete/$role->id") . '"]', 'Delete Role'); + $resp = $this->get('/settings/roles/'.$role->id); + $resp->assertElementContains('a[href="'.url("/settings/roles/delete/$role->id").'"]', 'Delete Role'); $resp = $this->get("/settings/roles/delete/$role->id"); $resp->assertSee($testRoleUpdateName); - $resp->assertElementContains('form[action="' . url("/settings/roles/delete/$role->id") . '"]', 'Confirm'); + $resp->assertElementContains('form[action="'.url("/settings/roles/delete/$role->id").'"]', 'Confirm'); $resp = $this->delete("/settings/roles/delete/$role->id"); $resp->assertRedirect('/settings/roles'); @@ -127,7 +127,7 @@ public function test_admin_role_cannot_be_removed_if_user_last_admin() $viewerRole = $this->getViewer()->roles()->first(); - $editUrl = '/settings/users/' . $adminUser->id; + $editUrl = '/settings/users/'.$adminUser->id; $resp = $this->actingAs($adminUser)->put($editUrl, [ 'name' => $adminUser->name, 'email' => $adminUser->email, @@ -172,7 +172,7 @@ public function test_manage_user_permission() public function test_manage_users_permission_shows_link_in_header_if_does_not_have_settings_manage_permision() { - $usersLink = 'href="' . url('/settings/users') . '"'; + $usersLink = 'href="'.url('/settings/users').'"'; $this->actingAs($this->user)->get('/')->assertDontSee($usersLink, false); $this->giveUserPermissions($this->user, ['users-manage']); $this->actingAs($this->user)->get('/')->assertSee($usersLink, false); @@ -182,7 +182,7 @@ public function test_manage_users_permission_shows_link_in_header_if_does_not_ha public function test_user_cannot_change_email_unless_they_have_manage_users_permission() { - $userProfileUrl = '/settings/users/' . $this->user->id; + $userProfileUrl = '/settings/users/'.$this->user->id; $originalEmail = $this->user->email; $this->actingAs($this->user); @@ -413,7 +413,7 @@ public function test_books_edit_own_permission() $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->createEntityChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-update-own', [ - $ownBook->getUrl() . '/edit', + $ownBook->getUrl().'/edit', ], [ $ownBook->getUrl() => 'Edit', ]); @@ -427,7 +427,7 @@ public function test_books_edit_all_permission() /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-update-all', [ - $otherBook->getUrl() . '/edit', + $otherBook->getUrl().'/edit', ], [ $otherBook->getUrl() => 'Edit', ]); @@ -440,7 +440,7 @@ public function test_books_delete_own_permission() $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->createEntityChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-delete-own', [ - $ownBook->getUrl() . '/delete', + $ownBook->getUrl().'/delete', ], [ $ownBook->getUrl() => 'Delete', ]); @@ -458,7 +458,7 @@ public function test_books_delete_all_permission() /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-delete-all', [ - $otherBook->getUrl() . '/delete', + $otherBook->getUrl().'/delete', ], [ $otherBook->getUrl() => 'Delete', ]); @@ -510,7 +510,7 @@ public function test_chapter_edit_own_permission() $otherChapter = Chapter::query()->first(); $ownChapter = $this->createEntityChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-update-own', [ - $ownChapter->getUrl() . '/edit', + $ownChapter->getUrl().'/edit', ], [ $ownChapter->getUrl() => 'Edit', ]); @@ -524,7 +524,7 @@ public function test_chapter_edit_all_permission() /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->take(1)->get()->first(); $this->checkAccessPermission('chapter-update-all', [ - $otherChapter->getUrl() . '/edit', + $otherChapter->getUrl().'/edit', ], [ $otherChapter->getUrl() => 'Edit', ]); @@ -537,7 +537,7 @@ public function test_chapter_delete_own_permission() $otherChapter = Chapter::query()->first(); $ownChapter = $this->createEntityChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-delete-own', [ - $ownChapter->getUrl() . '/delete', + $ownChapter->getUrl().'/delete', ], [ $ownChapter->getUrl() => 'Delete', ]); @@ -556,7 +556,7 @@ public function test_chapter_delete_all_permission() /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->first(); $this->checkAccessPermission('chapter-delete-all', [ - $otherChapter->getUrl() . '/delete', + $otherChapter->getUrl().'/delete', ], [ $otherChapter->getUrl() => 'Delete', ]); @@ -665,13 +665,13 @@ public function test_page_edit_own_permission() $otherPage = Page::query()->first(); $ownPage = $this->createEntityChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-update-own', [ - $ownPage->getUrl() . '/edit', + $ownPage->getUrl().'/edit', ], [ $ownPage->getUrl() => 'Edit', ]); $this->get($otherPage->getUrl())->assertElementNotContains('.action-buttons', 'Edit'); - $this->get($otherPage->getUrl() . '/edit')->assertRedirect('/'); + $this->get($otherPage->getUrl().'/edit')->assertRedirect('/'); } public function test_page_edit_all_permission() @@ -692,7 +692,7 @@ public function test_page_delete_own_permission() $otherPage = Page::query()->first(); $ownPage = $this->createEntityChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-delete-own', [ - $ownPage->getUrl() . '/delete', + $ownPage->getUrl().'/delete', ], [ $ownPage->getUrl() => 'Delete', ]); @@ -712,7 +712,7 @@ public function test_page_delete_all_permission() $otherPage = Page::query()->first(); $this->checkAccessPermission('page-delete-all', [ - $otherPage->getUrl() . '/delete', + $otherPage->getUrl().'/delete', ], [ $otherPage->getUrl() => 'Delete', ]); @@ -731,9 +731,9 @@ public function test_public_role_visible_in_user_edit_screen() $user = User::query()->first(); $adminRole = Role::getSystemRole('admin'); $publicRole = Role::getSystemRole('public'); - $this->asAdmin()->get('/settings/users/' . $user->id) - ->assertElementExists('[name="roles[' . $adminRole->id . ']"]') - ->assertElementExists('[name="roles[' . $publicRole->id . ']"]'); + $this->asAdmin()->get('/settings/users/'.$user->id) + ->assertElementExists('[name="roles['.$adminRole->id.']"]') + ->assertElementExists('[name="roles['.$publicRole->id.']"]'); } public function test_public_role_visible_in_role_listing() @@ -754,13 +754,13 @@ public function test_public_role_not_deletable() { /** @var Role $publicRole */ $publicRole = Role::getSystemRole('public'); - $resp = $this->asAdmin()->delete('/settings/roles/delete/' . $publicRole->id); + $resp = $this->asAdmin()->delete('/settings/roles/delete/'.$publicRole->id); $resp->assertRedirect('/'); - $this->get('/settings/roles/delete/' . $publicRole->id); - $resp = $this->delete('/settings/roles/delete/' . $publicRole->id); - $resp->assertRedirect('/settings/roles/delete/' . $publicRole->id); - $resp = $this->get('/settings/roles/delete/' . $publicRole->id); + $this->get('/settings/roles/delete/'.$publicRole->id); + $resp = $this->delete('/settings/roles/delete/'.$publicRole->id); + $resp->assertRedirect('/settings/roles/delete/'.$publicRole->id); + $resp = $this->get('/settings/roles/delete/'.$publicRole->id); $resp->assertSee('This role is a system role and cannot be deleted'); } @@ -775,11 +775,11 @@ public function test_image_delete_own_permission() 'updated_by' => $this->user->id, ]); - $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-own']); - $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); + $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } @@ -791,15 +791,15 @@ public function test_image_delete_all_permission() $page = Page::query()->first(); $image = factory(Image::class)->create(['uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id]); - $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-own']); - $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-all']); - $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); + $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } @@ -812,7 +812,7 @@ public function test_role_permission_removal() $viewer = $this->getViewer(); $this->actingAs($viewer)->get($page->getUrl())->assertOk(); - $this->asAdmin()->put('/settings/roles/' . $viewerRole->id, [ + $this->asAdmin()->put('/settings/roles/'.$viewerRole->id, [ 'display_name' => $viewerRole->display_name, 'description' => $viewerRole->description, 'permission' => [], @@ -940,6 +940,6 @@ private function updateComment(Comment $comment): TestResponse private function deleteComment(Comment $comment): TestResponse { - return $this->json('DELETE', '/comment/' . $comment->id); + return $this->json('DELETE', '/comment/'.$comment->id); } } diff --git a/tests/PublicActionTest.php b/tests/PublicActionTest.php index 499c0c9f971..3695be5d8a2 100644 --- a/tests/PublicActionTest.php +++ b/tests/PublicActionTest.php @@ -28,7 +28,7 @@ public function test_app_not_public() public function test_login_link_visible() { $this->setSettings(['app-public' => 'true']); - $this->get('/')->assertElementExists('a[href="' . url('/login') . '"]'); + $this->get('/')->assertElementExists('a[href="'.url('/login').'"]'); } public function test_register_link_visible_when_enabled() @@ -95,12 +95,12 @@ public function test_public_page_creation() $chapter = Chapter::query()->first(); $resp = $this->get($chapter->getUrl()); $resp->assertSee('New Page'); - $resp->assertElementExists('a[href="' . $chapter->getUrl('/create-page') . '"]'); + $resp->assertElementExists('a[href="'.$chapter->getUrl('/create-page').'"]'); $resp = $this->get($chapter->getUrl('/create-page')); $resp->assertSee('Continue'); $resp->assertSee('Page Name'); - $resp->assertElementExists('form[action="' . $chapter->getUrl('/create-guest-page') . '"]'); + $resp->assertElementExists('form[action="'.$chapter->getUrl('/create-guest-page').'"]'); $resp = $this->post($chapter->getUrl('/create-guest-page'), ['name' => 'My guest page']); $resp->assertRedirect($chapter->book->getUrl('/page/my-guest-page/edit')); diff --git a/tests/RecycleBinTest.php b/tests/RecycleBinTest.php index f3e30c0d07d..1716152b56d 100644 --- a/tests/RecycleBinTest.php +++ b/tests/RecycleBinTest.php @@ -66,8 +66,8 @@ public function test_recycle_bin_view() $viewReq->assertElementContains('table.table', $page->name); $viewReq->assertElementContains('table.table', $editor->name); $viewReq->assertElementContains('table.table', $book->name); - $viewReq->assertElementContains('table.table', $book->pages_count . ' Pages'); - $viewReq->assertElementContains('table.table', $book->chapters_count . ' Chapters'); + $viewReq->assertElementContains('table.table', $book->pages_count.' Pages'); + $viewReq->assertElementContains('table.table', $book->chapters_count.' Chapters'); } public function test_recycle_bin_empty() @@ -90,7 +90,7 @@ public function test_recycle_bin_empty() $itemCount = 2 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Deleted ' . $itemCount . ' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Deleted '.$itemCount.' total items from the recycle bin'); } public function test_entity_restore() @@ -111,7 +111,7 @@ public function test_entity_restore() $itemCount = 1 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Restored ' . $itemCount . ' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Restored '.$itemCount.' total items from the recycle bin'); } public function test_permanent_delete() @@ -130,7 +130,7 @@ public function test_permanent_delete() $itemCount = 1 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Deleted ' . $itemCount . ' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Deleted '.$itemCount.' total items from the recycle bin'); } public function test_permanent_delete_for_each_type() @@ -264,6 +264,6 @@ public function test_restore_page_shows_link_to_parent_restore_if_parent_also_de $pageRestoreView = $this->asAdmin()->get("/settings/recycle-bin/{$pageDeletion->id}/restore"); $pageRestoreView->assertSee('The parent of this item has also been deleted.'); - $pageRestoreView->assertElementContains('a[href$="/settings/recycle-bin/' . $bookDeletion->id . '/restore"]', 'Restore Parent'); + $pageRestoreView->assertElementContains('a[href$="/settings/recycle-bin/'.$bookDeletion->id.'/restore"]', 'Restore Parent'); } } diff --git a/tests/SecurityHeaderTest.php b/tests/SecurityHeaderTest.php index 78691badbbc..e10afe9e734 100644 --- a/tests/SecurityHeaderTest.php +++ b/tests/SecurityHeaderTest.php @@ -75,8 +75,8 @@ public function test_script_csp_nonce_matches_nonce_used_in_custom_head() $scriptHeader = $this->getCspHeader($resp, 'script-src'); $nonce = app()->make(CspService::class)->getNonce(); - $this->assertStringContainsString('nonce-' . $nonce, $scriptHeader); - $resp->assertSee('', false); + $this->assertStringContainsString('nonce-'.$nonce, $scriptHeader); + $resp->assertSee('', false); } public function test_script_csp_nonce_changes_per_request() diff --git a/tests/SharedTestHelpers.php b/tests/SharedTestHelpers.php index d96fcb71073..d6b37cb80a4 100644 --- a/tests/SharedTestHelpers.php +++ b/tests/SharedTestHelpers.php @@ -84,7 +84,7 @@ protected function getEditor(): User protected function getViewer(array $attributes = []): User { $user = Role::getRole('viewer')->users()->first(); - if (!empty($attributes)) { + if (! empty($attributes)) { $user->forceFill($attributes)->save(); } @@ -301,7 +301,7 @@ protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck $passed = true; foreach ($mapToInclude as $key => $value) { - if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) { + if (! isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) { $passed = false; } } diff --git a/tests/TestEmailTest.php b/tests/TestEmailTest.php index 0a2091fe3e9..2fbdcfd2845 100644 --- a/tests/TestEmailTest.php +++ b/tests/TestEmailTest.php @@ -13,7 +13,7 @@ public function test_a_send_test_button_shows() $pageView = $this->asAdmin()->get('/settings/maintenance'); $formCssSelector = 'form[action$="/settings/maintenance/send-test-email"]'; $pageView->assertElementExists($formCssSelector); - $pageView->assertElementContains($formCssSelector . ' button', 'Send Test Email'); + $pageView->assertElementContains($formCssSelector.' button', 'Send Test Email'); } public function test_send_test_email_endpoint_sends_email_and_redirects_user_and_shows_notification() @@ -23,7 +23,7 @@ public function test_send_test_email_endpoint_sends_email_and_redirects_user_and $sendReq = $this->actingAs($admin)->post('/settings/maintenance/send-test-email'); $sendReq->assertRedirect('/settings/maintenance#image-cleanup'); - $this->assertSessionHas('success', 'Email sent to ' . $admin->email); + $this->assertSessionHas('success', 'Email sent to '.$admin->email); Notification::assertSentTo($admin, TestEmail::class); } diff --git a/tests/TestResponse.php b/tests/TestResponse.php index 5e2be3ac35c..8957dd279a1 100644 --- a/tests/TestResponse.php +++ b/tests/TestResponse.php @@ -19,7 +19,7 @@ class TestResponse extends BaseTestResponse */ protected function crawler(): Crawler { - if (!is_object($this->crawlerInstance)) { + if (! is_object($this->crawlerInstance)) { $this->crawlerInstance = new Crawler($this->getContent()); } @@ -44,9 +44,9 @@ public function assertElementExists(string $selector) $elements = $this->crawler()->filter($selector); PHPUnit::assertTrue( $elements->count() > 0, - 'Unable to find element matching the selector: ' . PHP_EOL . PHP_EOL . - "[{$selector}]" . PHP_EOL . PHP_EOL . - 'within' . PHP_EOL . PHP_EOL . + 'Unable to find element matching the selector: '.PHP_EOL.PHP_EOL. + "[{$selector}]".PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. "[{$this->getContent()}]." ); @@ -63,9 +63,9 @@ public function assertElementNotExists(string $selector) $elements = $this->crawler()->filter($selector); PHPUnit::assertTrue( $elements->count() === 0, - 'Found elements matching the selector: ' . PHP_EOL . PHP_EOL . - "[{$selector}]" . PHP_EOL . PHP_EOL . - 'within' . PHP_EOL . PHP_EOL . + 'Found elements matching the selector: '.PHP_EOL.PHP_EOL. + "[{$selector}]".PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. "[{$this->getContent()}]." ); @@ -85,7 +85,7 @@ public function assertElementContains(string $selector, string $text, ?int $nthM $matched = false; $pattern = $this->getEscapedPattern($text); - if (!is_null($nthMatch)) { + if (! is_null($nthMatch)) { $elements = $elements->eq($nthMatch - 1); } @@ -99,12 +99,12 @@ public function assertElementContains(string $selector, string $text, ?int $nthM PHPUnit::assertTrue( $matched, - 'Unable to find element of selector: ' . PHP_EOL . PHP_EOL . - ($nthMatch ? ("at position {$nthMatch}" . PHP_EOL . PHP_EOL) : '') . - "[{$selector}]" . PHP_EOL . PHP_EOL . - 'containing text' . PHP_EOL . PHP_EOL . - "[{$text}]" . PHP_EOL . PHP_EOL . - 'within' . PHP_EOL . PHP_EOL . + 'Unable to find element of selector: '.PHP_EOL.PHP_EOL. + ($nthMatch ? ("at position {$nthMatch}".PHP_EOL.PHP_EOL) : ''). + "[{$selector}]".PHP_EOL.PHP_EOL. + 'containing text'.PHP_EOL.PHP_EOL. + "[{$text}]".PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. "[{$this->getContent()}]." ); @@ -124,7 +124,7 @@ public function assertElementNotContains(string $selector, string $text, ?int $n $matched = false; $pattern = $this->getEscapedPattern($text); - if (!is_null($nthMatch)) { + if (! is_null($nthMatch)) { $elements = $elements->eq($nthMatch - 1); } @@ -137,13 +137,13 @@ public function assertElementNotContains(string $selector, string $text, ?int $n } PHPUnit::assertTrue( - !$matched, - 'Found element of selector: ' . PHP_EOL . PHP_EOL . - ($nthMatch ? ("at position {$nthMatch}" . PHP_EOL . PHP_EOL) : '') . - "[{$selector}]" . PHP_EOL . PHP_EOL . - 'containing text' . PHP_EOL . PHP_EOL . - "[{$text}]" . PHP_EOL . PHP_EOL . - 'within' . PHP_EOL . PHP_EOL . + ! $matched, + 'Found element of selector: '.PHP_EOL.PHP_EOL. + ($nthMatch ? ("at position {$nthMatch}".PHP_EOL.PHP_EOL) : ''). + "[{$selector}]".PHP_EOL.PHP_EOL. + 'containing text'.PHP_EOL.PHP_EOL. + "[{$text}]".PHP_EOL.PHP_EOL. + 'within'.PHP_EOL.PHP_EOL. "[{$this->getContent()}]." ); diff --git a/tests/ThemeTest.php b/tests/ThemeTest.php index 2cab765ae43..aaec9232385 100644 --- a/tests/ThemeTest.php +++ b/tests/ThemeTest.php @@ -26,7 +26,7 @@ public function test_translation_text_can_be_overridden_via_theme() $customTranslations = ' \'Sandwiches\']; '; - file_put_contents($translationPath . '/entities.php', $customTranslations); + file_put_contents($translationPath.'/entities.php', $customTranslations); $homeRequest = $this->actingAs($this->getViewer())->get('/'); $homeRequest->assertElementContains('header nav', 'Sandwiches'); @@ -209,7 +209,7 @@ function ($driver) { protected function usingThemeFolder(callable $callback) { // Create a folder and configure a theme - $themeFolderName = 'testing_theme_' . rtrim(base64_encode(time()), '='); + $themeFolderName = 'testing_theme_'.rtrim(base64_encode(time()), '='); config()->set('view.theme', $themeFolderName); $themeFolderPath = theme_path(''); File::makeDirectory($themeFolderPath); diff --git a/tests/Unit/OidcIdTokenTest.php b/tests/Unit/OidcIdTokenTest.php index ad91eecd8b2..d89bcdf7cb7 100644 --- a/tests/Unit/OidcIdTokenTest.php +++ b/tests/Unit/OidcIdTokenTest.php @@ -46,9 +46,9 @@ public function test_token_structure_error_cases() ['Could not parse out a valid header within the provided token', ''], ['Could not parse out a valid header within the provided token', 'cat'], ['Could not parse out a valid payload within the provided token', $idTokenExploded[0]], - ['Could not parse out a valid payload within the provided token', $idTokenExploded[0] . '.' . 'dog'], - ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1]], - ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1] . '.' . '@$%'], + ['Could not parse out a valid payload within the provided token', $idTokenExploded[0].'.'.'dog'], + ['Could not parse out a valid signature within the provided token', $idTokenExploded[0].'.'.$idTokenExploded[1]], + ['Could not parse out a valid signature within the provided token', $idTokenExploded[0].'.'.$idTokenExploded[1].'.'.'@$%'], ]; foreach ($messagesAndTokenValues as [$message, $tokenValue]) { @@ -154,7 +154,7 @@ public function test_token_claim_error_cases() public function test_keys_can_be_a_local_file_reference_to_pem_key() { $file = tmpfile(); - $testFilePath = 'file://' . stream_get_meta_data($file)['uri']; + $testFilePath = 'file://'.stream_get_meta_data($file)['uri']; file_put_contents($testFilePath, OidcJwtHelper::publicPemKey()); $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $testFilePath, diff --git a/tests/Uploads/AttachmentTest.php b/tests/Uploads/AttachmentTest.php index 588b7054ac2..f92167ea279 100644 --- a/tests/Uploads/AttachmentTest.php +++ b/tests/Uploads/AttachmentTest.php @@ -160,7 +160,7 @@ public function test_attachment_updating() $this->asAdmin(); $attachment = $this->createAttachment($page); - $update = $this->call('PUT', 'attachments/' . $attachment->id, [ + $update = $this->call('PUT', 'attachments/'.$attachment->id, [ 'attachment_edit_name' => 'My new attachment name', 'attachment_edit_url' => 'https://test.example.com', ]); @@ -187,7 +187,7 @@ public function test_file_deletion() $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); - $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); + $this->assertTrue(file_exists($filePath), 'File at path '.$filePath.' does not exist'); $attachment = Attachment::first(); $this->delete($attachment->getUrl()); @@ -195,7 +195,7 @@ public function test_file_deletion() $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); - $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); + $this->assertFalse(file_exists($filePath), 'File at path '.$filePath.' was not deleted as expected'); $this->deleteUploads(); } @@ -210,7 +210,7 @@ public function test_attachment_deletion_on_page_deletion() $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); - $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); + $this->assertTrue(file_exists($filePath), 'File at path '.$filePath.' does not exist'); $this->assertDatabaseHas('attachments', [ 'name' => $fileName, ]); @@ -221,7 +221,7 @@ public function test_attachment_deletion_on_page_deletion() $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); - $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); + $this->assertFalse(file_exists($filePath), 'File at path '.$filePath.' was not deleted as expected'); $this->deleteUploads(); } @@ -280,7 +280,7 @@ public function test_data_and_js_links_cannot_be_attached_to_a_page() $attachment = $this->createAttachment($page); foreach ($badLinks as $badLink) { - $linkReq = $this->put('attachments/' . $attachment->id, [ + $linkReq = $this->put('attachments/'.$attachment->id, [ 'attachment_edit_url' => $badLink, 'attachment_edit_name' => 'Example Attachment Link', ]); diff --git a/tests/Uploads/AvatarTest.php b/tests/Uploads/AvatarTest.php index cf568d07cf6..ea80bfe8e8b 100644 --- a/tests/Uploads/AvatarTest.php +++ b/tests/Uploads/AvatarTest.php @@ -43,7 +43,7 @@ public function test_gravatar_fetched_on_user_create() 'services.disable_services' => false, ]); $user = factory(User::class)->make(); - $this->assertImageFetchFrom('https://www.gravatar.com/avatar/' . md5(strtolower($user->email)) . '?s=500&d=identicon'); + $this->assertImageFetchFrom('https://www.gravatar.com/avatar/'.md5(strtolower($user->email)).'?s=500&d=identicon'); $user = $this->createUserRequest($user); $this->assertDatabaseHas('images', [ @@ -61,7 +61,7 @@ public function test_custom_url_used_if_set() ]); $user = factory(User::class)->make(); - $url = 'https://example.com/' . urlencode(strtolower($user->email)) . '/' . md5(strtolower($user->email)) . '/500'; + $url = 'https://example.com/'.urlencode(strtolower($user->email)).'/'.md5(strtolower($user->email)).'/500'; $this->assertImageFetchFrom($url); $user = $this->createUserRequest($user); diff --git a/tests/Uploads/DrawioTest.php b/tests/Uploads/DrawioTest.php index 1fc3d104928..df4f98fb48f 100644 --- a/tests/Uploads/DrawioTest.php +++ b/tests/Uploads/DrawioTest.php @@ -47,7 +47,7 @@ public function test_drawing_base64_upload() ]); $image = Image::where('type', '=', 'drawio')->first(); - $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: ' . public_path($image->path)); + $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: '.public_path($image->path)); $testImageData = file_get_contents($this->getTestImageFilePath()); $uploadedImageData = file_get_contents(public_path($image->path)); diff --git a/tests/Uploads/ImageTest.php b/tests/Uploads/ImageTest.php index 69b6dc90e96..e2bea870144 100644 --- a/tests/Uploads/ImageTest.php +++ b/tests/Uploads/ImageTest.php @@ -22,12 +22,12 @@ public function test_image_upload() $imgDetails = $this->uploadGalleryImage($page); $relPath = $imgDetails['path']; - $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); + $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: '.public_path($relPath)); $this->deleteImage($relPath); $this->assertDatabaseHas('images', [ - 'url' => $this->baseUrl . $relPath, + 'url' => $this->baseUrl.$relPath, 'type' => 'gallery', 'uploaded_to' => $page->id, 'path' => $relPath, @@ -48,7 +48,7 @@ public function test_image_display_thumbnail_generation_does_not_increase_image_ $imgDetails = $this->uploadGalleryImage($page, 'compressed.png'); $relPath = $imgDetails['path']; - $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); + $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: '.public_path($relPath)); $displayImage = $imgDetails['response']->thumbs->display; $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3)); @@ -70,7 +70,7 @@ public function test_image_edit() $image = Image::query()->first(); $newName = Str::random(); - $update = $this->put('/images/' . $image->id, ['name' => $newName]); + $update = $this->put('/images/'.$image->id, ['name' => $newName]); $update->assertSuccessful(); $update->assertSee($newName); @@ -116,10 +116,10 @@ public function test_image_usage() $imgDetails = $this->uploadGalleryImage($page); $image = Image::query()->first(); - $page->html = ''; + $page->html = ''; $page->save(); - $usage = $this->get('/images/edit/' . $image->id . '?delete=true'); + $usage = $this->get('/images/edit/'.$image->id.'?delete=true'); $usage->assertSuccessful(); $usage->assertSeeText($page->name); $usage->assertSee($page->getUrl()); @@ -174,7 +174,7 @@ public function test_files_with_double_extensions_will_get_sanitized() $fileName = 'bad.phtml.png'; $relPath = $this->getTestImagePath('gallery', $fileName); - $expectedRelPath = dirname($relPath) . '/bad-phtml.png'; + $expectedRelPath = dirname($relPath).'/bad-phtml.png'; $this->deleteImage($expectedRelPath); $file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName); @@ -229,12 +229,12 @@ public function test_secure_images_uploads_to_correct_place() $this->asEditor(); $galleryFile = $this->getTestImage('my-secure-test-upload.png'); $page = Page::query()->first(); - $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); + $expectedPath = storage_path('uploads/images/gallery/'.date('Y-m').'/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); - $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); + $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '.$expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); @@ -247,7 +247,7 @@ public function test_secure_images_included_in_exports() $this->asEditor(); $galleryFile = $this->getTestImage('my-secure-test-upload.png'); $page = Page::query()->first(); - $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); + $expectedPath = storage_path('uploads/images/gallery/'.date('Y-m').'/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $imageUrl = json_decode($upload->getContent(), true)['url']; @@ -269,12 +269,12 @@ public function test_system_images_remain_public() config()->set('filesystems.images', 'local_secure'); $this->asAdmin(); $galleryFile = $this->getTestImage('my-system-test-upload.png'); - $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png'); + $expectedPath = public_path('uploads/images/system/'.date('Y-m').'/my-system-test-upload.png'); $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []); $upload->assertRedirect('/settings'); - $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); + $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '.$expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); @@ -292,11 +292,11 @@ public function test_image_delete() $this->uploadImage($imageName, $page->id); $image = Image::first(); - $delete = $this->delete('/images/' . $image->id); + $delete = $this->delete('/images/'.$image->id); $delete->assertStatus(200); $this->assertDatabaseMissing('images', [ - 'url' => $this->baseUrl . $relPath, + 'url' => $this->baseUrl.$relPath, 'type' => 'gallery', ]); @@ -318,12 +318,12 @@ public function test_image_delete_does_not_delete_similar_images() $image = Image::first(); $folder = public_path(dirname($relPath)); - $imageCount = count(glob($folder . '/*')); + $imageCount = count(glob($folder.'/*')); - $delete = $this->delete('/images/' . $image->id); + $delete = $this->delete('/images/'.$image->id); $delete->assertStatus(200); - $newCount = count(glob($folder . '/*')); + $newCount = count(glob($folder.'/*')); $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted'); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected'); } @@ -344,7 +344,7 @@ public function test_user_image_upload() $this->actingAs($admin); $file = $this->getTestProfileImage(); - $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []); + $this->call('PUT', '/settings/users/'.$editor->id, [], [], ['profile_image' => $file], []); $this->assertDatabaseHas('images', [ 'type' => 'user', @@ -359,7 +359,7 @@ public function test_user_images_deleted_on_user_deletion() $this->actingAs($editor); $file = $this->getTestProfileImage(); - $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []); + $this->call('PUT', '/settings/users/'.$editor->id, [], [], ['profile_image' => $file], []); $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get(); $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count'); @@ -399,7 +399,7 @@ public function test_deleted_unused_images() $pageRepo = app(PageRepo::class); $pageRepo->update($page, [ 'name' => $page->name, - 'html' => $page->html . "url}\">", + 'html' => $page->html."url}\">", 'summary' => '', ]); diff --git a/tests/Uploads/UsesImages.php b/tests/Uploads/UsesImages.php index 789c967c677..3e6875b1a76 100644 --- a/tests/Uploads/UsesImages.php +++ b/tests/Uploads/UsesImages.php @@ -16,7 +16,7 @@ protected function getTestImageFilePath(?string $fileName = null): string $fileName = 'test-image.png'; } - return base_path('tests/test-data/' . $fileName); + return base_path('tests/test-data/'.$fileName); } /** @@ -58,7 +58,7 @@ protected function getTestImageContent() */ protected function getTestImagePath(string $type, string $fileName): string { - return '/uploads/images/' . $type . '/' . date('Y-m') . '/' . $fileName; + return '/uploads/images/'.$type.'/'.date('Y-m').'/'.$fileName; } /** diff --git a/tests/User/UserApiTokenTest.php b/tests/User/UserApiTokenTest.php index d3404b72ef1..48e7bddb720 100644 --- a/tests/User/UserApiTokenTest.php +++ b/tests/User/UserApiTokenTest.php @@ -50,7 +50,7 @@ public function test_create_api_token() $resp = $this->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp->assertRedirect($editor->getEditUrl('/api-tokens/' . $token->id)); + $resp->assertRedirect($editor->getEditUrl('/api-tokens/'.$token->id)); $this->assertDatabaseHas('api_tokens', [ 'user_id' => $editor->id, 'name' => $this->testTokenData['name'], @@ -58,8 +58,8 @@ public function test_create_api_token() ]); // Check secret token - $this->assertSessionHas('api-token-secret:' . $token->id); - $secret = session('api-token-secret:' . $token->id); + $this->assertSessionHas('api-token-secret:'.$token->id); + $secret = session('api-token-secret:'.$token->id); $this->assertDatabaseMissing('api_tokens', [ 'secret' => $secret, ]); @@ -106,9 +106,9 @@ public function test_secret_shown_once_after_creation() $resp->assertSeeText('Token Secret'); $token = ApiToken::query()->latest()->first(); - $this->assertNull(session('api-token-secret:' . $token->id)); + $this->assertNull(session('api-token-secret:'.$token->id)); - $resp = $this->get($editor->getEditUrl('/api-tokens/' . $token->id)); + $resp = $this->get($editor->getEditUrl('/api-tokens/'.$token->id)); $resp->assertDontSeeText('Client Secret'); } @@ -122,8 +122,8 @@ public function test_token_update() 'expires_at' => '2011-01-01', ]; - $resp = $this->put($editor->getEditUrl('/api-tokens/' . $token->id), $updateData); - $resp->assertRedirect($editor->getEditUrl('/api-tokens/' . $token->id)); + $resp = $this->put($editor->getEditUrl('/api-tokens/'.$token->id), $updateData); + $resp->assertRedirect($editor->getEditUrl('/api-tokens/'.$token->id)); $this->assertDatabaseHas('api_tokens', array_merge($updateData, ['id' => $token->id])); $this->assertSessionHas('success'); @@ -136,7 +136,7 @@ public function test_token_update_with_blank_expiry_sets_to_hundred_years_away() $this->asAdmin()->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp = $this->put($editor->getEditUrl('/api-tokens/' . $token->id), [ + $resp = $this->put($editor->getEditUrl('/api-tokens/'.$token->id), [ 'name' => 'My updated token', 'expires_at' => '', ]); @@ -156,12 +156,12 @@ public function test_token_delete() $this->asAdmin()->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $tokenUrl = $editor->getEditUrl('/api-tokens/' . $token->id); + $tokenUrl = $editor->getEditUrl('/api-tokens/'.$token->id); - $resp = $this->get($tokenUrl . '/delete'); + $resp = $this->get($tokenUrl.'/delete'); $resp->assertSeeText('Delete Token'); $resp->assertSeeText($token->name); - $resp->assertElementExists('form[action="' . $tokenUrl . '"]'); + $resp->assertElementExists('form[action="'.$tokenUrl.'"]'); $resp = $this->delete($tokenUrl); $resp->assertRedirect($editor->getEditUrl('#api_tokens')); @@ -178,11 +178,11 @@ public function test_user_manage_can_delete_token_without_api_permission_themsel $this->asAdmin()->post($viewer->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp = $this->actingAs($editor)->get($viewer->getEditUrl('/api-tokens/' . $token->id)); + $resp = $this->actingAs($editor)->get($viewer->getEditUrl('/api-tokens/'.$token->id)); $resp->assertStatus(200); $resp->assertSeeText('Delete Token'); - $resp = $this->actingAs($editor)->delete($viewer->getEditUrl('/api-tokens/' . $token->id)); + $resp = $this->actingAs($editor)->delete($viewer->getEditUrl('/api-tokens/'.$token->id)); $resp->assertRedirect($viewer->getEditUrl('#api_tokens')); $this->assertDatabaseMissing('api_tokens', ['id' => $token->id]); } diff --git a/tests/User/UserManagementTest.php b/tests/User/UserManagementTest.php index ed2fb5f0480..6328fa9ee66 100644 --- a/tests/User/UserManagementTest.php +++ b/tests/User/UserManagementTest.php @@ -19,17 +19,17 @@ public function test_user_creation() $adminRole = Role::getRole('admin'); $resp = $this->asAdmin()->get('/settings/users'); - $resp->assertElementContains('a[href="' . url('/settings/users/create') . '"]', 'Add New User'); + $resp->assertElementContains('a[href="'.url('/settings/users/create').'"]', 'Add New User'); $this->get('/settings/users/create') - ->assertElementContains('form[action="' . url('/settings/users/create') . '"]', 'Save'); + ->assertElementContains('form[action="'.url('/settings/users/create').'"]', 'Save'); $resp = $this->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'password' => $user->password, 'password-confirm' => $user->password, - 'roles[' . $adminRole->id . ']' => 'true', + 'roles['.$adminRole->id.']' => 'true', ]); $resp->assertRedirect('/settings/users'); @@ -47,7 +47,7 @@ public function test_user_updating() $user = $this->getNormalUser(); $password = $user->password; - $resp = $this->asAdmin()->get('/settings/users/' . $user->id); + $resp = $this->asAdmin()->get('/settings/users/'.$user->id); $resp->assertSee($user->email); $this->put($user->getEditUrl(), [ @@ -64,7 +64,7 @@ public function test_user_updating() public function test_user_password_update() { $user = $this->getNormalUser(); - $userProfilePage = '/settings/users/' . $user->id; + $userProfilePage = '/settings/users/'.$user->id; $this->asAdmin()->get($userProfilePage); $this->put($userProfilePage, [ @@ -100,10 +100,10 @@ public function test_user_cannot_be_deleted_if_last_admin() /** @var User $user */ $user = $adminRole->users->first(); - $resp = $this->asAdmin()->delete('/settings/users/' . $user->id); - $resp->assertRedirect('/settings/users/' . $user->id); + $resp = $this->asAdmin()->delete('/settings/users/'.$user->id); + $resp->assertRedirect('/settings/users/'.$user->id); - $resp = $this->get('/settings/users/' . $user->id); + $resp = $this->get('/settings/users/'.$user->id); $resp->assertSee('You cannot delete the only admin'); $this->assertDatabaseHas('users', ['id' => $user->id]); @@ -146,7 +146,7 @@ public function test_delete_with_new_owner_id_changes_ownership() public function test_guest_profile_shows_limited_form() { $guest = User::getDefault(); - $resp = $this->asAdmin()->get('/settings/users/' . $guest->id); + $resp = $this->asAdmin()->get('/settings/users/'.$guest->id); $resp->assertSee('Guest'); $resp->assertElementNotExists('#password'); } @@ -154,13 +154,13 @@ public function test_guest_profile_shows_limited_form() public function test_guest_profile_cannot_be_deleted() { $guestUser = User::getDefault(); - $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete'); + $resp = $this->asAdmin()->get('/settings/users/'.$guestUser->id.'/delete'); $resp->assertSee('Delete User'); $resp->assertSee('Guest'); - $resp->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm'); + $resp->assertElementContains('form[action$="/settings/users/'.$guestUser->id.'"] button', 'Confirm'); - $resp = $this->delete('/settings/users/' . $guestUser->id); - $resp->assertRedirect('/settings/users/' . $guestUser->id); + $resp = $this->delete('/settings/users/'.$guestUser->id); + $resp->assertRedirect('/settings/users/'.$guestUser->id); $resp = $this->followRedirects($resp); $resp->assertSee('cannot delete the guest user'); } diff --git a/tests/User/UserPreferencesTest.php b/tests/User/UserPreferencesTest.php index b39c2c47c84..651bee26d23 100644 --- a/tests/User/UserPreferencesTest.php +++ b/tests/User/UserPreferencesTest.php @@ -12,18 +12,18 @@ public function test_update_sort_preference() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/books', [ + $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/books', [ 'sort' => 'created_at', 'order' => 'desc', ]); $updateRequest->assertStatus(302); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:' . $editor->id . ':books_sort', + 'setting_key' => 'user:'.$editor->id.':books_sort', 'value' => 'created_at', ]); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:' . $editor->id . ':books_sort_order', + 'setting_key' => 'user:'.$editor->id.':books_sort_order', 'value' => 'desc', ]); $this->assertEquals('created_at', setting()->getForCurrentUser('books_sort')); @@ -35,7 +35,7 @@ public function test_update_sort_preference_defaults() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/bookshelves', [ + $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/bookshelves', [ 'sort' => 'cat', 'order' => 'dog', ]); @@ -50,7 +50,7 @@ public function test_update_sort_bad_entity_type_handled() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/dogs', [ + $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/dogs', [ 'sort' => 'name', 'order' => 'asc', ]); @@ -65,16 +65,16 @@ public function test_update_expansion_preference() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/' . $editor->id . '/update-expansion-preference/home-details', ['expand' => 'true']); + $updateRequest = $this->patch('/settings/users/'.$editor->id.'/update-expansion-preference/home-details', ['expand' => 'true']); $updateRequest->assertStatus(204); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:' . $editor->id . ':section_expansion#home-details', + 'setting_key' => 'user:'.$editor->id.':section_expansion#home-details', 'value' => 'true', ]); $this->assertEquals(true, setting()->getForCurrentUser('section_expansion#home-details')); - $invalidKeyRequest = $this->patch('/settings/users/' . $editor->id . '/update-expansion-preference/my-home-details', ['expand' => 'true']); + $invalidKeyRequest = $this->patch('/settings/users/'.$editor->id.'/update-expansion-preference/my-home-details', ['expand' => 'true']); $invalidKeyRequest->assertStatus(500); } diff --git a/tests/User/UserProfileTest.php b/tests/User/UserProfileTest.php index 3942efa8e3d..09469c847c1 100644 --- a/tests/User/UserProfileTest.php +++ b/tests/User/UserProfileTest.php @@ -23,7 +23,7 @@ public function setUp(): void public function test_profile_page_shows_name() { $this->asAdmin() - ->get('/user/' . $this->user->slug) + ->get('/user/'.$this->user->slug) ->assertSee($this->user->name); } @@ -31,7 +31,7 @@ public function test_profile_page_shows_recent_entities() { $content = $this->createEntityChainBelongingToUser($this->user, $this->user); - $resp = $this->asAdmin()->get('/user/' . $this->user->slug); + $resp = $this->asAdmin()->get('/user/'.$this->user->slug); // Check the recently created page is shown $resp->assertSee($content['page']->name); // Check the recently created chapter is shown @@ -44,7 +44,7 @@ public function test_profile_page_shows_created_content_counts() { $newUser = factory(User::class)->create(); - $this->asAdmin()->get('/user/' . $newUser->slug) + $this->asAdmin()->get('/user/'.$newUser->slug) ->assertSee($newUser->name) ->assertElementContains('#content-counts', '0 Books') ->assertElementContains('#content-counts', '0 Chapters') @@ -52,7 +52,7 @@ public function test_profile_page_shows_created_content_counts() $this->createEntityChainBelongingToUser($newUser, $newUser); - $this->asAdmin()->get('/user/' . $newUser->slug) + $this->asAdmin()->get('/user/'.$newUser->slug) ->assertSee($newUser->name) ->assertElementContains('#content-counts', '1 Book') ->assertElementContains('#content-counts', '1 Chapter') @@ -67,7 +67,7 @@ public function test_profile_page_shows_recent_activity() Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); Activity::addForEntity($entities['page'], ActivityType::PAGE_CREATE); - $this->asAdmin()->get('/user/' . $newUser->slug) + $this->asAdmin()->get('/user/'.$newUser->slug) ->assertElementContains('#recent-user-activity', 'updated book') ->assertElementContains('#recent-user-activity', 'created page') ->assertElementContains('#recent-user-activity', $entities['page']->name); @@ -81,7 +81,7 @@ public function test_user_activity_has_link_leading_to_profile() Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); Activity::addForEntity($entities['page'], ActivityType::PAGE_CREATE); - $linkSelector = '#recent-activity a[href$="/user/' . $newUser->slug . '"]'; + $linkSelector = '#recent-activity a[href$="/user/'.$newUser->slug.'"]'; $this->asAdmin()->get('/') ->assertElementContains($linkSelector, $newUser->name); } @@ -89,17 +89,17 @@ public function test_user_activity_has_link_leading_to_profile() public function test_profile_has_search_links_in_created_entity_lists() { $user = $this->getEditor(); - $resp = $this->actingAs($this->getAdmin())->get('/user/' . $user->slug); + $resp = $this->actingAs($this->getAdmin())->get('/user/'.$user->slug); $expectedLinks = [ - '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Apage%7D', - '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Achapter%7D', - '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abook%7D', - '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abookshelf%7D', + '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Apage%7D', + '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Achapter%7D', + '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Abook%7D', + '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Abookshelf%7D', ]; foreach ($expectedLinks as $link) { - $resp->assertElementContains('[href$="' . $link . '"]', 'View All'); + $resp->assertElementContains('[href$="'.$link.'"]', 'View All'); } } } From ad2c74995dab0e14b0b91cbea01f65a274ac4bf0 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:53 +0000 Subject: [PATCH 02/19] Shift exception handler --- app/Exceptions/Handler.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 63b5cfc5ae3..3b4ad4a4da5 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -28,6 +28,7 @@ class Handler extends ExceptionHandler * @var array */ protected $dontFlash = [ + 'current_password', 'password', 'password_confirmation', ]; From 6950e6db3a56d746666d59330ff0c63312884b3c Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:55 +0000 Subject: [PATCH 03/19] Shift HTTP kernel and middleware --- app/Http/Kernel.php | 2 +- ...intenanceMode.php => PreventRequestsDuringMaintenance.php} | 4 ++-- app/Http/Middleware/TrustProxies.php | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) rename app/Http/Middleware/{CheckForMaintenanceMode.php => PreventRequestsDuringMaintenance.php} (58%) diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 7a09493afc8..91dbdd9634c 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -11,7 +11,7 @@ class Kernel extends HttpKernel * These middleware are run during every request to your application. */ protected $middleware = [ - \BookStack\Http\Middleware\CheckForMaintenanceMode::class, + \BookStack\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \BookStack\Http\Middleware\TrimStrings::class, \BookStack\Http\Middleware\TrustProxies::class, diff --git a/app/Http/Middleware/CheckForMaintenanceMode.php b/app/Http/Middleware/PreventRequestsDuringMaintenance.php similarity index 58% rename from app/Http/Middleware/CheckForMaintenanceMode.php rename to app/Http/Middleware/PreventRequestsDuringMaintenance.php index 0c76838367e..dfb9592e106 100644 --- a/app/Http/Middleware/CheckForMaintenanceMode.php +++ b/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -2,9 +2,9 @@ namespace BookStack\Http\Middleware; -use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware; +use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware; -class CheckForMaintenanceMode extends Middleware +class PreventRequestsDuringMaintenance extends Middleware { /** * The URIs that should be reachable while maintenance mode is enabled. diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 3f8b32eb2cb..0fe0247b829 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -3,7 +3,7 @@ namespace BookStack\Http\Middleware; use Closure; -use Fideloper\Proxy\TrustProxies as Middleware; +use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; class TrustProxies extends Middleware @@ -20,7 +20,7 @@ class TrustProxies extends Middleware * * @var int */ - protected $headers = Request::HEADER_X_FORWARDED_ALL; + protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB; /** * Handle the request, Set the correct user-configured proxy information. From b5db904db93f3eae91de2643d0eba3bcba812e40 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:56 +0000 Subject: [PATCH 04/19] Shift service providers --- app/Providers/EventServiceProvider.php | 1 - app/Providers/RouteServiceProvider.php | 33 +++++++++++++++++--------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index a826185d82d..659843ce33b 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -30,6 +30,5 @@ class EventServiceProvider extends ServiceProvider */ public function boot() { - parent::boot(); } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index e57aad5b2d5..8b9bea52891 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -2,6 +2,9 @@ namespace BookStack\Providers; +use Illuminate\Support\Facades\RateLimiter; +use Illuminate\Http\Request; +use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Route; @@ -23,20 +26,16 @@ class RouteServiceProvider extends ServiceProvider */ public function boot() { - parent::boot(); - } + $this->configureRateLimiting(); - /** - * Define the routes for the application. - * - * @return void - */ - public function map() - { - $this->mapWebRoutes(); - $this->mapApiRoutes(); + $this->routes(function () { + $this->mapWebRoutes(); + $this->mapApiRoutes(); + }); } + + /** * Define the "web" routes for the application. * @@ -71,4 +70,16 @@ protected function mapApiRoutes() require base_path('routes/api.php'); }); } + + /** + * Configure the rate limiters for the application. + * + * @return void + */ + protected function configureRateLimiting() + { + RateLimiter::for('api', function (Request $request) { + return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); + }); + } } From eb6a2c728e010000a5d4496ee70953c7fa370738 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:56 +0000 Subject: [PATCH 05/19] Convert options array to fluent methods Laravel 8 adopts the tuple syntax for controller actions. Since the old options array is incompatible with this syntax, Shift converted them to use modern, fluent methods. --- routes/web.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/routes/web.php b/routes/web.php index a5f35fb8af4..8ddd409b768 100644 --- a/routes/web.php +++ b/routes/web.php @@ -4,7 +4,7 @@ Route::get('/robots.txt', 'HomeController@robots'); // Authenticated routes... -Route::group(['middleware' => 'auth'], function () { +Route::middleware('auth')->group(function () { // Secure images routing Route::get('/uploads/images/{path}', 'Images\ImageController@showImage') @@ -17,7 +17,7 @@ // Shelves Route::get('/create-shelf', 'BookshelfController@create'); - Route::group(['prefix' => 'shelves'], function () { + Route::prefix('shelves')->group(function () { Route::get('/', 'BookshelfController@index'); Route::post('/', 'BookshelfController@store'); Route::get('/{slug}/edit', 'BookshelfController@edit'); @@ -34,7 +34,7 @@ }); Route::get('/create-book', 'BookController@create'); - Route::group(['prefix' => 'books'], function () { + Route::prefix('books')->group(function () { // Books Route::get('/', 'BookController@index'); @@ -135,7 +135,7 @@ Route::delete('/ajax/page/{id}', 'PageController@ajaxDestroy'); // Tag routes (AJAX) - Route::group(['prefix' => 'ajax/tags'], function () { + Route::prefix('ajax/tags')->group(function () { Route::get('/suggest/names', 'TagController@getNameSuggestions'); Route::get('/suggest/values', 'TagController@getValueSuggestions'); }); @@ -174,7 +174,7 @@ Route::get('/custom-head-content', 'HomeController@customHeadContent'); // Settings - Route::group(['prefix' => 'settings'], function () { + Route::prefix('settings')->group(function () { Route::get('/', 'SettingController@index')->name('settings'); Route::post('/', 'SettingController@update'); @@ -229,14 +229,14 @@ }); // MFA routes -Route::group(['middleware' => 'mfa-setup'], function () { +Route::middleware('mfa-setup')->group(function () { Route::get('/mfa/setup', 'Auth\MfaController@setup'); Route::get('/mfa/totp/generate', 'Auth\MfaTotpController@generate'); Route::post('/mfa/totp/confirm', 'Auth\MfaTotpController@confirm'); Route::get('/mfa/backup_codes/generate', 'Auth\MfaBackupCodesController@generate'); Route::post('/mfa/backup_codes/confirm', 'Auth\MfaBackupCodesController@confirm'); }); -Route::group(['middleware' => 'guest'], function () { +Route::middleware('guest')->group(function () { Route::get('/mfa/verify', 'Auth\MfaController@verify'); Route::post('/mfa/totp/verify', 'Auth\MfaTotpController@verify'); Route::post('/mfa/backup_codes/verify', 'Auth\MfaBackupCodesController@verify'); From 7dbdacaaf55cb1cba199ddd9068f843b436c26dd Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:56 +0000 Subject: [PATCH 06/19] Shift to class based routes --- app/Providers/RouteServiceProvider.php | 1 - routes/api.php | 103 +++--- routes/web.php | 423 +++++++++++++------------ 3 files changed, 284 insertions(+), 243 deletions(-) diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 8b9bea52891..e1d45082fd0 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -17,7 +17,6 @@ class RouteServiceProvider extends ServiceProvider * * @var string */ - protected $namespace = 'BookStack\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. diff --git a/routes/api.php b/routes/api.php index 49521bb8919..9742f9f49c3 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,53 +1,64 @@ group(function () { // Secure images routing - Route::get('/uploads/images/{path}', 'Images\ImageController@showImage') + Route::get('/uploads/images/{path}', [Images\ImageController::class, 'showImage']) ->where('path', '.*$'); // API docs routes - Route::get('/api/docs', 'Api\ApiDocsController@display'); + Route::get('/api/docs', [Api\ApiDocsController::class, 'display']); - Route::get('/pages/recently-updated', 'PageController@showRecentlyUpdated'); + Route::get('/pages/recently-updated', [PageController::class, 'showRecentlyUpdated']); // Shelves - Route::get('/create-shelf', 'BookshelfController@create'); + Route::get('/create-shelf', [BookshelfController::class, 'create']); Route::prefix('shelves')->group(function () { - Route::get('/', 'BookshelfController@index'); - Route::post('/', 'BookshelfController@store'); - Route::get('/{slug}/edit', 'BookshelfController@edit'); - Route::get('/{slug}/delete', 'BookshelfController@showDelete'); - Route::get('/{slug}', 'BookshelfController@show'); - Route::put('/{slug}', 'BookshelfController@update'); - Route::delete('/{slug}', 'BookshelfController@destroy'); - Route::get('/{slug}/permissions', 'BookshelfController@showPermissions'); - Route::put('/{slug}/permissions', 'BookshelfController@permissions'); - Route::post('/{slug}/copy-permissions', 'BookshelfController@copyPermissions'); - - Route::get('/{shelfSlug}/create-book', 'BookController@create'); - Route::post('/{shelfSlug}/create-book', 'BookController@store'); + Route::get('/', [BookshelfController::class, 'index']); + Route::post('/', [BookshelfController::class, 'store']); + Route::get('/{slug}/edit', [BookshelfController::class, 'edit']); + Route::get('/{slug}/delete', [BookshelfController::class, 'showDelete']); + Route::get('/{slug}', [BookshelfController::class, 'show']); + Route::put('/{slug}', [BookshelfController::class, 'update']); + Route::delete('/{slug}', [BookshelfController::class, 'destroy']); + Route::get('/{slug}/permissions', [BookshelfController::class, 'showPermissions']); + Route::put('/{slug}/permissions', [BookshelfController::class, 'permissions']); + Route::post('/{slug}/copy-permissions', [BookshelfController::class, 'copyPermissions']); + + Route::get('/{shelfSlug}/create-book', [BookController::class, 'create']); + Route::post('/{shelfSlug}/create-book', [BookController::class, 'store']); }); - Route::get('/create-book', 'BookController@create'); + Route::get('/create-book', [BookController::class, 'create']); Route::prefix('books')->group(function () { // Books - Route::get('/', 'BookController@index'); - Route::post('/', 'BookController@store'); - Route::get('/{slug}/edit', 'BookController@edit'); - Route::put('/{slug}', 'BookController@update'); - Route::delete('/{id}', 'BookController@destroy'); - Route::get('/{slug}/sort-item', 'BookSortController@showItem'); - Route::get('/{slug}', 'BookController@show'); - Route::get('/{bookSlug}/permissions', 'BookController@showPermissions'); - Route::put('/{bookSlug}/permissions', 'BookController@permissions'); - Route::get('/{slug}/delete', 'BookController@showDelete'); - Route::get('/{bookSlug}/sort', 'BookSortController@show'); - Route::put('/{bookSlug}/sort', 'BookSortController@update'); - Route::get('/{bookSlug}/export/html', 'BookExportController@html'); - Route::get('/{bookSlug}/export/pdf', 'BookExportController@pdf'); - Route::get('/{bookSlug}/export/markdown', 'BookExportController@markdown'); - Route::get('/{bookSlug}/export/zip', 'BookExportController@zip'); - Route::get('/{bookSlug}/export/plaintext', 'BookExportController@plainText'); + Route::get('/', [BookController::class, 'index']); + Route::post('/', [BookController::class, 'store']); + Route::get('/{slug}/edit', [BookController::class, 'edit']); + Route::put('/{slug}', [BookController::class, 'update']); + Route::delete('/{id}', [BookController::class, 'destroy']); + Route::get('/{slug}/sort-item', [BookSortController::class, 'showItem']); + Route::get('/{slug}', [BookController::class, 'show']); + Route::get('/{bookSlug}/permissions', [BookController::class, 'showPermissions']); + Route::put('/{bookSlug}/permissions', [BookController::class, 'permissions']); + Route::get('/{slug}/delete', [BookController::class, 'showDelete']); + Route::get('/{bookSlug}/sort', [BookSortController::class, 'show']); + Route::put('/{bookSlug}/sort', [BookSortController::class, 'update']); + Route::get('/{bookSlug}/export/html', [BookExportController::class, 'html']); + Route::get('/{bookSlug}/export/pdf', [BookExportController::class, 'pdf']); + Route::get('/{bookSlug}/export/markdown', [BookExportController::class, 'markdown']); + Route::get('/{bookSlug}/export/zip', [BookExportController::class, 'zip']); + Route::get('/{bookSlug}/export/plaintext', [BookExportController::class, 'plainText']); // Pages - Route::get('/{bookSlug}/create-page', 'PageController@create'); - Route::post('/{bookSlug}/create-guest-page', 'PageController@createAsGuest'); - Route::get('/{bookSlug}/draft/{pageId}', 'PageController@editDraft'); - Route::post('/{bookSlug}/draft/{pageId}', 'PageController@store'); - Route::get('/{bookSlug}/page/{pageSlug}', 'PageController@show'); - Route::get('/{bookSlug}/page/{pageSlug}/export/pdf', 'PageExportController@pdf'); - Route::get('/{bookSlug}/page/{pageSlug}/export/html', 'PageExportController@html'); - Route::get('/{bookSlug}/page/{pageSlug}/export/markdown', 'PageExportController@markdown'); - Route::get('/{bookSlug}/page/{pageSlug}/export/plaintext', 'PageExportController@plainText'); - Route::get('/{bookSlug}/page/{pageSlug}/edit', 'PageController@edit'); - Route::get('/{bookSlug}/page/{pageSlug}/move', 'PageController@showMove'); - Route::put('/{bookSlug}/page/{pageSlug}/move', 'PageController@move'); - Route::get('/{bookSlug}/page/{pageSlug}/copy', 'PageController@showCopy'); - Route::post('/{bookSlug}/page/{pageSlug}/copy', 'PageController@copy'); - Route::get('/{bookSlug}/page/{pageSlug}/delete', 'PageController@showDelete'); - Route::get('/{bookSlug}/draft/{pageId}/delete', 'PageController@showDeleteDraft'); - Route::get('/{bookSlug}/page/{pageSlug}/permissions', 'PageController@showPermissions'); - Route::put('/{bookSlug}/page/{pageSlug}/permissions', 'PageController@permissions'); - Route::put('/{bookSlug}/page/{pageSlug}', 'PageController@update'); - Route::delete('/{bookSlug}/page/{pageSlug}', 'PageController@destroy'); - Route::delete('/{bookSlug}/draft/{pageId}', 'PageController@destroyDraft'); + Route::get('/{bookSlug}/create-page', [PageController::class, 'create']); + Route::post('/{bookSlug}/create-guest-page', [PageController::class, 'createAsGuest']); + Route::get('/{bookSlug}/draft/{pageId}', [PageController::class, 'editDraft']); + Route::post('/{bookSlug}/draft/{pageId}', [PageController::class, 'store']); + Route::get('/{bookSlug}/page/{pageSlug}', [PageController::class, 'show']); + Route::get('/{bookSlug}/page/{pageSlug}/export/pdf', [PageExportController::class, 'pdf']); + Route::get('/{bookSlug}/page/{pageSlug}/export/html', [PageExportController::class, 'html']); + Route::get('/{bookSlug}/page/{pageSlug}/export/markdown', [PageExportController::class, 'markdown']); + Route::get('/{bookSlug}/page/{pageSlug}/export/plaintext', [PageExportController::class, 'plainText']); + Route::get('/{bookSlug}/page/{pageSlug}/edit', [PageController::class, 'edit']); + Route::get('/{bookSlug}/page/{pageSlug}/move', [PageController::class, 'showMove']); + Route::put('/{bookSlug}/page/{pageSlug}/move', [PageController::class, 'move']); + Route::get('/{bookSlug}/page/{pageSlug}/copy', [PageController::class, 'showCopy']); + Route::post('/{bookSlug}/page/{pageSlug}/copy', [PageController::class, 'copy']); + Route::get('/{bookSlug}/page/{pageSlug}/delete', [PageController::class, 'showDelete']); + Route::get('/{bookSlug}/draft/{pageId}/delete', [PageController::class, 'showDeleteDraft']); + Route::get('/{bookSlug}/page/{pageSlug}/permissions', [PageController::class, 'showPermissions']); + Route::put('/{bookSlug}/page/{pageSlug}/permissions', [PageController::class, 'permissions']); + Route::put('/{bookSlug}/page/{pageSlug}', [PageController::class, 'update']); + Route::delete('/{bookSlug}/page/{pageSlug}', [PageController::class, 'destroy']); + Route::delete('/{bookSlug}/draft/{pageId}', [PageController::class, 'destroyDraft']); // Revisions - Route::get('/{bookSlug}/page/{pageSlug}/revisions', 'PageRevisionController@index'); - Route::get('/{bookSlug}/page/{pageSlug}/revisions/{revId}', 'PageRevisionController@show'); - Route::get('/{bookSlug}/page/{pageSlug}/revisions/{revId}/changes', 'PageRevisionController@changes'); - Route::put('/{bookSlug}/page/{pageSlug}/revisions/{revId}/restore', 'PageRevisionController@restore'); - Route::delete('/{bookSlug}/page/{pageSlug}/revisions/{revId}/delete', 'PageRevisionController@destroy'); + Route::get('/{bookSlug}/page/{pageSlug}/revisions', [PageRevisionController::class, 'index']); + Route::get('/{bookSlug}/page/{pageSlug}/revisions/{revId}', [PageRevisionController::class, 'show']); + Route::get('/{bookSlug}/page/{pageSlug}/revisions/{revId}/changes', [PageRevisionController::class, 'changes']); + Route::put('/{bookSlug}/page/{pageSlug}/revisions/{revId}/restore', [PageRevisionController::class, 'restore']); + Route::delete('/{bookSlug}/page/{pageSlug}/revisions/{revId}/delete', [PageRevisionController::class, 'destroy']); // Chapters - Route::get('/{bookSlug}/chapter/{chapterSlug}/create-page', 'PageController@create'); - Route::post('/{bookSlug}/chapter/{chapterSlug}/create-guest-page', 'PageController@createAsGuest'); - Route::get('/{bookSlug}/create-chapter', 'ChapterController@create'); - Route::post('/{bookSlug}/create-chapter', 'ChapterController@store'); - Route::get('/{bookSlug}/chapter/{chapterSlug}', 'ChapterController@show'); - Route::put('/{bookSlug}/chapter/{chapterSlug}', 'ChapterController@update'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/move', 'ChapterController@showMove'); - Route::put('/{bookSlug}/chapter/{chapterSlug}/move', 'ChapterController@move'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/edit', 'ChapterController@edit'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/permissions', 'ChapterController@showPermissions'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/export/pdf', 'ChapterExportController@pdf'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/export/html', 'ChapterExportController@html'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/export/markdown', 'ChapterExportController@markdown'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/export/plaintext', 'ChapterExportController@plainText'); - Route::put('/{bookSlug}/chapter/{chapterSlug}/permissions', 'ChapterController@permissions'); - Route::get('/{bookSlug}/chapter/{chapterSlug}/delete', 'ChapterController@showDelete'); - Route::delete('/{bookSlug}/chapter/{chapterSlug}', 'ChapterController@destroy'); + Route::get('/{bookSlug}/chapter/{chapterSlug}/create-page', [PageController::class, 'create']); + Route::post('/{bookSlug}/chapter/{chapterSlug}/create-guest-page', [PageController::class, 'createAsGuest']); + Route::get('/{bookSlug}/create-chapter', [ChapterController::class, 'create']); + Route::post('/{bookSlug}/create-chapter', [ChapterController::class, 'store']); + Route::get('/{bookSlug}/chapter/{chapterSlug}', [ChapterController::class, 'show']); + Route::put('/{bookSlug}/chapter/{chapterSlug}', [ChapterController::class, 'update']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/move', [ChapterController::class, 'showMove']); + Route::put('/{bookSlug}/chapter/{chapterSlug}/move', [ChapterController::class, 'move']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/edit', [ChapterController::class, 'edit']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/permissions', [ChapterController::class, 'showPermissions']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/export/pdf', [ChapterExportController::class, 'pdf']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/export/html', [ChapterExportController::class, 'html']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/export/markdown', [ChapterExportController::class, 'markdown']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/export/plaintext', [ChapterExportController::class, 'plainText']); + Route::put('/{bookSlug}/chapter/{chapterSlug}/permissions', [ChapterController::class, 'permissions']); + Route::get('/{bookSlug}/chapter/{chapterSlug}/delete', [ChapterController::class, 'showDelete']); + Route::delete('/{bookSlug}/chapter/{chapterSlug}', [ChapterController::class, 'destroy']); }); // User Profile routes - Route::get('/user/{slug}', 'UserProfileController@show'); + Route::get('/user/{slug}', [UserProfileController::class, 'show']); // Image routes - Route::get('/images/gallery', 'Images\GalleryImageController@list'); - Route::post('/images/gallery', 'Images\GalleryImageController@create'); - Route::get('/images/drawio', 'Images\DrawioImageController@list'); - Route::get('/images/drawio/base64/{id}', 'Images\DrawioImageController@getAsBase64'); - Route::post('/images/drawio', 'Images\DrawioImageController@create'); - Route::get('/images/edit/{id}', 'Images\ImageController@edit'); - Route::put('/images/{id}', 'Images\ImageController@update'); - Route::delete('/images/{id}', 'Images\ImageController@destroy'); + Route::get('/images/gallery', [Images\GalleryImageController::class, 'list']); + Route::post('/images/gallery', [Images\GalleryImageController::class, 'create']); + Route::get('/images/drawio', [Images\DrawioImageController::class, 'list']); + Route::get('/images/drawio/base64/{id}', [Images\DrawioImageController::class, 'getAsBase64']); + Route::post('/images/drawio', [Images\DrawioImageController::class, 'create']); + Route::get('/images/edit/{id}', [Images\ImageController::class, 'edit']); + Route::put('/images/{id}', [Images\ImageController::class, 'update']); + Route::delete('/images/{id}', [Images\ImageController::class, 'destroy']); // Attachments routes - Route::get('/attachments/{id}', 'AttachmentController@get'); - Route::post('/attachments/upload', 'AttachmentController@upload'); - Route::post('/attachments/upload/{id}', 'AttachmentController@uploadUpdate'); - Route::post('/attachments/link', 'AttachmentController@attachLink'); - Route::put('/attachments/{id}', 'AttachmentController@update'); - Route::get('/attachments/edit/{id}', 'AttachmentController@getUpdateForm'); - Route::get('/attachments/get/page/{pageId}', 'AttachmentController@listForPage'); - Route::put('/attachments/sort/page/{pageId}', 'AttachmentController@sortForPage'); - Route::delete('/attachments/{id}', 'AttachmentController@delete'); + Route::get('/attachments/{id}', [AttachmentController::class, 'get']); + Route::post('/attachments/upload', [AttachmentController::class, 'upload']); + Route::post('/attachments/upload/{id}', [AttachmentController::class, 'uploadUpdate']); + Route::post('/attachments/link', [AttachmentController::class, 'attachLink']); + Route::put('/attachments/{id}', [AttachmentController::class, 'update']); + Route::get('/attachments/edit/{id}', [AttachmentController::class, 'getUpdateForm']); + Route::get('/attachments/get/page/{pageId}', [AttachmentController::class, 'listForPage']); + Route::put('/attachments/sort/page/{pageId}', [AttachmentController::class, 'sortForPage']); + Route::delete('/attachments/{id}', [AttachmentController::class, 'delete']); // AJAX routes - Route::put('/ajax/page/{id}/save-draft', 'PageController@saveDraft'); - Route::get('/ajax/page/{id}', 'PageController@getPageAjax'); - Route::delete('/ajax/page/{id}', 'PageController@ajaxDestroy'); + Route::put('/ajax/page/{id}/save-draft', [PageController::class, 'saveDraft']); + Route::get('/ajax/page/{id}', [PageController::class, 'getPageAjax']); + Route::delete('/ajax/page/{id}', [PageController::class, 'ajaxDestroy']); // Tag routes (AJAX) Route::prefix('ajax/tags')->group(function () { - Route::get('/suggest/names', 'TagController@getNameSuggestions'); - Route::get('/suggest/values', 'TagController@getValueSuggestions'); + Route::get('/suggest/names', [TagController::class, 'getNameSuggestions']); + Route::get('/suggest/values', [TagController::class, 'getValueSuggestions']); }); - Route::get('/ajax/search/entities', 'SearchController@searchEntitiesAjax'); + Route::get('/ajax/search/entities', [SearchController::class, 'searchEntitiesAjax']); // Comments - Route::post('/comment/{pageId}', 'CommentController@savePageComment'); - Route::put('/comment/{id}', 'CommentController@update'); - Route::delete('/comment/{id}', 'CommentController@destroy'); + Route::post('/comment/{pageId}', [CommentController::class, 'savePageComment']); + Route::put('/comment/{id}', [CommentController::class, 'update']); + Route::delete('/comment/{id}', [CommentController::class, 'destroy']); // Links - Route::get('/link/{id}', 'PageController@redirectFromLink'); + Route::get('/link/{id}', [PageController::class, 'redirectFromLink']); // Search - Route::get('/search', 'SearchController@search'); - Route::get('/search/book/{bookId}', 'SearchController@searchBook'); - Route::get('/search/chapter/{bookId}', 'SearchController@searchChapter'); - Route::get('/search/entity/siblings', 'SearchController@searchSiblings'); + Route::get('/search', [SearchController::class, 'search']); + Route::get('/search/book/{bookId}', [SearchController::class, 'searchBook']); + Route::get('/search/chapter/{bookId}', [SearchController::class, 'searchChapter']); + Route::get('/search/entity/siblings', [SearchController::class, 'searchSiblings']); // User Search - Route::get('/search/users/select', 'UserSearchController@forSelect'); + Route::get('/search/users/select', [UserSearchController::class, 'forSelect']); // Template System - Route::get('/templates', 'PageTemplateController@list'); - Route::get('/templates/{templateId}', 'PageTemplateController@get'); + Route::get('/templates', [PageTemplateController::class, 'list']); + Route::get('/templates/{templateId}', [PageTemplateController::class, 'get']); // Favourites - Route::get('/favourites', 'FavouriteController@index'); - Route::post('/favourites/add', 'FavouriteController@add'); - Route::post('/favourites/remove', 'FavouriteController@remove'); + Route::get('/favourites', [FavouriteController::class, 'index']); + Route::post('/favourites/add', [FavouriteController::class, 'add']); + Route::post('/favourites/remove', [FavouriteController::class, 'remove']); // Other Pages - Route::get('/', 'HomeController@index'); - Route::get('/home', 'HomeController@index'); - Route::get('/custom-head-content', 'HomeController@customHeadContent'); + Route::get('/', [HomeController::class, 'index']); + Route::get('/home', [HomeController::class, 'index']); + Route::get('/custom-head-content', [HomeController::class, 'customHeadContent']); // Settings Route::prefix('settings')->group(function () { - Route::get('/', 'SettingController@index')->name('settings'); - Route::post('/', 'SettingController@update'); + Route::get('/', [SettingController::class, 'index'])->name('settings'); + Route::post('/', [SettingController::class, 'update']); // Maintenance - Route::get('/maintenance', 'MaintenanceController@index'); - Route::delete('/maintenance/cleanup-images', 'MaintenanceController@cleanupImages'); - Route::post('/maintenance/send-test-email', 'MaintenanceController@sendTestEmail'); + Route::get('/maintenance', [MaintenanceController::class, 'index']); + Route::delete('/maintenance/cleanup-images', [MaintenanceController::class, 'cleanupImages']); + Route::post('/maintenance/send-test-email', [MaintenanceController::class, 'sendTestEmail']); // Recycle Bin - Route::get('/recycle-bin', 'RecycleBinController@index'); - Route::post('/recycle-bin/empty', 'RecycleBinController@empty'); - Route::get('/recycle-bin/{id}/destroy', 'RecycleBinController@showDestroy'); - Route::delete('/recycle-bin/{id}', 'RecycleBinController@destroy'); - Route::get('/recycle-bin/{id}/restore', 'RecycleBinController@showRestore'); - Route::post('/recycle-bin/{id}/restore', 'RecycleBinController@restore'); + Route::get('/recycle-bin', [RecycleBinController::class, 'index']); + Route::post('/recycle-bin/empty', [RecycleBinController::class, 'empty']); + Route::get('/recycle-bin/{id}/destroy', [RecycleBinController::class, 'showDestroy']); + Route::delete('/recycle-bin/{id}', [RecycleBinController::class, 'destroy']); + Route::get('/recycle-bin/{id}/restore', [RecycleBinController::class, 'showRestore']); + Route::post('/recycle-bin/{id}/restore', [RecycleBinController::class, 'restore']); // Audit Log - Route::get('/audit', 'AuditLogController@index'); + Route::get('/audit', [AuditLogController::class, 'index']); // Users - Route::get('/users', 'UserController@index'); - Route::get('/users/create', 'UserController@create'); - Route::get('/users/{id}/delete', 'UserController@delete'); - Route::patch('/users/{id}/switch-books-view', 'UserController@switchBooksView'); - Route::patch('/users/{id}/switch-shelves-view', 'UserController@switchShelvesView'); - Route::patch('/users/{id}/switch-shelf-view', 'UserController@switchShelfView'); - Route::patch('/users/{id}/change-sort/{type}', 'UserController@changeSort'); - Route::patch('/users/{id}/update-expansion-preference/{key}', 'UserController@updateExpansionPreference'); - Route::patch('/users/toggle-dark-mode', 'UserController@toggleDarkMode'); - Route::post('/users/create', 'UserController@store'); - Route::get('/users/{id}', 'UserController@edit'); - Route::put('/users/{id}', 'UserController@update'); - Route::delete('/users/{id}', 'UserController@destroy'); + Route::get('/users', [UserController::class, 'index']); + Route::get('/users/create', [UserController::class, 'create']); + Route::get('/users/{id}/delete', [UserController::class, 'delete']); + Route::patch('/users/{id}/switch-books-view', [UserController::class, 'switchBooksView']); + Route::patch('/users/{id}/switch-shelves-view', [UserController::class, 'switchShelvesView']); + Route::patch('/users/{id}/switch-shelf-view', [UserController::class, 'switchShelfView']); + Route::patch('/users/{id}/change-sort/{type}', [UserController::class, 'changeSort']); + Route::patch('/users/{id}/update-expansion-preference/{key}', [UserController::class, 'updateExpansionPreference']); + Route::patch('/users/toggle-dark-mode', [UserController::class, 'toggleDarkMode']); + Route::post('/users/create', [UserController::class, 'store']); + Route::get('/users/{id}', [UserController::class, 'edit']); + Route::put('/users/{id}', [UserController::class, 'update']); + Route::delete('/users/{id}', [UserController::class, 'destroy']); // User API Tokens - Route::get('/users/{userId}/create-api-token', 'UserApiTokenController@create'); - Route::post('/users/{userId}/create-api-token', 'UserApiTokenController@store'); - Route::get('/users/{userId}/api-tokens/{tokenId}', 'UserApiTokenController@edit'); - Route::put('/users/{userId}/api-tokens/{tokenId}', 'UserApiTokenController@update'); - Route::get('/users/{userId}/api-tokens/{tokenId}/delete', 'UserApiTokenController@delete'); - Route::delete('/users/{userId}/api-tokens/{tokenId}', 'UserApiTokenController@destroy'); + Route::get('/users/{userId}/create-api-token', [UserApiTokenController::class, 'create']); + Route::post('/users/{userId}/create-api-token', [UserApiTokenController::class, 'store']); + Route::get('/users/{userId}/api-tokens/{tokenId}', [UserApiTokenController::class, 'edit']); + Route::put('/users/{userId}/api-tokens/{tokenId}', [UserApiTokenController::class, 'update']); + Route::get('/users/{userId}/api-tokens/{tokenId}/delete', [UserApiTokenController::class, 'delete']); + Route::delete('/users/{userId}/api-tokens/{tokenId}', [UserApiTokenController::class, 'destroy']); // Roles - Route::get('/roles', 'RoleController@list'); - Route::get('/roles/new', 'RoleController@create'); - Route::post('/roles/new', 'RoleController@store'); - Route::get('/roles/delete/{id}', 'RoleController@showDelete'); - Route::delete('/roles/delete/{id}', 'RoleController@delete'); - Route::get('/roles/{id}', 'RoleController@edit'); - Route::put('/roles/{id}', 'RoleController@update'); + Route::get('/roles', [RoleController::class, 'list']); + Route::get('/roles/new', [RoleController::class, 'create']); + Route::post('/roles/new', [RoleController::class, 'store']); + Route::get('/roles/delete/{id}', [RoleController::class, 'showDelete']); + Route::delete('/roles/delete/{id}', [RoleController::class, 'delete']); + Route::get('/roles/{id}', [RoleController::class, 'edit']); + Route::put('/roles/{id}', [RoleController::class, 'update']); }); }); // MFA routes Route::middleware('mfa-setup')->group(function () { - Route::get('/mfa/setup', 'Auth\MfaController@setup'); - Route::get('/mfa/totp/generate', 'Auth\MfaTotpController@generate'); - Route::post('/mfa/totp/confirm', 'Auth\MfaTotpController@confirm'); - Route::get('/mfa/backup_codes/generate', 'Auth\MfaBackupCodesController@generate'); - Route::post('/mfa/backup_codes/confirm', 'Auth\MfaBackupCodesController@confirm'); + Route::get('/mfa/setup', [Auth\MfaController::class, 'setup']); + Route::get('/mfa/totp/generate', [Auth\MfaTotpController::class, 'generate']); + Route::post('/mfa/totp/confirm', [Auth\MfaTotpController::class, 'confirm']); + Route::get('/mfa/backup_codes/generate', [Auth\MfaBackupCodesController::class, 'generate']); + Route::post('/mfa/backup_codes/confirm', [Auth\MfaBackupCodesController::class, 'confirm']); }); Route::middleware('guest')->group(function () { - Route::get('/mfa/verify', 'Auth\MfaController@verify'); - Route::post('/mfa/totp/verify', 'Auth\MfaTotpController@verify'); - Route::post('/mfa/backup_codes/verify', 'Auth\MfaBackupCodesController@verify'); + Route::get('/mfa/verify', [Auth\MfaController::class, 'verify']); + Route::post('/mfa/totp/verify', [Auth\MfaTotpController::class, 'verify']); + Route::post('/mfa/backup_codes/verify', [Auth\MfaBackupCodesController::class, 'verify']); }); -Route::delete('/mfa/{method}/remove', 'Auth\MfaController@remove')->middleware('auth'); +Route::delete('/mfa/{method}/remove', [Auth\MfaController::class, 'remove'])->middleware('auth'); // Social auth routes -Route::get('/login/service/{socialDriver}', 'Auth\SocialController@login'); -Route::get('/login/service/{socialDriver}/callback', 'Auth\SocialController@callback'); -Route::post('/login/service/{socialDriver}/detach', 'Auth\SocialController@detach')->middleware('auth'); -Route::get('/register/service/{socialDriver}', 'Auth\SocialController@register'); +Route::get('/login/service/{socialDriver}', [Auth\SocialController::class, 'login']); +Route::get('/login/service/{socialDriver}/callback', [Auth\SocialController::class, 'callback']); +Route::post('/login/service/{socialDriver}/detach', [Auth\SocialController::class, 'detach'])->middleware('auth'); +Route::get('/register/service/{socialDriver}', [Auth\SocialController::class, 'register']); // Login/Logout routes -Route::get('/login', 'Auth\LoginController@getLogin'); -Route::post('/login', 'Auth\LoginController@login'); -Route::get('/logout', 'Auth\LoginController@logout'); -Route::get('/register', 'Auth\RegisterController@getRegister'); -Route::get('/register/confirm', 'Auth\ConfirmEmailController@show'); -Route::get('/register/confirm/awaiting', 'Auth\ConfirmEmailController@showAwaiting'); -Route::post('/register/confirm/resend', 'Auth\ConfirmEmailController@resend'); -Route::get('/register/confirm/{token}', 'Auth\ConfirmEmailController@confirm'); -Route::post('/register', 'Auth\RegisterController@postRegister'); +Route::get('/login', [Auth\LoginController::class, 'getLogin']); +Route::post('/login', [Auth\LoginController::class, 'login']); +Route::get('/logout', [Auth\LoginController::class, 'logout']); +Route::get('/register', [Auth\RegisterController::class, 'getRegister']); +Route::get('/register/confirm', [Auth\ConfirmEmailController::class, 'show']); +Route::get('/register/confirm/awaiting', [Auth\ConfirmEmailController::class, 'showAwaiting']); +Route::post('/register/confirm/resend', [Auth\ConfirmEmailController::class, 'resend']); +Route::get('/register/confirm/{token}', [Auth\ConfirmEmailController::class, 'confirm']); +Route::post('/register', [Auth\RegisterController::class, 'postRegister']); // SAML routes -Route::post('/saml2/login', 'Auth\Saml2Controller@login'); -Route::get('/saml2/logout', 'Auth\Saml2Controller@logout'); -Route::get('/saml2/metadata', 'Auth\Saml2Controller@metadata'); -Route::get('/saml2/sls', 'Auth\Saml2Controller@sls'); -Route::post('/saml2/acs', 'Auth\Saml2Controller@startAcs'); -Route::get('/saml2/acs', 'Auth\Saml2Controller@processAcs'); +Route::post('/saml2/login', [Auth\Saml2Controller::class, 'login']); +Route::get('/saml2/logout', [Auth\Saml2Controller::class, 'logout']); +Route::get('/saml2/metadata', [Auth\Saml2Controller::class, 'metadata']); +Route::get('/saml2/sls', [Auth\Saml2Controller::class, 'sls']); +Route::post('/saml2/acs', [Auth\Saml2Controller::class, 'startAcs']); +Route::get('/saml2/acs', [Auth\Saml2Controller::class, 'processAcs']); // OIDC routes -Route::post('/oidc/login', 'Auth\OidcController@login'); -Route::get('/oidc/callback', 'Auth\OidcController@callback'); +Route::post('/oidc/login', [Auth\OidcController::class, 'login']); +Route::get('/oidc/callback', [Auth\OidcController::class, 'callback']); // User invitation routes -Route::get('/register/invite/{token}', 'Auth\UserInviteController@showSetPassword'); -Route::post('/register/invite/{token}', 'Auth\UserInviteController@setPassword'); +Route::get('/register/invite/{token}', [Auth\UserInviteController::class, 'showSetPassword']); +Route::post('/register/invite/{token}', [Auth\UserInviteController::class, 'setPassword']); // Password reset link request routes... -Route::get('/password/email', 'Auth\ForgotPasswordController@showLinkRequestForm'); -Route::post('/password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail'); +Route::get('/password/email', [Auth\ForgotPasswordController::class, 'showLinkRequestForm']); +Route::post('/password/email', [Auth\ForgotPasswordController::class, 'sendResetLinkEmail']); // Password reset routes... -Route::get('/password/reset/{token}', 'Auth\ResetPasswordController@showResetForm'); -Route::post('/password/reset', 'Auth\ResetPasswordController@reset'); +Route::get('/password/reset/{token}', [Auth\ResetPasswordController::class, 'showResetForm']); +Route::post('/password/reset', [Auth\ResetPasswordController::class, 'reset']); -Route::fallback('HomeController@notFound')->name('fallback'); +Route::fallback([HomeController::class, 'notFound'])->name('fallback'); From b3898ac1fedd694edcd26b25b32c08d5107f5756 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:57 +0000 Subject: [PATCH 07/19] Shift console routes --- routes/console.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 routes/console.php diff --git a/routes/console.php b/routes/console.php new file mode 100644 index 00000000000..e05f4c9a1b2 --- /dev/null +++ b/routes/console.php @@ -0,0 +1,19 @@ +comment(Inspiring::quote()); +})->purpose('Display an inspiring quote'); From 01dd2b74a8e76c6234b2b58274e6342b0c2fe954 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:57 +0000 Subject: [PATCH 08/19] Ignore temporary framework files --- storage/framework/.gitignore | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/storage/framework/.gitignore b/storage/framework/.gitignore index 953edb7a993..05c4471f2b5 100755 --- a/storage/framework/.gitignore +++ b/storage/framework/.gitignore @@ -1,7 +1,9 @@ -config.php -routes.php compiled.php -services.json +config.php +down events.scanned.php +maintenance.php +routes.php routes.scanned.php -down +schedule-* +services.json From 3cd292a5c3b6a5a3cf83535aa82f1ef1f19e7109 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:05:59 +0000 Subject: [PATCH 09/19] Shift to class based factories --- app/Actions/Comment.php | 3 + app/Actions/Tag.php | 3 + app/Auth/Role.php | 3 + app/Auth/User.php | 3 + app/Entities/Models/Book.php | 3 + app/Entities/Models/Bookshelf.php | 3 + app/Entities/Models/Chapter.php | 3 + app/Entities/Models/Page.php | 3 + app/Uploads/Image.php | 3 + database/factories/Actions/CommentFactory.php | 42 ++++++++ database/factories/Actions/TagFactory.php | 38 ++++++++ database/factories/Auth/RoleFactory.php | 38 ++++++++ database/factories/Auth/UserFactory.php | 44 +++++++++ .../factories/Entities/Models/BookFactory.php | 39 ++++++++ .../Entities/Models/BookshelfFactory.php | 39 ++++++++ .../Entities/Models/ChapterFactory.php | 39 ++++++++ .../factories/Entities/Models/PageFactory.php | 43 +++++++++ database/factories/ModelFactory.php | 96 ------------------- database/factories/Uploads/ImageFactory.php | 41 ++++++++ database/seeds/DummyContentSeeder.php | 20 ++-- database/seeds/LargeContentSeeder.php | 8 +- tests/Auth/AuthTest.php | 8 +- tests/Auth/LdapTest.php | 26 ++--- tests/Auth/Saml2Test.php | 6 +- tests/Auth/SocialAuthTest.php | 8 +- tests/Entity/BookShelfTest.php | 2 +- tests/Entity/BookTest.php | 4 +- tests/Entity/ChapterTest.php | 2 +- tests/Entity/CommentTest.php | 6 +- tests/Entity/PageTest.php | 2 +- tests/Entity/TagTest.php | 34 +++---- tests/HomepageTest.php | 2 +- tests/Permissions/RolesTest.php | 12 +-- tests/SharedTestHelpers.php | 8 +- tests/ThemeTest.php | 2 +- tests/Uploads/AvatarTest.php | 8 +- tests/User/UserManagementTest.php | 2 +- tests/User/UserProfileTest.php | 6 +- 38 files changed, 473 insertions(+), 179 deletions(-) create mode 100644 database/factories/Actions/CommentFactory.php create mode 100644 database/factories/Actions/TagFactory.php create mode 100644 database/factories/Auth/RoleFactory.php create mode 100644 database/factories/Auth/UserFactory.php create mode 100644 database/factories/Entities/Models/BookFactory.php create mode 100644 database/factories/Entities/Models/BookshelfFactory.php create mode 100644 database/factories/Entities/Models/ChapterFactory.php create mode 100644 database/factories/Entities/Models/PageFactory.php delete mode 100644 database/factories/ModelFactory.php create mode 100644 database/factories/Uploads/ImageFactory.php diff --git a/app/Actions/Comment.php b/app/Actions/Comment.php index 34fd84709ec..ba77f1a94ae 100644 --- a/app/Actions/Comment.php +++ b/app/Actions/Comment.php @@ -2,6 +2,7 @@ namespace BookStack\Actions; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Model; use BookStack\Traits\HasCreatorAndUpdater; use Illuminate\Database\Eloquent\Relations\MorphTo; @@ -15,6 +16,8 @@ */ class Comment extends Model { + use HasFactory; + use HasCreatorAndUpdater; protected $fillable = ['text', 'parent_id']; diff --git a/app/Actions/Tag.php b/app/Actions/Tag.php index f9f278570cc..91957ef28f5 100644 --- a/app/Actions/Tag.php +++ b/app/Actions/Tag.php @@ -2,11 +2,14 @@ namespace BookStack\Actions; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; class Tag extends Model { + use HasFactory; + protected $fillable = ['name', 'value', 'order']; protected $hidden = ['id', 'entity_id', 'entity_type', 'created_at', 'updated_at']; diff --git a/app/Auth/Role.php b/app/Auth/Role.php index fc2e39aa9c5..4d527e8d741 100644 --- a/app/Auth/Role.php +++ b/app/Auth/Role.php @@ -2,6 +2,7 @@ namespace BookStack\Auth; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Auth\Permissions\JointPermission; use BookStack\Auth\Permissions\RolePermission; use BookStack\Interfaces\Loggable; @@ -23,6 +24,8 @@ */ class Role extends Model implements Loggable { + use HasFactory; + protected $fillable = ['display_name', 'description', 'external_auth_id']; /** diff --git a/app/Auth/User.php b/app/Auth/User.php index ae126576811..0c8b3bd6adc 100644 --- a/app/Auth/User.php +++ b/app/Auth/User.php @@ -2,6 +2,7 @@ namespace BookStack\Auth; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Actions\Favourite; use BookStack\Api\ApiToken; use BookStack\Auth\Access\Mfa\MfaValue; @@ -43,6 +44,8 @@ */ class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable { + use HasFactory; + use Authenticatable; use CanResetPassword; use Notifiable; diff --git a/app/Entities/Models/Book.php b/app/Entities/Models/Book.php index 7a4a6df500d..12f7950b033 100644 --- a/app/Entities/Models/Book.php +++ b/app/Entities/Models/Book.php @@ -2,6 +2,7 @@ namespace BookStack\Entities\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Uploads\Image; use Exception; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -21,6 +22,8 @@ */ class Book extends Entity implements HasCoverImage { + use HasFactory; + public $searchFactor = 2; protected $fillable = ['name', 'description']; diff --git a/app/Entities/Models/Bookshelf.php b/app/Entities/Models/Bookshelf.php index bc706050bf9..eda5294c9c1 100644 --- a/app/Entities/Models/Bookshelf.php +++ b/app/Entities/Models/Bookshelf.php @@ -2,12 +2,15 @@ namespace BookStack\Entities\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Uploads\Image; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Bookshelf extends Entity implements HasCoverImage { + use HasFactory; + protected $table = 'bookshelves'; public $searchFactor = 3; diff --git a/app/Entities/Models/Chapter.php b/app/Entities/Models/Chapter.php index 988d5e71ffb..0ce58d3f317 100644 --- a/app/Entities/Models/Chapter.php +++ b/app/Entities/Models/Chapter.php @@ -2,6 +2,7 @@ namespace BookStack\Entities\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Support\Collection; /** @@ -12,6 +13,8 @@ */ class Chapter extends BookChild { + use HasFactory; + public $searchFactor = 1.3; protected $fillable = ['name', 'description', 'priority', 'book_id']; diff --git a/app/Entities/Models/Page.php b/app/Entities/Models/Page.php index 1078b1318d0..77b4239c280 100644 --- a/app/Entities/Models/Page.php +++ b/app/Entities/Models/Page.php @@ -2,6 +2,7 @@ namespace BookStack\Entities\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Entities\Tools\PageContent; use BookStack\Uploads\Attachment; use Illuminate\Database\Eloquent\Builder; @@ -25,6 +26,8 @@ */ class Page extends BookChild { + use HasFactory; + public static $listAttributes = ['name', 'id', 'slug', 'book_id', 'chapter_id', 'draft', 'template', 'text', 'created_at', 'updated_at', 'priority']; public static $contentAttributes = ['name', 'id', 'slug', 'book_id', 'chapter_id', 'draft', 'template', 'html', 'text', 'created_at', 'updated_at', 'priority']; diff --git a/app/Uploads/Image.php b/app/Uploads/Image.php index 4e0abc85b9a..2557bc72b29 100644 --- a/app/Uploads/Image.php +++ b/app/Uploads/Image.php @@ -2,6 +2,7 @@ namespace BookStack\Uploads; +use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Entities\Models\Page; use BookStack\Model; use BookStack\Traits\HasCreatorAndUpdater; @@ -18,6 +19,8 @@ */ class Image extends Model { + use HasFactory; + use HasCreatorAndUpdater; protected $fillable = ['name']; diff --git a/database/factories/Actions/CommentFactory.php b/database/factories/Actions/CommentFactory.php new file mode 100644 index 00000000000..ec7233cf1f3 --- /dev/null +++ b/database/factories/Actions/CommentFactory.php @@ -0,0 +1,42 @@ +faker->paragraph(1); + $html = '

      '.$text.'

      '; + + return [ + 'html' => $html, + 'text' => $text, + 'parent_id' => null, + ]; + } +} diff --git a/database/factories/Actions/TagFactory.php b/database/factories/Actions/TagFactory.php new file mode 100644 index 00000000000..08aed1640ee --- /dev/null +++ b/database/factories/Actions/TagFactory.php @@ -0,0 +1,38 @@ + $this->faker->city, + 'value' => $this->faker->sentence(3), + ]; + } +} diff --git a/database/factories/Auth/RoleFactory.php b/database/factories/Auth/RoleFactory.php new file mode 100644 index 00000000000..c22e924df32 --- /dev/null +++ b/database/factories/Auth/RoleFactory.php @@ -0,0 +1,38 @@ + $this->faker->sentence(3), + 'description' => $this->faker->sentence(10), + ]; + } +} diff --git a/database/factories/Auth/UserFactory.php b/database/factories/Auth/UserFactory.php new file mode 100644 index 00000000000..35b450d5b34 --- /dev/null +++ b/database/factories/Auth/UserFactory.php @@ -0,0 +1,44 @@ +faker->name; + + return [ + 'name' => $name, + 'email' => $this->faker->email, + 'slug' => \Illuminate\Support\Str::slug($name.'-'.\Illuminate\Support\Str::random(5)), + 'password' => Str::random(10), + 'remember_token' => Str::random(10), + 'email_confirmed' => 1, + ]; + } +} diff --git a/database/factories/Entities/Models/BookFactory.php b/database/factories/Entities/Models/BookFactory.php new file mode 100644 index 00000000000..6d2b5c65da5 --- /dev/null +++ b/database/factories/Entities/Models/BookFactory.php @@ -0,0 +1,39 @@ + $this->faker->sentence, + 'slug' => Str::random(10), + 'description' => $this->faker->paragraph, + ]; + } +} diff --git a/database/factories/Entities/Models/BookshelfFactory.php b/database/factories/Entities/Models/BookshelfFactory.php new file mode 100644 index 00000000000..be281e9ee72 --- /dev/null +++ b/database/factories/Entities/Models/BookshelfFactory.php @@ -0,0 +1,39 @@ + $this->faker->sentence, + 'slug' => Str::random(10), + 'description' => $this->faker->paragraph, + ]; + } +} diff --git a/database/factories/Entities/Models/ChapterFactory.php b/database/factories/Entities/Models/ChapterFactory.php new file mode 100644 index 00000000000..12a6963d968 --- /dev/null +++ b/database/factories/Entities/Models/ChapterFactory.php @@ -0,0 +1,39 @@ + $this->faker->sentence, + 'slug' => Str::random(10), + 'description' => $this->faker->paragraph, + ]; + } +} diff --git a/database/factories/Entities/Models/PageFactory.php b/database/factories/Entities/Models/PageFactory.php new file mode 100644 index 00000000000..57612ac93d2 --- /dev/null +++ b/database/factories/Entities/Models/PageFactory.php @@ -0,0 +1,43 @@ +'.implode('

      ', $this->faker->paragraphs(5)).'

      '; + + return [ + 'name' => $this->faker->sentence, + 'slug' => Str::random(10), + 'html' => $html, + 'text' => strip_tags($html), + 'revision_count' => 1, + ]; + } +} diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php deleted file mode 100644 index 4771f56fb88..00000000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,96 +0,0 @@ -define(\BookStack\Auth\User::class, function ($faker) { - $name = $faker->name; - - return [ - 'name' => $name, - 'email' => $faker->email, - 'slug' => \Illuminate\Support\Str::slug($name.'-'.\Illuminate\Support\Str::random(5)), - 'password' => Str::random(10), - 'remember_token' => Str::random(10), - 'email_confirmed' => 1, - ]; -}); - -$factory->define(\BookStack\Entities\Models\Bookshelf::class, function ($faker) { - return [ - 'name' => $faker->sentence, - 'slug' => Str::random(10), - 'description' => $faker->paragraph, - ]; -}); - -$factory->define(\BookStack\Entities\Models\Book::class, function ($faker) { - return [ - 'name' => $faker->sentence, - 'slug' => Str::random(10), - 'description' => $faker->paragraph, - ]; -}); - -$factory->define(\BookStack\Entities\Models\Chapter::class, function ($faker) { - return [ - 'name' => $faker->sentence, - 'slug' => Str::random(10), - 'description' => $faker->paragraph, - ]; -}); - -$factory->define(\BookStack\Entities\Models\Page::class, function ($faker) { - $html = '

      '.implode('

      ', $faker->paragraphs(5)).'

      '; - - return [ - 'name' => $faker->sentence, - 'slug' => Str::random(10), - 'html' => $html, - 'text' => strip_tags($html), - 'revision_count' => 1, - ]; -}); - -$factory->define(\BookStack\Auth\Role::class, function ($faker) { - return [ - 'display_name' => $faker->sentence(3), - 'description' => $faker->sentence(10), - ]; -}); - -$factory->define(\BookStack\Actions\Tag::class, function ($faker) { - return [ - 'name' => $faker->city, - 'value' => $faker->sentence(3), - ]; -}); - -$factory->define(\BookStack\Uploads\Image::class, function ($faker) { - return [ - 'name' => $faker->slug.'.jpg', - 'url' => $faker->url, - 'path' => $faker->url, - 'type' => 'gallery', - 'uploaded_to' => 0, - ]; -}); - -$factory->define(\BookStack\Actions\Comment::class, function ($faker) { - $text = $faker->paragraph(1); - $html = '

      '.$text.'

      '; - - return [ - 'html' => $html, - 'text' => $text, - 'parent_id' => null, - ]; -}); diff --git a/database/factories/Uploads/ImageFactory.php b/database/factories/Uploads/ImageFactory.php new file mode 100644 index 00000000000..ce784d1bdf8 --- /dev/null +++ b/database/factories/Uploads/ImageFactory.php @@ -0,0 +1,41 @@ + $this->faker->slug.'.jpg', + 'url' => $this->faker->url, + 'path' => $this->faker->url, + 'type' => 'gallery', + 'uploaded_to' => 0, + ]; + } +} diff --git a/database/seeds/DummyContentSeeder.php b/database/seeds/DummyContentSeeder.php index d3431e14a33..ef373a89999 100644 --- a/database/seeds/DummyContentSeeder.php +++ b/database/seeds/DummyContentSeeder.php @@ -22,36 +22,36 @@ class DummyContentSeeder extends Seeder public function run() { // Create an editor user - $editorUser = factory(User::class)->create(); + $editorUser = User::factory()->create(); $editorRole = Role::getRole('editor'); $editorUser->attachRole($editorRole); // Create a viewer user - $viewerUser = factory(User::class)->create(); + $viewerUser = User::factory()->create(); $role = Role::getRole('viewer'); $viewerUser->attachRole($role); $byData = ['created_by' => $editorUser->id, 'updated_by' => $editorUser->id, 'owned_by' => $editorUser->id]; - factory(\BookStack\Entities\Models\Book::class, 5)->create($byData) + \BookStack\Entities\Models\Book::factory()->count(5)->create($byData) ->each(function ($book) use ($byData) { - $chapters = factory(Chapter::class, 3)->create($byData) + $chapters = Chapter::factory()->count(3)->create($byData) ->each(function ($chapter) use ($book, $byData) { - $pages = factory(Page::class, 3)->make(array_merge($byData, ['book_id' => $book->id])); + $pages = Page::factory()->count(3)->make(array_merge($byData, ['book_id' => $book->id])); $chapter->pages()->saveMany($pages); }); - $pages = factory(Page::class, 3)->make($byData); + $pages = Page::factory()->count(3)->make($byData); $book->chapters()->saveMany($chapters); $book->pages()->saveMany($pages); }); - $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(array_merge($byData, ['name' => 'Large book'.Str::random(10)])); - $pages = factory(Page::class, 200)->make($byData); - $chapters = factory(Chapter::class, 50)->make($byData); + $largeBook = \BookStack\Entities\Models\Book::factory()->create(array_merge($byData, ['name' => 'Large book'.Str::random(10)])); + $pages = Page::factory()->count(200)->make($byData); + $chapters = Chapter::factory()->count(50)->make($byData); $largeBook->pages()->saveMany($pages); $largeBook->chapters()->saveMany($chapters); - $shelves = factory(Bookshelf::class, 10)->create($byData); + $shelves = Bookshelf::factory()->count(10)->create($byData); $largeBook->shelves()->attach($shelves->pluck('id')); // Assign API permission to editor role and create an API key diff --git a/database/seeds/LargeContentSeeder.php b/database/seeds/LargeContentSeeder.php index 89c0b0aef6a..3ed647828cf 100644 --- a/database/seeds/LargeContentSeeder.php +++ b/database/seeds/LargeContentSeeder.php @@ -19,13 +19,13 @@ class LargeContentSeeder extends Seeder public function run() { // Create an editor user - $editorUser = factory(User::class)->create(); + $editorUser = User::factory()->create(); $editorRole = Role::getRole('editor'); $editorUser->attachRole($editorRole); - $largeBook = factory(\BookStack\Entities\Models\Book::class)->create(['name' => 'Large book'.Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); - $pages = factory(Page::class, 200)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); - $chapters = factory(Chapter::class, 50)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); + $largeBook = \BookStack\Entities\Models\Book::factory()->create(['name' => 'Large book'.Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); + $pages = Page::factory()->count(200)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); + $chapters = Chapter::factory()->count(50)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $largeBook->pages()->saveMany($pages); $largeBook->chapters()->saveMany($chapters); app(PermissionService::class)->buildJointPermissions(); diff --git a/tests/Auth/AuthTest.php b/tests/Auth/AuthTest.php index 4d318cd9eb8..9faccf6d2e0 100644 --- a/tests/Auth/AuthTest.php +++ b/tests/Auth/AuthTest.php @@ -44,7 +44,7 @@ public function test_normal_registration() { // Set settings and get user instance $this->setSettings(['registration-enabled' => 'true']); - $user = factory(User::class)->make(); + $user = User::factory()->make(); // Test form and ensure user is created $this->get('/register') @@ -102,7 +102,7 @@ public function test_confirmed_registration() // Set settings and get user instance $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); - $user = factory(User::class)->make(); + $user = User::factory()->make(); // Go through registration process $resp = $this->post('/register', $user->only('name', 'email', 'password')); @@ -140,7 +140,7 @@ public function test_confirmed_registration() public function test_restricted_registration() { $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true', 'registration-restrict' => 'example.com']); - $user = factory(User::class)->make(); + $user = User::factory()->make(); // Go through registration process $this->post('/register', $user->only('name', 'email', 'password')) @@ -166,7 +166,7 @@ public function test_restricted_registration() public function test_restricted_registration_with_confirmation_disabled() { $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'false', 'registration-restrict' => 'example.com']); - $user = factory(User::class)->make(); + $user = User::factory()->make(); // Go through registration process $this->post('/register', $user->only('name', 'email', 'password')) diff --git a/tests/Auth/LdapTest.php b/tests/Auth/LdapTest.php index 1b0fe99750f..0b346f1e418 100644 --- a/tests/Auth/LdapTest.php +++ b/tests/Auth/LdapTest.php @@ -42,7 +42,7 @@ public function setUp(): void ]); $this->mockLdap = \Mockery::mock(Ldap::class); $this->app[Ldap::class] = $this->mockLdap; - $this->mockUser = factory(User::class)->make(); + $this->mockUser = User::factory()->make(); } protected function runFailedAuthLogin() @@ -264,9 +264,9 @@ public function test_non_admins_cannot_change_auth_id() public function test_login_maps_roles_and_retains_existing_roles() { - $roleToReceive = factory(Role::class)->create(['display_name' => 'LdapTester']); - $roleToReceive2 = factory(Role::class)->create(['display_name' => 'LdapTester Second']); - $existingRole = factory(Role::class)->create(['display_name' => 'ldaptester-existing']); + $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); + $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']); + $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); $this->mockUser->attachRole($existingRole); @@ -310,8 +310,8 @@ public function test_login_maps_roles_and_retains_existing_roles() public function test_login_maps_roles_and_removes_old_roles_if_set() { - $roleToReceive = factory(Role::class)->create(['display_name' => 'LdapTester']); - $existingRole = factory(Role::class)->create(['display_name' => 'ldaptester-existing']); + $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); + $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); $this->mockUser->attachRole($existingRole); @@ -350,15 +350,15 @@ public function test_login_maps_roles_and_removes_old_roles_if_set() public function test_external_auth_id_visible_in_roles_page_when_ldap_active() { - $role = factory(Role::class)->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']); + $role = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']); $this->asAdmin()->get('/settings/roles/'.$role->id) ->assertSee('ex-auth-a'); } public function test_login_maps_roles_using_external_auth_ids_if_set() { - $roleToReceive = factory(Role::class)->create(['display_name' => 'ldaptester', 'external_auth_id' => 'test-second-param, ex-auth-a']); - $roleToNotReceive = factory(Role::class)->create(['display_name' => 'ex-auth-a', 'external_auth_id' => 'test-second-param']); + $roleToReceive = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'test-second-param, ex-auth-a']); + $roleToNotReceive = Role::factory()->create(['display_name' => 'ex-auth-a', 'external_auth_id' => 'test-second-param']); app('config')->set([ 'services.ldap.user_to_groups' => true, @@ -395,8 +395,8 @@ public function test_login_maps_roles_using_external_auth_ids_if_set() public function test_login_group_mapping_does_not_conflict_with_default_role() { - $roleToReceive = factory(Role::class)->create(['display_name' => 'LdapTester']); - $roleToReceive2 = factory(Role::class)->create(['display_name' => 'LdapTester Second']); + $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); + $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); setting()->put('registration-role', $roleToReceive->id); @@ -641,8 +641,8 @@ public function test_new_ldap_user_login_with_already_used_email_address_shows_e public function test_login_with_email_confirmation_required_maps_groups_but_shows_confirmation_screen() { - $roleToReceive = factory(Role::class)->create(['display_name' => 'LdapTester']); - $user = factory(User::class)->make(); + $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); + $user = User::factory()->make(); setting()->put('registration-confirmation', 'true'); app('config')->set([ diff --git a/tests/Auth/Saml2Test.php b/tests/Auth/Saml2Test.php index bedda0520cc..75432d786a4 100644 --- a/tests/Auth/Saml2Test.php +++ b/tests/Auth/Saml2Test.php @@ -119,7 +119,7 @@ public function test_group_role_sync_on_login() 'saml2.remove_from_groups' => false, ]); - $memberRole = factory(Role::class)->create(['external_auth_id' => 'member']); + $memberRole = Role::factory()->create(['external_auth_id' => 'member']); $adminRole = Role::getSystemRole('admin'); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); @@ -141,7 +141,7 @@ public function test_group_role_sync_removal_option_works_as_expected() $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $user = User::query()->where('external_auth_id', '=', 'user')->first(); - $randomRole = factory(Role::class)->create(['external_auth_id' => 'random']); + $randomRole = Role::factory()->create(['external_auth_id' => 'random']); $user->attachRole($randomRole); $this->assertContains($randomRole->id, $user->roles()->pluck('id')); @@ -295,7 +295,7 @@ public function test_group_sync_functions_when_email_confirmation_required() 'saml2.remove_from_groups' => false, ]); - $memberRole = factory(Role::class)->create(['external_auth_id' => 'member']); + $memberRole = Role::factory()->create(['external_auth_id' => 'member']); $adminRole = Role::getSystemRole('admin'); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); diff --git a/tests/Auth/SocialAuthTest.php b/tests/Auth/SocialAuthTest.php index 3a3fe23f944..2fb2e692c31 100644 --- a/tests/Auth/SocialAuthTest.php +++ b/tests/Auth/SocialAuthTest.php @@ -15,7 +15,7 @@ class SocialAuthTest extends TestCase { public function test_social_registration() { - $user = factory(User::class)->make(); + $user = User::factory()->make(); $this->setSettings(['registration-enabled' => 'true']); config(['GOOGLE_APP_ID' => 'abc123', 'GOOGLE_APP_SECRET' => '123abc', 'APP_URL' => 'http://localhost']); @@ -118,7 +118,7 @@ public function test_social_autoregister() 'APP_URL' => 'http://localhost', ]); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); @@ -156,7 +156,7 @@ public function test_social_auto_email_confirm() 'APP_URL' => 'http://localhost', 'services.google.auto_register' => true, 'services.google.auto_confirm' => true, ]); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); @@ -188,7 +188,7 @@ public function test_google_select_account_option_changes_redirect_url() public function test_social_registration_with_no_name_uses_email_as_name() { - $user = factory(User::class)->make(['email' => 'nonameuser@example.com']); + $user = User::factory()->make(['email' => 'nonameuser@example.com']); $this->setSettings(['registration-enabled' => 'true']); config(['GITHUB_APP_ID' => 'abc123', 'GITHUB_APP_SECRET' => '123abc', 'APP_URL' => 'http://localhost']); diff --git a/tests/Entity/BookShelfTest.php b/tests/Entity/BookShelfTest.php index f799f7672a9..aad78f99477 100644 --- a/tests/Entity/BookShelfTest.php +++ b/tests/Entity/BookShelfTest.php @@ -37,7 +37,7 @@ public function test_shelves_shows_in_header_if_have_view_permissions() public function test_shelves_shows_in_header_if_have_any_shelve_view_permission() { - $user = factory(User::class)->create(); + $user = User::factory()->create(); $this->giveUserPermissions($user, ['image-create-all']); $shelf = Bookshelf::first(); $userRole = $user->roles()->first(); diff --git a/tests/Entity/BookTest.php b/tests/Entity/BookTest.php index f232ebf3fa4..a34e67d82de 100644 --- a/tests/Entity/BookTest.php +++ b/tests/Entity/BookTest.php @@ -9,7 +9,7 @@ class BookTest extends TestCase { public function test_create() { - $book = factory(Book::class)->make([ + $book = Book::factory()->make([ 'name' => 'My First Book', ]); @@ -29,7 +29,7 @@ public function test_create() public function test_create_uses_different_slugs_when_name_reused() { - $book = factory(Book::class)->make([ + $book = Book::factory()->make([ 'name' => 'My First Book', ]); diff --git a/tests/Entity/ChapterTest.php b/tests/Entity/ChapterTest.php index 3f0fe0effbf..4dd272b4352 100644 --- a/tests/Entity/ChapterTest.php +++ b/tests/Entity/ChapterTest.php @@ -13,7 +13,7 @@ public function test_create() /** @var Book $book */ $book = Book::query()->first(); - $chapter = factory(Chapter::class)->make([ + $chapter = Chapter::factory()->make([ 'name' => 'My First Chapter', ]); diff --git a/tests/Entity/CommentTest.php b/tests/Entity/CommentTest.php index f150f6e6702..4584e6285ee 100644 --- a/tests/Entity/CommentTest.php +++ b/tests/Entity/CommentTest.php @@ -13,7 +13,7 @@ public function test_add_comment() $this->asAdmin(); $page = Page::first(); - $comment = factory(Comment::class)->make(['parent_id' => 2]); + $comment = Comment::factory()->make(['parent_id' => 2]); $resp = $this->postJson("/comment/$page->id", $comment->getAttributes()); $resp->assertStatus(200); @@ -36,7 +36,7 @@ public function test_comment_edit() $this->asAdmin(); $page = Page::first(); - $comment = factory(Comment::class)->make(); + $comment = Comment::factory()->make(); $this->postJson("/comment/$page->id", $comment->getAttributes()); $comment = $page->comments()->first(); @@ -60,7 +60,7 @@ public function test_comment_delete() $this->asAdmin(); $page = Page::first(); - $comment = factory(Comment::class)->make(); + $comment = Comment::factory()->make(); $this->postJson("/comment/$page->id", $comment->getAttributes()); $comment = $page->comments()->first(); diff --git a/tests/Entity/PageTest.php b/tests/Entity/PageTest.php index 48749420cac..60e0e94f688 100644 --- a/tests/Entity/PageTest.php +++ b/tests/Entity/PageTest.php @@ -14,7 +14,7 @@ public function test_create() { /** @var Chapter $chapter */ $chapter = Chapter::query()->first(); - $page = factory(Page::class)->make([ + $page = Page::factory()->make([ 'name' => 'My First Page', ]); diff --git a/tests/Entity/TagTest.php b/tests/Entity/TagTest.php index 2823aaf890b..9886bc28d23 100644 --- a/tests/Entity/TagTest.php +++ b/tests/Entity/TagTest.php @@ -19,7 +19,7 @@ protected function getEntityWithTags($class, ?array $tags = null): Entity $entity = $class::first(); if (is_null($tags)) { - $tags = factory(Tag::class, $this->defaultTagCount)->make(); + $tags = Tag::factory()->count($this->defaultTagCount)->make(); } $entity->tags()->saveMany($tags); @@ -31,12 +31,12 @@ public function test_tag_name_suggestions() { // Create some tags with similar names to test with $attrs = collect(); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'city'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'county'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'planet'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'plans'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'city'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'county'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'planet'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'plans'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); $this->asAdmin()->get('/ajax/tags/suggest/names?search=dog')->assertExactJson([]); @@ -49,12 +49,12 @@ public function test_tag_value_suggestions() { // Create some tags with similar values to test with $attrs = collect(); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country', 'value' => 'cats'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color', 'value' => 'cattery'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'city', 'value' => 'castle'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'county', 'value' => 'dog'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'planet', 'value' => 'catapult'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'plans', 'value' => 'dodgy'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country', 'value' => 'cats'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color', 'value' => 'cattery'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'city', 'value' => 'castle'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'county', 'value' => 'dog'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'planet', 'value' => 'catapult'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'plans', 'value' => 'dodgy'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); $this->asAdmin()->get('/ajax/tags/suggest/values?search=ora')->assertExactJson([]); @@ -67,8 +67,8 @@ public function test_entity_permissions_effect_tag_suggestions() { // Create some tags with similar names to test with and save to a page $attrs = collect(); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country'])); - $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country'])); + $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); $this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertExactJson(['color', 'country']); @@ -86,8 +86,8 @@ public function test_entity_permissions_effect_tag_suggestions() public function test_tags_shown_on_search_listing() { $tags = [ - factory(Tag::class)->make(['name' => 'category', 'value' => 'buckets']), - factory(Tag::class)->make(['name' => 'color', 'value' => 'red']), + Tag::factory()->make(['name' => 'category', 'value' => 'buckets']), + Tag::factory()->make(['name' => 'color', 'value' => 'red']), ]; $page = $this->getEntityWithTags(Page::class, $tags); diff --git a/tests/HomepageTest.php b/tests/HomepageTest.php index 466c36a0e33..f9762c39649 100644 --- a/tests/HomepageTest.php +++ b/tests/HomepageTest.php @@ -167,7 +167,7 @@ public function test_shelves_list_homepage_adheres_to_book_visibility_permission public function test_new_users_dont_have_any_recently_viewed() { - $user = factory(User::class)->create(); + $user = User::factory()->create(); $viewRole = Role::getRole('Viewer'); $user->attachRole($viewRole); diff --git a/tests/Permissions/RolesTest.php b/tests/Permissions/RolesTest.php index 6aa1e09a950..71c3f987175 100644 --- a/tests/Permissions/RolesTest.php +++ b/tests/Permissions/RolesTest.php @@ -769,7 +769,7 @@ public function test_image_delete_own_permission() $this->giveUserPermissions($this->user, ['image-update-all']); /** @var Page $page */ $page = Page::query()->first(); - $image = factory(Image::class)->create([ + $image = Image::factory()->create([ 'uploaded_to' => $page->id, 'created_by' => $this->user->id, 'updated_by' => $this->user->id, @@ -789,7 +789,7 @@ public function test_image_delete_all_permission() $admin = $this->getAdmin(); /** @var Page $page */ $page = Page::query()->first(); - $image = factory(Image::class)->create(['uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id]); + $image = Image::factory()->create(['uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id]); $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); @@ -825,14 +825,14 @@ public function test_empty_state_actions_not_visible_without_permission() { $admin = $this->getAdmin(); // Book links - $book = factory(Book::class)->create(['created_by' => $admin->id, 'updated_by' => $admin->id]); + $book = Book::factory()->create(['created_by' => $admin->id, 'updated_by' => $admin->id]); $this->regenEntityPermissions($book); $this->actingAs($this->getViewer())->get($book->getUrl()) ->assertDontSee('Create a new page') ->assertDontSee('Add a chapter'); // Chapter links - $chapter = factory(Chapter::class)->create(['created_by' => $admin->id, 'updated_by' => $admin->id, 'book_id' => $book->id]); + $chapter = Chapter::factory()->create(['created_by' => $admin->id, 'updated_by' => $admin->id, 'book_id' => $book->id]); $this->regenEntityPermissions($chapter); $this->actingAs($this->getViewer())->get($chapter->getUrl()) ->assertDontSee('Create a new page') @@ -926,14 +926,14 @@ public function test_comment_delete_all_permission() private function addComment(Page $page): TestResponse { - $comment = factory(Comment::class)->make(); + $comment = Comment::factory()->make(); return $this->postJson("/comment/$page->id", $comment->only('text', 'html')); } private function updateComment(Comment $comment): TestResponse { - $commentData = factory(Comment::class)->make(); + $commentData = Comment::factory()->make(); return $this->putJson("/comment/{$comment->id}", $commentData->only('text', 'html')); } diff --git a/tests/SharedTestHelpers.php b/tests/SharedTestHelpers.php index d6b37cb80a4..8da98d3c63a 100644 --- a/tests/SharedTestHelpers.php +++ b/tests/SharedTestHelpers.php @@ -210,7 +210,7 @@ protected function removePermissionFromUser(User $user, string $permission) protected function createNewRole(array $permissions = []): Role { $permissionRepo = app(PermissionsRepo::class); - $roleData = factory(Role::class)->make()->toArray(); + $roleData = Role::factory()->make()->toArray(); $roleData['permissions'] = array_flip($permissions); return $permissionRepo->saveNewRole($roleData); @@ -228,9 +228,9 @@ protected function createEntityChainBelongingToUser(User $creatorUser, ?User $up } $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id]; - $book = factory(Book::class)->create($userAttrs); - $chapter = factory(Chapter::class)->create(array_merge(['book_id' => $book->id], $userAttrs)); - $page = factory(Page::class)->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs)); + $book = Book::factory()->create($userAttrs); + $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs)); + $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs)); $restrictionService = $this->app[PermissionService::class]; $restrictionService->buildJointPermissionsForEntity($book); diff --git a/tests/ThemeTest.php b/tests/ThemeTest.php index aaec9232385..e73e04b1e18 100644 --- a/tests/ThemeTest.php +++ b/tests/ThemeTest.php @@ -150,7 +150,7 @@ public function test_event_auth_register_standard() Theme::listen(ThemeEvents::AUTH_REGISTER, $callback); $this->setSettings(['registration-enabled' => 'true']); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']); $this->assertCount(2, $args); diff --git a/tests/Uploads/AvatarTest.php b/tests/Uploads/AvatarTest.php index ea80bfe8e8b..442a4e2b75c 100644 --- a/tests/Uploads/AvatarTest.php +++ b/tests/Uploads/AvatarTest.php @@ -42,7 +42,7 @@ public function test_gravatar_fetched_on_user_create() config()->set([ 'services.disable_services' => false, ]); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $this->assertImageFetchFrom('https://www.gravatar.com/avatar/'.md5(strtolower($user->email)).'?s=500&d=identicon'); $user = $this->createUserRequest($user); @@ -60,7 +60,7 @@ public function test_custom_url_used_if_set() 'services.avatar_url' => 'https://example.com/${email}/${hash}/${size}', ]); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $url = 'https://example.com/'.urlencode(strtolower($user->email)).'/'.md5(strtolower($user->email)).'/500'; $this->assertImageFetchFrom($url); @@ -74,7 +74,7 @@ public function test_avatar_not_fetched_if_no_custom_url_and_services_disabled() 'services.disable_services' => true, ]); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $http = $this->mock(HttpFetcher::class); $http->shouldNotReceive('fetch'); @@ -93,7 +93,7 @@ public function test_no_failure_but_error_logged_on_failed_avatar_fetch() $logger = $this->withTestLogger(); - $user = factory(User::class)->make(); + $user = User::factory()->make(); $this->createUserRequest($user); $this->assertTrue($logger->hasError('Failed to save user avatar image')); } diff --git a/tests/User/UserManagementTest.php b/tests/User/UserManagementTest.php index 6328fa9ee66..05e54654718 100644 --- a/tests/User/UserManagementTest.php +++ b/tests/User/UserManagementTest.php @@ -15,7 +15,7 @@ class UserManagementTest extends TestCase public function test_user_creation() { /** @var User $user */ - $user = factory(User::class)->make(); + $user = User::factory()->make(); $adminRole = Role::getRole('admin'); $resp = $this->asAdmin()->get('/settings/users'); diff --git a/tests/User/UserProfileTest.php b/tests/User/UserProfileTest.php index 09469c847c1..44e038f0bbb 100644 --- a/tests/User/UserProfileTest.php +++ b/tests/User/UserProfileTest.php @@ -42,7 +42,7 @@ public function test_profile_page_shows_recent_entities() public function test_profile_page_shows_created_content_counts() { - $newUser = factory(User::class)->create(); + $newUser = User::factory()->create(); $this->asAdmin()->get('/user/'.$newUser->slug) ->assertSee($newUser->name) @@ -61,7 +61,7 @@ public function test_profile_page_shows_created_content_counts() public function test_profile_page_shows_recent_activity() { - $newUser = factory(User::class)->create(); + $newUser = User::factory()->create(); $this->actingAs($newUser); $entities = $this->createEntityChainBelongingToUser($newUser, $newUser); Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); @@ -75,7 +75,7 @@ public function test_profile_page_shows_recent_activity() public function test_user_activity_has_link_leading_to_profile() { - $newUser = factory(User::class)->create(); + $newUser = User::factory()->create(); $this->actingAs($newUser); $entities = $this->createEntityChainBelongingToUser($newUser, $newUser); Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); From 5604965154abb9320501b9f0edd87ab7f362baa2 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:00 +0000 Subject: [PATCH 10/19] Namespace seeders --- database/{seeds => seeders}/.gitkeep | 0 database/{seeds => seeders}/DatabaseSeeder.php | 2 ++ database/{seeds => seeders}/DummyContentSeeder.php | 2 ++ database/{seeds => seeders}/LargeContentSeeder.php | 2 ++ 4 files changed, 6 insertions(+) rename database/{seeds => seeders}/.gitkeep (100%) rename database/{seeds => seeders}/DatabaseSeeder.php (92%) rename database/{seeds => seeders}/DummyContentSeeder.php (98%) rename database/{seeds => seeders}/LargeContentSeeder.php (97%) diff --git a/database/seeds/.gitkeep b/database/seeders/.gitkeep similarity index 100% rename from database/seeds/.gitkeep rename to database/seeders/.gitkeep diff --git a/database/seeds/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php similarity index 92% rename from database/seeds/DatabaseSeeder.php rename to database/seeders/DatabaseSeeder.php index 069765eb48c..21eaefb19ff 100644 --- a/database/seeds/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -1,5 +1,7 @@ Date: Thu, 28 Oct 2021 16:06:00 +0000 Subject: [PATCH 11/19] Shift PSR-4 autoloading --- composer.json | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index b50cee7621a..75ed6a003d4 100644 --- a/composer.json +++ b/composer.json @@ -53,12 +53,10 @@ "nunomaduro/collision": "^4.3" }, "autoload": { - "classmap": [ - "database/seeds", - "database/factories" - ], "psr-4": { - "BookStack\\": "app/" + "BookStack\\": "app/", + "Database\\Factories\\": "database/factories/", + "Database\\Seeders\\": "database/seeders/" }, "files": [ "app/helpers.php" From 523e7b566c481cdf5420dcf9c6384bc8ef949cad Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:03 +0000 Subject: [PATCH 12/19] Shift config files --- config/app.php | 2 ++ config/cors.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 config/cors.php diff --git a/config/app.php b/config/app.php index f90a7dd7602..002cf62b8e2 100644 --- a/config/app.php +++ b/config/app.php @@ -143,6 +143,8 @@ // Class aliases, Registered on application start 'aliases' => [ + 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, + 'Date' => Illuminate\Support\Facades\Date::class, // Laravel 'App' => Illuminate\Support\Facades\App::class, diff --git a/config/cors.php b/config/cors.php new file mode 100644 index 00000000000..8a39e6daa63 --- /dev/null +++ b/config/cors.php @@ -0,0 +1,34 @@ + ['api/*', 'sanctum/csrf-cookie'], + + 'allowed_methods' => ['*'], + + 'allowed_origins' => ['*'], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => ['*'], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + +]; From 08af910bef5743fd14c394f1ff839d20c5a86ddd Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:04 +0000 Subject: [PATCH 13/19] Default config files In an effort to make upgrading the constantly changing config files easier, Shift defaulted them and merged your true customizations - where ENV variables may not be used. --- config/auth.php | 118 ++++++++++++++++++++++++++++++---------- config/broadcasting.php | 59 ++++++++++++-------- config/cache.php | 99 ++++++++++++++++++++++----------- config/filesystems.php | 81 ++++++++++++++++++--------- config/logging.php | 103 ++++++++++++++++++++--------------- config/queue.php | 87 ++++++++++++++++++++++------- 6 files changed, 370 insertions(+), 177 deletions(-) diff --git a/config/auth.php b/config/auth.php index 88c22e70aca..c134aefb4da 100644 --- a/config/auth.php +++ b/config/auth.php @@ -1,81 +1,139 @@ env('AUTH_METHOD', 'standard'), - // Authentication Defaults - // This option controls the default authentication "guard" and password - // reset options for your application. + /* + |-------------------------------------------------------------------------- + | Authentication Defaults + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + 'defaults' => [ 'guard' => env('AUTH_METHOD', 'standard'), 'passwords' => 'users', ], - // Authentication Guards - // All authentication drivers have a user provider. This defines how the - // users are actually retrieved out of your database or other storage - // mechanisms used by this application to persist your user's data. - // Supported drivers: "session", "api-token", "ldap-session", "async-external-session" + /* + |-------------------------------------------------------------------------- + | Authentication Guards + |-------------------------------------------------------------------------- + | + | Next, you may define every authentication guard for your application. + | Of course, a great default configuration has been defined for you + | here which uses session storage and the Eloquent user provider. + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | Supported: "session" + | + */ + 'guards' => [ 'standard' => [ 'driver' => 'session', 'provider' => 'users', ], + 'ldap' => [ 'driver' => 'ldap-session', 'provider' => 'external', ], + 'saml2' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], + 'oidc' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], - 'api' => [ - 'driver' => 'api-token', + + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', ], ], - // User Providers - // All authentication drivers have a user provider. This defines how the - // users are actually retrieved out of your database or other storage - // mechanisms used by this application to persist your user's data. + /* + |-------------------------------------------------------------------------- + | User Providers + |-------------------------------------------------------------------------- + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | If you have multiple user tables or models you may configure multiple + | sources which represent each model / table. These sources may then + | be assigned to any extra authentication guards you have defined. + | + | Supported: "database", "eloquent" + | + */ + 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \BookStack\Auth\User::class, ], + 'external' => [ 'driver' => 'external-users', 'model' => \BookStack\Auth\User::class, ], + + // 'users' => [ + // 'driver' => 'database', + // 'table' => 'users', + // ], ], - // Resetting Passwords - // The expire time is the number of minutes that the reset token should be - // considered valid. This security feature keeps tokens short-lived so - // they have less time to be guessed. You may change this as needed. + /* + |-------------------------------------------------------------------------- + | Resetting Passwords + |-------------------------------------------------------------------------- + | + | You may specify multiple password reset configurations if you have more + | than one user table or model in the application and you want to have + | separate password reset settings based on the specific user types. + | + | The expire time is the number of minutes that the reset token should be + | considered valid. This security feature keeps tokens short-lived so + | they have less time to be guessed. You may change this as needed. + | + */ + 'passwords' => [ 'users' => [ 'provider' => 'users', 'email' => 'emails.password', - 'table' => 'password_resets', - 'expire' => 60, + 'table' => 'password_resets', + 'expire' => 60, 'throttle' => 60, ], ], + /* + |-------------------------------------------------------------------------- + | Password Confirmation Timeout + |-------------------------------------------------------------------------- + | + | Here you may define the amount of seconds before a password confirmation + | times out and the user is prompted to re-enter their password via the + | confirmation screen. By default, the timeout lasts for three hours. + | + */ + + 'password_timeout' => 10800, + ]; diff --git a/config/broadcasting.php b/config/broadcasting.php index 5e929d3730f..2d529820cc5 100644 --- a/config/broadcasting.php +++ b/config/broadcasting.php @@ -1,40 +1,53 @@ env('BROADCAST_DRIVER', 'pusher'), + /* + |-------------------------------------------------------------------------- + | Default Broadcaster + |-------------------------------------------------------------------------- + | + | This option controls the default broadcaster that will be used by the + | framework when an event needs to be broadcast. You may set this to + | any of the connections defined in the "connections" array below. + | + | Supported: "pusher", "ably", "redis", "log", "null" + | + */ + + 'default' => env('BROADCAST_DRIVER', 'null'), + + /* + |-------------------------------------------------------------------------- + | Broadcast Connections + |-------------------------------------------------------------------------- + | + | Here you may define all of the broadcast connections that will be used + | to broadcast events to other systems or over websockets. Samples of + | each available type of connection are provided inside this array. + | + */ - // Broadcast Connections - // Here you may define all of the broadcast connections that will be used - // to broadcast events to other systems or over websockets. Samples of - // each available type of connection are provided inside this array. 'connections' => [ 'pusher' => [ - 'driver' => 'pusher', - 'key' => env('PUSHER_APP_KEY'), - 'secret' => env('PUSHER_APP_SECRET'), - 'app_id' => env('PUSHER_APP_ID'), + 'driver' => 'pusher', + 'key' => env('PUSHER_APP_KEY'), + 'secret' => env('PUSHER_APP_SECRET'), + 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), - 'useTLS' => true, + 'useTLS' => true, ], ], + 'ably' => [ + 'driver' => 'ably', + 'key' => env('ABLY_KEY'), + ], + 'redis' => [ - 'driver' => 'redis', + 'driver' => 'redis', 'connection' => 'default', ], diff --git a/config/cache.php b/config/cache.php index f9b7ed1d20e..21209af053a 100644 --- a/config/cache.php +++ b/config/cache.php @@ -1,36 +1,36 @@ $memcachedServer) { - $memcachedServerDetails = explode(':', $memcachedServer); - if (count($memcachedServerDetails) < 2) { - $memcachedServerDetails[] = '11211'; - } - if (count($memcachedServerDetails) < 3) { - $memcachedServerDetails[] = '100'; - } - $memcachedServers[$index] = array_combine($memcachedServerKeys, $memcachedServerDetails); - } -} +use Illuminate\Support\Str; return [ - // Default cache store to use - // Can be overridden at cache call-time + /* + |-------------------------------------------------------------------------- + | Default Cache Store + |-------------------------------------------------------------------------- + | + | This option controls the default cache connection that gets used while + | using this caching library. This connection is used when another is + | not explicitly specified when executing a given caching function. + | + */ + 'default' => env('CACHE_DRIVER', 'file'), - // Available caches stores + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Here you may define all of the cache "stores" for your application as + | well as their drivers. You may even define multiple stores for the + | same cache driver to group types of items stored in your caches. + | + | Supported drivers: "apc", "array", "database", "file", + | "memcached", "redis", "dynamodb", "octane", "null" + | + */ + 'stores' => [ 'apc' => [ @@ -39,12 +39,14 @@ 'array' => [ 'driver' => 'array', + 'serialize' => false, ], 'database' => [ - 'driver' => 'database', - 'table' => 'cache', + 'driver' => 'database', + 'table' => 'cache', 'connection' => null, + 'lock_connection' => null, ], 'file' => [ @@ -53,19 +55,50 @@ ], 'memcached' => [ - 'driver' => 'memcached', + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], 'servers' => env('CACHE_DRIVER') === 'memcached' ? $memcachedServers : [], ], 'redis' => [ - 'driver' => 'redis', + 'driver' => 'redis', 'connection' => 'default', + 'lock_connection' => 'default', + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), + ], + + 'octane' => [ + 'driver' => 'octane', ], ], - // Cache key prefix - // Used to prevent collisions in shared cache systems. - 'prefix' => env('CACHE_PREFIX', 'bookstack_cache'), + /* + |-------------------------------------------------------------------------- + | Cache Key Prefix + |-------------------------------------------------------------------------- + | + | When utilizing a RAM based store such as APC or Memcached, there might + | be other applications utilizing the same cache. So, we'll specify a + | value to get prefixed to all our keys so we can avoid collisions. + | + */ + + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'), ]; diff --git a/config/filesystems.php b/config/filesystems.php index a6b05c8c4aa..f4fb2d353e5 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -1,35 +1,39 @@ env('STORAGE_TYPE', 'local'), + /* + |-------------------------------------------------------------------------- + | Default Filesystem Disk + |-------------------------------------------------------------------------- + | + | Here you may specify the default filesystem disk that should be used + | by the framework. The "local" disk, as well as a variety of cloud + | based disks are available to your application. Just store away! + | + */ + + 'default' => env('FILESYSTEM_DRIVER', 'local'), - // Filesystem to use specifically for image uploads. 'images' => env('STORAGE_IMAGE_TYPE', env('STORAGE_TYPE', 'local')), - // Filesystem to use specifically for file attachments. 'attachments' => env('STORAGE_ATTACHMENT_TYPE', env('STORAGE_TYPE', 'local')), - // Storage URL - // This is the url to where the storage is located for when using an external - // file storage service, such as s3, to store publicly accessible assets. 'url' => env('STORAGE_URL', false), - // Default Cloud Filesystem Disk - 'cloud' => 's3', + /* + |-------------------------------------------------------------------------- + | Filesystem Disks + |-------------------------------------------------------------------------- + | + | Here you may configure as many filesystem "disks" as you wish, and you + | may even configure multiple disks of the same driver. Defaults have + | been setup for each driver as an example of the required options. + | + | Supported Drivers: "local", "ftp", "sftp", "s3" + | + */ - // Available filesystem disks - // Only local, local_secure & s3 are supported by BookStack 'disks' => [ 'local' => [ @@ -47,16 +51,39 @@ 'root' => storage_path('uploads/images/'), ], + 'public' => [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => env('APP_URL').'/storage', + 'visibility' => 'public', + ], + 's3' => [ - 'driver' => 's3', - 'key' => env('STORAGE_S3_KEY', 'your-key'), - 'secret' => env('STORAGE_S3_SECRET', 'your-secret'), - 'region' => env('STORAGE_S3_REGION', 'your-region'), - 'bucket' => env('STORAGE_S3_BUCKET', 'your-bucket'), - 'endpoint' => env('STORAGE_S3_ENDPOINT', null), - 'use_path_style_endpoint' => env('STORAGE_S3_ENDPOINT', null) !== null, + 'driver' => 's3', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION'), + 'bucket' => env('AWS_BUCKET'), + 'url' => env('AWS_URL'), + 'endpoint' => env('AWS_ENDPOINT'), + 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), ], ], + /* + |-------------------------------------------------------------------------- + | Symbolic Links + |-------------------------------------------------------------------------- + | + | Here you may configure the symbolic links that will be created when the + | `storage:link` Artisan command is executed. The array keys should be + | the locations of the links and the values should be their targets. + | + */ + + 'links' => [ + public_path('storage') => storage_path('app/public'), + ], + ]; diff --git a/config/logging.php b/config/logging.php index 220aa060704..cdaa4ea1e29 100644 --- a/config/logging.php +++ b/config/logging.php @@ -1,82 +1,98 @@ env('LOG_CHANNEL', 'single'), - - // Log Channels - // Here you may configure the log channels for your application. Out of - // the box, Laravel uses the Monolog PHP logging library. This gives - // you a variety of powerful log handlers / formatters to utilize. - // Available Drivers: "single", "daily", "slack", "syslog", - // "errorlog", "monolog", - // "custom", "stack" + /* + |-------------------------------------------------------------------------- + | Default Log Channel + |-------------------------------------------------------------------------- + | + | This option defines the default log channel that gets used when writing + | messages to the logs. The name specified in this option should match + | one of the channels defined in the "channels" configuration array. + | + */ + + 'default' => env('LOG_CHANNEL', 'stack'), + + /* + |-------------------------------------------------------------------------- + | Log Channels + |-------------------------------------------------------------------------- + | + | Here you may configure the log channels for your application. Out of + | the box, Laravel uses the Monolog PHP logging library. This gives + | you a variety of powerful log handlers / formatters to utilize. + | + | Available Drivers: "single", "daily", "slack", "syslog", + | "errorlog", "monolog", + | "custom", "stack" + | + */ + 'channels' => [ 'stack' => [ - 'driver' => 'stack', + 'driver' => 'stack', 'channels' => ['daily'], 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', - 'path' => storage_path('logs/laravel.log'), - 'level' => 'debug', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), 'days' => 14, ], 'daily' => [ 'driver' => 'daily', - 'path' => storage_path('logs/laravel.log'), - 'level' => 'debug', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), 'days' => 7, ], 'slack' => [ - 'driver' => 'slack', - 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Laravel Log', - 'emoji' => ':boom:', - 'level' => 'critical', + 'emoji' => ':boom:', + 'level' => env('LOG_LEVEL', 'critical'), + ], + + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => SyslogUdpHandler::class, + 'handler_with' => [ + 'host' => env('PAPERTRAIL_URL'), + 'port' => env('PAPERTRAIL_PORT'), + ], ], 'stderr' => [ - 'driver' => 'monolog', + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), 'handler' => StreamHandler::class, - 'with' => [ + 'formatter' => env('LOG_STDERR_FORMATTER'), + 'with' => [ 'stream' => 'php://stderr', ], ], 'syslog' => [ 'driver' => 'syslog', - 'level' => 'debug', + 'level' => env('LOG_LEVEL', 'debug'), ], 'errorlog' => [ 'driver' => 'errorlog', - 'level' => 'debug', + 'level' => env('LOG_LEVEL', 'debug'), ], - // Custom errorlog implementation that logs out a plain, - // non-formatted message intended for the webserver log. 'errorlog_plain_webserver' => [ 'driver' => 'monolog', 'level' => 'debug', @@ -89,20 +105,19 @@ ], 'null' => [ - 'driver' => 'monolog', + 'driver' => 'monolog', 'handler' => NullHandler::class, ], - // Testing channel - // Uses a shared testing instance during tests - // so that logs can be checked against. 'testing' => [ 'driver' => 'testing', ], + + 'emergency' => [ + 'path' => storage_path('logs/laravel.log'), + ], ], - // Failed Login Message - // Allows a configurable message to be logged when a login request fails. 'failed_login' => [ 'message' => env('LOG_FAILED_LOGIN_MESSAGE', null), 'channel' => env('LOG_FAILED_LOGIN_CHANNEL', 'errorlog_plain_webserver'), diff --git a/config/queue.php b/config/queue.php index 0c79fcdd20c..25ea5a81935 100644 --- a/config/queue.php +++ b/config/queue.php @@ -1,20 +1,33 @@ env('QUEUE_CONNECTION', 'sync'), - // Queue connection configuration + /* + |-------------------------------------------------------------------------- + | Queue Connections + |-------------------------------------------------------------------------- + | + | Here you may configure the connection information for each server that + | is used by your application. A default configuration has been added + | for each back-end shipped with Laravel. You are free to add more. + | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" + | + */ + 'connections' => [ 'sync' => [ @@ -22,25 +35,59 @@ ], 'database' => [ - 'driver' => 'database', - 'table' => 'jobs', - 'queue' => 'default', + 'driver' => 'database', + 'table' => 'jobs', + 'queue' => 'default', 'retry_after' => 90, + 'after_commit' => false, + ], + + 'beanstalkd' => [ + 'driver' => 'beanstalkd', + 'host' => 'localhost', + 'queue' => 'default', + 'retry_after' => 90, + 'block_for' => 0, + 'after_commit' => false, + ], + + 'sqs' => [ + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, ], 'redis' => [ - 'driver' => 'redis', - 'connection' => 'default', - 'queue' => env('REDIS_QUEUE', 'default'), + 'driver' => 'redis', + 'connection' => 'default', + 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => 90, - 'block_for' => null, + 'block_for' => null, + 'after_commit' => false, ], ], - // Failed queue job logging + /* + |-------------------------------------------------------------------------- + | Failed Queue Jobs + |-------------------------------------------------------------------------- + | + | These options configure the behavior of failed queue job logging so you + | can control which database and table are used to store the jobs that + | have failed. You may change them to any database / table you wish. + | + */ + 'failed' => [ - 'database' => 'mysql', 'table' => 'failed_jobs', + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'database' => env('DB_CONNECTION', 'mysql'), + 'table' => 'failed_jobs', ], ]; From 202bc56f160ed8786f89524837fc1a54d26a1eb2 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:04 +0000 Subject: [PATCH 14/19] Shift Laravel dependencies --- composer.json | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/composer.json b/composer.json index 75ed6a003d4..9256b6e96cf 100644 --- a/composer.json +++ b/composer.json @@ -20,10 +20,9 @@ "barryvdh/laravel-dompdf": "^0.9.0", "barryvdh/laravel-snappy": "^0.4.8", "doctrine/dbal": "^3.1", - "fideloper/proxy": "^4.4.1", "filp/whoops": "^2.14", "intervention/image": "^2.7", - "laravel/framework": "^7.29", + "laravel/framework": "^8.68", "laravel/socialite": "^5.2", "league/commonmark": "^1.5", "league/flysystem-aws-s3-v3": "^1.0.29", @@ -40,17 +39,19 @@ "socialiteproviders/slack": "^4.1", "socialiteproviders/twitch": "^5.3", "ssddanbrown/htmldiff": "^1.0.1", - "laravel/ui": "^2.5", + "laravel/ui": "^3.3", "guzzlehttp/guzzle": "^7.4.0", - "laravel/tinker": "^2.5" + "laravel/tinker": "^2.5", + "fruitcake/laravel-cors": "^2.0" }, "require-dev": { "barryvdh/laravel-debugbar": "^3.6", "fakerphp/faker": "^1.13.0", - "mockery/mockery": "^1.3.3", + "mockery/mockery": "^1.4.2", "phpunit/phpunit": "^9.5.3", "symfony/dom-crawler": "^5.3", - "nunomaduro/collision": "^4.3" + "nunomaduro/collision": "^5.0", + "facade/ignition": "^2.5" }, "autoload": { "psr-4": { @@ -88,6 +89,9 @@ "refresh-test-database": [ "@php artisan migrate:refresh --database=mysql_testing", "@php artisan db:seed --class=DummyContentSeeder --database=mysql_testing" + ], + "post-update-cmd": [ + "@php artisan vendor:publish --tag=laravel-assets --ansi" ] }, "config": { From 184581159540e6a64f68b67a6dd2999c72a36fe3 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:04 +0000 Subject: [PATCH 15/19] Shift return type of base TestCase methods From the [PHPUnit 8 release notes][1], the `TestCase` methods below now declare a `void` return type: - `setUpBeforeClass()` - `setUp()` - `assertPreConditions()` - `assertPostConditions()` - `tearDown()` - `tearDownAfterClass()` - `onNotSuccessfulTest()` [1]: https://phpunit.de/announcements/phpunit-8.html --- tests/AuditLogTest.php | 2 +- tests/Auth/LdapTest.php | 2 +- tests/Auth/OidcTest.php | 4 ++-- tests/Auth/Saml2Test.php | 2 +- tests/Entity/CommentSettingTest.php | 2 +- tests/Entity/PageDraftTest.php | 2 +- tests/Entity/PageEditorTest.php | 2 +- tests/Entity/SortTest.php | 2 +- tests/LanguageTest.php | 2 +- tests/Permissions/EntityPermissionsTest.php | 2 +- tests/Permissions/RolesTest.php | 2 +- tests/User/UserProfileTest.php | 2 +- 12 files changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/AuditLogTest.php b/tests/AuditLogTest.php index 90590a6fd48..70c5979f27b 100644 --- a/tests/AuditLogTest.php +++ b/tests/AuditLogTest.php @@ -17,7 +17,7 @@ class AuditLogTest extends TestCase /** @var ActivityService */ protected $activityService; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->activityService = app(ActivityService::class); diff --git a/tests/Auth/LdapTest.php b/tests/Auth/LdapTest.php index 0b346f1e418..ae4cbb3ee05 100644 --- a/tests/Auth/LdapTest.php +++ b/tests/Auth/LdapTest.php @@ -20,7 +20,7 @@ class LdapTest extends TestCase protected $mockUser; protected $resourceId = 'resource-test'; - public function setUp(): void + protected function setUp(): void { parent::setUp(); if (! defined('LDAP_OPT_REFERRALS')) { diff --git a/tests/Auth/OidcTest.php b/tests/Auth/OidcTest.php index cbe8762be42..ba555915a9a 100644 --- a/tests/Auth/OidcTest.php +++ b/tests/Auth/OidcTest.php @@ -16,7 +16,7 @@ class OidcTest extends TestCase protected $keyFilePath; protected $keyFile; - public function setUp(): void + protected function setUp(): void { parent::setUp(); // Set default config for OpenID Connect @@ -41,7 +41,7 @@ public function setUp(): void ]); } - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); if (file_exists($this->keyFilePath)) { diff --git a/tests/Auth/Saml2Test.php b/tests/Auth/Saml2Test.php index 75432d786a4..b5b72c5c75a 100644 --- a/tests/Auth/Saml2Test.php +++ b/tests/Auth/Saml2Test.php @@ -8,7 +8,7 @@ class Saml2Test extends TestCase { - public function setUp(): void + protected function setUp(): void { parent::setUp(); // Set default config for SAML2 diff --git a/tests/Entity/CommentSettingTest.php b/tests/Entity/CommentSettingTest.php index d8caa73585a..23607f5a70f 100644 --- a/tests/Entity/CommentSettingTest.php +++ b/tests/Entity/CommentSettingTest.php @@ -9,7 +9,7 @@ class CommentSettingTest extends TestCase { protected $page; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->page = Page::query()->first(); diff --git a/tests/Entity/PageDraftTest.php b/tests/Entity/PageDraftTest.php index 14865fb7853..7e066264011 100644 --- a/tests/Entity/PageDraftTest.php +++ b/tests/Entity/PageDraftTest.php @@ -20,7 +20,7 @@ class PageDraftTest extends TestCase */ protected $pageRepo; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->page = Page::query()->first(); diff --git a/tests/Entity/PageEditorTest.php b/tests/Entity/PageEditorTest.php index df08f415c5e..ee4a3ff7dea 100644 --- a/tests/Entity/PageEditorTest.php +++ b/tests/Entity/PageEditorTest.php @@ -11,7 +11,7 @@ class PageEditorTest extends TestCase /** @var Page */ protected $page; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->page = Page::query()->first(); diff --git a/tests/Entity/SortTest.php b/tests/Entity/SortTest.php index 1f47cd8e280..acf1db54ad9 100644 --- a/tests/Entity/SortTest.php +++ b/tests/Entity/SortTest.php @@ -12,7 +12,7 @@ class SortTest extends TestCase { protected $book; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->book = Book::first(); diff --git a/tests/LanguageTest.php b/tests/LanguageTest.php index a9070248e5f..ef44af0eebd 100644 --- a/tests/LanguageTest.php +++ b/tests/LanguageTest.php @@ -9,7 +9,7 @@ class LanguageTest extends TestCase /** * LanguageTest constructor. */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->langs = array_diff(scandir(resource_path('lang')), ['..', '.']); diff --git a/tests/Permissions/EntityPermissionsTest.php b/tests/Permissions/EntityPermissionsTest.php index 3e20694f075..cd98018984c 100644 --- a/tests/Permissions/EntityPermissionsTest.php +++ b/tests/Permissions/EntityPermissionsTest.php @@ -23,7 +23,7 @@ class EntityPermissionsTest extends TestCase */ protected $viewer; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->user = $this->getEditor(); diff --git a/tests/Permissions/RolesTest.php b/tests/Permissions/RolesTest.php index 71c3f987175..b4ae1c00af8 100644 --- a/tests/Permissions/RolesTest.php +++ b/tests/Permissions/RolesTest.php @@ -19,7 +19,7 @@ class RolesTest extends TestCase { protected $user; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->user = $this->getViewer(); diff --git a/tests/User/UserProfileTest.php b/tests/User/UserProfileTest.php index 44e038f0bbb..34e6443e629 100644 --- a/tests/User/UserProfileTest.php +++ b/tests/User/UserProfileTest.php @@ -14,7 +14,7 @@ class UserProfileTest extends TestCase */ protected $user; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->user = User::all()->last(); From f5ee0e90708738cae5276f60071ff6d86ab82158 Mon Sep 17 00:00:00 2001 From: Shift Date: Thu, 28 Oct 2021 16:06:23 +0000 Subject: [PATCH 16/19] Shift cleanup --- app/Actions/Comment.php | 3 +-- app/Actions/Tag.php | 2 +- app/Auth/Role.php | 2 +- app/Auth/User.php | 3 +-- app/Entities/Models/Book.php | 2 +- app/Entities/Models/Bookshelf.php | 2 +- app/Entities/Models/Page.php | 2 +- app/Http/Middleware/TrustHosts.php | 2 +- app/Providers/RouteServiceProvider.php | 6 ++---- app/Uploads/Image.php | 3 +-- database/factories/Actions/CommentFactory.php | 3 ++- database/factories/Actions/TagFactory.php | 3 ++- database/factories/Auth/RoleFactory.php | 3 ++- database/factories/Auth/UserFactory.php | 4 +++- database/factories/Entities/Models/BookFactory.php | 4 +++- database/factories/Entities/Models/BookshelfFactory.php | 4 +++- database/factories/Entities/Models/ChapterFactory.php | 4 +++- database/factories/Entities/Models/PageFactory.php | 4 +++- database/factories/Uploads/ImageFactory.php | 3 ++- database/seeders/DummyContentSeeder.php | 1 + routes/web.php | 2 +- 21 files changed, 36 insertions(+), 26 deletions(-) diff --git a/app/Actions/Comment.php b/app/Actions/Comment.php index ba77f1a94ae..885ba6ed1ac 100644 --- a/app/Actions/Comment.php +++ b/app/Actions/Comment.php @@ -2,9 +2,9 @@ namespace BookStack\Actions; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Model; use BookStack\Traits\HasCreatorAndUpdater; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\MorphTo; /** @@ -17,7 +17,6 @@ class Comment extends Model { use HasFactory; - use HasCreatorAndUpdater; protected $fillable = ['text', 'parent_id']; diff --git a/app/Actions/Tag.php b/app/Actions/Tag.php index 91957ef28f5..22d65bbd5af 100644 --- a/app/Actions/Tag.php +++ b/app/Actions/Tag.php @@ -2,8 +2,8 @@ namespace BookStack\Actions; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Model; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\MorphTo; class Tag extends Model diff --git a/app/Auth/Role.php b/app/Auth/Role.php index 4d527e8d741..71da88e19b1 100644 --- a/app/Auth/Role.php +++ b/app/Auth/Role.php @@ -2,12 +2,12 @@ namespace BookStack\Auth; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Auth\Permissions\JointPermission; use BookStack\Auth\Permissions\RolePermission; use BookStack\Interfaces\Loggable; use BookStack\Model; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; diff --git a/app/Auth/User.php b/app/Auth/User.php index 0c8b3bd6adc..d559a8f6136 100644 --- a/app/Auth/User.php +++ b/app/Auth/User.php @@ -2,7 +2,6 @@ namespace BookStack\Auth; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Actions\Favourite; use BookStack\Api\ApiToken; use BookStack\Auth\Access\Mfa\MfaValue; @@ -19,6 +18,7 @@ use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -45,7 +45,6 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable { use HasFactory; - use Authenticatable; use CanResetPassword; use Notifiable; diff --git a/app/Entities/Models/Book.php b/app/Entities/Models/Book.php index 12f7950b033..f73fe9c03cc 100644 --- a/app/Entities/Models/Book.php +++ b/app/Entities/Models/Book.php @@ -2,9 +2,9 @@ namespace BookStack\Entities\Models; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Uploads\Image; use Exception; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; diff --git a/app/Entities/Models/Bookshelf.php b/app/Entities/Models/Bookshelf.php index eda5294c9c1..e6809989a4c 100644 --- a/app/Entities/Models/Bookshelf.php +++ b/app/Entities/Models/Bookshelf.php @@ -2,8 +2,8 @@ namespace BookStack\Entities\Models; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Uploads\Image; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; diff --git a/app/Entities/Models/Page.php b/app/Entities/Models/Page.php index 77b4239c280..9ae7cfa8639 100644 --- a/app/Entities/Models/Page.php +++ b/app/Entities/Models/Page.php @@ -2,11 +2,11 @@ namespace BookStack\Entities\Models; -use Illuminate\Database\Eloquent\Factories\HasFactory; use BookStack\Entities\Tools\PageContent; use BookStack\Uploads\Attachment; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Permissions; diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php index b0550cfc7c6..7bd89ee51de 100644 --- a/app/Http/Middleware/TrustHosts.php +++ b/app/Http/Middleware/TrustHosts.php @@ -1,6 +1,6 @@ Date: Sat, 30 Oct 2021 20:28:11 +0100 Subject: [PATCH 17/19] Applied stylci style changes --- app/Actions/Activity.php | 2 +- app/Actions/ActivityService.php | 6 +- app/Actions/Tag.php | 4 +- app/Actions/TagRepo.php | 4 +- app/Api/ApiDocsGenerator.php | 4 +- app/Api/ApiTokenGuard.php | 8 +- app/Api/ListingResponseBuilder.php | 10 +- app/Auth/Access/ExternalBaseUserProvider.php | 2 +- .../Guards/ExternalBaseSessionGuard.php | 8 +- app/Auth/Access/Guards/LdapSessionGuard.php | 2 +- app/Auth/Access/LdapService.php | 12 +-- app/Auth/Access/LoginService.php | 6 +- app/Auth/Access/Mfa/BackupCodeService.php | 4 +- app/Auth/Access/Mfa/MfaSession.php | 4 +- app/Auth/Access/Oidc/OidcIdToken.php | 10 +- app/Auth/Access/Oidc/OidcJwtSigningKey.php | 2 +- app/Auth/Access/Oidc/OidcProviderSettings.php | 14 +-- app/Auth/Access/Oidc/OidcService.php | 2 +- app/Auth/Access/RegistrationService.php | 10 +- app/Auth/Access/Saml2Service.php | 16 +-- app/Auth/Access/SocialAuthService.php | 26 ++--- app/Auth/Access/UserTokenService.php | 2 +- app/Auth/Permissions/PermissionService.php | 36 +++---- app/Auth/User.php | 6 +- app/Auth/UserRepo.php | 10 +- app/Console/Commands/CleanupImages.php | 8 +- app/Console/Commands/CopyShelfPermissions.php | 12 +-- app/Console/Commands/CreateAdmin.php | 2 +- app/Console/Commands/ResetMfa.php | 4 +- app/Console/Commands/UpdateUrl.php | 4 +- .../Commands/UpgradeDatabaseEncoding.php | 8 +- app/Console/Kernel.php | 2 +- app/Entities/Models/Book.php | 4 +- app/Entities/Models/Bookshelf.php | 4 +- app/Entities/Models/Chapter.php | 2 +- app/Entities/Models/Deletion.php | 2 +- app/Entities/Models/Entity.php | 8 +- app/Entities/Models/Page.php | 2 +- app/Entities/Models/PageRevision.php | 4 +- app/Entities/Repos/BookshelfRepo.php | 4 +- app/Entities/Repos/PageRepo.php | 16 +-- app/Entities/Tools/BookContents.php | 8 +- app/Entities/Tools/ExportFormatter.php | 20 ++-- .../Markdown/CustomStrikethroughRenderer.php | 4 +- app/Entities/Tools/PageContent.php | 26 ++--- app/Entities/Tools/PageEditActivity.php | 2 +- app/Entities/Tools/PermissionsUpdater.php | 6 +- app/Entities/Tools/SearchIndex.php | 2 +- app/Entities/Tools/SearchOptions.php | 6 +- app/Entities/Tools/SearchRunner.php | 34 +++--- app/Entities/Tools/ShelfContext.php | 2 +- app/Entities/Tools/SiblingFetcher.php | 2 +- app/Entities/Tools/SlugGenerator.php | 2 +- app/Exceptions/NotifyException.php | 2 +- app/Exceptions/PrettyException.php | 2 +- .../Api/AttachmentApiController.php | 2 +- .../Api/BookExportApiController.php | 8 +- .../Api/ChapterExportApiController.php | 8 +- .../Controllers/Api/PageApiController.php | 4 +- .../Api/PageExportApiController.php | 8 +- .../Controllers/Auth/HandlesPartialLogins.php | 2 +- app/Http/Controllers/Auth/LoginController.php | 2 +- .../Auth/MfaBackupCodesController.php | 8 +- .../Controllers/Auth/MfaTotpController.php | 2 +- app/Http/Controllers/Auth/Saml2Controller.php | 6 +- .../Controllers/Auth/SocialController.php | 4 +- app/Http/Controllers/BookController.php | 4 +- app/Http/Controllers/BookExportController.php | 8 +- app/Http/Controllers/BookSortController.php | 2 +- app/Http/Controllers/BookshelfController.php | 4 +- .../Controllers/ChapterExportController.php | 8 +- app/Http/Controllers/Controller.php | 8 +- app/Http/Controllers/FavouriteController.php | 8 +- app/Http/Controllers/HomeController.php | 8 +- .../Images/DrawioImageController.php | 2 +- .../Controllers/Images/ImageController.php | 4 +- .../Controllers/MaintenanceController.php | 6 +- app/Http/Controllers/PageController.php | 4 +- app/Http/Controllers/PageExportController.php | 8 +- .../Controllers/PageTemplateController.php | 2 +- app/Http/Controllers/SearchController.php | 4 +- app/Http/Controllers/SettingController.php | 4 +- .../Controllers/UserApiTokenController.php | 8 +- app/Http/Controllers/UserController.php | 26 ++--- app/Http/Controllers/UserSearchController.php | 6 +- app/Http/Middleware/ApiAuthenticate.php | 2 +- app/Http/Middleware/Authenticate.php | 2 +- app/Http/Middleware/CheckEmailConfirmed.php | 2 +- app/Http/Middleware/CheckGuard.php | 2 +- .../Middleware/CheckUserHasPermission.php | 2 +- app/Http/Middleware/Localization.php | 2 +- .../Middleware/RedirectIfAuthenticated.php | 2 +- app/Http/Middleware/RunThemeActions.php | 2 +- app/Http/Request.php | 2 +- app/Notifications/ConfirmEmail.php | 2 +- app/Notifications/ResetPassword.php | 2 +- app/Notifications/UserInvite.php | 2 +- .../CustomValidationServiceProvider.php | 2 +- app/Providers/RouteServiceProvider.php | 2 +- app/Settings/SettingService.php | 12 +-- app/Theming/CustomHtmlHeadContentProvider.php | 4 +- app/Theming/ThemeService.php | 4 +- app/Uploads/Attachment.php | 8 +- app/Uploads/AttachmentService.php | 22 ++-- app/Uploads/ImageRepo.php | 6 +- app/Uploads/ImageService.php | 44 ++++---- app/Uploads/UserAvatars.php | 6 +- app/Util/CspService.php | 6 +- app/Util/HtmlContentFilter.php | 12 +-- app/Util/HtmlNonceApplicator.php | 2 +- app/helpers.php | 24 ++--- config/app.php | 2 +- config/auth.php | 6 +- config/broadcasting.php | 14 +-- config/cache.php | 28 ++--- config/filesystems.php | 20 ++-- config/logging.php | 38 +++---- config/queue.php | 46 ++++---- config/services.php | 22 ++-- config/session.php | 2 +- config/view.php | 2 +- database/factories/Actions/CommentFactory.php | 2 +- database/factories/Auth/UserFactory.php | 2 +- .../factories/Entities/Models/PageFactory.php | 2 +- database/factories/Uploads/ImageFactory.php | 2 +- ...08_29_105422_add_roles_and_permissions.php | 8 +- ...27_120329_update_permissions_and_roles.php | 12 +-- ...9_100730_add_view_permissions_to_roles.php | 6 +- ..._192649_create_joint_permissions_table.php | 4 +- ..._10_09_142037_create_attachments_table.php | 6 +- .../2017_04_20_185112_add_revision_counts.php | 4 +- ...017_08_01_130541_create_comments_table.php | 6 +- ..._08_04_115700_create_bookshelves_table.php | 8 +- .../2021_03_08_215138_add_user_slug.php | 2 +- database/seeders/DummyContentSeeder.php | 2 +- database/seeders/LargeContentSeeder.php | 2 +- tests/Api/ApiConfigTest.php | 4 +- tests/Api/ApiDocsTest.php | 2 +- tests/Api/ApiListingTest.php | 16 +-- tests/Api/AttachmentsApiTest.php | 6 +- tests/Api/BooksApiTest.php | 32 +++--- tests/Api/ChaptersApiTest.php | 30 +++--- tests/Api/PagesApiTest.php | 36 +++---- tests/Api/ShelvesApiTest.php | 12 +-- tests/AuditLogTest.php | 14 +-- tests/Auth/AuthTest.php | 16 +-- tests/Auth/LdapTest.php | 42 ++++---- tests/Auth/OidcTest.php | 28 ++--- tests/Auth/Saml2Test.php | 8 +- tests/Auth/SocialAuthTest.php | 2 +- tests/Auth/UserInviteTest.php | 20 ++-- tests/CreatesApplication.php | 2 +- tests/DebugViewTest.php | 8 +- tests/Entity/BookShelfTest.php | 18 ++-- tests/Entity/BookTest.php | 24 ++--- tests/Entity/ChapterTest.php | 4 +- tests/Entity/CommentTest.php | 2 +- tests/Entity/EntitySearchTest.php | 90 ++++++++-------- tests/Entity/ExportTest.php | 38 +++---- tests/Entity/PageContentTest.php | 18 ++-- tests/Entity/PageDraftTest.php | 20 ++-- tests/Entity/PageEditorTest.php | 8 +- tests/Entity/PageRevisionTest.php | 14 +-- tests/Entity/PageTemplateTest.php | 4 +- tests/Entity/PageTest.php | 12 +-- tests/Entity/SortTest.php | 30 +++--- tests/Entity/TagTest.php | 8 +- tests/Helpers/OidcJwtHelper.php | 2 +- tests/HomepageTest.php | 2 +- tests/OpenGraphTest.php | 8 +- tests/Permissions/EntityPermissionsTest.php | 102 +++++++++--------- tests/Permissions/ExportPermissionsTest.php | 4 +- tests/Permissions/RolesTest.php | 82 +++++++------- tests/PublicActionTest.php | 6 +- tests/RecycleBinTest.php | 12 +-- tests/SecurityHeaderTest.php | 4 +- tests/SharedTestHelpers.php | 4 +- tests/TestEmailTest.php | 4 +- tests/TestResponse.php | 44 ++++---- tests/ThemeTest.php | 4 +- tests/Unit/OidcIdTokenTest.php | 8 +- tests/Uploads/AttachmentTest.php | 12 +-- tests/Uploads/AvatarTest.php | 4 +- tests/Uploads/DrawioTest.php | 2 +- tests/Uploads/ImageTest.php | 40 +++---- tests/Uploads/UsesImages.php | 4 +- tests/User/UserApiTokenTest.php | 26 ++--- tests/User/UserManagementTest.php | 26 ++--- tests/User/UserPreferencesTest.php | 16 +-- tests/User/UserProfileTest.php | 24 ++--- 190 files changed, 1013 insertions(+), 1013 deletions(-) diff --git a/app/Actions/Activity.php b/app/Actions/Activity.php index 3eb7c3ca75b..3b1408cb94d 100644 --- a/app/Actions/Activity.php +++ b/app/Actions/Activity.php @@ -45,7 +45,7 @@ public function user(): BelongsTo */ public function getText(): string { - return trans('activities.'.$this->type); + return trans('activities.' . $this->type); } /** diff --git a/app/Actions/ActivityService.php b/app/Actions/ActivityService.php index a060b6f131b..bc7a6b6b7c3 100644 --- a/app/Actions/ActivityService.php +++ b/app/Actions/ActivityService.php @@ -160,7 +160,7 @@ protected function filterSimilar(iterable $activities): array $previousItem = null; foreach ($activities as $activityItem) { - if (! $previousItem || ! $activityItem->isSimilarTo($previousItem)) { + if (!$previousItem || !$activityItem->isSimilarTo($previousItem)) { $newActivity[] = $activityItem; } @@ -175,7 +175,7 @@ protected function filterSimilar(iterable $activities): array */ protected function setNotification(string $type) { - $notificationTextKey = 'activities.'.$type.'_notification'; + $notificationTextKey = 'activities.' . $type . '_notification'; if (trans()->has($notificationTextKey)) { $message = trans($notificationTextKey); session()->flash('success', $message); @@ -189,7 +189,7 @@ protected function setNotification(string $type) public function logFailedLogin(string $username) { $message = config('logging.failed_login.message'); - if (! $message) { + if (!$message) { return; } diff --git a/app/Actions/Tag.php b/app/Actions/Tag.php index 22d65bbd5af..db9328b7d59 100644 --- a/app/Actions/Tag.php +++ b/app/Actions/Tag.php @@ -26,7 +26,7 @@ public function entity(): MorphTo */ public function nameUrl(): string { - return url('/search?term=%5B'.urlencode($this->name).'%5D'); + return url('/search?term=%5B' . urlencode($this->name) . '%5D'); } /** @@ -34,6 +34,6 @@ public function nameUrl(): string */ public function valueUrl(): string { - return url('/search?term=%5B'.urlencode($this->name).'%3D'.urlencode($this->value).'%5D'); + return url('/search?term=%5B' . urlencode($this->name) . '%3D' . urlencode($this->value) . '%5D'); } } diff --git a/app/Actions/TagRepo.php b/app/Actions/TagRepo.php index a3b1db98a1e..b892efe5779 100644 --- a/app/Actions/TagRepo.php +++ b/app/Actions/TagRepo.php @@ -32,7 +32,7 @@ public function getNameSuggestions(?string $searchTerm): Collection ->groupBy('name'); if ($searchTerm) { - $query = $query->where('name', 'LIKE', $searchTerm.'%')->orderBy('name', 'desc'); + $query = $query->where('name', 'LIKE', $searchTerm . '%')->orderBy('name', 'desc'); } else { $query = $query->orderBy('count', 'desc')->take(50); } @@ -54,7 +54,7 @@ public function getValueSuggestions(?string $searchTerm, ?string $tagName): Coll ->groupBy('value'); if ($searchTerm) { - $query = $query->where('value', 'LIKE', $searchTerm.'%')->orderBy('value', 'desc'); + $query = $query->where('value', 'LIKE', $searchTerm . '%')->orderBy('value', 'desc'); } else { $query = $query->orderBy('count', 'desc')->take(50); } diff --git a/app/Api/ApiDocsGenerator.php b/app/Api/ApiDocsGenerator.php index 47719d41b34..0ed7e6712d3 100644 --- a/app/Api/ApiDocsGenerator.php +++ b/app/Api/ApiDocsGenerator.php @@ -24,7 +24,7 @@ class ApiDocsGenerator public static function generateConsideringCache(): Collection { $appVersion = trim(file_get_contents(base_path('version'))); - $cacheKey = 'api-docs::'.$appVersion; + $cacheKey = 'api-docs::' . $appVersion; if (Cache::has($cacheKey) && config('app.env') === 'production') { $docs = Cache::get($cacheKey); } else { @@ -139,7 +139,7 @@ protected function getFlatApiRoutes(): Collection })->map(function ($route) { [$controller, $controllerMethod] = explode('@', $route->action['uses']); $baseModelName = explode('.', explode('/', $route->uri)[1])[0]; - $shortName = $baseModelName.'-'.$controllerMethod; + $shortName = $baseModelName . '-' . $controllerMethod; return [ 'name' => $shortName, diff --git a/app/Api/ApiTokenGuard.php b/app/Api/ApiTokenGuard.php index 4c79ca75313..1bb672556df 100644 --- a/app/Api/ApiTokenGuard.php +++ b/app/Api/ApiTokenGuard.php @@ -48,7 +48,7 @@ public function user() { // Return the user if we've already retrieved them. // Effectively a request-instance cache for this method. - if (! is_null($this->user)) { + if (!is_null($this->user)) { return $this->user; } @@ -74,7 +74,7 @@ public function user() */ public function authenticate() { - if (! is_null($user = $this->user())) { + if (!is_null($user = $this->user())) { return $user; } @@ -137,7 +137,7 @@ protected function validateToken(?ApiToken $token, string $secret): void throw new ApiAuthException(trans('errors.api_user_token_not_found')); } - if (! Hash::check($secret, $token->secret)) { + if (!Hash::check($secret, $token->secret)) { throw new ApiAuthException(trans('errors.api_incorrect_token_secret')); } @@ -146,7 +146,7 @@ protected function validateToken(?ApiToken $token, string $secret): void throw new ApiAuthException(trans('errors.api_user_token_expired'), 403); } - if (! $token->user->can('access-api')) { + if (!$token->user->can('access-api')) { throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403); } } diff --git a/app/Api/ListingResponseBuilder.php b/app/Api/ListingResponseBuilder.php index 21b8adfd22d..02b3f680cf0 100644 --- a/app/Api/ListingResponseBuilder.php +++ b/app/Api/ListingResponseBuilder.php @@ -66,14 +66,14 @@ protected function filterQuery(Builder $query): Builder { $query = clone $query; $requestFilters = $this->request->get('filter', []); - if (! is_array($requestFilters)) { + if (!is_array($requestFilters)) { return $query; } $queryFilters = collect($requestFilters)->map(function ($value, $key) { return $this->requestFilterToQueryFilter($key, $value); })->filter(function ($value) { - return ! is_null($value); + return !is_null($value); })->values()->toArray(); return $query->where($queryFilters); @@ -88,11 +88,11 @@ protected function requestFilterToQueryFilter($fieldKey, $value): ?array $field = $splitKey[0]; $filterOperator = $splitKey[1] ?? 'eq'; - if (! in_array($field, $this->fields)) { + if (!in_array($field, $this->fields)) { return null; } - if (! in_array($filterOperator, array_keys($this->filterOperators))) { + if (!in_array($filterOperator, array_keys($this->filterOperators))) { $filterOperator = 'eq'; } @@ -117,7 +117,7 @@ protected function sortQuery(Builder $query): Builder } $sortName = ltrim($sort, '+- '); - if (! in_array($sortName, $this->fields)) { + if (!in_array($sortName, $this->fields)) { $sortName = $defaultSortName; } diff --git a/app/Auth/Access/ExternalBaseUserProvider.php b/app/Auth/Access/ExternalBaseUserProvider.php index 55abbfd2714..fde610c3e18 100644 --- a/app/Auth/Access/ExternalBaseUserProvider.php +++ b/app/Auth/Access/ExternalBaseUserProvider.php @@ -31,7 +31,7 @@ public function __construct(string $model) */ public function createModel() { - $class = '\\'.ltrim($this->model, '\\'); + $class = '\\' . ltrim($this->model, '\\'); return new $class(); } diff --git a/app/Auth/Access/Guards/ExternalBaseSessionGuard.php b/app/Auth/Access/Guards/ExternalBaseSessionGuard.php index ac8d2ddaa52..99bfd2e795e 100644 --- a/app/Auth/Access/Guards/ExternalBaseSessionGuard.php +++ b/app/Auth/Access/Guards/ExternalBaseSessionGuard.php @@ -84,7 +84,7 @@ public function user() // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. - if (! is_null($this->user)) { + if (!is_null($this->user)) { return $this->user; } @@ -92,7 +92,7 @@ public function user() // First we will try to load the user using the // identifier in the session if one exists. - if (! is_null($id)) { + if (!is_null($id)) { $this->user = $this->provider->retrieveById($id); } @@ -142,7 +142,7 @@ public function once(array $credentials = []) */ public function onceUsingId($id) { - if (! is_null($user = $this->provider->retrieveById($id))) { + if (!is_null($user = $this->provider->retrieveById($id))) { $this->setUser($user); return $user; @@ -264,7 +264,7 @@ public function getLastAttempted() */ public function getName() { - return 'login_'.$this->name.'_'.sha1(static::class); + return 'login_' . $this->name . '_' . sha1(static::class); } /** diff --git a/app/Auth/Access/Guards/LdapSessionGuard.php b/app/Auth/Access/Guards/LdapSessionGuard.php index 4576d7ace9c..7f6965937a1 100644 --- a/app/Auth/Access/Guards/LdapSessionGuard.php +++ b/app/Auth/Access/Guards/LdapSessionGuard.php @@ -76,7 +76,7 @@ public function attempt(array $credentials = [], $remember = false) ]); } - if (! $this->ldapService->validateUserCredentials($userDetails, $credentials['password'])) { + if (!$this->ldapService->validateUserCredentials($userDetails, $credentials['password'])) { return false; } diff --git a/app/Auth/Access/LdapService.php b/app/Auth/Access/LdapService.php index d7804f89488..e3a38537ac3 100644 --- a/app/Auth/Access/LdapService.php +++ b/app/Auth/Access/LdapService.php @@ -181,7 +181,7 @@ protected function bindSystemUser($connection) $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass); } - if (! $ldapBind) { + if (!$ldapBind) { throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed'))); } } @@ -201,7 +201,7 @@ protected function getConnection() } // Check LDAP extension in installed - if (! function_exists('ldap_connect') && config('app.env') !== 'testing') { + if (!function_exists('ldap_connect') && config('app.env') !== 'testing') { throw new LdapException(trans('errors.ldap_extension_not_installed')); } @@ -226,7 +226,7 @@ protected function getConnection() // Start and verify TLS if it's enabled if ($this->config['start_tls']) { $started = $this->ldap->startTls($ldapConnection); - if (! $started) { + if (!$started) { throw new LdapException('Could not start TLS connection'); } } @@ -263,7 +263,7 @@ protected function buildFilter(string $filterString, array $attrs): string { $newAttrs = []; foreach ($attrs as $key => $attrText) { - $newKey = '${'.$key.'}'; + $newKey = '${' . $key . '}'; $newAttrs[$newKey] = $this->ldap->escape($attrText); } @@ -332,7 +332,7 @@ private function getGroupGroups(string $groupName): array $baseDn = $this->config['base_dn']; $groupsAttr = strtolower($this->config['group_attribute']); - $groupFilter = 'CN='.$this->ldap->escape($groupName); + $groupFilter = 'CN=' . $this->ldap->escape($groupName); $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]); if ($groups['count'] === 0) { return []; @@ -357,7 +357,7 @@ protected function groupFilter(array $userGroupSearchResponse): array for ($i = 0; $i < $count; $i++) { $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1); - if (! in_array($dnComponents[0], $ldapGroups)) { + if (!in_array($dnComponents[0], $ldapGroups)) { $ldapGroups[] = $dnComponents[0]; } } diff --git a/app/Auth/Access/LoginService.php b/app/Auth/Access/LoginService.php index dd4aba01974..f41570417ef 100644 --- a/app/Auth/Access/LoginService.php +++ b/app/Auth/Access/LoginService.php @@ -90,7 +90,7 @@ public function getLastLoginAttemptUser(): ?User protected function getLastLoginAttemptDetails(): array { $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY); - if (! $value) { + if (!$value) { return ['user_id' => null, 'method' => null]; } @@ -131,7 +131,7 @@ protected function clearLastLoginAttempted(): void */ public function needsMfaVerification(User $user): bool { - return ! $this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user); + return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user); } /** @@ -139,7 +139,7 @@ public function needsMfaVerification(User $user): bool */ public function awaitingEmailConfirmation(User $user): bool { - return $this->emailConfirmationService->confirmationRequired() && ! $user->email_confirmed; + return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed; } /** diff --git a/app/Auth/Access/Mfa/BackupCodeService.php b/app/Auth/Access/Mfa/BackupCodeService.php index 32faf73ba48..d58d28ae12f 100644 --- a/app/Auth/Access/Mfa/BackupCodeService.php +++ b/app/Auth/Access/Mfa/BackupCodeService.php @@ -13,8 +13,8 @@ public function generateNewSet(): array { $codes = []; while (count($codes) < 16) { - $code = Str::random(5).'-'.Str::random(5); - if (! in_array($code, $codes)) { + $code = Str::random(5) . '-' . Str::random(5); + if (!in_array($code, $codes)) { $codes[] = strtolower($code); } } diff --git a/app/Auth/Access/Mfa/MfaSession.php b/app/Auth/Access/Mfa/MfaSession.php index 69a8b817155..72163b58ec4 100644 --- a/app/Auth/Access/Mfa/MfaSession.php +++ b/app/Auth/Access/Mfa/MfaSession.php @@ -21,7 +21,7 @@ public function isRequiredForUser(User $user): bool */ public function isPendingMfaSetup(User $user): bool { - return $this->isRequiredForUser($user) && ! $user->mfaValues()->exists(); + return $this->isRequiredForUser($user) && !$user->mfaValues()->exists(); } /** @@ -55,6 +55,6 @@ public function markVerifiedForUser(User $user): void */ protected function getMfaVerifiedSessionKey(User $user): string { - return 'mfa-verification-passed:'.$user->id; + return 'mfa-verification-passed:' . $user->id; } } diff --git a/app/Auth/Access/Oidc/OidcIdToken.php b/app/Auth/Access/Oidc/OidcIdToken.php index 83538755496..c955c3b0915 100644 --- a/app/Auth/Access/Oidc/OidcIdToken.php +++ b/app/Auth/Access/Oidc/OidcIdToken.php @@ -115,12 +115,12 @@ public function getAllClaims(): array protected function validateTokenStructure(): void { foreach (['header', 'payload'] as $prop) { - if (empty($this->$prop) || ! is_array($this->$prop)) { + if (empty($this->$prop) || !is_array($this->$prop)) { throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token"); } } - if (empty($this->signature) || ! is_string($this->signature)) { + if (empty($this->signature) || !is_string($this->signature)) { throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token'); } } @@ -140,13 +140,13 @@ protected function validateTokenSignature(): void try { return new OidcJwtSigningKey($key); } catch (OidcInvalidKeyException $e) { - throw new OidcInvalidTokenException('Failed to read signing key with error: '.$e->getMessage()); + throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage()); } }, $this->keys); $parsedKeys = array_filter($parsedKeys); - $contentToSign = $this->tokenParts[0].'.'.$this->tokenParts[1]; + $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1]; /** @var OidcJwtSigningKey $parsedKey */ foreach ($parsedKeys as $parsedKey) { if ($parsedKey->verify($contentToSign, $this->signature)) { @@ -181,7 +181,7 @@ protected function validateTokenClaims(string $clientId): void $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud']; if (count($aud) !== 1) { - throw new OidcInvalidTokenException('Token audience value has '.count($aud).' values, Expected 1'); + throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1'); } if ($aud[0] !== $clientId) { diff --git a/app/Auth/Access/Oidc/OidcJwtSigningKey.php b/app/Auth/Access/Oidc/OidcJwtSigningKey.php index 4828ecb9c09..9a5b3833ade 100644 --- a/app/Auth/Access/Oidc/OidcJwtSigningKey.php +++ b/app/Auth/Access/Oidc/OidcJwtSigningKey.php @@ -48,7 +48,7 @@ protected function loadFromPath(string $path) throw new OidcInvalidKeyException("Failed to load key from file path with error: {$exception->getMessage()}"); } - if (! ($this->key instanceof RSA)) { + if (!($this->key instanceof RSA)) { throw new OidcInvalidKeyException('Key loaded from file path is not an RSA key as expected'); } } diff --git a/app/Auth/Access/Oidc/OidcProviderSettings.php b/app/Auth/Access/Oidc/OidcProviderSettings.php index 71b0cf7af39..32946d058cf 100644 --- a/app/Auth/Access/Oidc/OidcProviderSettings.php +++ b/app/Auth/Access/Oidc/OidcProviderSettings.php @@ -111,7 +111,7 @@ public function validate(): void public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes) { try { - $cacheKey = 'oidc-discovery::'.$this->issuer; + $cacheKey = 'oidc-discovery::' . $this->issuer; $discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function () use ($httpClient) { return $this->loadSettingsFromIssuerDiscovery($httpClient); }); @@ -127,12 +127,12 @@ public function discoverFromIssuer(ClientInterface $httpClient, Repository $cach */ protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): array { - $issuerUrl = rtrim($this->issuer, '/').'/.well-known/openid-configuration'; + $issuerUrl = rtrim($this->issuer, '/') . '/.well-known/openid-configuration'; $request = new Request('GET', $issuerUrl); $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); - if (empty($result) || ! is_array($result)) { + if (empty($result) || !is_array($result)) { throw new OidcIssuerDiscoveryException("Error discovering provider settings from issuer at URL {$issuerUrl}"); } @@ -142,15 +142,15 @@ protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): $discoveredSettings = []; - if (! empty($result['authorization_endpoint'])) { + if (!empty($result['authorization_endpoint'])) { $discoveredSettings['authorizationEndpoint'] = $result['authorization_endpoint']; } - if (! empty($result['token_endpoint'])) { + if (!empty($result['token_endpoint'])) { $discoveredSettings['tokenEndpoint'] = $result['token_endpoint']; } - if (! empty($result['jwks_uri'])) { + if (!empty($result['jwks_uri'])) { $keys = $this->loadKeysFromUri($result['jwks_uri'], $httpClient); $discoveredSettings['keys'] = $this->filterKeys($keys); } @@ -180,7 +180,7 @@ protected function loadKeysFromUri(string $uri, ClientInterface $httpClient): ar $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); - if (empty($result) || ! is_array($result) || ! isset($result['keys'])) { + if (empty($result) || !is_array($result) || !isset($result['keys'])) { throw new OidcIssuerDiscoveryException('Error reading keys from issuer jwks_uri'); } diff --git a/app/Auth/Access/Oidc/OidcService.php b/app/Auth/Access/Oidc/OidcService.php index 9b1717bd6ee..b8e017b4b13 100644 --- a/app/Auth/Access/Oidc/OidcService.php +++ b/app/Auth/Access/Oidc/OidcService.php @@ -94,7 +94,7 @@ protected function getProviderSettings(): OidcProviderSettings ]); // Use keys if configured - if (! empty($config['jwt_public_key'])) { + if (!empty($config['jwt_public_key'])) { $settings->keys = [$config['jwt_public_key']]; } diff --git a/app/Auth/Access/RegistrationService.php b/app/Auth/Access/RegistrationService.php index 149c8f574de..dcdb68bd5cd 100644 --- a/app/Auth/Access/RegistrationService.php +++ b/app/Auth/Access/RegistrationService.php @@ -34,7 +34,7 @@ public function __construct(UserRepo $userRepo, EmailConfirmationService $emailC */ public function ensureRegistrationAllowed() { - if (! $this->registrationAllowed()) { + if (!$this->registrationAllowed()) { throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login'); } } @@ -90,7 +90,7 @@ public function registerUser(array $userData, ?SocialAccount $socialAccount = nu $this->ensureEmailDomainAllowed($userEmail); // Ensure user does not already exist - $alreadyUser = ! is_null($this->userRepo->getByEmail($userEmail)); + $alreadyUser = !is_null($this->userRepo->getByEmail($userEmail)); if ($alreadyUser) { throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login'); } @@ -107,7 +107,7 @@ public function registerUser(array $userData, ?SocialAccount $socialAccount = nu Theme::dispatch(ThemeEvents::AUTH_REGISTER, $socialAccount ? $socialAccount->driver : auth()->getDefaultDriver(), $newUser); // Start email confirmation flow if required - if ($this->emailConfirmationService->confirmationRequired() && ! $emailConfirmed) { + if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) { $newUser->save(); try { @@ -133,13 +133,13 @@ protected function ensureEmailDomainAllowed(string $userEmail): void { $registrationRestrict = setting('registration-restrict'); - if (! $registrationRestrict) { + if (!$registrationRestrict) { return; } $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict)); $userEmailDomain = $domain = mb_substr(mb_strrchr($userEmail, '@'), 1); - if (! in_array($userEmailDomain, $restrictedEmailDomains)) { + if (!in_array($userEmailDomain, $restrictedEmailDomains)) { $redirect = $this->registrationAllowed() ? '/register' : '/login'; throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), $redirect); diff --git a/app/Auth/Access/Saml2Service.php b/app/Auth/Access/Saml2Service.php index bcd441a64c7..ad889faf7c1 100644 --- a/app/Auth/Access/Saml2Service.php +++ b/app/Auth/Access/Saml2Service.php @@ -108,13 +108,13 @@ public function processAcsResponse(string $requestId, string $samlResponse): ?Us $toolkit->processResponse($requestId); $errors = $toolkit->getErrors(); - if (! empty($errors)) { + if (!empty($errors)) { throw new Error( - 'Invalid ACS Response: '.implode(', ', $errors) + 'Invalid ACS Response: ' . implode(', ', $errors) ); } - if (! $toolkit->isAuthenticated()) { + if (!$toolkit->isAuthenticated()) { return null; } @@ -141,9 +141,9 @@ public function processSlsResponse(?string $requestId): ?string $redirect = $toolkit->processSLO(true, $requestId, true, null, true); $errors = $toolkit->getErrors(); - if (! empty($errors)) { + if (!empty($errors)) { throw new Error( - 'Invalid SLS Response: '.implode(', ', $errors) + 'Invalid SLS Response: ' . implode(', ', $errors) ); } @@ -173,9 +173,9 @@ public function metadata(): string $metadata = $settings->getSPMetadata(); $errors = $settings->validateMetadata($metadata); - if (! empty($errors)) { + if (!empty($errors)) { throw new Error( - 'Invalid SP metadata: '.implode(', ', $errors), + 'Invalid SP metadata: ' . implode(', ', $errors), Error::METADATA_SP_INVALID ); } @@ -305,7 +305,7 @@ public function getUserGroups(array $samlAttributes): array $groupsAttr = $this->config['group_attribute']; $userGroups = $samlAttributes[$groupsAttr] ?? null; - if (! is_array($userGroups)) { + if (!is_array($userGroups)) { $userGroups = []; } diff --git a/app/Auth/Access/SocialAuthService.php b/app/Auth/Access/SocialAuthService.php index 9210f386fa2..d165e76b121 100644 --- a/app/Auth/Access/SocialAuthService.php +++ b/app/Auth/Access/SocialAuthService.php @@ -140,7 +140,7 @@ public function handleLoginCallback(string $socialDriver, SocialUser $socialUser // When a user is not logged in and a matching SocialAccount exists, // Simply log the user into the application. - if (! $isLoggedIn && $socialAccount !== null) { + if (!$isLoggedIn && $socialAccount !== null) { $this->loginService->login($socialAccount->user, $socialDriver); return redirect()->intended('/'); @@ -188,11 +188,11 @@ protected function validateDriver(string $socialDriver): string { $driver = trim(strtolower($socialDriver)); - if (! in_array($driver, $this->validSocialDrivers)) { + if (!in_array($driver, $this->validSocialDrivers)) { abort(404, trans('errors.social_driver_not_found')); } - if (! $this->checkDriverConfigured($driver)) { + if (!$this->checkDriverConfigured($driver)) { throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($socialDriver)])); } @@ -205,10 +205,10 @@ protected function validateDriver(string $socialDriver): string protected function checkDriverConfigured(string $driver): bool { $lowerName = strtolower($driver); - $configPrefix = 'services.'.$lowerName.'.'; - $config = [config($configPrefix.'client_id'), config($configPrefix.'client_secret'), config('services.callback_url')]; + $configPrefix = 'services.' . $lowerName . '.'; + $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')]; - return ! in_array(false, $config) && ! in_array(null, $config); + return !in_array(false, $config) && !in_array(null, $config); } /** @@ -232,7 +232,7 @@ public function getActiveDrivers(): array */ public function getDriverName(string $driver): string { - return config('services.'.strtolower($driver).'.name'); + return config('services.' . strtolower($driver) . '.name'); } /** @@ -240,7 +240,7 @@ public function getDriverName(string $driver): string */ public function driverAutoRegisterEnabled(string $driver): bool { - return config('services.'.strtolower($driver).'.auto_register') === true; + return config('services.' . strtolower($driver) . '.auto_register') === true; } /** @@ -248,7 +248,7 @@ public function driverAutoRegisterEnabled(string $driver): bool */ public function driverAutoConfirmEmailEnabled(string $driver): bool { - return config('services.'.strtolower($driver).'.auto_confirm') === true; + return config('services.' . strtolower($driver) . '.auto_confirm') === true; } /** @@ -306,11 +306,11 @@ public function addSocialDriver( callable $configureForRedirect = null ) { $this->validSocialDrivers[] = $driverName; - config()->set('services.'.$driverName, $config); - config()->set('services.'.$driverName.'.redirect', url('/login/service/'.$driverName.'/callback')); - config()->set('services.'.$driverName.'.name', $config['name'] ?? $driverName); + config()->set('services.' . $driverName, $config); + config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback')); + config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName); Event::listen(SocialiteWasCalled::class, $socialiteHandler); - if (! is_null($configureForRedirect)) { + if (!is_null($configureForRedirect)) { $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect; } } diff --git a/app/Auth/Access/UserTokenService.php b/app/Auth/Access/UserTokenService.php index dd60ae47847..ffd828ab509 100644 --- a/app/Auth/Access/UserTokenService.php +++ b/app/Auth/Access/UserTokenService.php @@ -55,7 +55,7 @@ public function checkTokenAndGetUserId(string $token): int $entry = $this->getEntryByToken($token); if (is_null($entry)) { - throw new UserTokenNotFoundException('Token "'.$token.'" not found'); + throw new UserTokenNotFoundException('Token "' . $token . '" not found'); } if ($this->entryExpired($entry)) { diff --git a/app/Auth/Permissions/PermissionService.php b/app/Auth/Permissions/PermissionService.php index 9c1764dc172..13972533971 100644 --- a/app/Auth/Permissions/PermissionService.php +++ b/app/Auth/Permissions/PermissionService.php @@ -68,7 +68,7 @@ protected function readyEntityCache(array $entities = []) foreach ($entities as $entity) { $class = get_class($entity); - if (! isset($this->entityCache[$class])) { + if (!isset($this->entityCache[$class])) { $this->entityCache[$class] = collect(); } $this->entityCache[$class]->put($entity->id, $entity); @@ -106,7 +106,7 @@ protected function getChapter(int $chapterId): ?Chapter */ protected function getCurrentUserRoles(): array { - if (! is_null($this->userRoles)) { + if (!is_null($this->userRoles)) { return $this->userRoles; } @@ -338,7 +338,7 @@ protected function createManyJointPermissions(array $entities, array $roles) $entityRestrictedMap = []; $permissionFetch = EntityPermission::query(); foreach ($entities as $entity) { - $entityRestrictedMap[$entity->getMorphClass().':'.$entity->id] = boolval($entity->getRawAttribute('restricted')); + $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted')); $permissionFetch->orWhere(function ($query) use ($entity) { $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass()); }); @@ -348,8 +348,8 @@ protected function createManyJointPermissions(array $entities, array $roles) // Create a mapping of explicit entity permissions $permissionMap = []; foreach ($permissions as $permission) { - $key = $permission->restrictable_type.':'.$permission->restrictable_id.':'.$permission->role_id.':'.$permission->action; - $isRestricted = $entityRestrictedMap[$permission->restrictable_type.':'.$permission->restrictable_id]; + $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action; + $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id]; $permissionMap[$key] = $isRestricted; } @@ -357,7 +357,7 @@ protected function createManyJointPermissions(array $entities, array $roles) $rolePermissionMap = []; foreach ($roles as $role) { foreach ($role->permissions as $permission) { - $rolePermissionMap[$role->getRawAttribute('id').':'.$permission->getRawAttribute('name')] = true; + $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true; } } @@ -399,9 +399,9 @@ protected function getActions(Entity $entity): array */ protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array { - $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType().'-') : '').$action; - $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id').':'.$permissionPrefix.'-all']); - $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id').':'.$permissionPrefix.'-own']); + $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action; + $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']); + $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']); $explodedAction = explode('-', $action); $restrictionAction = end($explodedAction); @@ -422,12 +422,12 @@ protected function createJointPermissionData(Entity $entity, Role $role, string // For chapters and pages, Check if explicit permissions are set on the Book. $book = $this->getBook($entity->book_id); $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction); - $hasPermissiveAccessToParents = ! $book->restricted; + $hasPermissiveAccessToParents = !$book->restricted; // For pages with a chapter, Check if explicit permissions are set on the Chapter if ($entity instanceof Page && intval($entity->chapter_id) !== 0) { $chapter = $this->getChapter($entity->chapter_id); - $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && ! $chapter->restricted; + $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted; if ($chapter->restricted) { $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction); } @@ -447,7 +447,7 @@ protected function createJointPermissionData(Entity $entity, Role $role, string */ protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool { - $key = $entity->getMorphClass().':'.$entity->getRawAttribute('id').':'.$role->getRawAttribute('id').':'.$action; + $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action; return $entityMap[$key] ?? false; } @@ -486,8 +486,8 @@ public function checkOwnableUserAccess(Model $ownable, string $permission): bool // Handle non entity specific jointPermissions if (in_array($explodedPermission[0], $nonJointPermissions)) { - $allPermission = $user && $user->can($permission.'-all'); - $ownPermission = $user && $user->can($permission.'-own'); + $allPermission = $user && $user->can($permission . '-all'); + $ownPermission = $user && $user->can($permission . '-own'); $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by'; $isOwner = $user && $user->id === $ownable->$ownerField; @@ -521,7 +521,7 @@ public function checkUserHasPermissionOnAnything(string $permission, ?string $en $this->addJointHasPermissionCheck($query, $userId); }); - if (! is_null($entityClass)) { + if (!is_null($entityClass)) { $entityInstance = app($entityClass); $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass()); } @@ -613,8 +613,8 @@ public function filterRestrictedEntityRelations($query, string $tableName, strin $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) { /** @var Builder $permissionQuery */ $permissionQuery->select(['role_id'])->from('joint_permissions') - ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'].'.'.$tableDetails['entityIdColumn']) - ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'].'.'.$tableDetails['entityTypeColumn']) + ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) + ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn']) ->where('action', '=', $action) ->whereIn('role_id', $this->getCurrentUserRoles()) ->where(function (QueryBuilder $query) { @@ -642,7 +642,7 @@ public function filterRelatedEntity(string $entityClass, Builder $query, string $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) { /** @var Builder $permissionQuery */ $permissionQuery->select('id')->from('joint_permissions') - ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'].'.'.$tableDetails['entityIdColumn']) + ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) ->where('entity_type', '=', $morphClass) ->where('action', '=', 'view') ->whereIn('role_id', $this->getCurrentUserRoles()) diff --git a/app/Auth/User.php b/app/Auth/User.php index d559a8f6136..68e2ad6253a 100644 --- a/app/Auth/User.php +++ b/app/Auth/User.php @@ -94,7 +94,7 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon */ public static function getDefault(): self { - if (! is_null(static::$defaultUser)) { + if (!is_null(static::$defaultUser)) { return static::$defaultUser; } @@ -295,7 +295,7 @@ public function scopeWithLastActivityAt(Builder $query) */ public function getEditUrl(string $path = ''): string { - $uri = '/settings/users/'.$this->id.'/'.trim($path, '/'); + $uri = '/settings/users/' . $this->id . '/' . trim($path, '/'); return url(rtrim($uri, '/')); } @@ -305,7 +305,7 @@ public function getEditUrl(string $path = ''): string */ public function getProfileUrl(): string { - return url('/user/'.$this->slug); + return url('/user/' . $this->slug); } /** diff --git a/app/Auth/UserRepo.php b/app/Auth/UserRepo.php index cefa9dbe395..6d48f124020 100644 --- a/app/Auth/UserRepo.php +++ b/app/Auth/UserRepo.php @@ -75,7 +75,7 @@ public function getAllUsersPaginatedAndSorted(int $count, array $sortData): Leng ->orderBy($sort, $sortData['order']); if ($sortData['search']) { - $term = '%'.$sortData['search'].'%'; + $term = '%' . $sortData['search'] . '%'; $query->where(function ($query) use ($term) { $query->where('name', 'like', $term) ->orWhere('email', 'like', $term); @@ -116,7 +116,7 @@ public function attachSystemRole(User $user, string $systemRoleName) */ public function isOnlyAdmin(User $user): bool { - if (! $user->hasSystemRole('admin')) { + if (!$user->hasSystemRole('admin')) { return false; } @@ -150,7 +150,7 @@ protected function demotingLastAdmin(User $user, array $newRoles): bool { if ($this->isOnlyAdmin($user)) { $adminRole = Role::getSystemRole('admin'); - if (! in_array(strval($adminRole->id), $newRoles)) { + if (!in_array(strval($adminRole->id), $newRoles)) { return true; } } @@ -195,9 +195,9 @@ public function destroy(User $user, ?int $newOwnerId = null) // Delete user profile images $this->userAvatar->destroyAllForUser($user); - if (! empty($newOwnerId)) { + if (!empty($newOwnerId)) { $newOwner = User::query()->find($newOwnerId); - if (! is_null($newOwner)) { + if (!is_null($newOwner)) { $this->migrateOwnership($user, $newOwner); } } diff --git a/app/Console/Commands/CleanupImages.php b/app/Console/Commands/CleanupImages.php index b4c17fab025..7221501979a 100644 --- a/app/Console/Commands/CleanupImages.php +++ b/app/Console/Commands/CleanupImages.php @@ -48,9 +48,9 @@ public function handle() $checkRevisions = $this->option('all') ? false : true; $dryRun = $this->option('force') ? false : true; - if (! $dryRun) { + if (!$dryRun) { $proceed = $this->confirm("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\nAre you sure you want to proceed?"); - if (! $proceed) { + if (!$proceed) { return; } } @@ -60,7 +60,7 @@ public function handle() if ($dryRun) { $this->comment('Dry run, No images have been deleted'); - $this->comment($deleteCount.' images found that would have been deleted'); + $this->comment($deleteCount . ' images found that would have been deleted'); $this->showDeletedImages($deleted); $this->comment('Run with -f or --force to perform deletions'); @@ -68,7 +68,7 @@ public function handle() } $this->showDeletedImages($deleted); - $this->comment($deleteCount.' images deleted'); + $this->comment($deleteCount . ' images deleted'); } protected function showDeletedImages($paths) diff --git a/app/Console/Commands/CopyShelfPermissions.php b/app/Console/Commands/CopyShelfPermissions.php index 6485dc364b3..32adf06839c 100644 --- a/app/Console/Commands/CopyShelfPermissions.php +++ b/app/Console/Commands/CopyShelfPermissions.php @@ -52,7 +52,7 @@ public function handle() $cascadeAll = $this->option('all'); $shelves = null; - if (! $cascadeAll && ! $shelfSlug) { + if (!$cascadeAll && !$shelfSlug) { $this->error('Either a --slug or --all option must be provided.'); return; @@ -60,12 +60,12 @@ public function handle() if ($cascadeAll) { $continue = $this->confirm( - 'Permission settings for all shelves will be cascaded. '. - 'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. '. + 'Permission settings for all shelves will be cascaded. ' . + 'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' . 'Are you sure you want to proceed?' ); - if (! $continue && ! $this->hasOption('no-interaction')) { + if (!$continue && !$this->hasOption('no-interaction')) { return; } @@ -81,9 +81,9 @@ public function handle() foreach ($shelves as $shelf) { $this->bookshelfRepo->copyDownPermissions($shelf, false); - $this->info('Copied permissions for shelf ['.$shelf->id.']'); + $this->info('Copied permissions for shelf [' . $shelf->id . ']'); } - $this->info('Permissions copied for '.$shelves->count().' shelves.'); + $this->info('Permissions copied for ' . $shelves->count() . ' shelves.'); } } diff --git a/app/Console/Commands/CreateAdmin.php b/app/Console/Commands/CreateAdmin.php index 362b431ae2f..a0fb8f31506 100644 --- a/app/Console/Commands/CreateAdmin.php +++ b/app/Console/Commands/CreateAdmin.php @@ -48,7 +48,7 @@ public function handle() if (empty($email)) { $email = $this->ask('Please specify an email address for the new admin user'); } - if (mb_strlen($email) < 5 || ! filter_var($email, FILTER_VALIDATE_EMAIL)) { + if (mb_strlen($email) < 5 || !filter_var($email, FILTER_VALIDATE_EMAIL)) { return $this->error('Invalid email address provided'); } diff --git a/app/Console/Commands/ResetMfa.php b/app/Console/Commands/ResetMfa.php index f7a9628fefb..031bec04bf2 100644 --- a/app/Console/Commands/ResetMfa.php +++ b/app/Console/Commands/ResetMfa.php @@ -43,7 +43,7 @@ public function handle() { $id = $this->option('id'); $email = $this->option('email'); - if (! $id && ! $email) { + if (!$id && !$email) { $this->error('Either a --id= or --email= option must be provided.'); return 1; @@ -56,7 +56,7 @@ public function handle() ->where($field, '=', $value) ->first(); - if (! $user) { + if (!$user) { $this->error("A user where {$field}={$value} could not be found."); return 1; diff --git a/app/Console/Commands/UpdateUrl.php b/app/Console/Commands/UpdateUrl.php index 206753530d8..a4bb6cf2288 100644 --- a/app/Console/Commands/UpdateUrl.php +++ b/app/Console/Commands/UpdateUrl.php @@ -47,13 +47,13 @@ public function handle() $newUrl = str_replace("'", '', $this->argument('newUrl')); $urlPattern = '/https?:\/\/(.+)/'; - if (! preg_match($urlPattern, $oldUrl) || ! preg_match($urlPattern, $newUrl)) { + if (!preg_match($urlPattern, $oldUrl) || !preg_match($urlPattern, $newUrl)) { $this->error('The given urls are expected to be full urls starting with http:// or https://'); return 1; } - if (! $this->checkUserOkayToProceed($oldUrl, $newUrl)) { + if (!$this->checkUserOkayToProceed($oldUrl, $newUrl)) { return 1; } diff --git a/app/Console/Commands/UpgradeDatabaseEncoding.php b/app/Console/Commands/UpgradeDatabaseEncoding.php index 6bde93252fe..32808729a54 100644 --- a/app/Console/Commands/UpgradeDatabaseEncoding.php +++ b/app/Console/Commands/UpgradeDatabaseEncoding.php @@ -43,12 +43,12 @@ public function handle() $database = DB::getDatabaseName(); $tables = DB::select('SHOW TABLES'); - $this->line('ALTER DATABASE `'.$database.'` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); - $this->line('USE `'.$database.'`;'); - $key = 'Tables_in_'.$database; + $this->line('ALTER DATABASE `' . $database . '` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); + $this->line('USE `' . $database . '`;'); + $key = 'Tables_in_' . $database; foreach ($tables as $table) { $tableName = $table->$key; - $this->line('ALTER TABLE `'.$tableName.'` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); + $this->line('ALTER TABLE `' . $tableName . '` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); } DB::setDefaultConnection($connection); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index eac23b4fe8f..11c8018c8d6 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -35,6 +35,6 @@ protected function schedule(Schedule $schedule) */ protected function commands() { - $this->load(__DIR__.'/Commands'); + $this->load(__DIR__ . '/Commands'); } } diff --git a/app/Entities/Models/Book.php b/app/Entities/Models/Book.php index f73fe9c03cc..982df5c90a7 100644 --- a/app/Entities/Models/Book.php +++ b/app/Entities/Models/Book.php @@ -34,7 +34,7 @@ class Book extends Entity implements HasCoverImage */ public function getUrl(string $path = ''): string { - return url('/books/'.implode('/', [urlencode($this->slug), trim($path, '/')])); + return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')])); } /** @@ -48,7 +48,7 @@ public function getUrl(string $path = ''): string public function getBookCover($width = 440, $height = 250) { $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - if (! $this->image_id) { + if (!$this->image_id) { return $default; } diff --git a/app/Entities/Models/Bookshelf.php b/app/Entities/Models/Bookshelf.php index e6809989a4c..8fe9dbe4159 100644 --- a/app/Entities/Models/Bookshelf.php +++ b/app/Entities/Models/Bookshelf.php @@ -45,7 +45,7 @@ public function visibleBooks(): BelongsToMany */ public function getUrl(string $path = ''): string { - return url('/shelves/'.implode('/', [urlencode($this->slug), trim($path, '/')])); + return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')])); } /** @@ -60,7 +60,7 @@ public function getBookCover($width = 440, $height = 250) { // TODO - Make generic, focused on books right now, Perhaps set-up a better image $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - if (! $this->image_id) { + if (!$this->image_id) { return $default; } diff --git a/app/Entities/Models/Chapter.php b/app/Entities/Models/Chapter.php index 0ce58d3f317..abf496b44b3 100644 --- a/app/Entities/Models/Chapter.php +++ b/app/Entities/Models/Chapter.php @@ -45,7 +45,7 @@ public function getUrl($path = ''): string trim($path, '/'), ]; - return url('/'.implode('/', $parts)); + return url('/' . implode('/', $parts)); } /** diff --git a/app/Entities/Models/Deletion.php b/app/Entities/Models/Deletion.php index d8330de0bc9..dab89ce3742 100644 --- a/app/Entities/Models/Deletion.php +++ b/app/Entities/Models/Deletion.php @@ -56,6 +56,6 @@ public function logDescriptor(): string */ public function getUrl($path): string { - return url("/settings/recycle-bin/{$this->id}/".ltrim($path, '/')); + return url("/settings/recycle-bin/{$this->id}/" . ltrim($path, '/')); } } diff --git a/app/Entities/Models/Entity.php b/app/Entities/Models/Entity.php index 84789a64608..f5f9d91f0c8 100644 --- a/app/Entities/Models/Entity.php +++ b/app/Entities/Models/Entity.php @@ -82,7 +82,7 @@ public function scopeHasPermission(Builder $query, string $permission) public function scopeWithLastView(Builder $query) { $viewedAtQuery = View::query()->select('updated_at') - ->whereColumn('viewable_id', '=', $this->getTable().'.id') + ->whereColumn('viewable_id', '=', $this->getTable() . '.id') ->where('viewable_type', '=', $this->getMorphClass()) ->where('user_id', '=', user()->id) ->take(1); @@ -96,7 +96,7 @@ public function scopeWithLastView(Builder $query) public function scopeWithViewCount(Builder $query) { $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count') - ->whereColumn('viewable_id', '=', $this->getTable().'.id') + ->whereColumn('viewable_id', '=', $this->getTable() . '.id') ->where('viewable_type', '=', $this->getMorphClass())->take(1); $query->addSelect(['view_count' => $viewCountQuery]); @@ -235,7 +235,7 @@ public function getShortName(int $length = 25): string return $this->name; } - return mb_substr($this->name, 0, $length - 3).'...'; + return mb_substr($this->name, 0, $length - 3) . '...'; } /** @@ -254,7 +254,7 @@ public function getExcerpt(int $length = 100): string $text = $this->getText(); if (mb_strlen($text) > $length) { - $text = mb_substr($text, 0, $length - 3).'...'; + $text = mb_substr($text, 0, $length - 3) . '...'; } return trim($text); diff --git a/app/Entities/Models/Page.php b/app/Entities/Models/Page.php index 9ae7cfa8639..fbe0db41b4c 100644 --- a/app/Entities/Models/Page.php +++ b/app/Entities/Models/Page.php @@ -116,7 +116,7 @@ public function getUrl($path = ''): string trim($path, '/'), ]; - return url('/'.implode('/', $parts)); + return url('/' . implode('/', $parts)); } /** diff --git a/app/Entities/Models/PageRevision.php b/app/Entities/Models/PageRevision.php index 59d9b8c6f65..b994e7a04ce 100644 --- a/app/Entities/Models/PageRevision.php +++ b/app/Entities/Models/PageRevision.php @@ -52,9 +52,9 @@ public function page(): BelongsTo */ public function getUrl($path = null) { - $url = $this->page->getUrl().'/revisions/'.$this->id; + $url = $this->page->getUrl() . '/revisions/' . $this->id; if ($path) { - return $url.'/'.trim($path, '/'); + return $url . '/' . trim($path, '/'); } return $url; diff --git a/app/Entities/Repos/BookshelfRepo.php b/app/Entities/Repos/BookshelfRepo.php index ed904e1e13a..3990bfbdcf0 100644 --- a/app/Entities/Repos/BookshelfRepo.php +++ b/app/Entities/Repos/BookshelfRepo.php @@ -102,7 +102,7 @@ public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshe { $this->baseRepo->update($shelf, $input); - if (! is_null($bookIds)) { + if (!is_null($bookIds)) { $this->updateBooks($shelf, $bookIds); } @@ -153,7 +153,7 @@ public function copyDownPermissions(Bookshelf $shelf, $checkUserPermissions = tr /** @var Book $book */ foreach ($shelfBooks as $book) { - if ($checkUserPermissions && ! userCan('restrictions-manage', $book)) { + if ($checkUserPermissions && !userCan('restrictions-manage', $book)) { continue; } $book->permissions()->delete(); diff --git a/app/Entities/Repos/PageRepo.php b/app/Entities/Repos/PageRepo.php index eab96fec8a6..ffa06d45954 100644 --- a/app/Entities/Repos/PageRepo.php +++ b/app/Entities/Repos/PageRepo.php @@ -40,7 +40,7 @@ public function getById(int $id, array $relations = ['book']): Page { $page = Page::visible()->with($relations)->find($id); - if (! $page) { + if (!$page) { throw new NotFoundException(trans('errors.page_not_found')); } @@ -56,7 +56,7 @@ public function getBySlug(string $bookSlug, string $pageSlug): Page { $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first(); - if (! $page) { + if (!$page) { throw new NotFoundException(trans('errors.page_not_found')); } @@ -95,7 +95,7 @@ public function getTemplates(int $count = 10, int $page = 1, string $search = '' ->take($count); if ($search) { - $query->where('name', 'like', '%'.$search.'%'); + $query->where('name', 'like', '%' . $search . '%'); } $paginator = $query->paginate($count, ['*'], 'page', $page); @@ -216,7 +216,7 @@ protected function updateTemplateStatusAndContentFromInput(Page $page, array $in } $pageContent = new PageContent($page); - if (! empty($input['markdown'] ?? '')) { + if (!empty($input['markdown'] ?? '')) { $pageContent->setNewMarkdown($input['markdown']); } elseif (isset($input['html'])) { $pageContent->setNewHTML($input['html']); @@ -297,7 +297,7 @@ public function restoreRevision(Page $page, int $revisionId): Page $page->fill($revision->toArray()); $content = new PageContent($page); - if (! empty($revision->markdown)) { + if (!empty($revision->markdown)) { $content->setNewMarkdown($revision->markdown); } else { $content->setNewHTML($revision->html); @@ -331,7 +331,7 @@ public function move(Page $page, string $parentIdentifier): Entity throw new MoveOperationException('Book or chapter to move page into not found'); } - if (! userCan('page-create', $parent)) { + if (!userCan('page-create', $parent)) { throw new PermissionsException('User does not have permission to create a page within the new parent'); } @@ -358,7 +358,7 @@ public function copy(Page $page, string $parentIdentifier = null, string $newNam throw new MoveOperationException('Book or chapter to move page into not found'); } - if (! userCan('page-create', $parent)) { + if (!userCan('page-create', $parent)) { throw new PermissionsException('User does not have permission to create a page within the new parent'); } @@ -366,7 +366,7 @@ public function copy(Page $page, string $parentIdentifier = null, string $newNam $pageData = $page->getAttributes(); // Update name - if (! empty($newName)) { + if (!empty($newName)) { $pageData['name'] = $newName; } diff --git a/app/Entities/Tools/BookContents.php b/app/Entities/Tools/BookContents.php index 30b01c633a6..8622d5e1294 100644 --- a/app/Entities/Tools/BookContents.php +++ b/app/Entities/Tools/BookContents.php @@ -99,7 +99,7 @@ protected function getPages(bool $showDrafts = false, bool $getPageContent = fal ->select($getPageContent ? Page::$contentAttributes : Page::$listAttributes) ->where('book_id', '=', $this->book->id); - if (! $showDrafts) { + if (!$showDrafts) { $query->where('draft', '=', false); } @@ -174,7 +174,7 @@ protected function applySortUpdates(\stdClass $sortMapItem) protected function loadModelsIntoSortMap(Collection $sortMap): void { $keyMap = $sortMap->keyBy(function (\stdClass $sortMapItem) { - return $sortMapItem->type.':'.$sortMapItem->id; + return $sortMapItem->type . ':' . $sortMapItem->id; }); $pageIds = $sortMap->where('type', '=', 'page')->pluck('id'); $chapterIds = $sortMap->where('type', '=', 'chapter')->pluck('id'); @@ -183,12 +183,12 @@ protected function loadModelsIntoSortMap(Collection $sortMap): void $chapters = Chapter::visible()->whereIn('id', $chapterIds)->get(); foreach ($pages as $page) { - $sortItem = $keyMap->get('page:'.$page->id); + $sortItem = $keyMap->get('page:' . $page->id); $sortItem->model = $page; } foreach ($chapters as $chapter) { - $sortItem = $keyMap->get('chapter:'.$chapter->id); + $sortItem = $keyMap->get('chapter:' . $chapter->id); $sortItem->model = $chapter; } } diff --git a/app/Entities/Tools/ExportFormatter.php b/app/Entities/Tools/ExportFormatter.php index e9d67be03cb..05d0ff13466 100644 --- a/app/Entities/Tools/ExportFormatter.php +++ b/app/Entities/Tools/ExportFormatter.php @@ -209,7 +209,7 @@ public function pageToPlainText(Page $page): string $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text); $text = html_entity_decode($text); // Add title - $text = $page->name."\n\n".$text; + $text = $page->name . "\n\n" . $text; return $text; } @@ -219,8 +219,8 @@ public function pageToPlainText(Page $page): string */ public function chapterToPlainText(Chapter $chapter): string { - $text = $chapter->name."\n\n"; - $text .= $chapter->description."\n\n"; + $text = $chapter->name . "\n\n"; + $text .= $chapter->description . "\n\n"; foreach ($chapter->getVisiblePages() as $page) { $text .= $this->pageToPlainText($page); } @@ -234,7 +234,7 @@ public function chapterToPlainText(Chapter $chapter): string public function bookToPlainText(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, false); - $text = $book->name."\n\n"; + $text = $book->name . "\n\n"; foreach ($bookTree as $bookChild) { if ($bookChild->isA('chapter')) { $text .= $this->chapterToPlainText($bookChild); @@ -252,10 +252,10 @@ public function bookToPlainText(Book $book): string public function pageToMarkdown(Page $page): string { if ($page->markdown) { - return '# '.$page->name."\n\n".$page->markdown; + return '# ' . $page->name . "\n\n" . $page->markdown; } - return '# '.$page->name."\n\n".(new HtmlToMarkdown($page->html))->convert(); + return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert(); } /** @@ -263,10 +263,10 @@ public function pageToMarkdown(Page $page): string */ public function chapterToMarkdown(Chapter $chapter): string { - $text = '# '.$chapter->name."\n\n"; - $text .= $chapter->description."\n\n"; + $text = '# ' . $chapter->name . "\n\n"; + $text .= $chapter->description . "\n\n"; foreach ($chapter->pages as $page) { - $text .= $this->pageToMarkdown($page)."\n\n"; + $text .= $this->pageToMarkdown($page) . "\n\n"; } return $text; @@ -278,7 +278,7 @@ public function chapterToMarkdown(Chapter $chapter): string public function bookToMarkdown(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); - $text = '# '.$book->name."\n\n"; + $text = '# ' . $book->name . "\n\n"; foreach ($bookTree as $bookChild) { if ($bookChild instanceof Chapter) { $text .= $this->chapterToMarkdown($bookChild); diff --git a/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php b/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php index fb389167f73..ca9f434af0f 100644 --- a/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php +++ b/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php @@ -17,8 +17,8 @@ class CustomStrikethroughRenderer implements InlineRendererInterface { public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer) { - if (! ($inline instanceof Strikethrough)) { - throw new \InvalidArgumentException('Incompatible inline type: '.get_class($inline)); + if (!($inline instanceof Strikethrough)) { + throw new \InvalidArgumentException('Incompatible inline type: ' . get_class($inline)); } return new HtmlElement('s', $inline->getData('attributes', []), $htmlRenderer->renderInlines($inline->children())); diff --git a/app/Entities/Tools/PageContent.php b/app/Entities/Tools/PageContent.php index 09d322067d0..9f4ac2893f7 100644 --- a/app/Entities/Tools/PageContent.php +++ b/app/Entities/Tools/PageContent.php @@ -96,13 +96,13 @@ protected function extractBase64ImagesFromHtml(string $htmlText): string $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png'); // Validate extension - if (! $imageRepo->imageExtensionSupported($extension)) { + if (!$imageRepo->imageExtensionSupported($extension)) { $imageNode->setAttribute('src', ''); continue; } // Save image from data with a random name - $imageName = 'embedded-image-'.Str::random(8).'.'.$extension; + $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension; try { $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id); @@ -135,13 +135,13 @@ protected function extractBase64ImagesFromMarkdown(string $markdown) $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png'); // Validate extension - if (! $imageRepo->imageExtensionSupported($extension)) { + if (!$imageRepo->imageExtensionSupported($extension)) { $markdown = str_replace($base64Match, '', $markdown); continue; } // Save image from data with a random name - $imageName = 'embedded-image-'.Str::random(8).'.'.$extension; + $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension; try { $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id); @@ -174,7 +174,7 @@ protected function formatHtml(string $htmlText): string foreach ($childNodes as $index => $childNode) { [$oldId, $newId] = $this->setUniqueId($childNode, $idMap); if ($newId && $newId !== $oldId) { - $this->updateLinks($xPath, '#'.$oldId, '#'.$newId); + $this->updateLinks($xPath, '#' . $oldId, '#' . $newId); } } @@ -183,7 +183,7 @@ protected function formatHtml(string $htmlText): string foreach ($idElems as $domElem) { [$oldId, $newId] = $this->setUniqueId($domElem, $idMap); if ($newId && $newId !== $oldId) { - $this->updateLinks($xPath, '#'.$oldId, '#'.$newId); + $this->updateLinks($xPath, '#' . $oldId, '#' . $newId); } } @@ -202,7 +202,7 @@ protected function formatHtml(string $htmlText): string protected function updateLinks(DOMXPath $xpath, string $old, string $new) { $old = str_replace('"', '', $old); - $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]'); + $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]'); foreach ($matchingLinks as $domElem) { $domElem->setAttribute('href', $new); } @@ -221,7 +221,7 @@ protected function setUniqueId(\DOMNode $element, array &$idMap): array // Stop if there's an existing valid id that has not already been used. $existingId = $element->getAttribute('id'); - if (strpos($existingId, 'bkmrk') === 0 && ! isset($idMap[$existingId])) { + if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) { $idMap[$existingId] = true; return [$existingId, $existingId]; @@ -230,12 +230,12 @@ protected function setUniqueId(\DOMNode $element, array &$idMap): array // Create an unique id for the element // Uses the content as a basis to ensure output is the same every time // the same content is passed through. - $contentId = 'bkmrk-'.mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20); + $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20); $newId = urlencode($contentId); $loopIndex = 0; while (isset($idMap[$newId])) { - $newId = urlencode($contentId.'-'.$loopIndex); + $newId = urlencode($contentId . '-' . $loopIndex); $loopIndex++; } @@ -262,7 +262,7 @@ public function render(bool $blankIncludes = false): string { $content = $this->page->html ?? ''; - if (! config('app.allow_content_scripts')) { + if (!config('app.allow_content_scripts')) { $content = HtmlContentFilter::removeScripts($content); } @@ -304,7 +304,7 @@ protected function headerNodesToLevelList(DOMNodeList $nodeList): array return [ 'nodeName' => strtolower($header->nodeName), 'level' => intval(str_replace('h', '', $header->nodeName)), - 'link' => '#'.$header->getAttribute('id'), + 'link' => '#' . $header->getAttribute('id'), 'text' => $text, ]; })->filter(function ($header) { @@ -407,7 +407,7 @@ protected function loadDocumentFromHtml(string $html): DOMDocument { libxml_use_internal_errors(true); $doc = new DOMDocument(); - $html = ''.$html.''; + $html = '' . $html . ''; $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); return $doc; diff --git a/app/Entities/Tools/PageEditActivity.php b/app/Entities/Tools/PageEditActivity.php index 5fe263b6f72..ef6c085ac72 100644 --- a/app/Entities/Tools/PageEditActivity.php +++ b/app/Entities/Tools/PageEditActivity.php @@ -81,7 +81,7 @@ public function getEditingActiveDraftMessage(PageRevision $draft): string return $message; } - return $message."\n".trans('entities.pages_draft_edited_notification'); + return $message . "\n" . trans('entities.pages_draft_edited_notification'); } /** diff --git a/app/Entities/Tools/PermissionsUpdater.php b/app/Entities/Tools/PermissionsUpdater.php index 2a6988d2455..4e8351776d8 100644 --- a/app/Entities/Tools/PermissionsUpdater.php +++ b/app/Entities/Tools/PermissionsUpdater.php @@ -23,12 +23,12 @@ public function updateFromPermissionsForm(Entity $entity, Request $request) $entity->restricted = $restricted; $entity->permissions()->delete(); - if (! is_null($permissions)) { + if (!is_null($permissions)) { $entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions); $entity->permissions()->createMany($entityPermissionData); } - if (! is_null($ownerId)) { + if (!is_null($ownerId)) { $this->updateOwnerFromId($entity, intval($ownerId)); } @@ -46,7 +46,7 @@ public function updateFromPermissionsForm(Entity $entity, Request $request) protected function updateOwnerFromId(Entity $entity, int $newOwnerId) { $newOwner = User::query()->find($newOwnerId); - if (! is_null($newOwner)) { + if (!is_null($newOwner)) { $entity->owned_by = $newOwner->id; } } diff --git a/app/Entities/Tools/SearchIndex.php b/app/Entities/Tools/SearchIndex.php index f24d0a61c62..cc0b32d6a00 100644 --- a/app/Entities/Tools/SearchIndex.php +++ b/app/Entities/Tools/SearchIndex.php @@ -101,7 +101,7 @@ protected function generateTermArrayFromText(string $text, int $scoreAdjustment $token = strtok($text, $splitChars); while ($token !== false) { - if (! isset($tokenMap[$token])) { + if (!isset($tokenMap[$token])) { $tokenMap[$token] = 0; } $tokenMap[$token]++; diff --git a/app/Entities/Tools/SearchOptions.php b/app/Entities/Tools/SearchOptions.php index 18271051b56..5ce64cc6504 100644 --- a/app/Entities/Tools/SearchOptions.php +++ b/app/Entities/Tools/SearchOptions.php @@ -47,7 +47,7 @@ public static function fromString(string $search): self */ public static function fromRequest(Request $request): self { - if (! $request->has('search') && ! $request->has('term')) { + if (!$request->has('search') && !$request->has('term')) { return static::fromString(''); } @@ -127,7 +127,7 @@ public function toString(): string $string = implode(' ', $this->searches ?? []); foreach ($this->exacts as $term) { - $string .= ' "'.$term.'"'; + $string .= ' "' . $term . '"'; } foreach ($this->tags as $term) { @@ -135,7 +135,7 @@ public function toString(): string } foreach ($this->filters as $filterName => $filterVal) { - $string .= ' {'.$filterName.($filterVal ? ':'.$filterVal : '').'}'; + $string .= ' {' . $filterName . ($filterVal ? ':' . $filterVal : '') . '}'; } return $string; diff --git a/app/Entities/Tools/SearchRunner.php b/app/Entities/Tools/SearchRunner.php index 3eb421d53d4..df566eb0b30 100644 --- a/app/Entities/Tools/SearchRunner.php +++ b/app/Entities/Tools/SearchRunner.php @@ -65,7 +65,7 @@ public function searchEntities(SearchOptions $searchOpts, string $entityType = ' $hasMore = false; foreach ($entityTypesToSearch as $entityType) { - if (! in_array($entityType, $entityTypes)) { + if (!in_array($entityType, $entityTypes)) { continue; } $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action); @@ -96,7 +96,7 @@ public function searchBook(int $bookId, string $searchString): Collection $results = collect(); foreach ($entityTypesToSearch as $entityType) { - if (! in_array($entityType, $entityTypes)) { + if (!in_array($entityType, $entityTypes)) { continue; } $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get(); @@ -151,12 +151,12 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent $subQuery->where('entity_type', '=', $entity->getMorphClass()); $subQuery->where(function (Builder $query) use ($searchOpts) { foreach ($searchOpts->searches as $inputTerm) { - $query->orWhere('term', 'like', $inputTerm.'%'); + $query->orWhere('term', 'like', $inputTerm . '%'); } })->groupBy('entity_type', 'entity_id'); - $entitySelect->join($this->db->raw('('.$subQuery->toSql().') as s'), function (JoinClause $join) { + $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) { $join->on('id', '=', 'entity_id'); - })->addSelect($entity->getTable().'.*') + })->addSelect($entity->getTable() . '.*') ->selectRaw('s.score') ->orderBy('score', 'desc'); $entitySelect->mergeBindings($subQuery); @@ -165,8 +165,8 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent // Handle exact term matching foreach ($searchOpts->exacts as $inputTerm) { $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) { - $query->where('name', 'like', '%'.$inputTerm.'%') - ->orWhere($entity->textField, 'like', '%'.$inputTerm.'%'); + $query->where('name', 'like', '%' . $inputTerm . '%') + ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%'); }); } @@ -177,7 +177,7 @@ protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $ent // Handle filters foreach ($searchOpts->filters as $filterTerm => $filterValue) { - $functionName = Str::camel('filter_'.$filterTerm); + $functionName = Str::camel('filter_' . $filterTerm); if (method_exists($this, $functionName)) { $this->$functionName($entitySelect, $entity, $filterValue); } @@ -204,14 +204,14 @@ protected function getRegexEscapedOperators(): string */ protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder { - preg_match('/^(.*?)(('.$this->getRegexEscapedOperators().')(.*?))?$/', $tagTerm, $tagSplit); + preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit); $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) { $tagName = $tagSplit[1]; $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : ''; $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : ''; $validOperator = in_array($tagOperator, $this->queryOperators); - if (! empty($tagOperator) && ! empty($tagValue) && $validOperator) { - if (! empty($tagName)) { + if (!empty($tagOperator) && !empty($tagValue) && $validOperator) { + if (!empty($tagName)) { $query->where('name', '=', $tagName); } if (is_numeric($tagValue) && $tagOperator !== 'like') { @@ -303,7 +303,7 @@ protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input) protected function filterInName(EloquentBuilder $query, Entity $model, $input) { - $query->where('name', 'like', '%'.$input.'%'); + $query->where('name', 'like', '%' . $input . '%'); } protected function filterInTitle(EloquentBuilder $query, Entity $model, $input) @@ -313,7 +313,7 @@ protected function filterInTitle(EloquentBuilder $query, Entity $model, $input) protected function filterInBody(EloquentBuilder $query, Entity $model, $input) { - $query->where($model->textField, 'like', '%'.$input.'%'); + $query->where($model->textField, 'like', '%' . $input . '%'); } protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input) @@ -337,7 +337,7 @@ protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $i protected function filterSortBy(EloquentBuilder $query, Entity $model, $input) { - $functionName = Str::camel('sort_by_'.$input); + $functionName = Str::camel('sort_by_' . $input); if (method_exists($this, $functionName)) { $this->$functionName($query, $model); } @@ -348,10 +348,10 @@ protected function filterSortBy(EloquentBuilder $query, Entity $model, $input) */ protected function sortByLastCommented(EloquentBuilder $query, Entity $model) { - $commentsTable = $this->db->getTablePrefix().'comments'; + $commentsTable = $this->db->getTablePrefix() . 'comments'; $morphClass = str_replace('\\', '\\\\', $model->getMorphClass()); - $commentQuery = $this->db->raw('(SELECT c1.entity_id, c1.entity_type, c1.created_at as last_commented FROM '.$commentsTable.' c1 LEFT JOIN '.$commentsTable.' c2 ON (c1.entity_id = c2.entity_id AND c1.entity_type = c2.entity_type AND c1.created_at < c2.created_at) WHERE c1.entity_type = \''.$morphClass.'\' AND c2.created_at IS NULL) as comments'); + $commentQuery = $this->db->raw('(SELECT c1.entity_id, c1.entity_type, c1.created_at as last_commented FROM ' . $commentsTable . ' c1 LEFT JOIN ' . $commentsTable . ' c2 ON (c1.entity_id = c2.entity_id AND c1.entity_type = c2.entity_type AND c1.created_at < c2.created_at) WHERE c1.entity_type = \'' . $morphClass . '\' AND c2.created_at IS NULL) as comments'); - $query->join($commentQuery, $model->getTable().'.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc'); + $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc'); } } diff --git a/app/Entities/Tools/ShelfContext.php b/app/Entities/Tools/ShelfContext.php index f1ad80f5d08..50d7981716e 100644 --- a/app/Entities/Tools/ShelfContext.php +++ b/app/Entities/Tools/ShelfContext.php @@ -16,7 +16,7 @@ public function getContextualShelfForBook(Book $book): ?Bookshelf { $contextBookshelfId = session()->get($this->KEY_SHELF_CONTEXT_ID, null); - if (! is_int($contextBookshelfId)) { + if (!is_int($contextBookshelfId)) { return null; } diff --git a/app/Entities/Tools/SiblingFetcher.php b/app/Entities/Tools/SiblingFetcher.php index 090b61339ee..e9dad0e134f 100644 --- a/app/Entities/Tools/SiblingFetcher.php +++ b/app/Entities/Tools/SiblingFetcher.php @@ -23,7 +23,7 @@ public function fetch(string $entityType, int $entityId): Collection } // Page in book or chapter - if (($entity->isA('page') && ! $entity->chapter) || $entity->isA('chapter')) { + if (($entity->isA('page') && !$entity->chapter) || $entity->isA('chapter')) { $entities = $entity->book->getDirectChildren(); } diff --git a/app/Entities/Tools/SlugGenerator.php b/app/Entities/Tools/SlugGenerator.php index 21ddaf70dde..52e5700da24 100644 --- a/app/Entities/Tools/SlugGenerator.php +++ b/app/Entities/Tools/SlugGenerator.php @@ -16,7 +16,7 @@ public function generate(Sluggable $model): string { $slug = $this->formatNameAsSlug($model->name); while ($this->slugInUse($slug, $model)) { - $slug .= '-'.Str::random(3); + $slug .= '-' . Str::random(3); } return $slug; diff --git a/app/Exceptions/NotifyException.php b/app/Exceptions/NotifyException.php index 7273ee55f7c..8e748a21dc7 100644 --- a/app/Exceptions/NotifyException.php +++ b/app/Exceptions/NotifyException.php @@ -29,7 +29,7 @@ public function toResponse($request) { $message = $this->getMessage(); - if (! empty($message)) { + if (!empty($message)) { session()->flash('error', $message); } diff --git a/app/Exceptions/PrettyException.php b/app/Exceptions/PrettyException.php index d93b62dd34b..f446442d058 100644 --- a/app/Exceptions/PrettyException.php +++ b/app/Exceptions/PrettyException.php @@ -26,7 +26,7 @@ public function toResponse($request) { $code = ($this->getCode() === 0) ? 500 : $this->getCode(); - return response()->view('errors.'.$code, [ + return response()->view('errors.' . $code, [ 'message' => $this->getMessage(), 'subtitle' => $this->subtitle, 'details' => $this->details, diff --git a/app/Http/Controllers/Api/AttachmentApiController.php b/app/Http/Controllers/Api/AttachmentApiController.php index 47b118964c1..06d9f6907ca 100644 --- a/app/Http/Controllers/Api/AttachmentApiController.php +++ b/app/Http/Controllers/Api/AttachmentApiController.php @@ -102,7 +102,7 @@ public function read(string $id) 'markdown' => $attachment->markdownLink(), ]); - if (! $attachment->external) { + if (!$attachment->external) { $attachmentContents = $this->attachmentService->getAttachmentFromStorage($attachment); $attachment->setAttribute('content', base64_encode($attachmentContents)); } else { diff --git a/app/Http/Controllers/Api/BookExportApiController.php b/app/Http/Controllers/Api/BookExportApiController.php index 878a0d9089b..028bc3a817e 100644 --- a/app/Http/Controllers/Api/BookExportApiController.php +++ b/app/Http/Controllers/Api/BookExportApiController.php @@ -26,7 +26,7 @@ public function exportPdf(int $id) $book = Book::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->bookToPdf($book); - return $this->downloadResponse($pdfContent, $book->slug.'.pdf'); + return $this->downloadResponse($pdfContent, $book->slug . '.pdf'); } /** @@ -39,7 +39,7 @@ public function exportHtml(int $id) $book = Book::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); - return $this->downloadResponse($htmlContent, $book->slug.'.html'); + return $this->downloadResponse($htmlContent, $book->slug . '.html'); } /** @@ -50,7 +50,7 @@ public function exportPlainText(int $id) $book = Book::visible()->findOrFail($id); $textContent = $this->exportFormatter->bookToPlainText($book); - return $this->downloadResponse($textContent, $book->slug.'.txt'); + return $this->downloadResponse($textContent, $book->slug . '.txt'); } /** @@ -61,6 +61,6 @@ public function exportMarkdown(int $id) $book = Book::visible()->findOrFail($id); $markdown = $this->exportFormatter->bookToMarkdown($book); - return $this->downloadResponse($markdown, $book->slug.'.md'); + return $this->downloadResponse($markdown, $book->slug . '.md'); } } diff --git a/app/Http/Controllers/Api/ChapterExportApiController.php b/app/Http/Controllers/Api/ChapterExportApiController.php index 79fc960ad9d..5715ab2e37c 100644 --- a/app/Http/Controllers/Api/ChapterExportApiController.php +++ b/app/Http/Controllers/Api/ChapterExportApiController.php @@ -29,7 +29,7 @@ public function exportPdf(int $id) $chapter = Chapter::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); - return $this->downloadResponse($pdfContent, $chapter->slug.'.pdf'); + return $this->downloadResponse($pdfContent, $chapter->slug . '.pdf'); } /** @@ -42,7 +42,7 @@ public function exportHtml(int $id) $chapter = Chapter::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->chapterToContainedHtml($chapter); - return $this->downloadResponse($htmlContent, $chapter->slug.'.html'); + return $this->downloadResponse($htmlContent, $chapter->slug . '.html'); } /** @@ -53,7 +53,7 @@ public function exportPlainText(int $id) $chapter = Chapter::visible()->findOrFail($id); $textContent = $this->exportFormatter->chapterToPlainText($chapter); - return $this->downloadResponse($textContent, $chapter->slug.'.txt'); + return $this->downloadResponse($textContent, $chapter->slug . '.txt'); } /** @@ -64,6 +64,6 @@ public function exportMarkdown(int $id) $chapter = Chapter::visible()->findOrFail($id); $markdown = $this->exportFormatter->chapterToMarkdown($chapter); - return $this->downloadResponse($markdown, $chapter->slug.'.md'); + return $this->downloadResponse($markdown, $chapter->slug . '.md'); } } diff --git a/app/Http/Controllers/Api/PageApiController.php b/app/Http/Controllers/Api/PageApiController.php index bf67c36d955..f698627a7e8 100644 --- a/app/Http/Controllers/Api/PageApiController.php +++ b/app/Http/Controllers/Api/PageApiController.php @@ -113,11 +113,11 @@ public function update(Request $request, string $id) $parent = Book::visible()->findOrFail($request->get('book_id')); } - if ($parent && ! $parent->matches($page->getParent())) { + if ($parent && !$parent->matches($page->getParent())) { $this->checkOwnablePermission('page-delete', $page); try { - $this->pageRepo->move($page, $parent->getType().':'.$parent->id); + $this->pageRepo->move($page, $parent->getType() . ':' . $parent->id); } catch (Exception $exception) { if ($exception instanceof PermissionsException) { $this->showPermissionError(); diff --git a/app/Http/Controllers/Api/PageExportApiController.php b/app/Http/Controllers/Api/PageExportApiController.php index 344766f7cb2..ce5700c79b9 100644 --- a/app/Http/Controllers/Api/PageExportApiController.php +++ b/app/Http/Controllers/Api/PageExportApiController.php @@ -26,7 +26,7 @@ public function exportPdf(int $id) $page = Page::visible()->findOrFail($id); $pdfContent = $this->exportFormatter->pageToPdf($page); - return $this->downloadResponse($pdfContent, $page->slug.'.pdf'); + return $this->downloadResponse($pdfContent, $page->slug . '.pdf'); } /** @@ -39,7 +39,7 @@ public function exportHtml(int $id) $page = Page::visible()->findOrFail($id); $htmlContent = $this->exportFormatter->pageToContainedHtml($page); - return $this->downloadResponse($htmlContent, $page->slug.'.html'); + return $this->downloadResponse($htmlContent, $page->slug . '.html'); } /** @@ -50,7 +50,7 @@ public function exportPlainText(int $id) $page = Page::visible()->findOrFail($id); $textContent = $this->exportFormatter->pageToPlainText($page); - return $this->downloadResponse($textContent, $page->slug.'.txt'); + return $this->downloadResponse($textContent, $page->slug . '.txt'); } /** @@ -61,6 +61,6 @@ public function exportMarkdown(int $id) $page = Page::visible()->findOrFail($id); $markdown = $this->exportFormatter->pageToMarkdown($page); - return $this->downloadResponse($markdown, $page->slug.'.md'); + return $this->downloadResponse($markdown, $page->slug . '.md'); } } diff --git a/app/Http/Controllers/Auth/HandlesPartialLogins.php b/app/Http/Controllers/Auth/HandlesPartialLogins.php index e66841e1ad6..c7f3621517f 100644 --- a/app/Http/Controllers/Auth/HandlesPartialLogins.php +++ b/app/Http/Controllers/Auth/HandlesPartialLogins.php @@ -16,7 +16,7 @@ protected function currentOrLastAttemptedUser(): User $loginService = app()->make(LoginService::class); $user = auth()->user() ?? $loginService->getLastLoginAttemptUser(); - if (! $user) { + if (!$user) { throw new NotFoundException('A user for this action could not be found'); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index f4f22621479..d12d7c9bc48 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -234,7 +234,7 @@ protected function updateIntendedFromPrevious(): void // Store the previous location for redirect after login $previous = url()->previous(''); $isPreviousFromInstance = (strpos($previous, url('/')) === 0); - if (! $previous || ! setting('app-public') || ! $isPreviousFromInstance) { + if (!$previous || !setting('app-public') || !$isPreviousFromInstance) { return; } diff --git a/app/Http/Controllers/Auth/MfaBackupCodesController.php b/app/Http/Controllers/Auth/MfaBackupCodesController.php index 9e3cbad2760..d92029bf1b7 100644 --- a/app/Http/Controllers/Auth/MfaBackupCodesController.php +++ b/app/Http/Controllers/Auth/MfaBackupCodesController.php @@ -27,7 +27,7 @@ public function generate(BackupCodeService $codeService) $codes = $codeService->generateNewSet(); session()->put(self::SETUP_SECRET_SESSION_KEY, encrypt($codes)); - $downloadUrl = 'data:application/octet-stream;base64,'.base64_encode(implode("\n\n", $codes)); + $downloadUrl = 'data:application/octet-stream;base64,' . base64_encode(implode("\n\n", $codes)); return view('mfa.backup-codes-generate', [ 'codes' => $codes, @@ -42,7 +42,7 @@ public function generate(BackupCodeService $codeService) */ public function confirm() { - if (! session()->has(self::SETUP_SECRET_SESSION_KEY)) { + if (!session()->has(self::SETUP_SECRET_SESSION_KEY)) { return response('No generated codes found in the session', 500); } @@ -51,7 +51,7 @@ public function confirm() $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'backup-codes'); - if (! auth()->check()) { + if (!auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); @@ -76,7 +76,7 @@ public function verify(Request $request, BackupCodeService $codeService, MfaSess 'required', 'max:12', 'min:8', function ($attribute, $value, $fail) use ($codeService, $codes) { - if (! $codeService->inputCodeExistsInSet($value, $codes)) { + if (!$codeService->inputCodeExistsInSet($value, $codes)) { $fail(trans('validation.backup_codes')); } }, diff --git a/app/Http/Controllers/Auth/MfaTotpController.php b/app/Http/Controllers/Auth/MfaTotpController.php index 553034bd8b4..5644f02688e 100644 --- a/app/Http/Controllers/Auth/MfaTotpController.php +++ b/app/Http/Controllers/Auth/MfaTotpController.php @@ -62,7 +62,7 @@ public function confirm(Request $request) session()->remove(static::SETUP_SECRET_SESSION_KEY); $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp'); - if (! auth()->check()) { + if (!auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); diff --git a/app/Http/Controllers/Auth/Saml2Controller.php b/app/Http/Controllers/Auth/Saml2Controller.php index 89ff80cb56a..bd3b25da770 100644 --- a/app/Http/Controllers/Auth/Saml2Controller.php +++ b/app/Http/Controllers/Auth/Saml2Controller.php @@ -93,10 +93,10 @@ public function startAcs(Request $request) } $acsId = Str::random(16); - $cacheKey = 'saml2_acs:'.$acsId; + $cacheKey = 'saml2_acs:' . $acsId; cache()->set($cacheKey, encrypt($samlResponse), 10); - return redirect()->guest('/saml2/acs?id='.$acsId); + return redirect()->guest('/saml2/acs?id=' . $acsId); } /** @@ -107,7 +107,7 @@ public function startAcs(Request $request) public function processAcs(Request $request) { $acsId = $request->get('id', null); - $cacheKey = 'saml2_acs:'.$acsId; + $cacheKey = 'saml2_acs:' . $acsId; $samlResponse = null; try { diff --git a/app/Http/Controllers/Auth/SocialController.php b/app/Http/Controllers/Auth/SocialController.php index 40557938c80..1691668a2bb 100644 --- a/app/Http/Controllers/Auth/SocialController.php +++ b/app/Http/Controllers/Auth/SocialController.php @@ -69,7 +69,7 @@ public function register(string $socialDriver) */ public function callback(Request $request, string $socialDriver) { - if (! session()->has('social-callback')) { + if (!session()->has('social-callback')) { throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login'); } @@ -134,7 +134,7 @@ protected function socialRegisterCallback(string $socialDriver, SocialUser $soci ]; // Take name from email address if empty - if (! $userData['name']) { + if (!$userData['name']) { $userData['name'] = explode('@', $userData['email'])[0]; } diff --git a/app/Http/Controllers/BookController.php b/app/Http/Controllers/BookController.php index 57befe7408c..7c099377cb6 100644 --- a/app/Http/Controllers/BookController.php +++ b/app/Http/Controllers/BookController.php @@ -87,7 +87,7 @@ public function store(Request $request, string $shelfSlug = null) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|'.$this->getImageValidationRules(), + 'image' => 'nullable|' . $this->getImageValidationRules(), ]); $bookshelf = null; @@ -158,7 +158,7 @@ public function update(Request $request, string $slug) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|'.$this->getImageValidationRules(), + 'image' => 'nullable|' . $this->getImageValidationRules(), ]); $book = $this->bookRepo->update($book, $request->all()); diff --git a/app/Http/Controllers/BookExportController.php b/app/Http/Controllers/BookExportController.php index 6038e0a6b67..7f6dd801752 100644 --- a/app/Http/Controllers/BookExportController.php +++ b/app/Http/Controllers/BookExportController.php @@ -31,7 +31,7 @@ public function pdf(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $pdfContent = $this->exportFormatter->bookToPdf($book); - return $this->downloadResponse($pdfContent, $bookSlug.'.pdf'); + return $this->downloadResponse($pdfContent, $bookSlug . '.pdf'); } /** @@ -44,7 +44,7 @@ public function html(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); - return $this->downloadResponse($htmlContent, $bookSlug.'.html'); + return $this->downloadResponse($htmlContent, $bookSlug . '.html'); } /** @@ -55,7 +55,7 @@ public function plainText(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $textContent = $this->exportFormatter->bookToPlainText($book); - return $this->downloadResponse($textContent, $bookSlug.'.txt'); + return $this->downloadResponse($textContent, $bookSlug . '.txt'); } /** @@ -66,6 +66,6 @@ public function markdown(string $bookSlug) $book = $this->bookRepo->getBySlug($bookSlug); $textContent = $this->exportFormatter->bookToMarkdown($book); - return $this->downloadResponse($textContent, $bookSlug.'.md'); + return $this->downloadResponse($textContent, $bookSlug . '.md'); } } diff --git a/app/Http/Controllers/BookSortController.php b/app/Http/Controllers/BookSortController.php index 870e33eea93..0bd39477801 100644 --- a/app/Http/Controllers/BookSortController.php +++ b/app/Http/Controllers/BookSortController.php @@ -55,7 +55,7 @@ public function update(Request $request, string $bookSlug) $this->checkOwnablePermission('book-update', $book); // Return if no map sent - if (! $request->filled('sort-tree')) { + if (!$request->filled('sort-tree')) { return redirect($book->getUrl()); } diff --git a/app/Http/Controllers/BookshelfController.php b/app/Http/Controllers/BookshelfController.php index 80bdecc61ff..da16d782281 100644 --- a/app/Http/Controllers/BookshelfController.php +++ b/app/Http/Controllers/BookshelfController.php @@ -86,7 +86,7 @@ public function store(Request $request) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|'.$this->getImageValidationRules(), + 'image' => 'nullable|' . $this->getImageValidationRules(), ]); $bookIds = explode(',', $request->get('books', '')); @@ -163,7 +163,7 @@ public function update(Request $request, string $slug) $this->validate($request, [ 'name' => 'required|string|max:255', 'description' => 'string|max:1000', - 'image' => 'nullable|'.$this->getImageValidationRules(), + 'image' => 'nullable|' . $this->getImageValidationRules(), ]); $bookIds = explode(',', $request->get('books', '')); diff --git a/app/Http/Controllers/ChapterExportController.php b/app/Http/Controllers/ChapterExportController.php index b6ec1a96b64..480280c99ef 100644 --- a/app/Http/Controllers/ChapterExportController.php +++ b/app/Http/Controllers/ChapterExportController.php @@ -33,7 +33,7 @@ public function pdf(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); - return $this->downloadResponse($pdfContent, $chapterSlug.'.pdf'); + return $this->downloadResponse($pdfContent, $chapterSlug . '.pdf'); } /** @@ -47,7 +47,7 @@ public function html(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $containedHtml = $this->exportFormatter->chapterToContainedHtml($chapter); - return $this->downloadResponse($containedHtml, $chapterSlug.'.html'); + return $this->downloadResponse($containedHtml, $chapterSlug . '.html'); } /** @@ -60,7 +60,7 @@ public function plainText(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToPlainText($chapter); - return $this->downloadResponse($chapterText, $chapterSlug.'.txt'); + return $this->downloadResponse($chapterText, $chapterSlug . '.txt'); } /** @@ -74,6 +74,6 @@ public function markdown(string $bookSlug, string $chapterSlug) $chapter = $this->chapterRepo->getBySlug($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToMarkdown($chapter); - return $this->downloadResponse($chapterText, $chapterSlug.'.md'); + return $this->downloadResponse($chapterText, $chapterSlug . '.md'); } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 49561eaf6d3..283a01cfb6a 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -66,7 +66,7 @@ protected function showPermissionError() */ protected function checkPermission(string $permission): void { - if (! user() || ! user()->can($permission)) { + if (!user() || !user()->can($permission)) { $this->showPermissionError(); } } @@ -76,7 +76,7 @@ protected function checkPermission(string $permission): void */ protected function checkOwnablePermission(string $permission, Model $ownable): void { - if (! userCan($permission, $ownable)) { + if (!userCan($permission, $ownable)) { $this->showPermissionError(); } } @@ -118,7 +118,7 @@ protected function downloadResponse(string $content, string $fileName): Response { return response()->make($content, 200, [ 'Content-Type' => 'application/octet-stream', - 'Content-Disposition' => 'attachment; filename="'.$fileName.'"', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', ]); } @@ -133,7 +133,7 @@ protected function inlineDownloadResponse(string $content, string $fileName): Re return response()->make($content, 200, [ 'Content-Type' => $mime, - 'Content-Disposition' => 'inline; filename="'.$fileName.'"', + 'Content-Disposition' => 'inline; filename="' . $fileName . '"', ]); } diff --git a/app/Http/Controllers/FavouriteController.php b/app/Http/Controllers/FavouriteController.php index 899c9f43326..a990ff82578 100644 --- a/app/Http/Controllers/FavouriteController.php +++ b/app/Http/Controllers/FavouriteController.php @@ -19,7 +19,7 @@ public function index(Request $request) $page = intval($request->get('page', 1)); $favourites = (new TopFavourites())->run($viewCount + 1, (($page - 1) * $viewCount)); - $hasMoreLink = ($favourites->count() > $viewCount) ? url('/favourites?page='.($page + 1)) : null; + $hasMoreLink = ($favourites->count() > $viewCount) ? url('/favourites?page=' . ($page + 1)) : null; return view('common.detailed-listing-with-more', [ 'title' => trans('entities.my_favourites'), @@ -73,13 +73,13 @@ protected function getValidatedModelFromRequest(Request $request): Favouritable 'id' => 'required|integer', ]); - if (! class_exists($modelInfo['type'])) { + if (!class_exists($modelInfo['type'])) { throw new \Exception('Model not found'); } /** @var Model $model */ $model = new $modelInfo['type'](); - if (! $model instanceof Favouritable) { + if (!$model instanceof Favouritable) { throw new \Exception('Model not favouritable'); } @@ -87,7 +87,7 @@ protected function getValidatedModelFromRequest(Request $request): Favouritable ->where('id', '=', $modelInfo['id']) ->first(['id', 'name']); - $inaccessibleEntity = ($modelInstance instanceof Entity && ! userCan('view', $modelInstance)); + $inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance)); if (is_null($modelInstance) || $inaccessibleEntity) { throw new \Exception('Model instance not found'); } diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index bc829409c1d..5451c0abfe8 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -45,7 +45,7 @@ public function index() $homepageOptions = ['default', 'books', 'bookshelves', 'page']; $homepageOption = setting('app-homepage-type', 'default'); - if (! in_array($homepageOption, $homepageOptions)) { + if (!in_array($homepageOption, $homepageOptions)) { $homepageOption = 'default'; } @@ -60,9 +60,9 @@ public function index() // Add required list ordering & sorting for books & shelves views. if ($homepageOption === 'bookshelves' || $homepageOption === 'books') { $key = $homepageOption; - $view = setting()->getForCurrentUser($key.'_view_type'); - $sort = setting()->getForCurrentUser($key.'_sort', 'name'); - $order = setting()->getForCurrentUser($key.'_sort_order', 'asc'); + $view = setting()->getForCurrentUser($key . '_view_type'); + $sort = setting()->getForCurrentUser($key . '_sort', 'name'); + $order = setting()->getForCurrentUser($key . '_sort_order', 'asc'); $sortOptions = [ 'name' => trans('common.sort_name'), diff --git a/app/Http/Controllers/Images/DrawioImageController.php b/app/Http/Controllers/Images/DrawioImageController.php index 1a0ec87dc92..d99bb8e6f6a 100644 --- a/app/Http/Controllers/Images/DrawioImageController.php +++ b/app/Http/Controllers/Images/DrawioImageController.php @@ -68,7 +68,7 @@ public function getAsBase64($id) { $image = $this->imageRepo->getById($id); $page = $image->getPage(); - if ($image === null || $image->type !== 'drawio' || ! userCan('page-view', $page)) { + if ($image === null || $image->type !== 'drawio' || !userCan('page-view', $page)) { return $this->jsonError('Image data could not be found'); } diff --git a/app/Http/Controllers/Images/ImageController.php b/app/Http/Controllers/Images/ImageController.php index c0ed23b3817..4070a0e2fe6 100644 --- a/app/Http/Controllers/Images/ImageController.php +++ b/app/Http/Controllers/Images/ImageController.php @@ -35,8 +35,8 @@ public function __construct(Image $image, File $file, ImageRepo $imageRepo) */ public function showImage(string $path) { - $path = storage_path('uploads/images/'.$path); - if (! file_exists($path)) { + $path = storage_path('uploads/images/' . $path); + if (!file_exists($path)) { throw (new NotFoundException(trans('errors.image_not_found'))) ->setSubtitle(trans('errors.image_not_found_subtitle')) ->setDetails(trans('errors.image_not_found_details')); diff --git a/app/Http/Controllers/MaintenanceController.php b/app/Http/Controllers/MaintenanceController.php index a1649bf1cbe..d6abe468298 100644 --- a/app/Http/Controllers/MaintenanceController.php +++ b/app/Http/Controllers/MaintenanceController.php @@ -38,8 +38,8 @@ public function cleanupImages(Request $request, ImageService $imageService) $this->checkPermission('settings-manage'); $this->logActivity(ActivityType::MAINTENANCE_ACTION_RUN, 'cleanup-images'); - $checkRevisions = ! ($request->get('ignore_revisions', 'false') === 'true'); - $dryRun = ! ($request->has('confirm')); + $checkRevisions = !($request->get('ignore_revisions', 'false') === 'true'); + $dryRun = !($request->has('confirm')); $imagesToDelete = $imageService->deleteUnusedImages($checkRevisions, $dryRun); $deleteCount = count($imagesToDelete); @@ -70,7 +70,7 @@ public function sendTestEmail() user()->notify(new TestEmail()); $this->showSuccessNotification(trans('settings.maint_send_test_email_success', ['address' => user()->email])); } catch (\Exception $exception) { - $errorMessage = trans('errors.maintenance_test_email_failure')."\n".$exception->getMessage(); + $errorMessage = trans('errors.maintenance_test_email_failure') . "\n" . $exception->getMessage(); $this->showErrorNotification($errorMessage); } diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index aa306761315..ddb15a7aadc 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -145,7 +145,7 @@ public function show(string $bookSlug, string $pageSlug) $pageNav = $pageContent->getNavigation($page->html); // Check if page comments are enabled - $commentsEnabled = ! setting('app-disable-comments'); + $commentsEnabled = !setting('app-disable-comments'); if ($commentsEnabled) { $page->load(['comments.createdBy']); } @@ -254,7 +254,7 @@ public function saveDraft(Request $request, int $pageId) $page = $this->pageRepo->getById($pageId); $this->checkOwnablePermission('page-update', $page); - if (! $this->isSignedIn()) { + if (!$this->isSignedIn()) { return $this->jsonError(trans('errors.guests_cannot_save_drafts'), 500); } diff --git a/app/Http/Controllers/PageExportController.php b/app/Http/Controllers/PageExportController.php index 9516aeb3970..0287916de28 100644 --- a/app/Http/Controllers/PageExportController.php +++ b/app/Http/Controllers/PageExportController.php @@ -36,7 +36,7 @@ public function pdf(string $bookSlug, string $pageSlug) $page->html = (new PageContent($page))->render(); $pdfContent = $this->exportFormatter->pageToPdf($page); - return $this->downloadResponse($pdfContent, $pageSlug.'.pdf'); + return $this->downloadResponse($pdfContent, $pageSlug . '.pdf'); } /** @@ -51,7 +51,7 @@ public function html(string $bookSlug, string $pageSlug) $page->html = (new PageContent($page))->render(); $containedHtml = $this->exportFormatter->pageToContainedHtml($page); - return $this->downloadResponse($containedHtml, $pageSlug.'.html'); + return $this->downloadResponse($containedHtml, $pageSlug . '.html'); } /** @@ -64,7 +64,7 @@ public function plainText(string $bookSlug, string $pageSlug) $page = $this->pageRepo->getBySlug($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToPlainText($page); - return $this->downloadResponse($pageText, $pageSlug.'.txt'); + return $this->downloadResponse($pageText, $pageSlug . '.txt'); } /** @@ -77,6 +77,6 @@ public function markdown(string $bookSlug, string $pageSlug) $page = $this->pageRepo->getBySlug($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToMarkdown($page); - return $this->downloadResponse($pageText, $pageSlug.'.md'); + return $this->downloadResponse($pageText, $pageSlug . '.md'); } } diff --git a/app/Http/Controllers/PageTemplateController.php b/app/Http/Controllers/PageTemplateController.php index 4029e1ed26e..1e24c29eeff 100644 --- a/app/Http/Controllers/PageTemplateController.php +++ b/app/Http/Controllers/PageTemplateController.php @@ -45,7 +45,7 @@ public function get(int $templateId) { $page = $this->pageRepo->getById($templateId); - if (! $page->template) { + if (!$page->template) { throw new NotFoundException(); } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index 8908719ef32..d12c23b5a2c 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -32,7 +32,7 @@ public function search(Request $request) $this->setPageTitle(trans('entities.search_for_term', ['term' => $fullSearchString])); $page = intval($request->get('page', '0')) ?: 1; - $nextPageLink = url('/search?term='.urlencode($fullSearchString).'&page='.($page + 1)); + $nextPageLink = url('/search?term=' . urlencode($fullSearchString) . '&page=' . ($page + 1)); $results = $this->searchRunner->searchEntities($searchOpts, 'all', $page, 20); @@ -80,7 +80,7 @@ public function searchEntitiesAjax(Request $request) // Search for entities otherwise show most popular if ($searchTerm !== false) { - $searchTerm .= ' {type:'.implode('|', $entityTypes).'}'; + $searchTerm .= ' {type:' . implode('|', $entityTypes) . '}'; $entities = $this->searchRunner->searchEntities(SearchOptions::fromString($searchTerm), 'all', 1, 20, $permission)['results']; } else { $entities = (new Popular())->run(20, 0, $entityTypes, $permission); diff --git a/app/Http/Controllers/SettingController.php b/app/Http/Controllers/SettingController.php index 61256e338d9..d9f172081ef 100644 --- a/app/Http/Controllers/SettingController.php +++ b/app/Http/Controllers/SettingController.php @@ -44,7 +44,7 @@ public function update(Request $request) $this->preventAccessInDemoMode(); $this->checkPermission('settings-manage'); $this->validate($request, [ - 'app_logo' => 'nullable|'.$this->getImageValidationRules(), + 'app_logo' => 'nullable|' . $this->getImageValidationRules(), ]); // Cycles through posted settings and update them @@ -73,7 +73,7 @@ public function update(Request $request) $section = $request->get('section', ''); $this->logActivity(ActivityType::SETTINGS_UPDATE, $section); $this->showSuccessNotification(trans('settings.settings_save_success')); - $redirectLocation = '/settings#'.$section; + $redirectLocation = '/settings#' . $section; return redirect(rtrim($redirectLocation, '#')); } diff --git a/app/Http/Controllers/UserApiTokenController.php b/app/Http/Controllers/UserApiTokenController.php index fbc38f7f918..bdc25f79dc7 100644 --- a/app/Http/Controllers/UserApiTokenController.php +++ b/app/Http/Controllers/UserApiTokenController.php @@ -57,11 +57,11 @@ public function store(Request $request, int $userId) $token->save(); - session()->flash('api-token-secret:'.$token->id, $secret); + session()->flash('api-token-secret:' . $token->id, $secret); $this->showSuccessNotification(trans('settings.user_api_token_create_success')); $this->logActivity(ActivityType::API_TOKEN_CREATE, $token); - return redirect($user->getEditUrl('/api-tokens/'.$token->id)); + return redirect($user->getEditUrl('/api-tokens/' . $token->id)); } /** @@ -70,7 +70,7 @@ public function store(Request $request, int $userId) public function edit(int $userId, int $tokenId) { [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); - $secret = session()->pull('api-token-secret:'.$token->id, null); + $secret = session()->pull('api-token-secret:' . $token->id, null); return view('users.api-tokens.edit', [ 'user' => $user, @@ -99,7 +99,7 @@ public function update(Request $request, int $userId, int $tokenId) $this->showSuccessNotification(trans('settings.user_api_token_update_success')); $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token); - return redirect($user->getEditUrl('/api-tokens/'.$token->id)); + return redirect($user->getEditUrl('/api-tokens/' . $token->id)); } /** diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index c7f44d106b2..2ee303f3fee 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -81,7 +81,7 @@ public function store(Request $request) $authMethod = config('auth.method'); $sendInvite = ($request->get('send_invite', 'false') === 'true'); - if ($authMethod === 'standard' && ! $sendInvite) { + if ($authMethod === 'standard' && !$sendInvite) { $validationRules['password'] = 'required|min:6'; $validationRules['password-confirm'] = 'required|same:password'; } elseif ($authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'openid') { @@ -156,11 +156,11 @@ public function update(Request $request, int $id) $this->validate($request, [ 'name' => 'min:2', - 'email' => 'min:2|email|unique:users,email,'.$id, + 'email' => 'min:2|email|unique:users,email,' . $id, 'password' => 'min:6|required_with:password_confirm', 'password-confirm' => 'same:password|required_with:password', 'setting' => 'array', - 'profile_image' => 'nullable|'.$this->getImageValidationRules(), + 'profile_image' => 'nullable|' . $this->getImageValidationRules(), ]); $user = $this->userRepo->getById($id); @@ -217,7 +217,7 @@ public function update(Request $request, int $id) $this->showSuccessNotification(trans('settings.users_edit_success')); $this->logActivity(ActivityType::USER_UPDATE, $user); - $redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/'.$user->id); + $redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/' . $user->id); return redirect($redirectUrl); } @@ -299,12 +299,12 @@ protected function switchViewType(int $userId, Request $request, string $listNam $this->checkPermissionOrCurrentUser('users-manage', $userId); $viewType = $request->get('view_type'); - if (! in_array($viewType, ['grid', 'list'])) { + if (!in_array($viewType, ['grid', 'list'])) { $viewType = 'list'; } $user = $this->userRepo->getById($userId); - $key = $listName.'_view_type'; + $key = $listName . '_view_type'; setting()->putUser($user, $key, $viewType); return redirect()->back(302, [], "/settings/users/$userId"); @@ -316,7 +316,7 @@ protected function switchViewType(int $userId, Request $request, string $listNam public function changeSort(Request $request, string $id, string $type) { $validSortTypes = ['books', 'bookshelves', 'shelf_books']; - if (! in_array($type, $validSortTypes)) { + if (!in_array($type, $validSortTypes)) { return redirect()->back(500); } @@ -341,14 +341,14 @@ public function updateExpansionPreference(Request $request, string $id, string $ { $this->checkPermissionOrCurrentUser('users-manage', $id); $keyWhitelist = ['home-details']; - if (! in_array($key, $keyWhitelist)) { + if (!in_array($key, $keyWhitelist)) { return response('Invalid key', 500); } $newState = $request->get('expand', 'false'); $user = $this->user->findOrFail($id); - setting()->putUser($user, 'section_expansion#'.$key, $newState); + setting()->putUser($user, 'section_expansion#' . $key, $newState); return response('', 204); } @@ -361,18 +361,18 @@ protected function changeListSort(int $userId, Request $request, string $listNam $this->checkPermissionOrCurrentUser('users-manage', $userId); $sort = $request->get('sort'); - if (! in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) { + if (!in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) { $sort = 'name'; } $order = $request->get('order'); - if (! in_array($order, ['asc', 'desc'])) { + if (!in_array($order, ['asc', 'desc'])) { $order = 'asc'; } $user = $this->user->findOrFail($userId); - $sortKey = $listName.'_sort'; - $orderKey = $listName.'_sort_order'; + $sortKey = $listName . '_sort'; + $orderKey = $listName . '_sort_order'; setting()->putUser($user, $sortKey, $sort); setting()->putUser($user, $orderKey, $order); diff --git a/app/Http/Controllers/UserSearchController.php b/app/Http/Controllers/UserSearchController.php index a4b37332d85..f7ed9e57a94 100644 --- a/app/Http/Controllers/UserSearchController.php +++ b/app/Http/Controllers/UserSearchController.php @@ -18,10 +18,10 @@ public function forSelect(Request $request) $query = User::query()->orderBy('name', 'desc') ->take(20); - if (! empty($search)) { + if (!empty($search)) { $query->where(function (Builder $query) use ($search) { - $query->where('email', 'like', '%'.$search.'%') - ->orWhere('name', 'like', '%'.$search.'%'); + $query->where('email', 'like', '%' . $search . '%') + ->orWhere('name', 'like', '%' . $search . '%'); }); } diff --git a/app/Http/Middleware/ApiAuthenticate.php b/app/Http/Middleware/ApiAuthenticate.php index 66de6230f95..bc584d3c5a4 100644 --- a/app/Http/Middleware/ApiAuthenticate.php +++ b/app/Http/Middleware/ApiAuthenticate.php @@ -35,7 +35,7 @@ protected function ensureAuthorizedBySessionOrToken(): void // Return if the user is already found to be signed in via session-based auth. // This is to make it easy to browser the API via browser after just logging into the system. if (signedInUser() || session()->isStarted()) { - if (! user()->can('access-api')) { + if (!user()->can('access-api')) { throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index df47528e3eb..a320291122b 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -12,7 +12,7 @@ class Authenticate */ public function handle(Request $request, Closure $next) { - if (! hasAppAccess()) { + if (!hasAppAccess()) { if ($request->ajax()) { return response('Unauthorized.', 401); } diff --git a/app/Http/Middleware/CheckEmailConfirmed.php b/app/Http/Middleware/CheckEmailConfirmed.php index 9b88407944b..7dd970ade11 100644 --- a/app/Http/Middleware/CheckEmailConfirmed.php +++ b/app/Http/Middleware/CheckEmailConfirmed.php @@ -38,7 +38,7 @@ public function handle($request, Closure $next) { /** @var User $user */ $user = auth()->user(); - if (auth()->check() && ! $user->email_confirmed && $this->confirmationService->confirmationRequired()) { + if (auth()->check() && !$user->email_confirmed && $this->confirmationService->confirmationRequired()) { auth()->logout(); return redirect()->to('/'); diff --git a/app/Http/Middleware/CheckGuard.php b/app/Http/Middleware/CheckGuard.php index 769f18f7436..adc1d1f3ec0 100644 --- a/app/Http/Middleware/CheckGuard.php +++ b/app/Http/Middleware/CheckGuard.php @@ -18,7 +18,7 @@ class CheckGuard public function handle($request, Closure $next, ...$allowedGuards) { $activeGuard = config('auth.method'); - if (! in_array($activeGuard, $allowedGuards)) { + if (!in_array($activeGuard, $allowedGuards)) { session()->flash('error', trans('errors.permission')); return redirect('/'); diff --git a/app/Http/Middleware/CheckUserHasPermission.php b/app/Http/Middleware/CheckUserHasPermission.php index edd83f4f9b5..4a6a06468d1 100644 --- a/app/Http/Middleware/CheckUserHasPermission.php +++ b/app/Http/Middleware/CheckUserHasPermission.php @@ -18,7 +18,7 @@ class CheckUserHasPermission */ public function handle($request, Closure $next, $permission) { - if (! user()->can($permission)) { + if (!user()->can($permission)) { return $this->errorResponse($request); } diff --git a/app/Http/Middleware/Localization.php b/app/Http/Middleware/Localization.php index 0f7fa061495..d8e1253e5ed 100644 --- a/app/Http/Middleware/Localization.php +++ b/app/Http/Middleware/Localization.php @@ -133,7 +133,7 @@ protected function setSystemDateLocale(string $locale) $systemLocale = $this->getLocaleIso($locale); $set = setlocale(LC_TIME, $systemLocale); if ($set === false) { - setlocale(LC_TIME, $systemLocale.'.utf8'); + setlocale(LC_TIME, $systemLocale . '.utf8'); } } } diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index a0fa075afa0..6853809ea9d 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -37,7 +37,7 @@ public function __construct(Guard $auth) public function handle($request, Closure $next) { $requireConfirmation = setting('registration-confirmation'); - if ($this->auth->check() && (! $requireConfirmation || ($requireConfirmation && $this->auth->user()->email_confirmed))) { + if ($this->auth->check() && (!$requireConfirmation || ($requireConfirmation && $this->auth->user()->email_confirmed))) { return redirect('/'); } diff --git a/app/Http/Middleware/RunThemeActions.php b/app/Http/Middleware/RunThemeActions.php index a34ea776906..5e727daae5e 100644 --- a/app/Http/Middleware/RunThemeActions.php +++ b/app/Http/Middleware/RunThemeActions.php @@ -19,7 +19,7 @@ class RunThemeActions public function handle($request, Closure $next) { $earlyResponse = Theme::dispatch(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $request); - if (! is_null($earlyResponse)) { + if (!is_null($earlyResponse)) { return $earlyResponse; } diff --git a/app/Http/Request.php b/app/Http/Request.php index f90128779f8..c5b38f1c1bb 100644 --- a/app/Http/Request.php +++ b/app/Http/Request.php @@ -19,7 +19,7 @@ public function getSchemeAndHttpHost() if ($base) { $base = trim($base, '/'); } else { - $base = $this->getScheme().'://'.$this->getHttpHost(); + $base = $this->getScheme() . '://' . $this->getHttpHost(); } return $base; diff --git a/app/Notifications/ConfirmEmail.php b/app/Notifications/ConfirmEmail.php index 75164018aa3..5399c25a849 100644 --- a/app/Notifications/ConfirmEmail.php +++ b/app/Notifications/ConfirmEmail.php @@ -31,6 +31,6 @@ public function toMail($notifiable) ->subject(trans('auth.email_confirm_subject', $appName)) ->greeting(trans('auth.email_confirm_greeting', $appName)) ->line(trans('auth.email_confirm_text')) - ->action(trans('auth.email_confirm_action'), url('/register/confirm/'.$this->token)); + ->action(trans('auth.email_confirm_action'), url('/register/confirm/' . $this->token)); } } diff --git a/app/Notifications/ResetPassword.php b/app/Notifications/ResetPassword.php index 94f8f0d4a2d..7fa14659604 100644 --- a/app/Notifications/ResetPassword.php +++ b/app/Notifications/ResetPassword.php @@ -31,7 +31,7 @@ public function toMail() return $this->newMailMessage() ->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')])) ->line(trans('auth.email_reset_text')) - ->action(trans('auth.reset_password'), url('password/reset/'.$this->token)) + ->action(trans('auth.reset_password'), url('password/reset/' . $this->token)) ->line(trans('auth.email_reset_not_requested')); } } diff --git a/app/Notifications/UserInvite.php b/app/Notifications/UserInvite.php index da7066ca638..b0dc9afac3f 100644 --- a/app/Notifications/UserInvite.php +++ b/app/Notifications/UserInvite.php @@ -31,6 +31,6 @@ public function toMail($notifiable) ->subject(trans('auth.user_invite_email_subject', $appName)) ->greeting(trans('auth.user_invite_email_greeting', $appName)) ->line(trans('auth.user_invite_email_text')) - ->action(trans('auth.user_invite_email_action'), url('/register/invite/'.$this->token)); + ->action(trans('auth.user_invite_email_action'), url('/register/invite/' . $this->token)); } } diff --git a/app/Providers/CustomValidationServiceProvider.php b/app/Providers/CustomValidationServiceProvider.php index b005b89c404..c54f48ca313 100644 --- a/app/Providers/CustomValidationServiceProvider.php +++ b/app/Providers/CustomValidationServiceProvider.php @@ -23,7 +23,7 @@ public function boot(): void $isJs = strpos($cleanLinkName, 'javascript:') === 0; $isData = strpos($cleanLinkName, 'data:') === 0; - return ! $isJs && ! $isData; + return !$isJs && !$isData; }); } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index a101e82e3cb..82d57703fad 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -61,7 +61,7 @@ protected function mapApiRoutes() { Route::group([ 'middleware' => 'api', - 'namespace' => $this->namespace.'\Api', + 'namespace' => $this->namespace . '\Api', 'prefix' => 'api', ], function ($router) { require base_path('routes/api.php'); diff --git a/app/Settings/SettingService.php b/app/Settings/SettingService.php index 174b98329cc..f2c4c8305c4 100644 --- a/app/Settings/SettingService.php +++ b/app/Settings/SettingService.php @@ -34,7 +34,7 @@ public function __construct(Setting $setting, Cache $cache) public function get(string $key, $default = null) { if (is_null($default)) { - $default = config('setting-defaults.'.$key, false); + $default = config('setting-defaults.' . $key, false); } if (isset($this->localCache[$key])) { @@ -64,7 +64,7 @@ protected function getFromSession(string $key, $default = false) public function getUser(User $user, string $key, $default = null) { if (is_null($default)) { - $default = config('setting-defaults.user.'.$key, false); + $default = config('setting-defaults.user.' . $key, false); } if ($user->isDefault()) { @@ -90,7 +90,7 @@ public function getForCurrentUser(string $key, $default = null) protected function getValueFromStore(string $key) { // Check the cache - $cacheKey = $this->cachePrefix.$key; + $cacheKey = $this->cachePrefix . $key; $cacheVal = $this->cache->get($cacheKey, null); if ($cacheVal !== null) { return $cacheVal; @@ -118,7 +118,7 @@ protected function getValueFromStore(string $key) */ protected function clearFromCache(string $key) { - $cacheKey = $this->cachePrefix.$key; + $cacheKey = $this->cachePrefix . $key; $this->cache->forget($cacheKey); if (isset($this->localCache[$key])) { unset($this->localCache[$key]); @@ -211,7 +211,7 @@ public function putUser(User $user, string $key, string $value): bool */ protected function userKey(string $userId, string $key = ''): string { - return 'user:'.$userId.':'.$key; + return 'user:' . $userId . ':' . $key; } /** @@ -232,7 +232,7 @@ public function remove(string $key): void public function deleteUserSettings(string $userId) { return $this->setting->newQuery() - ->where('setting_key', 'like', $this->userKey($userId).'%') + ->where('setting_key', 'like', $this->userKey($userId) . '%') ->delete(); } diff --git a/app/Theming/CustomHtmlHeadContentProvider.php b/app/Theming/CustomHtmlHeadContentProvider.php index 8a6f1a0ee4e..041e5d025bd 100644 --- a/app/Theming/CustomHtmlHeadContentProvider.php +++ b/app/Theming/CustomHtmlHeadContentProvider.php @@ -33,7 +33,7 @@ public function forWeb(): string { $content = $this->getSourceContent(); $hash = md5($content); - $html = $this->cache->remember('custom-head-web:'.$hash, 86400, function () use ($content) { + $html = $this->cache->remember('custom-head-web:' . $hash, 86400, function () use ($content) { return HtmlNonceApplicator::prepare($content); }); @@ -49,7 +49,7 @@ public function forExport(): string $content = $this->getSourceContent(); $hash = md5($content); - return $this->cache->remember('custom-head-export:'.$hash, 86400, function () use ($content) { + return $this->cache->remember('custom-head-export:' . $hash, 86400, function () use ($content) { return HtmlContentFilter::removeScripts($content); }); } diff --git a/app/Theming/ThemeService.php b/app/Theming/ThemeService.php index b18ecaa5850..602abaf1c5a 100644 --- a/app/Theming/ThemeService.php +++ b/app/Theming/ThemeService.php @@ -14,7 +14,7 @@ class ThemeService */ public function listen(string $event, callable $action) { - if (! isset($this->listeners[$event])) { + if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; } @@ -35,7 +35,7 @@ public function dispatch(string $event, ...$args) { foreach ($this->listeners[$event] ?? [] as $action) { $result = call_user_func_array($action, $args); - if (! is_null($result)) { + if (!is_null($result)) { return $result; } } diff --git a/app/Uploads/Attachment.php b/app/Uploads/Attachment.php index 1c644ebbbd1..5e637246a66 100644 --- a/app/Uploads/Attachment.php +++ b/app/Uploads/Attachment.php @@ -45,7 +45,7 @@ public function getFileName() return $this->name; } - return $this->name.'.'.$this->extension; + return $this->name . '.' . $this->extension; } /** @@ -65,7 +65,7 @@ public function getUrl($openInline = false): string return $this->path; } - return url('/attachments/'.$this->id.($openInline ? '?open=true' : '')); + return url('/attachments/' . $this->id . ($openInline ? '?open=true' : '')); } /** @@ -73,7 +73,7 @@ public function getUrl($openInline = false): string */ public function htmlLink(): string { - return ''.e($this->name).''; + return '' . e($this->name) . ''; } /** @@ -81,7 +81,7 @@ public function htmlLink(): string */ public function markdownLink(): string { - return '['.$this->name.']('.$this->getUrl().')'; + return '[' . $this->name . '](' . $this->getUrl() . ')'; } /** diff --git a/app/Uploads/AttachmentService.php b/app/Uploads/AttachmentService.php index e13772f1803..f7a0918c609 100644 --- a/app/Uploads/AttachmentService.php +++ b/app/Uploads/AttachmentService.php @@ -60,7 +60,7 @@ protected function adjustPathForStorageDisk(string $path): string return $path; } - return 'uploads/files/'.$path; + return 'uploads/files/' . $path; } /** @@ -106,7 +106,7 @@ public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachme */ public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment { - if (! $attachment->external) { + if (!$attachment->external) { $this->deleteFileInStorage($attachment); } @@ -161,8 +161,8 @@ public function updateFile(Attachment $attachment, array $requestData): Attachme $attachment->name = $requestData['name']; $link = trim($requestData['link'] ?? ''); - if (! empty($link)) { - if (! $attachment->external) { + if (!empty($link)) { + if (!$attachment->external) { $this->deleteFileInStorage($attachment); $attachment->external = true; $attachment->extension = ''; @@ -182,7 +182,7 @@ public function updateFile(Attachment $attachment, array $requestData): Attachme */ public function deleteFile(Attachment $attachment) { - if (! $attachment->external) { + if (!$attachment->external) { $this->deleteFileInStorage($attachment); } @@ -214,19 +214,19 @@ protected function putFileInStorage(UploadedFile $uploadedFile): string $attachmentData = file_get_contents($uploadedFile->getRealPath()); $storage = $this->getStorage(); - $basePath = 'uploads/files/'.date('Y-m-M').'/'; + $basePath = 'uploads/files/' . date('Y-m-M') . '/'; - $uploadFileName = Str::random(16).'.'.$uploadedFile->getClientOriginalExtension(); - while ($storage->exists($this->adjustPathForStorageDisk($basePath.$uploadFileName))) { - $uploadFileName = Str::random(3).$uploadFileName; + $uploadFileName = Str::random(16) . '.' . $uploadedFile->getClientOriginalExtension(); + while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) { + $uploadFileName = Str::random(3) . $uploadFileName; } - $attachmentPath = $basePath.$uploadFileName; + $attachmentPath = $basePath . $uploadFileName; try { $storage->put($this->adjustPathForStorageDisk($attachmentPath), $attachmentData); } catch (Exception $e) { - Log::error('Error when attempting file upload:'.$e->getMessage()); + Log::error('Error when attempting file upload:' . $e->getMessage()); throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentPath])); } diff --git a/app/Uploads/ImageRepo.php b/app/Uploads/ImageRepo.php index 1ff6a1e9cd7..c4205e35740 100644 --- a/app/Uploads/ImageRepo.php +++ b/app/Uploads/ImageRepo.php @@ -88,7 +88,7 @@ public function getPaginatedByType( } if ($search !== null) { - $imageQuery = $imageQuery->where('name', 'LIKE', '%'.$search.'%'); + $imageQuery = $imageQuery->where('name', 'LIKE', '%' . $search . '%'); } // Filter by page access @@ -162,7 +162,7 @@ public function saveNewFromData(string $imageName, string $imageData, string $ty */ public function saveDrawing(string $base64Uri, int $uploadedTo): Image { - $name = 'Drawing-'.strval(user()->id).'-'.strval(time()).'.png'; + $name = 'Drawing-' . strval(user()->id) . '-' . strval(time()) . '.png'; return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo); } @@ -256,7 +256,7 @@ public function getImageData(Image $image): ?string public function getPagesUsingImage(Image $image): array { $pages = Page::visible() - ->where('html', 'like', '%'.$image->url.'%') + ->where('html', 'like', '%' . $image->url . '%') ->get(['id', 'name', 'slug', 'book_id']); foreach ($pages as $page) { diff --git a/app/Uploads/ImageService.php b/app/Uploads/ImageService.php index 48ad0f6b223..d6c74c751c7 100644 --- a/app/Uploads/ImageService.php +++ b/app/Uploads/ImageService.php @@ -56,7 +56,7 @@ protected function adjustPathForStorageDisk(string $path, string $imageType = '' return $path; } - return 'uploads/images/'.$path; + return 'uploads/images/' . $path; } /** @@ -130,21 +130,21 @@ public function saveNew(string $imageName, string $imageData, string $type, int $secureUploads = setting('app-secure-images'); $fileName = $this->cleanImageFileName($imageName); - $imagePath = '/uploads/images/'.$type.'/'.date('Y-m').'/'; + $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/'; - while ($storage->exists($this->adjustPathForStorageDisk($imagePath.$fileName, $type))) { - $fileName = Str::random(3).$fileName; + while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) { + $fileName = Str::random(3) . $fileName; } - $fullPath = $imagePath.$fileName; + $fullPath = $imagePath . $fileName; if ($secureUploads) { - $fullPath = $imagePath.Str::random(16).'-'.$fileName; + $fullPath = $imagePath . Str::random(16) . '-' . $fileName; } try { $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData); } catch (Exception $e) { - \Log::error('Error when attempting image upload:'.$e->getMessage()); + \Log::error('Error when attempting image upload:' . $e->getMessage()); throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath])); } @@ -182,8 +182,8 @@ protected function saveImageDataInPublicSpace(Storage $storage, string $path, st // Attempting to set ACL during above put request requires different permissions // hence would technically be a breaking change for actual s3 usage. $usingS3 = strtolower(config('filesystems.images')) === 's3'; - $usingS3Like = $usingS3 && ! is_null(config('filesystems.disks.s3.endpoint')); - if (! $usingS3Like) { + $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint')); + if (!$usingS3Like) { $storage->setVisibility($path, 'public'); } } @@ -203,7 +203,7 @@ protected function cleanImageFileName(string $name): string $name = Str::random(10); } - return $name.'.'.$extension; + return $name . '.' . $extension; } /** @@ -235,11 +235,11 @@ public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRat return $this->getPublicUrl($image->path); } - $thumbDirName = '/'.($keepRatio ? 'scaled-' : 'thumbs-').$width.'-'.$height.'/'; + $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/'; $imagePath = $image->path; - $thumbFilePath = dirname($imagePath).$thumbDirName.basename($imagePath); + $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath); - if ($this->cache->has('images-'.$image->id.'-'.$thumbFilePath) && $this->cache->get('images-'.$thumbFilePath)) { + if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) { return $this->getPublicUrl($thumbFilePath); } @@ -251,7 +251,7 @@ public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRat $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio); $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData); - $this->cache->put('images-'.$image->id.'-'.$thumbFilePath, $thumbFilePath, 60 * 60 * 72); + $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72); return $this->getPublicUrl($thumbFilePath); } @@ -379,7 +379,7 @@ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = t $this->image->newQuery()->whereIn('type', $types) ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) { foreach ($images as $image) { - $searchQuery = '%'.basename($image->path).'%'; + $searchQuery = '%' . basename($image->path) . '%'; $inPage = DB::table('pages') ->where('html', 'like', $searchQuery)->count() > 0; @@ -389,9 +389,9 @@ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = t ->where('html', 'like', $searchQuery)->count() > 0; } - if (! $inPage && ! $inRevision) { + if (!$inPage && !$inRevision) { $deletedPaths[] = $image->path; - if (! $dryRun) { + if (!$dryRun) { $this->destroy($image); } } @@ -432,7 +432,7 @@ public function imageUriToBase64(string $uri): ?string $extension = 'svg+xml'; } - return 'data:image/'.$extension.';base64,'.base64_encode($imageData); + return 'data:image/' . $extension . ';base64,' . base64_encode($imageData); } /** @@ -463,7 +463,7 @@ private function imageUrlToStoragePath(string $url): ?string foreach ($potentialHostPaths as $potentialBasePath) { $potentialBasePath = strtolower($potentialBasePath); if (strpos(strtolower($url), $potentialBasePath) === 0) { - return 'uploads/images/'.trim(substr($url, strlen($potentialBasePath)), '/'); + return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/'); } } @@ -485,9 +485,9 @@ private function getPublicUrl(string $filePath): string if ($storageUrl == false && config('filesystems.images') === 's3') { $storageDetails = config('filesystems.disks.s3'); if (strpos($storageDetails['bucket'], '.') === false) { - $storageUrl = 'https://'.$storageDetails['bucket'].'.s3.amazonaws.com'; + $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com'; } else { - $storageUrl = 'https://s3-'.$storageDetails['region'].'.amazonaws.com/'.$storageDetails['bucket']; + $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket']; } } $this->storageUrl = $storageUrl; @@ -495,6 +495,6 @@ private function getPublicUrl(string $filePath): string $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl; - return rtrim($basePath, '/').$filePath; + return rtrim($basePath, '/') . $filePath; } } diff --git a/app/Uploads/UserAvatars.php b/app/Uploads/UserAvatars.php index e317ee74af0..f5b085a35d5 100644 --- a/app/Uploads/UserAvatars.php +++ b/app/Uploads/UserAvatars.php @@ -23,7 +23,7 @@ public function __construct(ImageService $imageService, HttpFetcher $http) */ public function fetchAndAssignToUser(User $user): void { - if (! $this->avatarFetchEnabled()) { + if (!$this->avatarFetchEnabled()) { return; } @@ -93,7 +93,7 @@ protected function saveAvatarImage(User $user, int $size = 500): Image */ protected function createAvatarImageFromData(User $user, string $imageData, string $extension): Image { - $imageName = str_replace(' ', '-', $user->id.'-avatar.'.$extension); + $imageName = str_replace(' ', '-', $user->id . '-avatar.' . $extension); $image = $this->imageService->saveNew($imageName, $imageData, 'user', $user->id); $image->created_by = $user->id; @@ -136,7 +136,7 @@ protected function getAvatarUrl(): string { $url = trim(config('services.avatar_url')); - if (empty($url) && ! config('services.disable_services')) { + if (empty($url) && !config('services.disable_services')) { $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon'; } diff --git a/app/Util/CspService.php b/app/Util/CspService.php index 520344a2fd0..812e1a4bed1 100644 --- a/app/Util/CspService.php +++ b/app/Util/CspService.php @@ -36,11 +36,11 @@ public function setScriptSrc(Response $response) $parts = [ 'http:', 'https:', - '\'nonce-'.$this->nonce.'\'', + '\'nonce-' . $this->nonce . '\'', '\'strict-dynamic\'', ]; - $value = 'script-src '.implode(' ', $parts); + $value = 'script-src ' . implode(' ', $parts); $response->headers->set('Content-Security-Policy', $value, false); } @@ -53,7 +53,7 @@ public function setFrameAncestors(Response $response) { $iframeHosts = $this->getAllowedIframeHosts(); array_unshift($iframeHosts, "'self'"); - $cspValue = 'frame-ancestors '.implode(' ', $iframeHosts); + $cspValue = 'frame-ancestors ' . implode(' ', $iframeHosts); $response->headers->set('Content-Security-Policy', $cspValue, false); } diff --git a/app/Util/HtmlContentFilter.php b/app/Util/HtmlContentFilter.php index ffde21ba36d..1943aa7802c 100644 --- a/app/Util/HtmlContentFilter.php +++ b/app/Util/HtmlContentFilter.php @@ -18,7 +18,7 @@ public static function removeScripts(string $html): string return $html; } - $html = ''.$html.''; + $html = '' . $html . ''; libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); @@ -29,19 +29,19 @@ public static function removeScripts(string $html): string static::removeNodes($scriptElems); // Remove clickable links to JavaScript URI - $badLinks = $xPath->query('//*['.static::xpathContains('@href', 'javascript:').']'); + $badLinks = $xPath->query('//*[' . static::xpathContains('@href', 'javascript:') . ']'); static::removeNodes($badLinks); // Remove forms with calls to JavaScript URI - $badForms = $xPath->query('//*['.static::xpathContains('@action', 'javascript:').'] | //*['.static::xpathContains('@formaction', 'javascript:').']'); + $badForms = $xPath->query('//*[' . static::xpathContains('@action', 'javascript:') . '] | //*[' . static::xpathContains('@formaction', 'javascript:') . ']'); static::removeNodes($badForms); // Remove meta tag to prevent external redirects - $metaTags = $xPath->query('//meta['.static::xpathContains('@content', 'url').']'); + $metaTags = $xPath->query('//meta[' . static::xpathContains('@content', 'url') . ']'); static::removeNodes($metaTags); // Remove data or JavaScript iFrames - $badIframes = $xPath->query('//*['.static::xpathContains('@src', 'data:').'] | //*['.static::xpathContains('@src', 'javascript:').'] | //*[@srcdoc]'); + $badIframes = $xPath->query('//*[' . static::xpathContains('@src', 'data:') . '] | //*[' . static::xpathContains('@src', 'javascript:') . '] | //*[@srcdoc]'); static::removeNodes($badIframes); // Remove elements with a xlink:href attribute @@ -71,7 +71,7 @@ protected static function xpathContains(string $property, string $value): string $value = strtolower($value); $upperVal = strtoupper($value); - return 'contains(translate('.$property.', \''.$upperVal.'\', \''.$value.'\'), \''.$value.'\')'; + return 'contains(translate(' . $property . ', \'' . $upperVal . '\', \'' . $value . '\'), \'' . $value . '\')'; } /** diff --git a/app/Util/HtmlNonceApplicator.php b/app/Util/HtmlNonceApplicator.php index d6afb53e3ce..07298577cf5 100644 --- a/app/Util/HtmlNonceApplicator.php +++ b/app/Util/HtmlNonceApplicator.php @@ -21,7 +21,7 @@ public static function prepare(string $html): string return $html; } - $html = ''.$html.''; + $html = '' . $html . ''; libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML($html, LIBXML_SCHEMA_CREATE); diff --git a/app/helpers.php b/app/helpers.php index 860fddd1d44..9edc22c403d 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -24,7 +24,7 @@ function versioned_asset(string $file = ''): string $additional = sha1_file(public_path($file)); } - $path = $file.'?version='.urlencode($version).$additional; + $path = $file . '?version=' . urlencode($version) . $additional; return url($path); } @@ -43,7 +43,7 @@ function user(): User */ function signedInUser(): bool { - return auth()->user() && ! auth()->user()->isDefault(); + return auth()->user() && !auth()->user()->isDefault(); } /** @@ -51,7 +51,7 @@ function signedInUser(): bool */ function hasAppAccess(): bool { - return ! auth()->guest() || setting('app-public'); + return !auth()->guest() || setting('app-public'); } /** @@ -106,11 +106,11 @@ function theme_path(string $path = ''): ?string { $theme = config('view.theme'); - if (! $theme) { + if (!$theme) { return null; } - return base_path('themes/'.$theme.($path ? DIRECTORY_SEPARATOR.$path : $path)); + return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path)); } /** @@ -129,21 +129,21 @@ function icon(string $name, array $attrs = []): string ], $attrs); $attrString = ' '; foreach ($attrs as $attrName => $attr) { - $attrString .= $attrName.'="'.$attr.'" '; + $attrString .= $attrName . '="' . $attr . '" '; } - $iconPath = resource_path('icons/'.$name.'.svg'); - $themeIconPath = theme_path('icons/'.$name.'.svg'); + $iconPath = resource_path('icons/' . $name . '.svg'); + $themeIconPath = theme_path('icons/' . $name . '.svg'); if ($themeIconPath && file_exists($themeIconPath)) { $iconPath = $themeIconPath; - } elseif (! file_exists($iconPath)) { + } elseif (!file_exists($iconPath)) { return ''; } $fileContents = file_get_contents($iconPath); - return str_replace(' [ 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, - 'Date' => Illuminate\Support\Facades\Date::class, + 'Date' => Illuminate\Support\Facades\Date::class, // Laravel 'App' => Illuminate\Support\Facades\App::class, diff --git a/config/auth.php b/config/auth.php index c134aefb4da..1c3bb3edddf 100644 --- a/config/auth.php +++ b/config/auth.php @@ -59,7 +59,7 @@ ], 'web' => [ - 'driver' => 'session', + 'driver' => 'session', 'provider' => 'users', ], ], @@ -117,8 +117,8 @@ 'users' => [ 'provider' => 'users', 'email' => 'emails.password', - 'table' => 'password_resets', - 'expire' => 60, + 'table' => 'password_resets', + 'expire' => 60, 'throttle' => 60, ], ], diff --git a/config/broadcasting.php b/config/broadcasting.php index 2d529820cc5..59bccd52243 100644 --- a/config/broadcasting.php +++ b/config/broadcasting.php @@ -31,23 +31,23 @@ 'connections' => [ 'pusher' => [ - 'driver' => 'pusher', - 'key' => env('PUSHER_APP_KEY'), - 'secret' => env('PUSHER_APP_SECRET'), - 'app_id' => env('PUSHER_APP_ID'), + 'driver' => 'pusher', + 'key' => env('PUSHER_APP_KEY'), + 'secret' => env('PUSHER_APP_SECRET'), + 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), - 'useTLS' => true, + 'useTLS' => true, ], ], 'ably' => [ 'driver' => 'ably', - 'key' => env('ABLY_KEY'), + 'key' => env('ABLY_KEY'), ], 'redis' => [ - 'driver' => 'redis', + 'driver' => 'redis', 'connection' => 'default', ], diff --git a/config/cache.php b/config/cache.php index 21209af053a..6fd4807da33 100644 --- a/config/cache.php +++ b/config/cache.php @@ -38,14 +38,14 @@ ], 'array' => [ - 'driver' => 'array', + 'driver' => 'array', 'serialize' => false, ], 'database' => [ - 'driver' => 'database', - 'table' => 'cache', - 'connection' => null, + 'driver' => 'database', + 'table' => 'cache', + 'connection' => null, 'lock_connection' => null, ], @@ -55,9 +55,9 @@ ], 'memcached' => [ - 'driver' => 'memcached', + 'driver' => 'memcached', 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), - 'sasl' => [ + 'sasl' => [ env('MEMCACHED_USERNAME'), env('MEMCACHED_PASSWORD'), ], @@ -68,17 +68,17 @@ ], 'redis' => [ - 'driver' => 'redis', - 'connection' => 'default', + 'driver' => 'redis', + 'connection' => 'default', 'lock_connection' => 'default', ], 'dynamodb' => [ - 'driver' => 'dynamodb', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 'endpoint' => env('DYNAMODB_ENDPOINT'), ], @@ -99,6 +99,6 @@ | */ - 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'), + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_') . '_cache'), ]; diff --git a/config/filesystems.php b/config/filesystems.php index f4fb2d353e5..b3fa5fc2577 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -52,20 +52,20 @@ ], 'public' => [ - 'driver' => 'local', - 'root' => storage_path('app/public'), - 'url' => env('APP_URL').'/storage', + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => env('APP_URL') . '/storage', 'visibility' => 'public', ], 's3' => [ - 'driver' => 's3', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION'), - 'bucket' => env('AWS_BUCKET'), - 'url' => env('AWS_URL'), - 'endpoint' => env('AWS_ENDPOINT'), + 'driver' => 's3', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION'), + 'bucket' => env('AWS_BUCKET'), + 'url' => env('AWS_URL'), + 'endpoint' => env('AWS_ENDPOINT'), 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), ], diff --git a/config/logging.php b/config/logging.php index cdaa4ea1e29..48022940555 100644 --- a/config/logging.php +++ b/config/logging.php @@ -36,37 +36,37 @@ 'channels' => [ 'stack' => [ - 'driver' => 'stack', + 'driver' => 'stack', 'channels' => ['daily'], 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', - 'path' => storage_path('logs/laravel.log'), - 'level' => env('LOG_LEVEL', 'debug'), + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), 'days' => 14, ], 'daily' => [ 'driver' => 'daily', - 'path' => storage_path('logs/laravel.log'), - 'level' => env('LOG_LEVEL', 'debug'), + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), 'days' => 7, ], 'slack' => [ - 'driver' => 'slack', - 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Laravel Log', - 'emoji' => ':boom:', - 'level' => env('LOG_LEVEL', 'critical'), + 'emoji' => ':boom:', + 'level' => env('LOG_LEVEL', 'critical'), ], 'papertrail' => [ - 'driver' => 'monolog', - 'level' => env('LOG_LEVEL', 'debug'), - 'handler' => SyslogUdpHandler::class, + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => SyslogUdpHandler::class, 'handler_with' => [ 'host' => env('PAPERTRAIL_URL'), 'port' => env('PAPERTRAIL_PORT'), @@ -74,23 +74,23 @@ ], 'stderr' => [ - 'driver' => 'monolog', - 'level' => env('LOG_LEVEL', 'debug'), - 'handler' => StreamHandler::class, + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => StreamHandler::class, 'formatter' => env('LOG_STDERR_FORMATTER'), - 'with' => [ + 'with' => [ 'stream' => 'php://stderr', ], ], 'syslog' => [ 'driver' => 'syslog', - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => env('LOG_LEVEL', 'debug'), ], 'errorlog' => [ 'driver' => 'errorlog', - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => env('LOG_LEVEL', 'debug'), ], 'errorlog_plain_webserver' => [ @@ -105,7 +105,7 @@ ], 'null' => [ - 'driver' => 'monolog', + 'driver' => 'monolog', 'handler' => NullHandler::class, ], diff --git a/config/queue.php b/config/queue.php index 25ea5a81935..84f74388b23 100644 --- a/config/queue.php +++ b/config/queue.php @@ -35,39 +35,39 @@ ], 'database' => [ - 'driver' => 'database', - 'table' => 'jobs', - 'queue' => 'default', - 'retry_after' => 90, + 'driver' => 'database', + 'table' => 'jobs', + 'queue' => 'default', + 'retry_after' => 90, 'after_commit' => false, ], 'beanstalkd' => [ - 'driver' => 'beanstalkd', - 'host' => 'localhost', - 'queue' => 'default', - 'retry_after' => 90, - 'block_for' => 0, + 'driver' => 'beanstalkd', + 'host' => 'localhost', + 'queue' => 'default', + 'retry_after' => 90, + 'block_for' => 0, 'after_commit' => false, ], 'sqs' => [ - 'driver' => 'sqs', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), - 'queue' => env('SQS_QUEUE', 'default'), - 'suffix' => env('SQS_SUFFIX'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 'after_commit' => false, ], 'redis' => [ - 'driver' => 'redis', - 'connection' => 'default', - 'queue' => env('REDIS_QUEUE', 'default'), - 'retry_after' => 90, - 'block_for' => null, + 'driver' => 'redis', + 'connection' => 'default', + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => 90, + 'block_for' => null, 'after_commit' => false, ], @@ -85,9 +85,9 @@ */ 'failed' => [ - 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 'database' => env('DB_CONNECTION', 'mysql'), - 'table' => 'failed_jobs', + 'table' => 'failed_jobs', ], ]; diff --git a/config/services.php b/config/services.php index 5173d6b0d26..2d7253fb81e 100644 --- a/config/services.php +++ b/config/services.php @@ -14,7 +14,7 @@ 'disable_services' => env('DISABLE_EXTERNAL_SERVICES', false), // Draw.io integration active - 'drawio' => env('DRAWIO', ! env('DISABLE_EXTERNAL_SERVICES', false)), + 'drawio' => env('DRAWIO', !env('DISABLE_EXTERNAL_SERVICES', false)), // URL for fetching avatars 'avatar_url' => env('AVATAR_URL', ''), @@ -25,7 +25,7 @@ 'github' => [ 'client_id' => env('GITHUB_APP_ID', false), 'client_secret' => env('GITHUB_APP_SECRET', false), - 'redirect' => env('APP_URL').'/login/service/github/callback', + 'redirect' => env('APP_URL') . '/login/service/github/callback', 'name' => 'GitHub', 'auto_register' => env('GITHUB_AUTO_REGISTER', false), 'auto_confirm' => env('GITHUB_AUTO_CONFIRM_EMAIL', false), @@ -34,7 +34,7 @@ 'google' => [ 'client_id' => env('GOOGLE_APP_ID', false), 'client_secret' => env('GOOGLE_APP_SECRET', false), - 'redirect' => env('APP_URL').'/login/service/google/callback', + 'redirect' => env('APP_URL') . '/login/service/google/callback', 'name' => 'Google', 'auto_register' => env('GOOGLE_AUTO_REGISTER', false), 'auto_confirm' => env('GOOGLE_AUTO_CONFIRM_EMAIL', false), @@ -44,7 +44,7 @@ 'slack' => [ 'client_id' => env('SLACK_APP_ID', false), 'client_secret' => env('SLACK_APP_SECRET', false), - 'redirect' => env('APP_URL').'/login/service/slack/callback', + 'redirect' => env('APP_URL') . '/login/service/slack/callback', 'name' => 'Slack', 'auto_register' => env('SLACK_AUTO_REGISTER', false), 'auto_confirm' => env('SLACK_AUTO_CONFIRM_EMAIL', false), @@ -53,7 +53,7 @@ 'facebook' => [ 'client_id' => env('FACEBOOK_APP_ID', false), 'client_secret' => env('FACEBOOK_APP_SECRET', false), - 'redirect' => env('APP_URL').'/login/service/facebook/callback', + 'redirect' => env('APP_URL') . '/login/service/facebook/callback', 'name' => 'Facebook', 'auto_register' => env('FACEBOOK_AUTO_REGISTER', false), 'auto_confirm' => env('FACEBOOK_AUTO_CONFIRM_EMAIL', false), @@ -62,7 +62,7 @@ 'twitter' => [ 'client_id' => env('TWITTER_APP_ID', false), 'client_secret' => env('TWITTER_APP_SECRET', false), - 'redirect' => env('APP_URL').'/login/service/twitter/callback', + 'redirect' => env('APP_URL') . '/login/service/twitter/callback', 'name' => 'Twitter', 'auto_register' => env('TWITTER_AUTO_REGISTER', false), 'auto_confirm' => env('TWITTER_AUTO_CONFIRM_EMAIL', false), @@ -72,7 +72,7 @@ 'client_id' => env('AZURE_APP_ID', false), 'client_secret' => env('AZURE_APP_SECRET', false), 'tenant' => env('AZURE_TENANT', false), - 'redirect' => env('APP_URL').'/login/service/azure/callback', + 'redirect' => env('APP_URL') . '/login/service/azure/callback', 'name' => 'Microsoft Azure', 'auto_register' => env('AZURE_AUTO_REGISTER', false), 'auto_confirm' => env('AZURE_AUTO_CONFIRM_EMAIL', false), @@ -81,7 +81,7 @@ 'okta' => [ 'client_id' => env('OKTA_APP_ID'), 'client_secret' => env('OKTA_APP_SECRET'), - 'redirect' => env('APP_URL').'/login/service/okta/callback', + 'redirect' => env('APP_URL') . '/login/service/okta/callback', 'base_url' => env('OKTA_BASE_URL'), 'name' => 'Okta', 'auto_register' => env('OKTA_AUTO_REGISTER', false), @@ -91,7 +91,7 @@ 'gitlab' => [ 'client_id' => env('GITLAB_APP_ID'), 'client_secret' => env('GITLAB_APP_SECRET'), - 'redirect' => env('APP_URL').'/login/service/gitlab/callback', + 'redirect' => env('APP_URL') . '/login/service/gitlab/callback', 'instance_uri' => env('GITLAB_BASE_URI'), // Needed only for self hosted instances 'name' => 'GitLab', 'auto_register' => env('GITLAB_AUTO_REGISTER', false), @@ -101,7 +101,7 @@ 'twitch' => [ 'client_id' => env('TWITCH_APP_ID'), 'client_secret' => env('TWITCH_APP_SECRET'), - 'redirect' => env('APP_URL').'/login/service/twitch/callback', + 'redirect' => env('APP_URL') . '/login/service/twitch/callback', 'name' => 'Twitch', 'auto_register' => env('TWITCH_AUTO_REGISTER', false), 'auto_confirm' => env('TWITCH_AUTO_CONFIRM_EMAIL', false), @@ -110,7 +110,7 @@ 'discord' => [ 'client_id' => env('DISCORD_APP_ID'), 'client_secret' => env('DISCORD_APP_SECRET'), - 'redirect' => env('APP_URL').'/login/service/discord/callback', + 'redirect' => env('APP_URL') . '/login/service/discord/callback', 'name' => 'Discord', 'auto_register' => env('DISCORD_AUTO_REGISTER', false), 'auto_confirm' => env('DISCORD_AUTO_CONFIRM_EMAIL', false), diff --git a/config/session.php b/config/session.php index 321530df397..4bbb789010f 100644 --- a/config/session.php +++ b/config/session.php @@ -59,7 +59,7 @@ // The session cookie path determines the path for which the cookie will // be regarded as available. Typically, this will be the root path of // your application but you are free to change this when necessary. - 'path' => '/'.(explode('/', env('APP_URL', ''), 4)[3] ?? ''), + 'path' => '/' . (explode('/', env('APP_URL', ''), 4)[3] ?? ''), // Session Cookie Domain // Here you may change the domain of the cookie used to identify a session diff --git a/config/view.php b/config/view.php index 811cedc7f95..80bc9ef8fe8 100644 --- a/config/view.php +++ b/config/view.php @@ -11,7 +11,7 @@ // Join up possible view locations $viewPaths = [realpath(base_path('resources/views'))]; if ($theme = env('APP_THEME', false)) { - array_unshift($viewPaths, base_path('themes/'.$theme)); + array_unshift($viewPaths, base_path('themes/' . $theme)); } return [ diff --git a/database/factories/Actions/CommentFactory.php b/database/factories/Actions/CommentFactory.php index 4b3707e5a28..06b69d31c6c 100644 --- a/database/factories/Actions/CommentFactory.php +++ b/database/factories/Actions/CommentFactory.php @@ -32,7 +32,7 @@ class CommentFactory extends Factory public function definition() { $text = $this->faker->paragraph(1); - $html = '

      '.$text.'

      '; + $html = '

      ' . $text . '

      '; return [ 'html' => $html, diff --git a/database/factories/Auth/UserFactory.php b/database/factories/Auth/UserFactory.php index 670d1a7f98b..19dc01de5ad 100644 --- a/database/factories/Auth/UserFactory.php +++ b/database/factories/Auth/UserFactory.php @@ -37,7 +37,7 @@ public function definition() return [ 'name' => $name, 'email' => $this->faker->email, - 'slug' => \Illuminate\Support\Str::slug($name.'-'.\Illuminate\Support\Str::random(5)), + 'slug' => \Illuminate\Support\Str::slug($name . '-' . \Illuminate\Support\Str::random(5)), 'password' => Str::random(10), 'remember_token' => Str::random(10), 'email_confirmed' => 1, diff --git a/database/factories/Entities/Models/PageFactory.php b/database/factories/Entities/Models/PageFactory.php index ac9cce38bfc..3ced0ad631e 100644 --- a/database/factories/Entities/Models/PageFactory.php +++ b/database/factories/Entities/Models/PageFactory.php @@ -32,7 +32,7 @@ class PageFactory extends Factory */ public function definition() { - $html = '

      '.implode('

      ', $this->faker->paragraphs(5)).'

      '; + $html = '

      ' . implode('

      ', $this->faker->paragraphs(5)) . '

      '; return [ 'name' => $this->faker->sentence, diff --git a/database/factories/Uploads/ImageFactory.php b/database/factories/Uploads/ImageFactory.php index d0e892ebd2b..f7c700917d8 100644 --- a/database/factories/Uploads/ImageFactory.php +++ b/database/factories/Uploads/ImageFactory.php @@ -32,7 +32,7 @@ class ImageFactory extends Factory public function definition() { return [ - 'name' => $this->faker->slug.'.jpg', + 'name' => $this->faker->slug . '.jpg', 'url' => $this->faker->url, 'path' => $this->faker->url, 'type' => 'gallery', diff --git a/database/migrations/2015_08_29_105422_add_roles_and_permissions.php b/database/migrations/2015_08_29_105422_add_roles_and_permissions.php index 19e5a76e67c..c17f72e2fed 100644 --- a/database/migrations/2015_08_29_105422_add_roles_and_permissions.php +++ b/database/migrations/2015_08_29_105422_add_roles_and_permissions.php @@ -94,8 +94,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $newPermId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower($op), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower($op), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -112,8 +112,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $newPermId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower($op), - 'display_name' => $op.' '.$entity, + 'name' => strtolower($entity) . '-' . strtolower($op), + 'display_name' => $op . ' ' . $entity, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); diff --git a/database/migrations/2016_02_27_120329_update_permissions_and_roles.php b/database/migrations/2016_02_27_120329_update_permissions_and_roles.php index c5f202c7364..1bab5a873b1 100644 --- a/database/migrations/2016_02_27_120329_update_permissions_and_roles.php +++ b/database/migrations/2016_02_27_120329_update_permissions_and_roles.php @@ -45,8 +45,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -83,8 +83,8 @@ public function down() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower($op), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower($op), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -101,8 +101,8 @@ public function down() foreach ($entities as $entity) { foreach ($ops as $op) { $permissionId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower($op), - 'display_name' => $op.' '.$entity, + 'name' => strtolower($entity) . '-' . strtolower($op), + 'display_name' => $op . ' ' . $entity, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); diff --git a/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php b/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php index 2459284a415..48a913f8201 100644 --- a/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php +++ b/database/migrations/2016_04_09_100730_add_view_permissions_to_roles.php @@ -19,8 +19,8 @@ public function up() foreach ($entities as $entity) { foreach ($ops as $op) { $permId = DB::table('permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -47,7 +47,7 @@ public function down() $ops = ['View All', 'View Own']; foreach ($entities as $entity) { foreach ($ops as $op) { - $permissionName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); + $permissionName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); $permission = DB::table('permissions')->where('name', '=', $permissionName)->first(); DB::table('permission_role')->where('permission_id', '=', $permission->id)->delete(); DB::table('permissions')->where('name', '=', $permissionName)->delete(); diff --git a/database/migrations/2016_04_20_192649_create_joint_permissions_table.php b/database/migrations/2016_04_20_192649_create_joint_permissions_table.php index 31e050696de..8c3d9124c75 100644 --- a/database/migrations/2016_04_20_192649_create_joint_permissions_table.php +++ b/database/migrations/2016_04_20_192649_create_joint_permissions_table.php @@ -54,7 +54,7 @@ public function up() // Ensure unique name while (DB::table('roles')->where('name', '=', $publicRoleData['display_name'])->count() > 0) { - $publicRoleData['display_name'] = $publicRoleData['display_name'].Str::random(2); + $publicRoleData['display_name'] = $publicRoleData['display_name'] . Str::random(2); } $publicRoleId = DB::table('roles')->insertGetId($publicRoleData); @@ -63,7 +63,7 @@ public function up() $ops = ['View All', 'View Own']; foreach ($entities as $entity) { foreach ($ops as $op) { - $name = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); + $name = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); $permission = DB::table('role_permissions')->where('name', '=', $name)->first(); // Assign view permission to public DB::table('permission_role')->insert([ diff --git a/database/migrations/2016_10_09_142037_create_attachments_table.php b/database/migrations/2016_10_09_142037_create_attachments_table.php index f175a41405b..9c5422f0899 100644 --- a/database/migrations/2016_10_09_142037_create_attachments_table.php +++ b/database/migrations/2016_10_09_142037_create_attachments_table.php @@ -38,8 +38,8 @@ public function up() $entity = 'Attachment'; foreach ($ops as $op) { $permissionId = DB::table('role_permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -63,7 +63,7 @@ public function down() $ops = ['Create All', 'Create Own', 'Update All', 'Update Own', 'Delete All', 'Delete Own']; $entity = 'Attachment'; foreach ($ops as $op) { - $permName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); + $permName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); DB::table('role_permissions')->where('name', '=', $permName)->delete(); } } diff --git a/database/migrations/2017_04_20_185112_add_revision_counts.php b/database/migrations/2017_04_20_185112_add_revision_counts.php index 922e0d9c3df..8c6d75e778c 100644 --- a/database/migrations/2017_04_20_185112_add_revision_counts.php +++ b/database/migrations/2017_04_20_185112_add_revision_counts.php @@ -22,8 +22,8 @@ public function up() }); // Update revision count - $pTable = DB::getTablePrefix().'pages'; - $rTable = DB::getTablePrefix().'page_revisions'; + $pTable = DB::getTablePrefix() . 'pages'; + $rTable = DB::getTablePrefix() . 'page_revisions'; DB::statement("UPDATE ${pTable} SET ${pTable}.revision_count=(SELECT count(*) FROM ${rTable} WHERE ${rTable}.page_id=${pTable}.id)"); } diff --git a/database/migrations/2017_08_01_130541_create_comments_table.php b/database/migrations/2017_08_01_130541_create_comments_table.php index 9b0b38651c0..7e64d347b4c 100644 --- a/database/migrations/2017_08_01_130541_create_comments_table.php +++ b/database/migrations/2017_08_01_130541_create_comments_table.php @@ -35,8 +35,8 @@ public function up() $entity = 'Comment'; foreach ($ops as $op) { $permissionId = DB::table('role_permissions')->insertGetId([ - 'name' => strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)), - 'display_name' => $op.' '.$entity.'s', + 'name' => strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)), + 'display_name' => $op . ' ' . $entity . 's', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); @@ -60,7 +60,7 @@ public function down() $ops = ['Create All', 'Create Own', 'Update All', 'Update Own', 'Delete All', 'Delete Own']; $entity = 'Comment'; foreach ($ops as $op) { - $permName = strtolower($entity).'-'.strtolower(str_replace(' ', '-', $op)); + $permName = strtolower($entity) . '-' . strtolower(str_replace(' ', '-', $op)); DB::table('role_permissions')->where('name', '=', $permName)->delete(); } } diff --git a/database/migrations/2018_08_04_115700_create_bookshelves_table.php b/database/migrations/2018_08_04_115700_create_bookshelves_table.php index 51f6587cb6a..8dc2a72e9b9 100644 --- a/database/migrations/2018_08_04_115700_create_bookshelves_table.php +++ b/database/migrations/2018_08_04_115700_create_bookshelves_table.php @@ -77,17 +77,17 @@ public function up() $roleIdsWithBookPermission = DB::table('role_permissions') ->leftJoin('permission_role', 'role_permissions.id', '=', 'permission_role.permission_id') ->leftJoin('roles', 'roles.id', '=', 'permission_role.role_id') - ->where('role_permissions.name', '=', 'book-'.$dbOpName)->get(['roles.id'])->pluck('id'); + ->where('role_permissions.name', '=', 'book-' . $dbOpName)->get(['roles.id'])->pluck('id'); $permId = DB::table('role_permissions')->insertGetId([ - 'name' => 'bookshelf-'.$dbOpName, - 'display_name' => $op.' '.'BookShelves', + 'name' => 'bookshelf-' . $dbOpName, + 'display_name' => $op . ' ' . 'BookShelves', 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' => \Carbon\Carbon::now()->toDateTimeString(), ]); $rowsToInsert = $roleIdsWithBookPermission->filter(function ($roleId) { - return ! is_null($roleId); + return !is_null($roleId); })->map(function ($roleId) use ($permId) { return [ 'role_id' => $roleId, diff --git a/database/migrations/2021_03_08_215138_add_user_slug.php b/database/migrations/2021_03_08_215138_add_user_slug.php index e4f7c9e1137..dad1e42273c 100644 --- a/database/migrations/2021_03_08_215138_add_user_slug.php +++ b/database/migrations/2021_03_08_215138_add_user_slug.php @@ -22,7 +22,7 @@ public function up() DB::table('users')->cursor()->each(function ($user) use (&$slugMap) { $userSlug = Str::slug($user->name); while (isset($slugMap[$userSlug])) { - $userSlug = Str::slug($user->name.Str::random(4)); + $userSlug = Str::slug($user->name . Str::random(4)); } $slugMap[$userSlug] = true; diff --git a/database/seeders/DummyContentSeeder.php b/database/seeders/DummyContentSeeder.php index f410681e723..d54732b2635 100644 --- a/database/seeders/DummyContentSeeder.php +++ b/database/seeders/DummyContentSeeder.php @@ -48,7 +48,7 @@ public function run() $book->pages()->saveMany($pages); }); - $largeBook = \BookStack\Entities\Models\Book::factory()->create(array_merge($byData, ['name' => 'Large book'.Str::random(10)])); + $largeBook = \BookStack\Entities\Models\Book::factory()->create(array_merge($byData, ['name' => 'Large book' . Str::random(10)])); $pages = Page::factory()->count(200)->make($byData); $chapters = Chapter::factory()->count(50)->make($byData); $largeBook->pages()->saveMany($pages); diff --git a/database/seeders/LargeContentSeeder.php b/database/seeders/LargeContentSeeder.php index 2d4ef16178e..2fbf4a5c982 100644 --- a/database/seeders/LargeContentSeeder.php +++ b/database/seeders/LargeContentSeeder.php @@ -25,7 +25,7 @@ public function run() $editorRole = Role::getRole('editor'); $editorUser->attachRole($editorRole); - $largeBook = \BookStack\Entities\Models\Book::factory()->create(['name' => 'Large book'.Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); + $largeBook = \BookStack\Entities\Models\Book::factory()->create(['name' => 'Large book' . Str::random(10), 'created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $pages = Page::factory()->count(200)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $chapters = Chapter::factory()->count(50)->make(['created_by' => $editorUser->id, 'updated_by' => $editorUser->id]); $largeBook->pages()->saveMany($pages); diff --git a/tests/Api/ApiConfigTest.php b/tests/Api/ApiConfigTest.php index 7a5b701ee9c..af808a76ca3 100644 --- a/tests/Api/ApiConfigTest.php +++ b/tests/Api/ApiConfigTest.php @@ -27,7 +27,7 @@ public function test_default_item_count_does_not_limit_count_param() { $this->actingAsApiEditor(); config()->set(['api.default_item_count' => 1]); - $resp = $this->get($this->endpoint.'?count=5'); + $resp = $this->get($this->endpoint . '?count=5'); $resp->assertJsonCount(5, 'data'); } @@ -39,7 +39,7 @@ public function test_max_item_count_limits_listing_requests() $resp = $this->get($this->endpoint); $resp->assertJsonCount(2, 'data'); - $resp = $this->get($this->endpoint.'?count=5'); + $resp = $this->get($this->endpoint . '?count=5'); $resp->assertJsonCount(2, 'data'); } diff --git a/tests/Api/ApiDocsTest.php b/tests/Api/ApiDocsTest.php index 1aabaccfc30..062adce5376 100644 --- a/tests/Api/ApiDocsTest.php +++ b/tests/Api/ApiDocsTest.php @@ -21,7 +21,7 @@ public function test_docs_page_returns_view_with_docs_content() public function test_docs_json_endpoint_returns_json() { - $resp = $this->actingAsApiEditor()->get($this->endpoint.'.json'); + $resp = $this->actingAsApiEditor()->get($this->endpoint . '.json'); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'application/json'); $resp->assertJson([ diff --git a/tests/Api/ApiListingTest.php b/tests/Api/ApiListingTest.php index 45d06b5dca2..f90ec5a3dd2 100644 --- a/tests/Api/ApiListingTest.php +++ b/tests/Api/ApiListingTest.php @@ -19,7 +19,7 @@ public function test_count_parameter_limits_responses() $resp = $this->get($this->endpoint); $resp->assertJsonCount($bookCount, 'data'); - $resp = $this->get($this->endpoint.'?count=1'); + $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJsonCount(1, 'data'); } @@ -28,10 +28,10 @@ public function test_offset_parameter() $this->actingAsApiEditor(); $books = Book::visible()->orderBy('id')->take(3)->get(); - $resp = $this->get($this->endpoint.'?count=1'); + $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJsonMissing(['name' => $books[1]->name]); - $resp = $this->get($this->endpoint.'?count=1&offset=1000'); + $resp = $this->get($this->endpoint . '?count=1&offset=1000'); $resp->assertJsonCount(0, 'data'); } @@ -47,7 +47,7 @@ public function test_sort_parameter() ]; foreach ($sortChecks as $sortOption => $result) { - $resp = $this->get($this->endpoint.'?count=1&sort='.$sortOption); + $resp = $this->get($this->endpoint . '?count=1&sort=' . $sortOption); $resp->assertJson(['data' => [ [ 'id' => $result->id, @@ -71,14 +71,14 @@ public function test_filter_parameter() "filter[id:gt]={$book->id}" => Book::visible()->where('id', '>', $book->id)->count(), "filter[id:gte]={$book->id}" => Book::visible()->where('id', '>=', $book->id)->count(), "filter[id:lt]={$book->id}" => Book::visible()->where('id', '<', $book->id)->count(), - "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr.'%')->count(), + "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr . '%')->count(), // Test mulitple filters 'and' together "filter[id]={$book->id}&filter[name]=random_non_existing_string" => 0, ]; foreach ($filterChecks as $filterOption => $resultCount) { - $resp = $this->get($this->endpoint.'?count=1&'.$filterOption); + $resp = $this->get($this->endpoint . '?count=1&' . $filterOption); $resp->assertJson(['total' => $resultCount]); } } @@ -87,7 +87,7 @@ public function test_total_on_results_shows_correctly() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); - $resp = $this->get($this->endpoint.'?count=1'); + $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJson(['total' => $bookCount]); } @@ -95,7 +95,7 @@ public function test_total_on_results_shows_correctly_when_offset_provided() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); - $resp = $this->get($this->endpoint.'?count=1&offset=1'); + $resp = $this->get($this->endpoint . '?count=1&offset=1'); $resp->assertJson(['total' => $bookCount]); } } diff --git a/tests/Api/AttachmentsApiTest.php b/tests/Api/AttachmentsApiTest.php index a9ff9d80389..ceab5d49afa 100644 --- a/tests/Api/AttachmentsApiTest.php +++ b/tests/Api/AttachmentsApiTest.php @@ -22,7 +22,7 @@ public function test_index_endpoint_returns_expected_book() 'external' => true, ]); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, @@ -43,7 +43,7 @@ public function test_attachments_listing_based_upon_page_visibility() 'external' => true, ]); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, @@ -54,7 +54,7 @@ public function test_attachments_listing_based_upon_page_visibility() $page->save(); $this->regenEntityPermissions($page); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJsonMissing(['data' => [ [ 'id' => $attachment->id, diff --git a/tests/Api/BooksApiTest.php b/tests/Api/BooksApiTest.php index df59546fe48..91e2db9e52d 100644 --- a/tests/Api/BooksApiTest.php +++ b/tests/Api/BooksApiTest.php @@ -16,7 +16,7 @@ public function test_index_endpoint_returns_expected_book() $this->actingAsApiEditor(); $firstBook = Book::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBook->id, @@ -66,7 +66,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->getJson($this->baseEndpoint."/{$book->id}"); + $resp = $this->getJson($this->baseEndpoint . "/{$book->id}"); $resp->assertStatus(200); $resp->assertJson([ @@ -93,7 +93,7 @@ public function test_update_endpoint() 'description' => 'A book created via the API', ]; - $resp = $this->putJson($this->baseEndpoint."/{$book->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$book->id}", $details); $book->refresh(); $resp->assertStatus(200); @@ -105,7 +105,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint."/{$book->id}"); + $resp = $this->deleteJson($this->baseEndpoint . "/{$book->id}"); $resp->assertStatus(204); $this->assertActivityExists('book_delete'); @@ -116,10 +116,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$book->id}/export/html"); + $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($book->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); } public function test_export_plain_text_endpoint() @@ -127,10 +127,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$book->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($book->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); } public function test_export_pdf_endpoint() @@ -138,9 +138,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$book->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); } public function test_export_markdown_endpoint() @@ -148,12 +148,12 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $book = Book::visible()->has('pages')->has('chapters')->first(); - $resp = $this->get($this->baseEndpoint."/{$book->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.md"'); - $resp->assertSee('# '.$book->name); - $resp->assertSee('# '.$book->pages()->first()->name); - $resp->assertSee('# '.$book->chapters()->first()->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.md"'); + $resp->assertSee('# ' . $book->name); + $resp->assertSee('# ' . $book->pages()->first()->name); + $resp->assertSee('# ' . $book->chapters()->first()->name); } public function test_cant_export_when_not_have_permission() @@ -164,7 +164,7 @@ public function test_cant_export_when_not_have_permission() $book = Book::visible()->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint."/{$book->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint . "/{$book->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/ChaptersApiTest.php b/tests/Api/ChaptersApiTest.php index 8660ca518ba..c9ed1a2892e 100644 --- a/tests/Api/ChaptersApiTest.php +++ b/tests/Api/ChaptersApiTest.php @@ -17,7 +17,7 @@ public function test_index_endpoint_returns_expected_chapter() $this->actingAsApiEditor(); $firstChapter = Chapter::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstChapter->id, @@ -96,7 +96,7 @@ public function test_read_endpoint() $chapter = Chapter::visible()->first(); $page = $chapter->pages()->first(); - $resp = $this->getJson($this->baseEndpoint."/{$chapter->id}"); + $resp = $this->getJson($this->baseEndpoint . "/{$chapter->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $chapter->id, @@ -137,7 +137,7 @@ public function test_update_endpoint() ], ]; - $resp = $this->putJson($this->baseEndpoint."/{$chapter->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", $details); $chapter->refresh(); $resp->assertStatus(200); @@ -151,7 +151,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint."/{$chapter->id}"); + $resp = $this->deleteJson($this->baseEndpoint . "/{$chapter->id}"); $resp->assertStatus(204); $this->assertActivityExists('chapter_delete'); @@ -162,10 +162,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/html"); + $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($chapter->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); } public function test_export_plain_text_endpoint() @@ -173,10 +173,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($chapter->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); } public function test_export_pdf_endpoint() @@ -184,9 +184,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); } public function test_export_markdown_endpoint() @@ -194,11 +194,11 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $chapter = Chapter::visible()->has('pages')->first(); - $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.md"'); - $resp->assertSee('# '.$chapter->name); - $resp->assertSee('# '.$chapter->pages()->first()->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.md"'); + $resp->assertSee('# ' . $chapter->name); + $resp->assertSee('# ' . $chapter->pages()->first()->name); } public function test_cant_export_when_not_have_permission() @@ -209,7 +209,7 @@ public function test_cant_export_when_not_have_permission() $chapter = Chapter::visible()->has('pages')->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint."/{$chapter->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint . "/{$chapter->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/PagesApiTest.php b/tests/Api/PagesApiTest.php index 1f4bd11823b..4eb109d9dec 100644 --- a/tests/Api/PagesApiTest.php +++ b/tests/Api/PagesApiTest.php @@ -18,7 +18,7 @@ public function test_index_endpoint_returns_expected_page() $this->actingAsApiEditor(); $firstPage = Page::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstPage->id, @@ -126,7 +126,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->getJson($this->baseEndpoint."/{$page->id}"); + $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $page->id, @@ -151,7 +151,7 @@ public function test_read_endpoint_provides_rendered_html() $page->html = "

      testing

      Hello

      "; $page->save(); - $resp = $this->getJson($this->baseEndpoint."/{$page->id}"); + $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); $html = $resp->json('html'); $this->assertStringNotContainsString('script', $html); $this->assertStringContainsString('Hello', $html); @@ -173,7 +173,7 @@ public function test_update_endpoint() ], ]; - $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $page->refresh(); $resp->assertStatus(200); @@ -195,7 +195,7 @@ public function test_providing_new_chapter_id_on_update_will_move_page() 'html' => '

      A page created via the API

      ', ]; - $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $resp->assertStatus(200); $resp->assertJson([ 'chapter_id' => $chapter->id, @@ -215,7 +215,7 @@ public function test_providing_move_via_update_requires_page_create_permission_o 'html' => '

      A page created via the API

      ', ]; - $resp = $this->putJson($this->baseEndpoint."/{$page->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $resp->assertStatus(403); } @@ -234,7 +234,7 @@ public function test_update_endpoint_does_not_wipe_content_if_no_html_or_md_prov ], ]; - $this->putJson($this->baseEndpoint."/{$page->id}", $details); + $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $page->refresh(); $this->assertEquals($originalContent, $page->html); @@ -244,7 +244,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint."/{$page->id}"); + $resp = $this->deleteJson($this->baseEndpoint . "/{$page->id}"); $resp->assertStatus(204); $this->assertActivityExists('page_delete', $page); @@ -255,10 +255,10 @@ public function test_export_html_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$page->id}/export/html"); + $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); } public function test_export_plain_text_endpoint() @@ -266,10 +266,10 @@ public function test_export_plain_text_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$page->id}/export/plaintext"); + $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); } public function test_export_pdf_endpoint() @@ -277,9 +277,9 @@ public function test_export_pdf_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$page->id}/export/pdf"); + $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/pdf"); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); } public function test_export_markdown_endpoint() @@ -287,10 +287,10 @@ public function test_export_markdown_endpoint() $this->actingAsApiEditor(); $page = Page::visible()->first(); - $resp = $this->get($this->baseEndpoint."/{$page->id}/export/markdown"); + $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/markdown"); $resp->assertStatus(200); - $resp->assertSee('# '.$page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.md"'); + $resp->assertSee('# ' . $page->name); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); } public function test_cant_export_when_not_have_permission() @@ -301,7 +301,7 @@ public function test_cant_export_when_not_have_permission() $page = Page::visible()->first(); foreach ($types as $type) { - $resp = $this->get($this->baseEndpoint."/{$page->id}/export/{$type}"); + $resp = $this->get($this->baseEndpoint . "/{$page->id}/export/{$type}"); $this->assertPermissionError($resp); } } diff --git a/tests/Api/ShelvesApiTest.php b/tests/Api/ShelvesApiTest.php index 2a709af12fc..8868c686e50 100644 --- a/tests/Api/ShelvesApiTest.php +++ b/tests/Api/ShelvesApiTest.php @@ -17,7 +17,7 @@ public function test_index_endpoint_returns_expected_shelf() $this->actingAsApiEditor(); $firstBookshelf = Bookshelf::query()->orderBy('id', 'asc')->first(); - $resp = $this->getJson($this->baseEndpoint.'?count=1&sort=+id'); + $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBookshelf->id, @@ -76,7 +76,7 @@ public function test_read_endpoint() $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); - $resp = $this->getJson($this->baseEndpoint."/{$shelf->id}"); + $resp = $this->getJson($this->baseEndpoint . "/{$shelf->id}"); $resp->assertStatus(200); $resp->assertJson([ @@ -103,7 +103,7 @@ public function test_update_endpoint() 'description' => 'A shelf created via the API', ]; - $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $shelf->refresh(); $resp->assertStatus(200); @@ -120,11 +120,11 @@ public function test_update_only_assigns_books_if_param_provided() 'name' => 'My updated API shelf', ]; - $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", $details); + $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() > 0); - $resp = $this->putJson($this->baseEndpoint."/{$shelf->id}", ['books' => []]); + $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", ['books' => []]); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() === 0); } @@ -133,7 +133,7 @@ public function test_delete_endpoint() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); - $resp = $this->deleteJson($this->baseEndpoint."/{$shelf->id}"); + $resp = $this->deleteJson($this->baseEndpoint . "/{$shelf->id}"); $resp->assertStatus(204); $this->assertActivityExists('bookshelf_delete'); diff --git a/tests/AuditLogTest.php b/tests/AuditLogTest.php index 70c5979f27b..f909cd79a29 100644 --- a/tests/AuditLogTest.php +++ b/tests/AuditLogTest.php @@ -68,7 +68,7 @@ public function test_shows_name_for_deleted_items() $resp = $this->get('settings/audit'); $resp->assertSeeText('Deleted Item'); - $resp->assertSeeText('Name: '.$pageName); + $resp->assertSeeText('Name: ' . $pageName); } public function test_shows_activity_for_deleted_users() @@ -107,16 +107,16 @@ public function test_date_filters() $yesterday = (Carbon::now()->subDay()->format('Y-m-d')); $tomorrow = (Carbon::now()->addDay()->format('Y-m-d')); - $resp = $this->get('settings/audit?date_from='.$yesterday); + $resp = $this->get('settings/audit?date_from=' . $yesterday); $resp->assertSeeText($page->name); - $resp = $this->get('settings/audit?date_from='.$tomorrow); + $resp = $this->get('settings/audit?date_from=' . $tomorrow); $resp->assertDontSeeText($page->name); - $resp = $this->get('settings/audit?date_to='.$tomorrow); + $resp = $this->get('settings/audit?date_to=' . $tomorrow); $resp->assertSeeText($page->name); - $resp = $this->get('settings/audit?date_to='.$yesterday); + $resp = $this->get('settings/audit?date_to=' . $yesterday); $resp->assertDontSeeText($page->name); } @@ -132,11 +132,11 @@ public function test_user_filter() $chapter = Chapter::query()->first(); $this->activityService->addForEntity($chapter, ActivityType::CHAPTER_UPDATE); - $resp = $this->actingAs($admin)->get('settings/audit?user='.$admin->id); + $resp = $this->actingAs($admin)->get('settings/audit?user=' . $admin->id); $resp->assertSeeText($page->name); $resp->assertDontSeeText($chapter->name); - $resp = $this->actingAs($admin)->get('settings/audit?user='.$editor->id); + $resp = $this->actingAs($admin)->get('settings/audit?user=' . $editor->id); $resp->assertSeeText($chapter->name); $resp->assertDontSeeText($page->name); } diff --git a/tests/Auth/AuthTest.php b/tests/Auth/AuthTest.php index 9faccf6d2e0..66ab09d3c62 100644 --- a/tests/Auth/AuthTest.php +++ b/tests/Auth/AuthTest.php @@ -37,7 +37,7 @@ public function test_registration_showing() // Ensure registration form is showing $this->setSettings(['registration-enabled' => 'true']); $this->get('/login') - ->assertElementContains('a[href="'.url('/register').'"]', 'Sign up'); + ->assertElementContains('a[href="' . url('/register') . '"]', 'Sign up'); } public function test_normal_registration() @@ -49,7 +49,7 @@ public function test_normal_registration() // Test form and ensure user is created $this->get('/register') ->assertSee('Sign Up') - ->assertElementContains('form[action="'.url('/register').'"]', 'Create Account'); + ->assertElementContains('form[action="' . url('/register') . '"]', 'Create Account'); $resp = $this->post('/register', $user->only('password', 'name', 'email')); $resp->assertRedirect('/'); @@ -119,7 +119,7 @@ public function test_confirmed_registration() $resp->assertRedirect('/register/confirm/awaiting'); $resp = $this->get('/register/confirm/awaiting'); - $resp->assertElementContains('form[action="'.url('/register/confirm/resend').'"]', 'Resend'); + $resp->assertElementContains('form[action="' . url('/register/confirm/resend') . '"]', 'Resend'); $this->get('/books')->assertRedirect('/login'); $this->post('/register/confirm/resend', $user->only('email')); @@ -131,7 +131,7 @@ public function test_confirmed_registration() }); // Check confirmation email confirmation activation. - $this->get('/register/confirm/'.$emailConfirmation->token)->assertRedirect('/'); + $this->get('/register/confirm/' . $emailConfirmation->token)->assertRedirect('/'); $this->get('/')->assertSee($user->name); $this->assertDatabaseMissing('email_confirmations', ['token' => $emailConfirmation->token]); $this->assertDatabaseHas('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]); @@ -213,10 +213,10 @@ public function test_reset_password_flow() Notification::fake(); $this->get('/login') - ->assertElementContains('a[href="'.url('/password/email').'"]', 'Forgot Password?'); + ->assertElementContains('a[href="' . url('/password/email') . '"]', 'Forgot Password?'); $this->get('/password/email') - ->assertElementContains('form[action="'.url('/password/email').'"]', 'Send Reset Link'); + ->assertElementContains('form[action="' . url('/password/email') . '"]', 'Send Reset Link'); $resp = $this->post('/password/email', [ 'email' => 'admin@admin.com', @@ -236,7 +236,7 @@ public function test_reset_password_flow() Notification::assertSentTo($user, ResetPassword::class); $n = Notification::sent($user, ResetPassword::class); - $this->get('/password/reset/'.$n->first()->token) + $this->get('/password/reset/' . $n->first()->token) ->assertOk() ->assertSee('Reset Password'); @@ -295,7 +295,7 @@ public function test_reset_password_request_is_throttled() 'email' => $editor->email, ]); Notification::assertTimesSent(1, ResetPassword::class); - $resp->assertSee('A password reset link will be sent to '.$editor->email.' if that email address is found in the system.'); + $resp->assertSee('A password reset link will be sent to ' . $editor->email . ' if that email address is found in the system.'); } public function test_login_redirects_to_initially_requested_url_correctly() diff --git a/tests/Auth/LdapTest.php b/tests/Auth/LdapTest.php index ae4cbb3ee05..d00e8cf15df 100644 --- a/tests/Auth/LdapTest.php +++ b/tests/Auth/LdapTest.php @@ -23,7 +23,7 @@ class LdapTest extends TestCase protected function setUp(): void { parent::setUp(); - if (! defined('LDAP_OPT_REFERRALS')) { + if (!defined('LDAP_OPT_REFERRALS')) { define('LDAP_OPT_REFERRALS', 1); } config()->set([ @@ -96,7 +96,7 @@ public function test_login() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $resp = $this->mockUserLogin(); @@ -127,7 +127,7 @@ public function test_email_domain_restriction_active_on_new_ldap_login() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $resp = $this->mockUserLogin(); @@ -144,7 +144,7 @@ public function test_email_domain_restriction_active_on_new_ldap_login() public function test_login_works_when_no_uid_provided_by_ldap_server() { - $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->commonLdapMocks(1, 1, 1, 2, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) @@ -166,7 +166,7 @@ public function test_a_custom_uid_attribute_can_be_specified_and_is_used_properl config()->set(['services.ldap.id_attribute' => 'my_custom_id']); $this->commonLdapMocks(1, 1, 1, 2, 1); - $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ @@ -190,7 +190,7 @@ public function test_initial_incorrect_credentials() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $this->mockLdap->shouldReceive('bind')->times(2)->andReturn(true, false); @@ -258,7 +258,7 @@ public function test_non_admins_cannot_change_auth_id() { $testUser = $this->getNormalUser(); $this->actingAs($testUser) - ->get('/settings/users/'.$testUser->id) + ->get('/settings/users/' . $testUser->id) ->assertDontSee('External Authentication'); } @@ -282,7 +282,7 @@ public function test_login_maps_roles_and_retains_existing_roles() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, @@ -327,7 +327,7 @@ public function test_login_maps_roles_and_removes_old_roles_if_set() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, @@ -351,7 +351,7 @@ public function test_login_maps_roles_and_removes_old_roles_if_set() public function test_external_auth_id_visible_in_roles_page_when_ldap_active() { $role = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']); - $this->asAdmin()->get('/settings/roles/'.$role->id) + $this->asAdmin()->get('/settings/roles/' . $role->id) ->assertSee('ex-auth-a'); } @@ -372,7 +372,7 @@ public function test_login_maps_roles_using_external_auth_ids_if_set() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, @@ -413,7 +413,7 @@ public function test_login_group_mapping_does_not_conflict_with_default_role() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, @@ -447,7 +447,7 @@ public function test_login_uses_specified_display_name_attribute() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'displayname' => 'displayNameAttribute', ]]); @@ -472,7 +472,7 @@ public function test_login_uses_default_display_name_attribute_if_specified_not_ ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $this->mockUserLogin()->assertRedirect('/login'); @@ -500,7 +500,7 @@ protected function checkLdapReceivesCorrectDetails($serverString, $expectedHost, $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $this->mockLdap->shouldReceive('connect')->once() @@ -567,7 +567,7 @@ public function test_dump_user_details_option_works() ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $resp = $this->post('/login', [ @@ -606,7 +606,7 @@ public function test_ldap_attributes_can_be_binary_decoded_if_marked() ->andReturn(['count' => 1, 0 => [ 'uid' => [hex2bin('FFF8F7')], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], ]]); $details = $ldapService->getUserDetails('test'); @@ -621,12 +621,12 @@ public function test_new_ldap_user_login_with_already_used_email_address_shows_e ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => 'tester@example.com', ]], ['count' => 1, 0 => [ 'uid' => ['Barry'], 'cn' => ['Scott'], - 'dn' => ['dc=bscott'.config('services.ldap.base_dn')], + 'dn' => ['dc=bscott' . config('services.ldap.base_dn')], 'mail' => 'tester@example.com', ]]); @@ -657,7 +657,7 @@ public function test_login_with_email_confirmation_required_maps_groups_but_show ->andReturn(['count' => 1, 0 => [ 'uid' => [$user->name], 'cn' => [$user->name], - 'dn' => ['dc=test'.config('services.ldap.base_dn')], + 'dn' => ['dc=test' . config('services.ldap.base_dn')], 'mail' => [$user->email], 'memberof' => [ 'count' => 1, @@ -700,7 +700,7 @@ public function test_thumbnail_attribute_used_as_user_avatar_if_configured() config()->set(['services.ldap.thumbnail_attribute' => 'jpegPhoto']); $this->commonLdapMocks(1, 1, 1, 2, 1); - $ldapDn = 'cn=test-user,dc=test'.config('services.ldap.base_dn'); + $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ diff --git a/tests/Auth/OidcTest.php b/tests/Auth/OidcTest.php index ba555915a9a..e7665a679a4 100644 --- a/tests/Auth/OidcTest.php +++ b/tests/Auth/OidcTest.php @@ -22,7 +22,7 @@ protected function setUp(): void // Set default config for OpenID Connect $this->keyFile = tmpfile(); - $this->keyFilePath = 'file://'.stream_get_meta_data($this->keyFile)['uri']; + $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri']; file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey()); config()->set([ @@ -61,7 +61,7 @@ public function test_oidc_routes_are_only_active_if_oidc_enabled() config()->set(['auth.method' => 'standard']); $routes = ['/login' => 'post', '/callback' => 'get']; foreach ($routes as $uri => $method) { - $req = $this->call($method, '/oidc'.$uri); + $req = $this->call($method, '/oidc' . $uri); $this->assertPermissionError($req); } } @@ -120,8 +120,8 @@ public function test_login() $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location'); $this->assertFalse($this->isAuthenticated()); $this->assertStringContainsString('scope=openid%20profile%20email', $redirect); - $this->assertStringContainsString('client_id='.OidcJwtHelper::defaultClientId(), $redirect); - $this->assertStringContainsString('redirect_uri='.urlencode(url('/oidc/callback')), $redirect); + $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect); + $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect); } public function test_login_success_flow() @@ -137,17 +137,17 @@ public function test_login_success_flow() // Callback from auth provider // App calls token endpoint to get id token - $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state='.$state); + $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); $resp->assertRedirect('/'); $this->assertCount(1, $transactions); /** @var Request $tokenRequest */ $tokenRequest = $transactions[0]['request']; $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri()); $this->assertEquals('POST', $tokenRequest->getMethod()); - $this->assertEquals('Basic '.base64_encode(OidcJwtHelper::defaultClientId().':testpass'), $tokenRequest->getHeader('Authorization')[0]); + $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]); $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody()); $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody()); - $this->assertStringContainsString('redirect_uri='.urlencode(url('/oidc/callback')), $tokenRequest->getBody()); + $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody()); $this->assertTrue(auth()->check()); $this->assertDatabaseHas('users', [ @@ -241,7 +241,7 @@ public function test_auth_login_as_existing_user_email_with_different_auth_id_fa 'sub' => 'benny505', ]); - $this->assertSessionError('A user with the email '.$editor->email.' already exists but with different credentials.'); + $this->assertSessionError('A user with the email ' . $editor->email . ' already exists but with different credentials.'); $this->assertFalse(auth()->check()); } @@ -276,8 +276,8 @@ public function test_auth_login_with_autodiscovery() $this->assertEquals('GET', $keysRequest->getMethod()); $this->assertEquals('GET', $discoverRequest->getMethod()); - $this->assertEquals(OidcJwtHelper::defaultIssuer().'/.well-known/openid-configuration', $discoverRequest->getUri()); - $this->assertEquals(OidcJwtHelper::defaultIssuer().'/oidc/keys', $keysRequest->getUri()); + $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri()); + $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri()); } public function test_auth_fails_if_autodiscovery_fails() @@ -335,7 +335,7 @@ protected function runLogin($claimOverrides = []): TestResponse $state = session()->get('oidc_state'); $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]); - return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state='.$state); + return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); } protected function getAutoDiscoveryResponse($responseOverrides = []): Response @@ -345,9 +345,9 @@ protected function getAutoDiscoveryResponse($responseOverrides = []): Response 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache', ], json_encode(array_merge([ - 'token_endpoint' => OidcJwtHelper::defaultIssuer().'/oidc/token', - 'authorization_endpoint' => OidcJwtHelper::defaultIssuer().'/oidc/authorize', - 'jwks_uri' => OidcJwtHelper::defaultIssuer().'/oidc/keys', + 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token', + 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize', + 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys', 'issuer' => OidcJwtHelper::defaultIssuer(), ], $responseOverrides))); } diff --git a/tests/Auth/Saml2Test.php b/tests/Auth/Saml2Test.php index b5b72c5c75a..aac2710a889 100644 --- a/tests/Auth/Saml2Test.php +++ b/tests/Auth/Saml2Test.php @@ -74,11 +74,11 @@ public function test_login() $this->assertTrue(strlen($acsId) > 12); $this->assertStringContainsString('/saml2/acs?id=', $redirect); - $this->assertTrue(cache()->has('saml2_acs:'.$acsId)); + $this->assertTrue(cache()->has('saml2_acs:' . $acsId)); $acsGet = $this->get($redirect); $acsGet->assertRedirect('/'); - $this->assertFalse(cache()->has('saml2_acs:'.$acsId)); + $this->assertFalse(cache()->has('saml2_acs:' . $acsId)); $this->assertTrue($this->isAuthenticated()); $this->assertDatabaseHas('users', [ @@ -218,13 +218,13 @@ public function test_saml_routes_are_only_active_if_saml_enabled() config()->set(['auth.method' => 'standard']); $getRoutes = ['/logout', '/metadata', '/sls']; foreach ($getRoutes as $route) { - $req = $this->get('/saml2'.$route); + $req = $this->get('/saml2' . $route); $this->assertPermissionError($req); } $postRoutes = ['/login', '/acs']; foreach ($postRoutes as $route) { - $req = $this->post('/saml2'.$route); + $req = $this->post('/saml2' . $route); $this->assertPermissionError($req); } } diff --git a/tests/Auth/SocialAuthTest.php b/tests/Auth/SocialAuthTest.php index 2fb2e692c31..90d7e37aa5e 100644 --- a/tests/Auth/SocialAuthTest.php +++ b/tests/Auth/SocialAuthTest.php @@ -83,7 +83,7 @@ public function test_social_login() ]); $resp = $this->followingRedirects()->get('/login/service/github/callback'); $resp->assertDontSee('login-form'); - $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, 'github; ('.$this->getAdmin()->id.') '.$this->getAdmin()->name); + $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, 'github; (' . $this->getAdmin()->id . ') ' . $this->getAdmin()->name); } public function test_social_account_detach() diff --git a/tests/Auth/UserInviteTest.php b/tests/Auth/UserInviteTest.php index 39c9f415bee..dcf9e23df9b 100644 --- a/tests/Auth/UserInviteTest.php +++ b/tests/Auth/UserInviteTest.php @@ -18,7 +18,7 @@ public function test_user_creation_creates_invite() Notification::fake(); $admin = $this->getAdmin(); - $email = Str::random(16).'@example.com'; + $email = Str::random(16) . '@example.com'; $resp = $this->actingAs($admin)->post('/settings/users/create', [ 'name' => 'Barry', 'email' => $email, @@ -43,13 +43,13 @@ public function test_invite_set_password() $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; - $setPasswordPageResp = $this->get('/register/invite/'.$token); + $setPasswordPageResp = $this->get('/register/invite/' . $token); $setPasswordPageResp->assertSuccessful(); $setPasswordPageResp->assertSee('Welcome to BookStack!'); $setPasswordPageResp->assertSee('Password'); $setPasswordPageResp->assertSee('Confirm Password'); - $setPasswordResp = $this->followingRedirects()->post('/register/invite/'.$token, [ + $setPasswordResp = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => 'my test password', ]); $setPasswordResp->assertSee('Password set, you now have access to BookStack!'); @@ -72,14 +72,14 @@ public function test_invite_set_has_password_validation() $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; - $this->get('/register/invite/'.$token); - $shortPassword = $this->followingRedirects()->post('/register/invite/'.$token, [ + $this->get('/register/invite/' . $token); + $shortPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => 'mypassw', ]); $shortPassword->assertSee('The password must be at least 8 characters.'); - $this->get('/register/invite/'.$token); - $noPassword = $this->followingRedirects()->post('/register/invite/'.$token, [ + $this->get('/register/invite/' . $token); + $noPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => '', ]); $noPassword->assertSee('The password field is required.'); @@ -91,10 +91,10 @@ public function test_invite_set_has_password_validation() public function test_non_existent_invite_token_redirects_to_home() { - $setPasswordPageResp = $this->get('/register/invite/'.Str::random(12)); + $setPasswordPageResp = $this->get('/register/invite/' . Str::random(12)); $setPasswordPageResp->assertRedirect('/'); - $setPasswordResp = $this->post('/register/invite/'.Str::random(12), ['password' => 'Password Test']); + $setPasswordResp = $this->post('/register/invite/' . Str::random(12), ['password' => 'Password Test']); $setPasswordResp->assertRedirect('/'); } @@ -108,7 +108,7 @@ public function test_token_expires_after_two_weeks() $tokenEntry = DB::table('user_invites')->where('user_id', '=', $user->id)->first(); DB::table('user_invites')->update(['created_at' => Carbon::now()->subDays(14)->subHour(1)]); - $setPasswordPageResp = $this->get('/register/invite/'.$tokenEntry->token); + $setPasswordPageResp = $this->get('/register/invite/' . $tokenEntry->token); $setPasswordPageResp->assertRedirect('/password/email'); $setPasswordPageResp->assertSessionHas('error', 'This invitation link has expired. You can instead try to reset your account password.'); } diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index f27337b0a98..b1cefbb6584 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -13,7 +13,7 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__.'/../bootstrap/app.php'; + $app = require __DIR__ . '/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; diff --git a/tests/DebugViewTest.php b/tests/DebugViewTest.php index e780c4cb6e8..63d6472b982 100644 --- a/tests/DebugViewTest.php +++ b/tests/DebugViewTest.php @@ -21,12 +21,12 @@ public function test_debug_view_shows_expected_details() // Warning message $resp->assertSeeText('WARNING: Application is in debug mode. This mode has the potential to leak'); // PHP version - $resp->assertSeeText('PHP Version: '.phpversion()); + $resp->assertSeeText('PHP Version: ' . phpversion()); // BookStack version - $resp->assertSeeText('BookStack Version: '.trim(file_get_contents(base_path('version')))); + $resp->assertSeeText('BookStack Version: ' . trim(file_get_contents(base_path('version')))); // Dynamic help links - $resp->assertElementExists('a[href*="q='.urlencode('BookStack An error occurred during testing').'"]'); - $resp->assertElementExists('a[href*="?q=is%3Aissue+'.urlencode('An error occurred during testing').'"]'); + $resp->assertElementExists('a[href*="q=' . urlencode('BookStack An error occurred during testing') . '"]'); + $resp->assertElementExists('a[href*="?q=is%3Aissue+' . urlencode('An error occurred during testing') . '"]'); } public function test_debug_view_only_shows_when_debug_mode_is_enabled() diff --git a/tests/Entity/BookShelfTest.php b/tests/Entity/BookShelfTest.php index aad78f99477..fcbc17ea94b 100644 --- a/tests/Entity/BookShelfTest.php +++ b/tests/Entity/BookShelfTest.php @@ -80,8 +80,8 @@ public function test_shelves_create() { $booksToInclude = Book::take(2)->get(); $shelfInfo = [ - 'name' => 'My test book'.Str::random(4), - 'description' => 'Test book description '.Str::random(10), + 'name' => 'My test book' . Str::random(4), + 'description' => 'Test book description ' . Str::random(10), ]; $resp = $this->asEditor()->post('/shelves', array_merge($shelfInfo, [ 'books' => $booksToInclude->implode('id', ','), @@ -110,8 +110,8 @@ public function test_shelves_create() public function test_shelves_create_sets_cover_image() { $shelfInfo = [ - 'name' => 'My test book'.Str::random(4), - 'description' => 'Test book description '.Str::random(10), + 'name' => 'My test book' . Str::random(4), + 'description' => 'Test book description ' . Str::random(10), ]; $imageFile = $this->getTestImage('shelf-test.png'); @@ -206,8 +206,8 @@ public function test_shelf_edit() $booksToInclude = Book::take(2)->get(); $shelfInfo = [ - 'name' => 'My test book'.Str::random(4), - 'description' => 'Test book description '.Str::random(10), + 'name' => 'My test book' . Str::random(4), + 'description' => 'Test book description ' . Str::random(10), ]; $resp = $this->asEditor()->put($shelf->getUrl(), array_merge($shelfInfo, [ @@ -345,8 +345,8 @@ public function test_bookshelves_show_on_book() { // Create shelf $shelfInfo = [ - 'name' => 'My test shelf'.Str::random(4), - 'description' => 'Test shelf description '.Str::random(10), + 'name' => 'My test shelf' . Str::random(4), + 'description' => 'Test shelf description ' . Str::random(10), ]; $this->asEditor()->post('/shelves', $shelfInfo); @@ -375,6 +375,6 @@ public function test_cancel_on_child_book_creation_returns_to_original_shelf() /** @var Bookshelf $shelf */ $shelf = Bookshelf::query()->first(); $resp = $this->asEditor()->get($shelf->getUrl('/create-book')); - $resp->assertElementContains('form a[href="'.$shelf->getUrl().'"]', 'Cancel'); + $resp->assertElementContains('form a[href="' . $shelf->getUrl() . '"]', 'Cancel'); } } diff --git a/tests/Entity/BookTest.php b/tests/Entity/BookTest.php index a34e67d82de..2894fbb98f8 100644 --- a/tests/Entity/BookTest.php +++ b/tests/Entity/BookTest.php @@ -14,10 +14,10 @@ public function test_create() ]); $resp = $this->asEditor()->get('/books'); - $resp->assertElementContains('a[href="'.url('/create-book').'"]', 'Create New Book'); + $resp->assertElementContains('a[href="' . url('/create-book') . '"]', 'Create New Book'); $resp = $this->get('/create-book'); - $resp->assertElementContains('form[action="'.url('/books').'"][method="POST"]', 'Save Book'); + $resp->assertElementContains('form[action="' . url('/books') . '"][method="POST"]', 'Save Book'); $resp = $this->post('/books', $book->only('name', 'description')); $resp->assertRedirect('/books/my-first-book'); @@ -50,21 +50,21 @@ public function test_update() /** @var Book $book */ $book = Book::query()->first(); // Cheeky initial update to refresh slug - $this->asEditor()->put($book->getUrl(), ['name' => $book->name.'5', 'description' => $book->description]); + $this->asEditor()->put($book->getUrl(), ['name' => $book->name . '5', 'description' => $book->description]); $book->refresh(); - $newName = $book->name.' Updated'; - $newDesc = $book->description.' with more content'; + $newName = $book->name . ' Updated'; + $newDesc = $book->description . ' with more content'; $resp = $this->get($book->getUrl('/edit')); $resp->assertSee($book->name); $resp->assertSee($book->description); - $resp->assertElementContains('form[action="'.$book->getUrl().'"]', 'Save Book'); + $resp->assertElementContains('form[action="' . $book->getUrl() . '"]', 'Save Book'); $resp = $this->put($book->getUrl(), ['name' => $newName, 'description' => $newDesc]); - $resp->assertRedirect($book->getUrl().'-updated'); + $resp->assertRedirect($book->getUrl() . '-updated'); - $resp = $this->get($book->getUrl().'-updated'); + $resp = $this->get($book->getUrl() . '-updated'); $resp->assertSee($newName); $resp->assertSee($newDesc); } @@ -99,7 +99,7 @@ public function test_delete() public function test_cancel_on_create_page_leads_back_to_books_listing() { $resp = $this->asEditor()->get('/create-book'); - $resp->assertElementContains('form a[href="'.url('/books').'"]', 'Cancel'); + $resp->assertElementContains('form a[href="' . url('/books') . '"]', 'Cancel'); } public function test_cancel_on_edit_book_page_leads_back_to_book() @@ -107,7 +107,7 @@ public function test_cancel_on_edit_book_page_leads_back_to_book() /** @var Book $book */ $book = Book::query()->first(); $resp = $this->asEditor()->get($book->getUrl('/edit')); - $resp->assertElementContains('form a[href="'.$book->getUrl().'"]', 'Cancel'); + $resp->assertElementContains('form a[href="' . $book->getUrl() . '"]', 'Cancel'); } public function test_next_previous_navigation_controls_show_within_book_content() @@ -165,7 +165,7 @@ public function test_books_view_shows_view_toggle_option() setting()->putUser($editor, 'books_view_type', 'list'); $resp = $this->actingAs($editor)->get('/books'); - $resp->assertElementContains('form[action$="/settings/users/'.$editor->id.'/switch-books-view"]', 'Grid View'); + $resp->assertElementContains('form[action$="/settings/users/' . $editor->id . '/switch-books-view"]', 'Grid View'); $resp->assertElementExists('input[name="view_type"][value="grid"]'); $resp = $this->patch("/settings/users/{$editor->id}/switch-books-view", ['view_type' => 'grid']); @@ -173,7 +173,7 @@ public function test_books_view_shows_view_toggle_option() $this->assertEquals('grid', setting()->getUser($editor, 'books_view_type')); $resp = $this->actingAs($editor)->get('/books'); - $resp->assertElementContains('form[action$="/settings/users/'.$editor->id.'/switch-books-view"]', 'List View'); + $resp->assertElementContains('form[action$="/settings/users/' . $editor->id . '/switch-books-view"]', 'List View'); $resp->assertElementExists('input[name="view_type"][value="list"]'); $resp = $this->patch("/settings/users/{$editor->id}/switch-books-view", ['view_type' => 'list']); diff --git a/tests/Entity/ChapterTest.php b/tests/Entity/ChapterTest.php index 4dd272b4352..9868dc03058 100644 --- a/tests/Entity/ChapterTest.php +++ b/tests/Entity/ChapterTest.php @@ -18,10 +18,10 @@ public function test_create() ]); $resp = $this->asEditor()->get($book->getUrl()); - $resp->assertElementContains('a[href="'.$book->getUrl('/create-chapter').'"]', 'New Chapter'); + $resp->assertElementContains('a[href="' . $book->getUrl('/create-chapter') . '"]', 'New Chapter'); $resp = $this->get($book->getUrl('/create-chapter')); - $resp->assertElementContains('form[action="'.$book->getUrl('/create-chapter').'"][method="POST"]', 'Save Chapter'); + $resp->assertElementContains('form[action="' . $book->getUrl('/create-chapter') . '"][method="POST"]', 'Save Chapter'); $resp = $this->post($book->getUrl('/create-chapter'), $chapter->only('name', 'description')); $resp->assertRedirect($book->getUrl('/chapter/my-first-chapter')); diff --git a/tests/Entity/CommentTest.php b/tests/Entity/CommentTest.php index 4584e6285ee..1e8ecbcac2c 100644 --- a/tests/Entity/CommentTest.php +++ b/tests/Entity/CommentTest.php @@ -107,7 +107,7 @@ public function test_html_cannot_be_injected_via_comment_content() $comment = $page->comments()->first(); $this->putJson("/comment/$comment->id", [ - 'text' => $script.'updated', + 'text' => $script . 'updated', ]); $pageView = $this->get($page->getUrl()); diff --git a/tests/Entity/EntitySearchTest.php b/tests/Entity/EntitySearchTest.php index 83b16ecf375..8d2ef0fded2 100644 --- a/tests/Entity/EntitySearchTest.php +++ b/tests/Entity/EntitySearchTest.php @@ -16,7 +16,7 @@ public function test_page_search() $book = Book::all()->first(); $page = $book->pages->first(); - $search = $this->asEditor()->get('/search?term='.urlencode($page->name)); + $search = $this->asEditor()->get('/search?term=' . urlencode($page->name)); $search->assertSee('Search Results'); $search->assertSee($page->name); } @@ -24,14 +24,14 @@ public function test_page_search() public function test_bookshelf_search() { $shelf = Bookshelf::first(); - $search = $this->asEditor()->get('/search?term='.urlencode(mb_substr($shelf->name, 0, 3)).' {type:bookshelf}'); + $search = $this->asEditor()->get('/search?term=' . urlencode(mb_substr($shelf->name, 0, 3)) . ' {type:bookshelf}'); $search->assertStatus(200); $search->assertSee($shelf->name); } public function test_invalid_page_search() { - $resp = $this->asEditor()->get('/search?term='.urlencode('

      test

      ')); + $resp = $this->asEditor()->get('/search?term=' . urlencode('

      test

      ')); $resp->assertSee('Search Results'); $resp->assertStatus(200); $this->get('/search?term=cat+-')->assertStatus(200); @@ -48,10 +48,10 @@ public function test_searching_accents_and_small_terms() $page = $this->newPage(['name' => 'My new test quaffleachits', 'html' => 'some áéííúü¿¡ test content a2 orange dog']); $this->asEditor(); - $accentSearch = $this->get('/search?term='.urlencode('áéíí')); + $accentSearch = $this->get('/search?term=' . urlencode('áéíí')); $accentSearch->assertStatus(200)->assertSee($page->name); - $smallSearch = $this->get('/search?term='.urlencode('a2')); + $smallSearch = $this->get('/search?term=' . urlencode('a2')); $smallSearch->assertStatus(200)->assertSee($page->name); } @@ -61,10 +61,10 @@ public function test_book_search() $page = $book->pages->last(); $chapter = $book->chapters->last(); - $pageTestResp = $this->asEditor()->get('/search/book/'.$book->id.'?term='.urlencode($page->name)); + $pageTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($page->name)); $pageTestResp->assertSee($page->name); - $chapterTestResp = $this->asEditor()->get('/search/book/'.$book->id.'?term='.urlencode($chapter->name)); + $chapterTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($chapter->name)); $chapterTestResp->assertSee($chapter->name); } @@ -73,7 +73,7 @@ public function test_chapter_search() $chapter = Chapter::has('pages')->first(); $page = $chapter->pages[0]; - $pageTestResp = $this->asEditor()->get('/search/chapter/'.$chapter->id.'?term='.urlencode($page->name)); + $pageTestResp = $this->asEditor()->get('/search/chapter/' . $chapter->id . '?term=' . urlencode($page->name)); $pageTestResp->assertSee($page->name); } @@ -111,10 +111,10 @@ public function test_exact_searches() { $page = $this->newPage(['name' => 'My new test page', 'html' => 'this is a story about an orange donkey']); - $exactSearchA = $this->asEditor()->get('/search?term='.urlencode('"story about an orange"')); + $exactSearchA = $this->asEditor()->get('/search?term=' . urlencode('"story about an orange"')); $exactSearchA->assertStatus(200)->assertSee($page->name); - $exactSearchB = $this->asEditor()->get('/search?term='.urlencode('"story not about an orange"')); + $exactSearchB = $this->asEditor()->get('/search?term=' . urlencode('"story not about an orange"')); $exactSearchB->assertStatus(200)->assertDontSee($page->name); } @@ -126,59 +126,59 @@ public function test_search_filters() $editorSlug = $this->getEditor()->slug; // Viewed filter searches - $this->get('/search?term='.urlencode('danzorbhsing {not_viewed_by_me}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {viewed_by_me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertDontSee($page->name); $this->get($page->getUrl()); - $this->get('/search?term='.urlencode('danzorbhsing {not_viewed_by_me}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {viewed_by_me}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertSee($page->name); // User filters - $this->get('/search?term='.urlencode('danzorbhsing {created_by:me}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_by:'.$editorSlug.'}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editorSlug . '}'))->assertDontSee($page->name); $page->created_by = $editorId; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {created_by:me}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {created_by: '.$editorSlug.'}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_by: ' . $editorSlug . '}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->updated_by = $editorId; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {updated_by:me}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_by:'.$editorSlug.'}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editorSlug . '}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->owned_by = $editorId; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {owned_by:me}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {owned_by:'.$editorSlug.'}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:' . $editorSlug . '}'))->assertSee($page->name); // Content filters - $this->get('/search?term='.urlencode('{in_name:danzorbhsing}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('{in_body:danzorbhsing}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('{in_name:test quaffleachits}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('{in_body:test quaffleachits}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('{in_name:danzorbhsing}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('{in_body:danzorbhsing}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('{in_name:test quaffleachits}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('{in_body:test quaffleachits}'))->assertDontSee($page->name); // Restricted filter - $this->get('/search?term='.urlencode('danzorbhsing {is_restricted}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertDontSee($page->name); $page->restricted = true; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {is_restricted}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertSee($page->name); // Date filters - $this->get('/search?term='.urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertSee($page->name); $page->updated_at = '2037-02-01'; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {created_after:2037-01-01}'))->assertDontSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {created_before:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertSee($page->name); $page->created_at = '2037-02-01'; $page->save(); - $this->get('/search?term='.urlencode('danzorbhsing {created_after:2037-01-01}'))->assertSee($page->name); - $this->get('/search?term='.urlencode('danzorbhsing {created_before:2037-01-01}'))->assertDontSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertSee($page->name); + $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertDontSee($page->name); } public function test_ajax_entity_search() @@ -189,10 +189,10 @@ public function test_ajax_entity_search() // Visit the page to make popular $this->asEditor()->get($page->getUrl()); - $normalSearch = $this->get('/ajax/search/entities?term='.urlencode($page->name)); + $normalSearch = $this->get('/ajax/search/entities?term=' . urlencode($page->name)); $normalSearch->assertSee($page->name); - $bookSearch = $this->get('/ajax/search/entities?types=book&term='.urlencode($page->name)); + $bookSearch = $this->get('/ajax/search/entities?types=book&term=' . urlencode($page->name)); $bookSearch->assertDontSee($page->name); $defaultListTest = $this->get('/ajax/search/entities'); @@ -206,12 +206,12 @@ public function test_ajax_entity_serach_shows_breadcrumbs() $page = $chapter->pages->first(); $this->asEditor(); - $pageSearch = $this->get('/ajax/search/entities?term='.urlencode($page->name)); + $pageSearch = $this->get('/ajax/search/entities?term=' . urlencode($page->name)); $pageSearch->assertSee($page->name); $pageSearch->assertSee($chapter->getShortName(42)); $pageSearch->assertSee($page->book->getShortName(42)); - $chapterSearch = $this->get('/ajax/search/entities?term='.urlencode($chapter->name)); + $chapterSearch = $this->get('/ajax/search/entities?term=' . urlencode($chapter->name)); $chapterSearch->assertSee($chapter->name); $chapterSearch->assertSee($chapter->book->getShortName(42)); } diff --git a/tests/Entity/ExportTest.php b/tests/Entity/ExportTest.php index 38db7ade092..9ea336db8ff 100644 --- a/tests/Entity/ExportTest.php +++ b/tests/Entity/ExportTest.php @@ -20,7 +20,7 @@ public function test_page_text_export() $resp = $this->get($page->getUrl('/export/plaintext')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); } public function test_page_pdf_export() @@ -30,7 +30,7 @@ public function test_page_pdf_export() $resp = $this->get($page->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); } public function test_page_html_export() @@ -41,7 +41,7 @@ public function test_page_html_export() $resp = $this->get($page->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); } public function test_book_text_export() @@ -54,7 +54,7 @@ public function test_book_text_export() $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); } public function test_book_pdf_export() @@ -65,7 +65,7 @@ public function test_book_pdf_export() $resp = $this->get($book->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); } public function test_book_html_export() @@ -78,12 +78,12 @@ public function test_book_html_export() $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$book->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); } public function test_book_html_export_shows_chapter_descriptions() { - $chapterDesc = 'My custom test chapter description '.Str::random(12); + $chapterDesc = 'My custom test chapter description ' . Str::random(12); $chapter = Chapter::query()->first(); $chapter->description = $chapterDesc; $chapter->save(); @@ -105,7 +105,7 @@ public function test_chapter_text_export() $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.txt"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); } public function test_chapter_pdf_export() @@ -115,7 +115,7 @@ public function test_chapter_pdf_export() $resp = $this->get($chapter->getUrl('/export/pdf')); $resp->assertStatus(200); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.pdf"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); } public function test_chapter_html_export() @@ -128,7 +128,7 @@ public function test_chapter_html_export() $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$chapter->slug.'.html"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); } public function test_page_html_export_contains_custom_head_if_set() @@ -211,8 +211,8 @@ public function test_page_export_contained_html_image_fetches_only_run_when_url_ { $page = Page::query()->first(); $page->html = '' - .'' - .''; + . '' + . ''; $storageDisk = Storage::disk('local'); $storageDisk->makeDirectory('uploads/images/gallery'); $storageDisk->put('uploads/images/gallery/svg_test.svg', 'good'); @@ -296,7 +296,7 @@ public function test_page_markdown_export() $resp = $this->asEditor()->get($page->getUrl('/export/markdown')); $resp->assertStatus(200); $resp->assertSee($page->name); - $resp->assertHeader('Content-Disposition', 'attachment; filename="'.$page->slug.'.md"'); + $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); } public function test_page_markdown_export_uses_existing_markdown_if_apparent() @@ -340,7 +340,7 @@ public function test_page_markdown_export_handles_bookstacks_wysiwyg_codeblock_f { $page = Page::query()->first()->forceFill([ 'markdown' => '', - 'html' => '

      Dogcat

      '."\r\n".'
      var a = \'cat\';

      Another line

      ', + 'html' => '

      Dogcat

      ' . "\r\n" . '
      var a = \'cat\';

      Another line

      ', ]); $page->save(); @@ -354,8 +354,8 @@ public function test_chapter_markdown_export() $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($chapter->getUrl('/export/markdown')); - $resp->assertSee('# '.$chapter->name); - $resp->assertSee('# '.$page->name); + $resp->assertSee('# ' . $chapter->name); + $resp->assertSee('# ' . $page->name); } public function test_book_markdown_export() @@ -365,9 +365,9 @@ public function test_book_markdown_export() $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($book->getUrl('/export/markdown')); - $resp->assertSee('# '.$book->name); - $resp->assertSee('# '.$chapter->name); - $resp->assertSee('# '.$page->name); + $resp->assertSee('# ' . $book->name); + $resp->assertSee('# ' . $chapter->name); + $resp->assertSee('# ' . $page->name); } public function test_export_option_only_visible_and_accessible_with_permission() diff --git a/tests/Entity/PageContentTest.php b/tests/Entity/PageContentTest.php index e1ecd6a1189..dd996b92633 100644 --- a/tests/Entity/PageContentTest.php +++ b/tests/Entity/PageContentTest.php @@ -34,7 +34,7 @@ public function test_page_includes() $pageContent->assertSee('Hello, This is a test'); $pageContent->assertSee('This is a second block of content'); - $page->html = $originalHtml." Well {{@{$secondPage->id}#section2}}"; + $page->html = $originalHtml . " Well {{@{$secondPage->id}#section2}}"; $page->save(); $pageContent = $this->get($page->getUrl()); @@ -48,8 +48,8 @@ public function test_saving_page_with_includes() $secondPage = Page::query()->where('id', '!=', $page->id)->first(); $this->asEditor(); - $includeTag = '{{@'.$secondPage->id.'}}'; - $page->html = '

      '.$includeTag.'

      '; + $includeTag = '{{@' . $secondPage->id . '}}'; + $page->html = '

      ' . $includeTag . '

      '; $resp = $this->put($page->getUrl(), ['name' => $page->name, 'html' => $page->html, 'summary' => '']); @@ -352,7 +352,7 @@ public function test_duplicate_ids_does_not_break_page_render() $pageA->html = $content; $pageA->save(); - $pageB->html = '

        {{@'.$pageA->id.'#test}}

        '; + $pageB->html = '

          {{@' . $pageA->id . '#test}}

          '; $pageB->save(); $pageView = $this->get($pageB->getUrl()); @@ -555,7 +555,7 @@ public function test_base64_images_get_extracted_from_page_content() $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

          test

          ', + 'html' => '

          test

          ', ]); $page->refresh(); @@ -579,7 +579,7 @@ public function test_base64_images_get_extracted_when_containing_whitespace() $base64PngWithoutWhitespace = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQAB'; $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

          test

          ', + 'html' => '

          test

          ', ]); $page->refresh(); @@ -601,7 +601,7 @@ public function test_base64_images_within_html_blanked_if_not_supported_extensio $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'html' => '

          test

          ', + 'html' => '

          test

          ', ]); $page->refresh(); @@ -615,7 +615,7 @@ public function test_base64_images_get_extracted_from_markdown_page_content() $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'markdown' => 'test ![test](data:image/jpeg;base64,'.$this->base64Jpeg.')', + 'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')', ]); $page->refresh(); @@ -637,7 +637,7 @@ public function test_base64_images_within_markdown_blanked_if_not_supported_exte $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', - 'markdown' => 'test ![test](data:image/jiff;base64,'.$this->base64Jpeg.')', + 'markdown' => 'test ![test](data:image/jiff;base64,' . $this->base64Jpeg . ')', ]); $page->refresh(); diff --git a/tests/Entity/PageDraftTest.php b/tests/Entity/PageDraftTest.php index 7e066264011..9e2ceff51a1 100644 --- a/tests/Entity/PageDraftTest.php +++ b/tests/Entity/PageDraftTest.php @@ -34,7 +34,7 @@ public function test_draft_content_shows_if_available() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html.$addedContent; + $newContent = $this->page->html . $addedContent; $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementContains('[name="html"]', $newContent); @@ -46,7 +46,7 @@ public function test_draft_not_visible_by_others() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html.$addedContent; + $newContent = $this->page->html . $addedContent; $newUser = $this->getEditor(); $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); @@ -69,7 +69,7 @@ public function test_alert_message_shows_if_someone_else_editing() $this->asAdmin()->get($this->page->getUrl('/edit')) ->assertElementNotContains('[name="html"]', $addedContent); - $newContent = $this->page->html.$addedContent; + $newContent = $this->page->html . $addedContent; $newUser = $this->getEditor(); $this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]); @@ -77,7 +77,7 @@ public function test_alert_message_shows_if_someone_else_editing() ->get($this->page->getUrl('/edit')) ->assertSee('Admin has started editing this page'); $this->flushSession(); - $this->get($nonEditedPage->getUrl().'/edit') + $this->get($nonEditedPage->getUrl() . '/edit') ->assertElementNotContains('.notification', 'Admin has started editing this page'); } @@ -88,7 +88,7 @@ public function test_draft_save_shows_alert_if_draft_older_than_last_page_update /** @var Page $page */ $page = Page::query()->first(); - $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ + $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ 'name' => $page->name, 'html' => '

          updated draft

          ', ]); @@ -106,7 +106,7 @@ public function test_draft_save_shows_alert_if_draft_older_than_last_page_update 'html' => '

          admin update

          ', ]); - $resp = $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ + $resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ 'name' => $page->name, 'html' => '

          updated draft again

          ', ]); @@ -123,12 +123,12 @@ public function test_draft_save_shows_alert_if_draft_edit_started_by_someone_els /** @var Page $page */ $page = Page::query()->first(); - $this->actingAs($admin)->put('/ajax/page/'.$page->id.'/save-draft', [ + $this->actingAs($admin)->put('/ajax/page/' . $page->id . '/save-draft', [ 'name' => $page->name, 'html' => '

          updated draft

          ', ]); - $resp = $this->actingAs($editor)->put('/ajax/page/'.$page->id.'/save-draft', [ + $resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [ 'name' => $page->name, 'html' => '

          updated draft again

          ', ]); @@ -145,7 +145,7 @@ public function test_draft_pages_show_on_homepage() $this->asAdmin()->get('/') ->assertElementNotContains('#recent-drafts', 'New Page'); - $this->get($book->getUrl().'/create-page'); + $this->get($book->getUrl() . '/create-page'); $this->get('/')->assertElementContains('#recent-drafts', 'New Page'); } @@ -174,7 +174,7 @@ public function test_page_html_in_ajax_fetch_response() /** @var Page $page */ $page = Page::query()->first(); - $this->getJson('/ajax/page/'.$page->id)->assertJson([ + $this->getJson('/ajax/page/' . $page->id)->assertJson([ 'html' => $page->html, ]); } diff --git a/tests/Entity/PageEditorTest.php b/tests/Entity/PageEditorTest.php index ee4a3ff7dea..652bc1336e5 100644 --- a/tests/Entity/PageEditorTest.php +++ b/tests/Entity/PageEditorTest.php @@ -20,14 +20,14 @@ protected function setUp(): void public function test_default_editor_is_wysiwyg() { $this->assertEquals('wysiwyg', setting('app-editor')); - $this->asAdmin()->get($this->page->getUrl().'/edit') + $this->asAdmin()->get($this->page->getUrl() . '/edit') ->assertElementExists('#html-editor'); } public function test_markdown_setting_shows_markdown_editor() { $this->setSettings(['app-editor' => 'markdown']); - $this->asAdmin()->get($this->page->getUrl().'/edit') + $this->asAdmin()->get($this->page->getUrl() . '/edit') ->assertElementNotExists('#html-editor') ->assertElementExists('#markdown-editor'); } @@ -40,14 +40,14 @@ public function test_markdown_content_given_to_editor() $this->page->markdown = $mdContent; $this->page->save(); - $this->asAdmin()->get($this->page->getUrl().'/edit') + $this->asAdmin()->get($this->page->getUrl() . '/edit') ->assertElementContains('[name="markdown"]', $mdContent); } public function test_html_content_given_to_editor_if_no_markdown() { $this->setSettings(['app-editor' => 'markdown']); - $this->asAdmin()->get($this->page->getUrl().'/edit') + $this->asAdmin()->get($this->page->getUrl() . '/edit') ->assertElementContains('[name="markdown"]', $this->page->html); } diff --git a/tests/Entity/PageRevisionTest.php b/tests/Entity/PageRevisionTest.php index d16640a3505..2ed7d3b411e 100644 --- a/tests/Entity/PageRevisionTest.php +++ b/tests/Entity/PageRevisionTest.php @@ -17,11 +17,11 @@ public function test_page_revision_views_viewable() $pageRepo->update($page, ['name' => 'updated page', 'html' => '

          new content

          ', 'summary' => 'page revision testing']); $pageRevision = $page->revisions->last(); - $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id); + $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); $revisionView->assertStatus(200); $revisionView->assertSee('new content'); - $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id.'/changes'); + $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id . '/changes'); $revisionView->assertStatus(200); $revisionView->assertSee('new content'); } @@ -36,7 +36,7 @@ public function test_page_revision_preview_shows_content_of_revision() $pageRevision = $page->revisions->last(); $pageRepo->update($page, ['name' => 'updated page', 'html' => '

          Updated content

          ', 'summary' => 'page revision testing 2']); - $revisionView = $this->get($page->getUrl().'/revisions/'.$pageRevision->id); + $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); $revisionView->assertStatus(200); $revisionView->assertSee('new revision content'); } @@ -56,7 +56,7 @@ public function test_page_revision_restore_updates_content() $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $restoreReq = $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); + $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); @@ -82,7 +82,7 @@ public function test_page_revision_restore_with_markdown_retains_markdown_conten $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $restoreReq = $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); + $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); @@ -108,7 +108,7 @@ public function test_page_revision_restore_sets_new_revision_with_summary() $page->refresh(); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); - $this->put($page->getUrl().'/revisions/'.$revToRestore->id.'/restore'); + $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page->refresh(); $this->assertDatabaseHas('page_revisions', [ @@ -139,7 +139,7 @@ public function test_revision_count_shown_in_page_meta() $page = Page::find($page->id); $pageView = $this->get($page->getUrl()); - $pageView->assertSee('Revision #'.$page->revision_count); + $pageView->assertSee('Revision #' . $page->revision_count); } public function test_revision_deletion() diff --git a/tests/Entity/PageTemplateTest.php b/tests/Entity/PageTemplateTest.php index fa93df08bb2..3d16895102f 100644 --- a/tests/Entity/PageTemplateTest.php +++ b/tests/Entity/PageTemplateTest.php @@ -56,14 +56,14 @@ public function test_templates_content_should_be_fetchable_only_if_page_marked_a $editor = $this->getEditor(); $this->actingAs($editor); - $templateFetch = $this->get('/templates/'.$page->id); + $templateFetch = $this->get('/templates/' . $page->id); $templateFetch->assertStatus(404); $page->html = $content; $page->template = true; $page->save(); - $templateFetch = $this->get('/templates/'.$page->id); + $templateFetch = $this->get('/templates/' . $page->id); $templateFetch->assertStatus(200); $templateFetch->assertJson([ 'html' => $content, diff --git a/tests/Entity/PageTest.php b/tests/Entity/PageTest.php index 60e0e94f688..32459a84a69 100644 --- a/tests/Entity/PageTest.php +++ b/tests/Entity/PageTest.php @@ -19,7 +19,7 @@ public function test_create() ]); $resp = $this->asEditor()->get($chapter->getUrl()); - $resp->assertElementContains('a[href="'.$chapter->getUrl('/create-page').'"]', 'New Page'); + $resp->assertElementContains('a[href="' . $chapter->getUrl('/create-page') . '"]', 'New Page'); $resp = $this->get($chapter->getUrl('/create-page')); /** @var Page $draftPage */ @@ -30,7 +30,7 @@ public function test_create() $resp->assertRedirect($draftPage->getUrl()); $resp = $this->get($draftPage->getUrl()); - $resp->assertElementContains('form[action="'.$draftPage->getUrl().'"][method="POST"]', 'Save Page'); + $resp->assertElementContains('form[action="' . $draftPage->getUrl() . '"][method="POST"]', 'Save Page'); $resp = $this->post($draftPage->getUrl(), $draftPage->only('name', 'html')); $draftPage->refresh(); @@ -49,7 +49,7 @@ public function test_page_view_when_creator_is_deleted_but_owner_exists() $resp = $this->asAdmin()->get($page->getUrl()); $resp->assertStatus(200); - $resp->assertSeeText('Owned by '.$owner->name); + $resp->assertSeeText('Owned by ' . $owner->name); } public function test_page_creation_with_markdown_content() @@ -141,7 +141,7 @@ public function test_page_copy() $resp->assertSee('Copy Page'); $movePageResp = $this->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); @@ -160,7 +160,7 @@ public function test_page_copy_with_markdown_has_both_html_and_markdown() $newBook = Book::where('id', '!=', $page->book->id)->first(); $this->asEditor()->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); @@ -207,7 +207,7 @@ public function test_page_can_be_copied_without_edit_permission() $resp->assertSee($page->getUrl('/copy')); $movePageResp = $this->post($page->getUrl('/copy'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $movePageResp->assertRedirect(); diff --git a/tests/Entity/SortTest.php b/tests/Entity/SortTest.php index acf1db54ad9..89279bfcf90 100644 --- a/tests/Entity/SortTest.php +++ b/tests/Entity/SortTest.php @@ -27,7 +27,7 @@ public function test_drafts_do_not_show_up() $resp = $this->get($this->book->getUrl()); $resp->assertSee($draft->name); - $resp = $this->get($this->book->getUrl().'/sort'); + $resp = $this->get($this->book->getUrl() . '/sort'); $resp->assertDontSee($draft->name); } @@ -41,7 +41,7 @@ public function test_page_move_into_book() $resp->assertSee('Move Page'); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $page = Page::find($page->id); @@ -61,7 +61,7 @@ public function test_page_move_into_chapter() $newChapter = $newBook->chapters()->first(); $movePageResp = $this->actingAs($this->getEditor())->put($page->getUrl('/move'), [ - 'entity_selection' => 'chapter:'.$newChapter->id, + 'entity_selection' => 'chapter:' . $newChapter->id, ]); $page = Page::find($page->id); @@ -79,7 +79,7 @@ public function test_page_move_from_chapter_to_book() $newBook = Book::where('id', '!=', $oldChapter->book_id)->first(); $movePageResp = $this->actingAs($this->getEditor())->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $page->refresh(); @@ -101,13 +101,13 @@ public function test_page_move_requires_create_permissions_on_parent() $this->setEntityRestrictions($newBook, ['view', 'update', 'delete'], $editor->roles->all()); $movePageResp = $this->actingAs($editor)->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $this->assertPermissionError($movePageResp); $this->setEntityRestrictions($newBook, ['view', 'update', 'delete', 'create'], $editor->roles->all()); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $page = Page::find($page->id); @@ -127,7 +127,7 @@ public function test_page_move_requires_delete_permissions() $this->setEntityRestrictions($page, ['view', 'update', 'create'], $editor->roles->all()); $movePageResp = $this->actingAs($editor)->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $this->assertPermissionError($movePageResp); $pageView = $this->get($page->getUrl()); @@ -135,7 +135,7 @@ public function test_page_move_requires_delete_permissions() $this->setEntityRestrictions($page, ['view', 'update', 'create', 'delete'], $editor->roles->all()); $movePageResp = $this->put($page->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $page = Page::find($page->id); @@ -154,7 +154,7 @@ public function test_chapter_move() $chapterMoveResp->assertSee('Move Chapter'); $moveChapterResp = $this->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $chapter = Chapter::find($chapter->id); @@ -182,7 +182,7 @@ public function test_chapter_move_requires_delete_permissions() $this->setEntityRestrictions($chapter, ['view', 'update', 'create'], $editor->roles->all()); $moveChapterResp = $this->actingAs($editor)->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $this->assertPermissionError($moveChapterResp); $pageView = $this->get($chapter->getUrl()); @@ -190,7 +190,7 @@ public function test_chapter_move_requires_delete_permissions() $this->setEntityRestrictions($chapter, ['view', 'update', 'create', 'delete'], $editor->roles->all()); $moveChapterResp = $this->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $chapter = Chapter::find($chapter->id); @@ -209,7 +209,7 @@ public function test_chapter_move_changes_book_for_deleted_pages_within() $pageToCheck->delete(); $this->asEditor()->put($chapter->getUrl('/move'), [ - 'entity_selection' => 'book:'.$newBook->id, + 'entity_selection' => 'book:' . $newBook->id, ]); $pageToCheck->refresh(); @@ -222,7 +222,7 @@ public function test_book_sort_page_shows() $bookToSort = Book::query()->first(); $resp = $this->asAdmin()->get($bookToSort->getUrl()); - $resp->assertElementExists('a[href="'.$bookToSort->getUrl('/sort').'"]'); + $resp->assertElementExists('a[href="' . $bookToSort->getUrl('/sort') . '"]'); $resp = $this->get($bookToSort->getUrl('/sort')); $resp->assertStatus(200); @@ -256,7 +256,7 @@ public function test_book_sort() ]; } - $sortResp = $this->asEditor()->put($newBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]); + $sortResp = $this->asEditor()->put($newBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]); $sortResp->assertRedirect($newBook->getUrl()); $sortResp->assertStatus(302); $this->assertDatabaseHas('chapters', [ @@ -279,7 +279,7 @@ public function test_book_sort_item_returns_book_content() $firstPage = $bookToSort->pages[0]; $firstChapter = $bookToSort->chapters[0]; - $resp = $this->asAdmin()->get($bookToSort->getUrl().'/sort-item'); + $resp = $this->asAdmin()->get($bookToSort->getUrl() . '/sort-item'); // Ensure book details are returned $resp->assertSee($bookToSort->name); diff --git a/tests/Entity/TagTest.php b/tests/Entity/TagTest.php index 9886bc28d23..fab2dc731e3 100644 --- a/tests/Entity/TagTest.php +++ b/tests/Entity/TagTest.php @@ -93,9 +93,9 @@ public function test_tags_shown_on_search_listing() $page = $this->getEntityWithTags(Page::class, $tags); $resp = $this->asEditor()->get('/search?term=[category]'); $resp->assertSee($page->name); - $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'category'); - $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'buckets'); - $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'color'); - $resp->assertElementContains('[href="'.$page->getUrl().'"]', 'red'); + $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'category'); + $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'buckets'); + $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'color'); + $resp->assertElementContains('[href="' . $page->getUrl() . '"]', 'red'); } } diff --git a/tests/Helpers/OidcJwtHelper.php b/tests/Helpers/OidcJwtHelper.php index fd5a4852bce..55a34d4dc96 100644 --- a/tests/Helpers/OidcJwtHelper.php +++ b/tests/Helpers/OidcJwtHelper.php @@ -56,7 +56,7 @@ public static function idToken($payloadOverrides = [], $headerOverrides = []): s $privateKey = static::privateKeyInstance(); $signature = $privateKey->sign($top); - return $top.'.'.static::base64UrlEncode($signature); + return $top . '.' . static::base64UrlEncode($signature); } public static function privateKeyInstance() diff --git a/tests/HomepageTest.php b/tests/HomepageTest.php index f9762c39649..dc1b2277959 100644 --- a/tests/HomepageTest.php +++ b/tests/HomepageTest.php @@ -89,7 +89,7 @@ public function test_custom_homepage_renders_includes() $included->save(); $name = 'My custom homepage'; - $customPage = $this->newPage(['name' => $name, 'html' => '{{@'.$included->id.'}}']); + $customPage = $this->newPage(['name' => $name, 'html' => '{{@' . $included->id . '}}']); $this->setSettings(['app-homepage' => $customPage->id]); $this->setSettings(['app-homepage-type' => 'page']); diff --git a/tests/OpenGraphTest.php b/tests/OpenGraphTest.php index b9066c41e82..17a5aa2c56f 100644 --- a/tests/OpenGraphTest.php +++ b/tests/OpenGraphTest.php @@ -21,7 +21,7 @@ public function test_page_tags() $resp = $this->asEditor()->get($page->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($page->getShortName().' | BookStack', $tags['title']); + $this->assertEquals($page->getShortName() . ' | BookStack', $tags['title']); $this->assertEquals($page->getUrl(), $tags['url']); $this->assertEquals(Str::limit($page->text, 100, '...'), $tags['description']); } @@ -32,7 +32,7 @@ public function test_chapter_tags() $resp = $this->asEditor()->get($chapter->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($chapter->getShortName().' | BookStack', $tags['title']); + $this->assertEquals($chapter->getShortName() . ' | BookStack', $tags['title']); $this->assertEquals($chapter->getUrl(), $tags['url']); $this->assertEquals(Str::limit($chapter->description, 100, '...'), $tags['description']); } @@ -43,7 +43,7 @@ public function test_book_tags() $resp = $this->asEditor()->get($book->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($book->getShortName().' | BookStack', $tags['title']); + $this->assertEquals($book->getShortName() . ' | BookStack', $tags['title']); $this->assertEquals($book->getUrl(), $tags['url']); $this->assertEquals(Str::limit($book->description, 100, '...'), $tags['description']); $this->assertArrayNotHasKey('image', $tags); @@ -63,7 +63,7 @@ public function test_shelf_tags() $resp = $this->asEditor()->get($shelf->getUrl()); $tags = $this->getOpenGraphTags($resp); - $this->assertEquals($shelf->getShortName().' | BookStack', $tags['title']); + $this->assertEquals($shelf->getShortName() . ' | BookStack', $tags['title']); $this->assertEquals($shelf->getUrl(), $tags['url']); $this->assertEquals(Str::limit($shelf->description, 100, '...'), $tags['description']); $this->assertArrayNotHasKey('image', $tags); diff --git a/tests/Permissions/EntityPermissionsTest.php b/tests/Permissions/EntityPermissionsTest.php index cd98018984c..96d4792b9c6 100644 --- a/tests/Permissions/EntityPermissionsTest.php +++ b/tests/Permissions/EntityPermissionsTest.php @@ -149,10 +149,10 @@ public function test_book_create_restriction() $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); - $this->get($bookUrl.'/create-chapter')->assertRedirect('/'); + $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookUrl.'/create-page')->assertRedirect('/'); + $this->get($bookUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl) @@ -190,23 +190,23 @@ public function test_book_update_restriction() $bookUrl = $book->getUrl(); $this->actingAs($this->user) - ->get($bookUrl.'/edit') + ->get($bookUrl . '/edit') ->assertSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl.'/edit')->assertRedirect('/'); + $this->get($bookUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl().'/edit')->assertRedirect('/'); + $this->get($bookPage->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl().'/edit')->assertRedirect('/'); + $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl.'/edit')->assertOk(); - $this->get($bookPage->getUrl().'/edit')->assertOk(); - $this->get($bookChapter->getUrl().'/edit')->assertSee('Edit Chapter'); + $this->get($bookUrl . '/edit')->assertOk(); + $this->get($bookPage->getUrl() . '/edit')->assertOk(); + $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction() @@ -217,21 +217,21 @@ public function test_book_delete_restriction() $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); - $this->actingAs($this->user)->get($bookUrl.'/delete') + $this->actingAs($this->user)->get($bookUrl . '/delete') ->assertSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl.'/delete')->assertRedirect('/'); + $this->get($bookUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl().'/delete')->assertRedirect('/'); + $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl().'/delete')->assertRedirect('/'); + $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl.'/delete')->assertOk()->assertSee('Delete Book'); + $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); $this->get($bookPage->getUrl('/delete'))->assertOk()->assertSee('Delete Page'); $this->get($bookChapter->getUrl('/delete'))->assertSee('Delete Chapter'); } @@ -268,7 +268,7 @@ public function test_chapter_create_restriction() $this->setRestrictionsForTestRoles($chapter, ['view', 'delete', 'update']); - $this->get($chapterUrl.'/create-page')->assertRedirect('/'); + $this->get($chapterUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($chapterUrl)->assertElementNotContains('.actions', 'New Page'); @@ -293,20 +293,20 @@ public function test_chapter_update_restriction() $chapterPage = $chapter->pages->first(); $chapterUrl = $chapter->getUrl(); - $this->actingAs($this->user)->get($chapterUrl.'/edit') + $this->actingAs($this->user)->get($chapterUrl . '/edit') ->assertSee('Edit Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); - $this->get($chapterUrl.'/edit')->assertRedirect('/'); + $this->get($chapterUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($chapterPage->getUrl().'/edit')->assertRedirect('/'); + $this->get($chapterPage->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); - $this->get($chapterUrl.'/edit')->assertOk()->assertSee('Edit Chapter'); - $this->get($chapterPage->getUrl().'/edit')->assertOk(); + $this->get($chapterUrl . '/edit')->assertOk()->assertSee('Edit Chapter'); + $this->get($chapterPage->getUrl() . '/edit')->assertOk(); } public function test_chapter_delete_restriction() @@ -317,20 +317,20 @@ public function test_chapter_delete_restriction() $chapterUrl = $chapter->getUrl(); $this->actingAs($this->user) - ->get($chapterUrl.'/delete') + ->get($chapterUrl . '/delete') ->assertSee('Delete Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); - $this->get($chapterUrl.'/delete')->assertRedirect('/'); + $this->get($chapterUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($chapterPage->getUrl().'/delete')->assertRedirect('/'); + $this->get($chapterPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); - $this->get($chapterUrl.'/delete')->assertOk()->assertSee('Delete Chapter'); - $this->get($chapterPage->getUrl().'/delete')->assertOk()->assertSee('Delete Page'); + $this->get($chapterUrl . '/delete')->assertOk()->assertSee('Delete Chapter'); + $this->get($chapterPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); } public function test_page_view_restriction() @@ -357,19 +357,19 @@ public function test_page_update_restriction() $pageUrl = $page->getUrl(); $this->actingAs($this->user) - ->get($pageUrl.'/edit') - ->assertElementExists('input[name="name"][value="'.$page->name.'"]'); + ->get($pageUrl . '/edit') + ->assertElementExists('input[name="name"][value="' . $page->name . '"]'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); - $this->get($pageUrl.'/edit')->assertRedirect('/'); + $this->get($pageUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); - $this->get($pageUrl.'/edit') + $this->get($pageUrl . '/edit') ->assertOk() - ->assertElementExists('input[name="name"][value="'.$page->name.'"]'); + ->assertElementExists('input[name="name"][value="' . $page->name . '"]'); } public function test_page_delete_restriction() @@ -379,17 +379,17 @@ public function test_page_delete_restriction() $pageUrl = $page->getUrl(); $this->actingAs($this->user) - ->get($pageUrl.'/delete') + ->get($pageUrl . '/delete') ->assertSee('Delete Page'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); - $this->get($pageUrl.'/delete')->assertRedirect('/'); + $this->get($pageUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); - $this->get($pageUrl.'/delete')->assertOk()->assertSee('Delete Page'); + $this->get($pageUrl . '/delete')->assertOk()->assertSee('Delete Page'); } protected function entityRestrictionFormTest(string $model, string $title, string $permission, string $roleId) @@ -545,9 +545,9 @@ public function test_book_create_restriction_override() $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); - $this->get($bookUrl.'/create-chapter')->assertRedirect('/'); + $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookUrl.'/create-page')->assertRedirect('/'); + $this->get($bookUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); @@ -582,23 +582,23 @@ public function test_book_update_restriction_override() $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); - $this->actingAs($this->viewer)->get($bookUrl.'/edit') + $this->actingAs($this->viewer)->get($bookUrl . '/edit') ->assertDontSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl.'/edit')->assertRedirect('/'); + $this->get($bookUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl().'/edit')->assertRedirect('/'); + $this->get($bookPage->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl().'/edit')->assertRedirect('/'); + $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl.'/edit')->assertOk(); - $this->get($bookPage->getUrl().'/edit')->assertOk(); - $this->get($bookChapter->getUrl().'/edit')->assertSee('Edit Chapter'); + $this->get($bookUrl . '/edit')->assertOk(); + $this->get($bookPage->getUrl() . '/edit')->assertOk(); + $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction_override() @@ -610,23 +610,23 @@ public function test_book_delete_restriction_override() $bookUrl = $book->getUrl(); $this->actingAs($this->viewer) - ->get($bookUrl.'/delete') + ->get($bookUrl . '/delete') ->assertDontSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); - $this->get($bookUrl.'/delete')->assertRedirect('/'); + $this->get($bookUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookPage->getUrl().'/delete')->assertRedirect('/'); + $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); - $this->get($bookChapter->getUrl().'/delete')->assertRedirect('/'); + $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); - $this->get($bookUrl.'/delete')->assertOk()->assertSee('Delete Book'); - $this->get($bookPage->getUrl().'/delete')->assertOk()->assertSee('Delete Page'); - $this->get($bookChapter->getUrl().'/delete')->assertSee('Delete Chapter'); + $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); + $this->get($bookPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); + $this->get($bookChapter->getUrl() . '/delete')->assertSee('Delete Chapter'); } public function test_page_visible_if_has_permissions_when_book_not_visible() @@ -695,7 +695,7 @@ public function test_book_sort_permission() ]; // Move chapter from first book to a second book - $this->actingAs($this->user)->put($firstBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]) + $this->actingAs($this->user)->put($firstBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]) ->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); @@ -710,7 +710,7 @@ public function test_book_sort_permission() ]; // Move chapter from second book to first book - $this->actingAs($this->user)->put($firstBook->getUrl().'/sort', ['sort-tree' => json_encode($reqData)]) + $this->actingAs($this->user)->put($firstBook->getUrl() . '/sort', ['sort-tree' => json_encode($reqData)]) ->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); } diff --git a/tests/Permissions/ExportPermissionsTest.php b/tests/Permissions/ExportPermissionsTest.php index 076021edc31..2e3d84fa13e 100644 --- a/tests/Permissions/ExportPermissionsTest.php +++ b/tests/Permissions/ExportPermissionsTest.php @@ -14,7 +14,7 @@ public function test_page_content_without_view_access_hidden_on_chapter_export() $chapter = Chapter::query()->first(); $page = $chapter->pages()->firstOrFail(); $pageContent = Str::random(48); - $page->html = '

          '.$pageContent.'

          '; + $page->html = '

          ' . $pageContent . '

          '; $page->save(); $viewer = $this->getViewer(); $this->actingAs($viewer); @@ -42,7 +42,7 @@ public function test_page_content_without_view_access_hidden_on_book_export() $book = Book::query()->first(); $page = $book->pages()->firstOrFail(); $pageContent = Str::random(48); - $page->html = '

          '.$pageContent.'

          '; + $page->html = '

          ' . $pageContent . '

          '; $page->save(); $viewer = $this->getViewer(); $this->actingAs($viewer); diff --git a/tests/Permissions/RolesTest.php b/tests/Permissions/RolesTest.php index b4ae1c00af8..c880bdd0089 100644 --- a/tests/Permissions/RolesTest.php +++ b/tests/Permissions/RolesTest.php @@ -33,7 +33,7 @@ public function test_admin_can_see_settings() public function test_cannot_delete_admin_role() { $adminRole = Role::getRole('admin'); - $deletePageUrl = '/settings/roles/delete/'.$adminRole->id; + $deletePageUrl = '/settings/roles/delete/' . $adminRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); @@ -45,7 +45,7 @@ public function test_role_cannot_be_deleted_if_default() $newRole = $this->createNewRole(); $this->setSettings(['registration-role' => $newRole->id]); - $deletePageUrl = '/settings/roles/delete/'.$newRole->id; + $deletePageUrl = '/settings/roles/delete/' . $newRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); $this->get($deletePageUrl)->assertSee('cannot be deleted'); @@ -59,13 +59,13 @@ public function test_role_create_update_delete_flow() // Creation $resp = $this->asAdmin()->get('/settings'); - $resp->assertElementContains('a[href="'.url('/settings/roles').'"]', 'Roles'); + $resp->assertElementContains('a[href="' . url('/settings/roles') . '"]', 'Roles'); $resp = $this->get('/settings/roles'); - $resp->assertElementContains('a[href="'.url('/settings/roles/new').'"]', 'Create New Role'); + $resp->assertElementContains('a[href="' . url('/settings/roles/new') . '"]', 'Create New Role'); $resp = $this->get('/settings/roles/new'); - $resp->assertElementContains('form[action="'.url('/settings/roles/new').'"]', 'Save Role'); + $resp->assertElementContains('form[action="' . url('/settings/roles/new') . '"]', 'Save Role'); $resp = $this->post('/settings/roles/new', [ 'display_name' => $testRoleName, @@ -86,12 +86,12 @@ public function test_role_create_update_delete_flow() $role = Role::query()->where('display_name', '=', $testRoleName)->first(); // Updating - $resp = $this->get('/settings/roles/'.$role->id); + $resp = $this->get('/settings/roles/' . $role->id); $resp->assertSee($testRoleName); $resp->assertSee($testRoleDesc); - $resp->assertElementContains('form[action="'.url('/settings/roles/'.$role->id).'"]', 'Save Role'); + $resp->assertElementContains('form[action="' . url('/settings/roles/' . $role->id) . '"]', 'Save Role'); - $resp = $this->put('/settings/roles/'.$role->id, [ + $resp = $this->put('/settings/roles/' . $role->id, [ 'display_name' => $testRoleUpdateName, 'description' => $testRoleDesc, 'mfa_enforced' => 'true', @@ -104,12 +104,12 @@ public function test_role_create_update_delete_flow() ]); // Deleting - $resp = $this->get('/settings/roles/'.$role->id); - $resp->assertElementContains('a[href="'.url("/settings/roles/delete/$role->id").'"]', 'Delete Role'); + $resp = $this->get('/settings/roles/' . $role->id); + $resp->assertElementContains('a[href="' . url("/settings/roles/delete/$role->id") . '"]', 'Delete Role'); $resp = $this->get("/settings/roles/delete/$role->id"); $resp->assertSee($testRoleUpdateName); - $resp->assertElementContains('form[action="'.url("/settings/roles/delete/$role->id").'"]', 'Confirm'); + $resp->assertElementContains('form[action="' . url("/settings/roles/delete/$role->id") . '"]', 'Confirm'); $resp = $this->delete("/settings/roles/delete/$role->id"); $resp->assertRedirect('/settings/roles'); @@ -127,7 +127,7 @@ public function test_admin_role_cannot_be_removed_if_user_last_admin() $viewerRole = $this->getViewer()->roles()->first(); - $editUrl = '/settings/users/'.$adminUser->id; + $editUrl = '/settings/users/' . $adminUser->id; $resp = $this->actingAs($adminUser)->put($editUrl, [ 'name' => $adminUser->name, 'email' => $adminUser->email, @@ -172,7 +172,7 @@ public function test_manage_user_permission() public function test_manage_users_permission_shows_link_in_header_if_does_not_have_settings_manage_permision() { - $usersLink = 'href="'.url('/settings/users').'"'; + $usersLink = 'href="' . url('/settings/users') . '"'; $this->actingAs($this->user)->get('/')->assertDontSee($usersLink, false); $this->giveUserPermissions($this->user, ['users-manage']); $this->actingAs($this->user)->get('/')->assertSee($usersLink, false); @@ -182,7 +182,7 @@ public function test_manage_users_permission_shows_link_in_header_if_does_not_ha public function test_user_cannot_change_email_unless_they_have_manage_users_permission() { - $userProfileUrl = '/settings/users/'.$this->user->id; + $userProfileUrl = '/settings/users/' . $this->user->id; $originalEmail = $this->user->email; $this->actingAs($this->user); @@ -413,7 +413,7 @@ public function test_books_edit_own_permission() $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->createEntityChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-update-own', [ - $ownBook->getUrl().'/edit', + $ownBook->getUrl() . '/edit', ], [ $ownBook->getUrl() => 'Edit', ]); @@ -427,7 +427,7 @@ public function test_books_edit_all_permission() /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-update-all', [ - $otherBook->getUrl().'/edit', + $otherBook->getUrl() . '/edit', ], [ $otherBook->getUrl() => 'Edit', ]); @@ -440,7 +440,7 @@ public function test_books_delete_own_permission() $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->createEntityChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-delete-own', [ - $ownBook->getUrl().'/delete', + $ownBook->getUrl() . '/delete', ], [ $ownBook->getUrl() => 'Delete', ]); @@ -458,7 +458,7 @@ public function test_books_delete_all_permission() /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-delete-all', [ - $otherBook->getUrl().'/delete', + $otherBook->getUrl() . '/delete', ], [ $otherBook->getUrl() => 'Delete', ]); @@ -510,7 +510,7 @@ public function test_chapter_edit_own_permission() $otherChapter = Chapter::query()->first(); $ownChapter = $this->createEntityChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-update-own', [ - $ownChapter->getUrl().'/edit', + $ownChapter->getUrl() . '/edit', ], [ $ownChapter->getUrl() => 'Edit', ]); @@ -524,7 +524,7 @@ public function test_chapter_edit_all_permission() /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->take(1)->get()->first(); $this->checkAccessPermission('chapter-update-all', [ - $otherChapter->getUrl().'/edit', + $otherChapter->getUrl() . '/edit', ], [ $otherChapter->getUrl() => 'Edit', ]); @@ -537,7 +537,7 @@ public function test_chapter_delete_own_permission() $otherChapter = Chapter::query()->first(); $ownChapter = $this->createEntityChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-delete-own', [ - $ownChapter->getUrl().'/delete', + $ownChapter->getUrl() . '/delete', ], [ $ownChapter->getUrl() => 'Delete', ]); @@ -556,7 +556,7 @@ public function test_chapter_delete_all_permission() /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->first(); $this->checkAccessPermission('chapter-delete-all', [ - $otherChapter->getUrl().'/delete', + $otherChapter->getUrl() . '/delete', ], [ $otherChapter->getUrl() => 'Delete', ]); @@ -665,13 +665,13 @@ public function test_page_edit_own_permission() $otherPage = Page::query()->first(); $ownPage = $this->createEntityChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-update-own', [ - $ownPage->getUrl().'/edit', + $ownPage->getUrl() . '/edit', ], [ $ownPage->getUrl() => 'Edit', ]); $this->get($otherPage->getUrl())->assertElementNotContains('.action-buttons', 'Edit'); - $this->get($otherPage->getUrl().'/edit')->assertRedirect('/'); + $this->get($otherPage->getUrl() . '/edit')->assertRedirect('/'); } public function test_page_edit_all_permission() @@ -692,7 +692,7 @@ public function test_page_delete_own_permission() $otherPage = Page::query()->first(); $ownPage = $this->createEntityChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-delete-own', [ - $ownPage->getUrl().'/delete', + $ownPage->getUrl() . '/delete', ], [ $ownPage->getUrl() => 'Delete', ]); @@ -712,7 +712,7 @@ public function test_page_delete_all_permission() $otherPage = Page::query()->first(); $this->checkAccessPermission('page-delete-all', [ - $otherPage->getUrl().'/delete', + $otherPage->getUrl() . '/delete', ], [ $otherPage->getUrl() => 'Delete', ]); @@ -731,9 +731,9 @@ public function test_public_role_visible_in_user_edit_screen() $user = User::query()->first(); $adminRole = Role::getSystemRole('admin'); $publicRole = Role::getSystemRole('public'); - $this->asAdmin()->get('/settings/users/'.$user->id) - ->assertElementExists('[name="roles['.$adminRole->id.']"]') - ->assertElementExists('[name="roles['.$publicRole->id.']"]'); + $this->asAdmin()->get('/settings/users/' . $user->id) + ->assertElementExists('[name="roles[' . $adminRole->id . ']"]') + ->assertElementExists('[name="roles[' . $publicRole->id . ']"]'); } public function test_public_role_visible_in_role_listing() @@ -754,13 +754,13 @@ public function test_public_role_not_deletable() { /** @var Role $publicRole */ $publicRole = Role::getSystemRole('public'); - $resp = $this->asAdmin()->delete('/settings/roles/delete/'.$publicRole->id); + $resp = $this->asAdmin()->delete('/settings/roles/delete/' . $publicRole->id); $resp->assertRedirect('/'); - $this->get('/settings/roles/delete/'.$publicRole->id); - $resp = $this->delete('/settings/roles/delete/'.$publicRole->id); - $resp->assertRedirect('/settings/roles/delete/'.$publicRole->id); - $resp = $this->get('/settings/roles/delete/'.$publicRole->id); + $this->get('/settings/roles/delete/' . $publicRole->id); + $resp = $this->delete('/settings/roles/delete/' . $publicRole->id); + $resp->assertRedirect('/settings/roles/delete/' . $publicRole->id); + $resp = $this->get('/settings/roles/delete/' . $publicRole->id); $resp->assertSee('This role is a system role and cannot be deleted'); } @@ -775,11 +775,11 @@ public function test_image_delete_own_permission() 'updated_by' => $this->user->id, ]); - $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-own']); - $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertOk(); + $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } @@ -791,15 +791,15 @@ public function test_image_delete_all_permission() $page = Page::query()->first(); $image = Image::factory()->create(['uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id]); - $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-own']); - $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertStatus(403); + $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->giveUserPermissions($this->user, ['image-delete-all']); - $this->actingAs($this->user)->json('delete', '/images/'.$image->id)->assertOk(); + $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } @@ -812,7 +812,7 @@ public function test_role_permission_removal() $viewer = $this->getViewer(); $this->actingAs($viewer)->get($page->getUrl())->assertOk(); - $this->asAdmin()->put('/settings/roles/'.$viewerRole->id, [ + $this->asAdmin()->put('/settings/roles/' . $viewerRole->id, [ 'display_name' => $viewerRole->display_name, 'description' => $viewerRole->description, 'permission' => [], @@ -940,6 +940,6 @@ private function updateComment(Comment $comment): TestResponse private function deleteComment(Comment $comment): TestResponse { - return $this->json('DELETE', '/comment/'.$comment->id); + return $this->json('DELETE', '/comment/' . $comment->id); } } diff --git a/tests/PublicActionTest.php b/tests/PublicActionTest.php index 3695be5d8a2..499c0c9f971 100644 --- a/tests/PublicActionTest.php +++ b/tests/PublicActionTest.php @@ -28,7 +28,7 @@ public function test_app_not_public() public function test_login_link_visible() { $this->setSettings(['app-public' => 'true']); - $this->get('/')->assertElementExists('a[href="'.url('/login').'"]'); + $this->get('/')->assertElementExists('a[href="' . url('/login') . '"]'); } public function test_register_link_visible_when_enabled() @@ -95,12 +95,12 @@ public function test_public_page_creation() $chapter = Chapter::query()->first(); $resp = $this->get($chapter->getUrl()); $resp->assertSee('New Page'); - $resp->assertElementExists('a[href="'.$chapter->getUrl('/create-page').'"]'); + $resp->assertElementExists('a[href="' . $chapter->getUrl('/create-page') . '"]'); $resp = $this->get($chapter->getUrl('/create-page')); $resp->assertSee('Continue'); $resp->assertSee('Page Name'); - $resp->assertElementExists('form[action="'.$chapter->getUrl('/create-guest-page').'"]'); + $resp->assertElementExists('form[action="' . $chapter->getUrl('/create-guest-page') . '"]'); $resp = $this->post($chapter->getUrl('/create-guest-page'), ['name' => 'My guest page']); $resp->assertRedirect($chapter->book->getUrl('/page/my-guest-page/edit')); diff --git a/tests/RecycleBinTest.php b/tests/RecycleBinTest.php index 1716152b56d..f3e30c0d07d 100644 --- a/tests/RecycleBinTest.php +++ b/tests/RecycleBinTest.php @@ -66,8 +66,8 @@ public function test_recycle_bin_view() $viewReq->assertElementContains('table.table', $page->name); $viewReq->assertElementContains('table.table', $editor->name); $viewReq->assertElementContains('table.table', $book->name); - $viewReq->assertElementContains('table.table', $book->pages_count.' Pages'); - $viewReq->assertElementContains('table.table', $book->chapters_count.' Chapters'); + $viewReq->assertElementContains('table.table', $book->pages_count . ' Pages'); + $viewReq->assertElementContains('table.table', $book->chapters_count . ' Chapters'); } public function test_recycle_bin_empty() @@ -90,7 +90,7 @@ public function test_recycle_bin_empty() $itemCount = 2 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Deleted '.$itemCount.' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Deleted ' . $itemCount . ' total items from the recycle bin'); } public function test_entity_restore() @@ -111,7 +111,7 @@ public function test_entity_restore() $itemCount = 1 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Restored '.$itemCount.' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Restored ' . $itemCount . ' total items from the recycle bin'); } public function test_permanent_delete() @@ -130,7 +130,7 @@ public function test_permanent_delete() $itemCount = 1 + $book->pages->count() + $book->chapters->count(); $redirectReq = $this->get('/settings/recycle-bin'); - $redirectReq->assertNotificationContains('Deleted '.$itemCount.' total items from the recycle bin'); + $redirectReq->assertNotificationContains('Deleted ' . $itemCount . ' total items from the recycle bin'); } public function test_permanent_delete_for_each_type() @@ -264,6 +264,6 @@ public function test_restore_page_shows_link_to_parent_restore_if_parent_also_de $pageRestoreView = $this->asAdmin()->get("/settings/recycle-bin/{$pageDeletion->id}/restore"); $pageRestoreView->assertSee('The parent of this item has also been deleted.'); - $pageRestoreView->assertElementContains('a[href$="/settings/recycle-bin/'.$bookDeletion->id.'/restore"]', 'Restore Parent'); + $pageRestoreView->assertElementContains('a[href$="/settings/recycle-bin/' . $bookDeletion->id . '/restore"]', 'Restore Parent'); } } diff --git a/tests/SecurityHeaderTest.php b/tests/SecurityHeaderTest.php index e10afe9e734..78691badbbc 100644 --- a/tests/SecurityHeaderTest.php +++ b/tests/SecurityHeaderTest.php @@ -75,8 +75,8 @@ public function test_script_csp_nonce_matches_nonce_used_in_custom_head() $scriptHeader = $this->getCspHeader($resp, 'script-src'); $nonce = app()->make(CspService::class)->getNonce(); - $this->assertStringContainsString('nonce-'.$nonce, $scriptHeader); - $resp->assertSee('', false); + $this->assertStringContainsString('nonce-' . $nonce, $scriptHeader); + $resp->assertSee('', false); } public function test_script_csp_nonce_changes_per_request() diff --git a/tests/SharedTestHelpers.php b/tests/SharedTestHelpers.php index 8da98d3c63a..cbf49bf71f4 100644 --- a/tests/SharedTestHelpers.php +++ b/tests/SharedTestHelpers.php @@ -84,7 +84,7 @@ protected function getEditor(): User protected function getViewer(array $attributes = []): User { $user = Role::getRole('viewer')->users()->first(); - if (! empty($attributes)) { + if (!empty($attributes)) { $user->forceFill($attributes)->save(); } @@ -301,7 +301,7 @@ protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck $passed = true; foreach ($mapToInclude as $key => $value) { - if (! isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) { + if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) { $passed = false; } } diff --git a/tests/TestEmailTest.php b/tests/TestEmailTest.php index 2fbdcfd2845..0a2091fe3e9 100644 --- a/tests/TestEmailTest.php +++ b/tests/TestEmailTest.php @@ -13,7 +13,7 @@ public function test_a_send_test_button_shows() $pageView = $this->asAdmin()->get('/settings/maintenance'); $formCssSelector = 'form[action$="/settings/maintenance/send-test-email"]'; $pageView->assertElementExists($formCssSelector); - $pageView->assertElementContains($formCssSelector.' button', 'Send Test Email'); + $pageView->assertElementContains($formCssSelector . ' button', 'Send Test Email'); } public function test_send_test_email_endpoint_sends_email_and_redirects_user_and_shows_notification() @@ -23,7 +23,7 @@ public function test_send_test_email_endpoint_sends_email_and_redirects_user_and $sendReq = $this->actingAs($admin)->post('/settings/maintenance/send-test-email'); $sendReq->assertRedirect('/settings/maintenance#image-cleanup'); - $this->assertSessionHas('success', 'Email sent to '.$admin->email); + $this->assertSessionHas('success', 'Email sent to ' . $admin->email); Notification::assertSentTo($admin, TestEmail::class); } diff --git a/tests/TestResponse.php b/tests/TestResponse.php index 8957dd279a1..5e2be3ac35c 100644 --- a/tests/TestResponse.php +++ b/tests/TestResponse.php @@ -19,7 +19,7 @@ class TestResponse extends BaseTestResponse */ protected function crawler(): Crawler { - if (! is_object($this->crawlerInstance)) { + if (!is_object($this->crawlerInstance)) { $this->crawlerInstance = new Crawler($this->getContent()); } @@ -44,9 +44,9 @@ public function assertElementExists(string $selector) $elements = $this->crawler()->filter($selector); PHPUnit::assertTrue( $elements->count() > 0, - 'Unable to find element matching the selector: '.PHP_EOL.PHP_EOL. - "[{$selector}]".PHP_EOL.PHP_EOL. - 'within'.PHP_EOL.PHP_EOL. + 'Unable to find element matching the selector: ' . PHP_EOL . PHP_EOL . + "[{$selector}]" . PHP_EOL . PHP_EOL . + 'within' . PHP_EOL . PHP_EOL . "[{$this->getContent()}]." ); @@ -63,9 +63,9 @@ public function assertElementNotExists(string $selector) $elements = $this->crawler()->filter($selector); PHPUnit::assertTrue( $elements->count() === 0, - 'Found elements matching the selector: '.PHP_EOL.PHP_EOL. - "[{$selector}]".PHP_EOL.PHP_EOL. - 'within'.PHP_EOL.PHP_EOL. + 'Found elements matching the selector: ' . PHP_EOL . PHP_EOL . + "[{$selector}]" . PHP_EOL . PHP_EOL . + 'within' . PHP_EOL . PHP_EOL . "[{$this->getContent()}]." ); @@ -85,7 +85,7 @@ public function assertElementContains(string $selector, string $text, ?int $nthM $matched = false; $pattern = $this->getEscapedPattern($text); - if (! is_null($nthMatch)) { + if (!is_null($nthMatch)) { $elements = $elements->eq($nthMatch - 1); } @@ -99,12 +99,12 @@ public function assertElementContains(string $selector, string $text, ?int $nthM PHPUnit::assertTrue( $matched, - 'Unable to find element of selector: '.PHP_EOL.PHP_EOL. - ($nthMatch ? ("at position {$nthMatch}".PHP_EOL.PHP_EOL) : ''). - "[{$selector}]".PHP_EOL.PHP_EOL. - 'containing text'.PHP_EOL.PHP_EOL. - "[{$text}]".PHP_EOL.PHP_EOL. - 'within'.PHP_EOL.PHP_EOL. + 'Unable to find element of selector: ' . PHP_EOL . PHP_EOL . + ($nthMatch ? ("at position {$nthMatch}" . PHP_EOL . PHP_EOL) : '') . + "[{$selector}]" . PHP_EOL . PHP_EOL . + 'containing text' . PHP_EOL . PHP_EOL . + "[{$text}]" . PHP_EOL . PHP_EOL . + 'within' . PHP_EOL . PHP_EOL . "[{$this->getContent()}]." ); @@ -124,7 +124,7 @@ public function assertElementNotContains(string $selector, string $text, ?int $n $matched = false; $pattern = $this->getEscapedPattern($text); - if (! is_null($nthMatch)) { + if (!is_null($nthMatch)) { $elements = $elements->eq($nthMatch - 1); } @@ -137,13 +137,13 @@ public function assertElementNotContains(string $selector, string $text, ?int $n } PHPUnit::assertTrue( - ! $matched, - 'Found element of selector: '.PHP_EOL.PHP_EOL. - ($nthMatch ? ("at position {$nthMatch}".PHP_EOL.PHP_EOL) : ''). - "[{$selector}]".PHP_EOL.PHP_EOL. - 'containing text'.PHP_EOL.PHP_EOL. - "[{$text}]".PHP_EOL.PHP_EOL. - 'within'.PHP_EOL.PHP_EOL. + !$matched, + 'Found element of selector: ' . PHP_EOL . PHP_EOL . + ($nthMatch ? ("at position {$nthMatch}" . PHP_EOL . PHP_EOL) : '') . + "[{$selector}]" . PHP_EOL . PHP_EOL . + 'containing text' . PHP_EOL . PHP_EOL . + "[{$text}]" . PHP_EOL . PHP_EOL . + 'within' . PHP_EOL . PHP_EOL . "[{$this->getContent()}]." ); diff --git a/tests/ThemeTest.php b/tests/ThemeTest.php index e73e04b1e18..9aa7873b07c 100644 --- a/tests/ThemeTest.php +++ b/tests/ThemeTest.php @@ -26,7 +26,7 @@ public function test_translation_text_can_be_overridden_via_theme() $customTranslations = ' \'Sandwiches\']; '; - file_put_contents($translationPath.'/entities.php', $customTranslations); + file_put_contents($translationPath . '/entities.php', $customTranslations); $homeRequest = $this->actingAs($this->getViewer())->get('/'); $homeRequest->assertElementContains('header nav', 'Sandwiches'); @@ -209,7 +209,7 @@ function ($driver) { protected function usingThemeFolder(callable $callback) { // Create a folder and configure a theme - $themeFolderName = 'testing_theme_'.rtrim(base64_encode(time()), '='); + $themeFolderName = 'testing_theme_' . rtrim(base64_encode(time()), '='); config()->set('view.theme', $themeFolderName); $themeFolderPath = theme_path(''); File::makeDirectory($themeFolderPath); diff --git a/tests/Unit/OidcIdTokenTest.php b/tests/Unit/OidcIdTokenTest.php index d89bcdf7cb7..ad91eecd8b2 100644 --- a/tests/Unit/OidcIdTokenTest.php +++ b/tests/Unit/OidcIdTokenTest.php @@ -46,9 +46,9 @@ public function test_token_structure_error_cases() ['Could not parse out a valid header within the provided token', ''], ['Could not parse out a valid header within the provided token', 'cat'], ['Could not parse out a valid payload within the provided token', $idTokenExploded[0]], - ['Could not parse out a valid payload within the provided token', $idTokenExploded[0].'.'.'dog'], - ['Could not parse out a valid signature within the provided token', $idTokenExploded[0].'.'.$idTokenExploded[1]], - ['Could not parse out a valid signature within the provided token', $idTokenExploded[0].'.'.$idTokenExploded[1].'.'.'@$%'], + ['Could not parse out a valid payload within the provided token', $idTokenExploded[0] . '.' . 'dog'], + ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1]], + ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1] . '.' . '@$%'], ]; foreach ($messagesAndTokenValues as [$message, $tokenValue]) { @@ -154,7 +154,7 @@ public function test_token_claim_error_cases() public function test_keys_can_be_a_local_file_reference_to_pem_key() { $file = tmpfile(); - $testFilePath = 'file://'.stream_get_meta_data($file)['uri']; + $testFilePath = 'file://' . stream_get_meta_data($file)['uri']; file_put_contents($testFilePath, OidcJwtHelper::publicPemKey()); $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $testFilePath, diff --git a/tests/Uploads/AttachmentTest.php b/tests/Uploads/AttachmentTest.php index f92167ea279..588b7054ac2 100644 --- a/tests/Uploads/AttachmentTest.php +++ b/tests/Uploads/AttachmentTest.php @@ -160,7 +160,7 @@ public function test_attachment_updating() $this->asAdmin(); $attachment = $this->createAttachment($page); - $update = $this->call('PUT', 'attachments/'.$attachment->id, [ + $update = $this->call('PUT', 'attachments/' . $attachment->id, [ 'attachment_edit_name' => 'My new attachment name', 'attachment_edit_url' => 'https://test.example.com', ]); @@ -187,7 +187,7 @@ public function test_file_deletion() $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); - $this->assertTrue(file_exists($filePath), 'File at path '.$filePath.' does not exist'); + $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); $attachment = Attachment::first(); $this->delete($attachment->getUrl()); @@ -195,7 +195,7 @@ public function test_file_deletion() $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); - $this->assertFalse(file_exists($filePath), 'File at path '.$filePath.' was not deleted as expected'); + $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); $this->deleteUploads(); } @@ -210,7 +210,7 @@ public function test_attachment_deletion_on_page_deletion() $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); - $this->assertTrue(file_exists($filePath), 'File at path '.$filePath.' does not exist'); + $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); $this->assertDatabaseHas('attachments', [ 'name' => $fileName, ]); @@ -221,7 +221,7 @@ public function test_attachment_deletion_on_page_deletion() $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); - $this->assertFalse(file_exists($filePath), 'File at path '.$filePath.' was not deleted as expected'); + $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); $this->deleteUploads(); } @@ -280,7 +280,7 @@ public function test_data_and_js_links_cannot_be_attached_to_a_page() $attachment = $this->createAttachment($page); foreach ($badLinks as $badLink) { - $linkReq = $this->put('attachments/'.$attachment->id, [ + $linkReq = $this->put('attachments/' . $attachment->id, [ 'attachment_edit_url' => $badLink, 'attachment_edit_name' => 'Example Attachment Link', ]); diff --git a/tests/Uploads/AvatarTest.php b/tests/Uploads/AvatarTest.php index 442a4e2b75c..d10b5cfc6cb 100644 --- a/tests/Uploads/AvatarTest.php +++ b/tests/Uploads/AvatarTest.php @@ -43,7 +43,7 @@ public function test_gravatar_fetched_on_user_create() 'services.disable_services' => false, ]); $user = User::factory()->make(); - $this->assertImageFetchFrom('https://www.gravatar.com/avatar/'.md5(strtolower($user->email)).'?s=500&d=identicon'); + $this->assertImageFetchFrom('https://www.gravatar.com/avatar/' . md5(strtolower($user->email)) . '?s=500&d=identicon'); $user = $this->createUserRequest($user); $this->assertDatabaseHas('images', [ @@ -61,7 +61,7 @@ public function test_custom_url_used_if_set() ]); $user = User::factory()->make(); - $url = 'https://example.com/'.urlencode(strtolower($user->email)).'/'.md5(strtolower($user->email)).'/500'; + $url = 'https://example.com/' . urlencode(strtolower($user->email)) . '/' . md5(strtolower($user->email)) . '/500'; $this->assertImageFetchFrom($url); $user = $this->createUserRequest($user); diff --git a/tests/Uploads/DrawioTest.php b/tests/Uploads/DrawioTest.php index df4f98fb48f..1fc3d104928 100644 --- a/tests/Uploads/DrawioTest.php +++ b/tests/Uploads/DrawioTest.php @@ -47,7 +47,7 @@ public function test_drawing_base64_upload() ]); $image = Image::where('type', '=', 'drawio')->first(); - $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: '.public_path($image->path)); + $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: ' . public_path($image->path)); $testImageData = file_get_contents($this->getTestImageFilePath()); $uploadedImageData = file_get_contents(public_path($image->path)); diff --git a/tests/Uploads/ImageTest.php b/tests/Uploads/ImageTest.php index e2bea870144..69b6dc90e96 100644 --- a/tests/Uploads/ImageTest.php +++ b/tests/Uploads/ImageTest.php @@ -22,12 +22,12 @@ public function test_image_upload() $imgDetails = $this->uploadGalleryImage($page); $relPath = $imgDetails['path']; - $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: '.public_path($relPath)); + $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); $this->deleteImage($relPath); $this->assertDatabaseHas('images', [ - 'url' => $this->baseUrl.$relPath, + 'url' => $this->baseUrl . $relPath, 'type' => 'gallery', 'uploaded_to' => $page->id, 'path' => $relPath, @@ -48,7 +48,7 @@ public function test_image_display_thumbnail_generation_does_not_increase_image_ $imgDetails = $this->uploadGalleryImage($page, 'compressed.png'); $relPath = $imgDetails['path']; - $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: '.public_path($relPath)); + $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); $displayImage = $imgDetails['response']->thumbs->display; $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3)); @@ -70,7 +70,7 @@ public function test_image_edit() $image = Image::query()->first(); $newName = Str::random(); - $update = $this->put('/images/'.$image->id, ['name' => $newName]); + $update = $this->put('/images/' . $image->id, ['name' => $newName]); $update->assertSuccessful(); $update->assertSee($newName); @@ -116,10 +116,10 @@ public function test_image_usage() $imgDetails = $this->uploadGalleryImage($page); $image = Image::query()->first(); - $page->html = ''; + $page->html = ''; $page->save(); - $usage = $this->get('/images/edit/'.$image->id.'?delete=true'); + $usage = $this->get('/images/edit/' . $image->id . '?delete=true'); $usage->assertSuccessful(); $usage->assertSeeText($page->name); $usage->assertSee($page->getUrl()); @@ -174,7 +174,7 @@ public function test_files_with_double_extensions_will_get_sanitized() $fileName = 'bad.phtml.png'; $relPath = $this->getTestImagePath('gallery', $fileName); - $expectedRelPath = dirname($relPath).'/bad-phtml.png'; + $expectedRelPath = dirname($relPath) . '/bad-phtml.png'; $this->deleteImage($expectedRelPath); $file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName); @@ -229,12 +229,12 @@ public function test_secure_images_uploads_to_correct_place() $this->asEditor(); $galleryFile = $this->getTestImage('my-secure-test-upload.png'); $page = Page::query()->first(); - $expectedPath = storage_path('uploads/images/gallery/'.date('Y-m').'/my-secure-test-upload.png'); + $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); - $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '.$expectedPath); + $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); @@ -247,7 +247,7 @@ public function test_secure_images_included_in_exports() $this->asEditor(); $galleryFile = $this->getTestImage('my-secure-test-upload.png'); $page = Page::query()->first(); - $expectedPath = storage_path('uploads/images/gallery/'.date('Y-m').'/my-secure-test-upload.png'); + $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $imageUrl = json_decode($upload->getContent(), true)['url']; @@ -269,12 +269,12 @@ public function test_system_images_remain_public() config()->set('filesystems.images', 'local_secure'); $this->asAdmin(); $galleryFile = $this->getTestImage('my-system-test-upload.png'); - $expectedPath = public_path('uploads/images/system/'.date('Y-m').'/my-system-test-upload.png'); + $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png'); $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []); $upload->assertRedirect('/settings'); - $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '.$expectedPath); + $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); @@ -292,11 +292,11 @@ public function test_image_delete() $this->uploadImage($imageName, $page->id); $image = Image::first(); - $delete = $this->delete('/images/'.$image->id); + $delete = $this->delete('/images/' . $image->id); $delete->assertStatus(200); $this->assertDatabaseMissing('images', [ - 'url' => $this->baseUrl.$relPath, + 'url' => $this->baseUrl . $relPath, 'type' => 'gallery', ]); @@ -318,12 +318,12 @@ public function test_image_delete_does_not_delete_similar_images() $image = Image::first(); $folder = public_path(dirname($relPath)); - $imageCount = count(glob($folder.'/*')); + $imageCount = count(glob($folder . '/*')); - $delete = $this->delete('/images/'.$image->id); + $delete = $this->delete('/images/' . $image->id); $delete->assertStatus(200); - $newCount = count(glob($folder.'/*')); + $newCount = count(glob($folder . '/*')); $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted'); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected'); } @@ -344,7 +344,7 @@ public function test_user_image_upload() $this->actingAs($admin); $file = $this->getTestProfileImage(); - $this->call('PUT', '/settings/users/'.$editor->id, [], [], ['profile_image' => $file], []); + $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []); $this->assertDatabaseHas('images', [ 'type' => 'user', @@ -359,7 +359,7 @@ public function test_user_images_deleted_on_user_deletion() $this->actingAs($editor); $file = $this->getTestProfileImage(); - $this->call('PUT', '/settings/users/'.$editor->id, [], [], ['profile_image' => $file], []); + $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []); $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get(); $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count'); @@ -399,7 +399,7 @@ public function test_deleted_unused_images() $pageRepo = app(PageRepo::class); $pageRepo->update($page, [ 'name' => $page->name, - 'html' => $page->html."url}\">", + 'html' => $page->html . "url}\">", 'summary' => '', ]); diff --git a/tests/Uploads/UsesImages.php b/tests/Uploads/UsesImages.php index 3e6875b1a76..789c967c677 100644 --- a/tests/Uploads/UsesImages.php +++ b/tests/Uploads/UsesImages.php @@ -16,7 +16,7 @@ protected function getTestImageFilePath(?string $fileName = null): string $fileName = 'test-image.png'; } - return base_path('tests/test-data/'.$fileName); + return base_path('tests/test-data/' . $fileName); } /** @@ -58,7 +58,7 @@ protected function getTestImageContent() */ protected function getTestImagePath(string $type, string $fileName): string { - return '/uploads/images/'.$type.'/'.date('Y-m').'/'.$fileName; + return '/uploads/images/' . $type . '/' . date('Y-m') . '/' . $fileName; } /** diff --git a/tests/User/UserApiTokenTest.php b/tests/User/UserApiTokenTest.php index 48e7bddb720..d3404b72ef1 100644 --- a/tests/User/UserApiTokenTest.php +++ b/tests/User/UserApiTokenTest.php @@ -50,7 +50,7 @@ public function test_create_api_token() $resp = $this->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp->assertRedirect($editor->getEditUrl('/api-tokens/'.$token->id)); + $resp->assertRedirect($editor->getEditUrl('/api-tokens/' . $token->id)); $this->assertDatabaseHas('api_tokens', [ 'user_id' => $editor->id, 'name' => $this->testTokenData['name'], @@ -58,8 +58,8 @@ public function test_create_api_token() ]); // Check secret token - $this->assertSessionHas('api-token-secret:'.$token->id); - $secret = session('api-token-secret:'.$token->id); + $this->assertSessionHas('api-token-secret:' . $token->id); + $secret = session('api-token-secret:' . $token->id); $this->assertDatabaseMissing('api_tokens', [ 'secret' => $secret, ]); @@ -106,9 +106,9 @@ public function test_secret_shown_once_after_creation() $resp->assertSeeText('Token Secret'); $token = ApiToken::query()->latest()->first(); - $this->assertNull(session('api-token-secret:'.$token->id)); + $this->assertNull(session('api-token-secret:' . $token->id)); - $resp = $this->get($editor->getEditUrl('/api-tokens/'.$token->id)); + $resp = $this->get($editor->getEditUrl('/api-tokens/' . $token->id)); $resp->assertDontSeeText('Client Secret'); } @@ -122,8 +122,8 @@ public function test_token_update() 'expires_at' => '2011-01-01', ]; - $resp = $this->put($editor->getEditUrl('/api-tokens/'.$token->id), $updateData); - $resp->assertRedirect($editor->getEditUrl('/api-tokens/'.$token->id)); + $resp = $this->put($editor->getEditUrl('/api-tokens/' . $token->id), $updateData); + $resp->assertRedirect($editor->getEditUrl('/api-tokens/' . $token->id)); $this->assertDatabaseHas('api_tokens', array_merge($updateData, ['id' => $token->id])); $this->assertSessionHas('success'); @@ -136,7 +136,7 @@ public function test_token_update_with_blank_expiry_sets_to_hundred_years_away() $this->asAdmin()->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp = $this->put($editor->getEditUrl('/api-tokens/'.$token->id), [ + $resp = $this->put($editor->getEditUrl('/api-tokens/' . $token->id), [ 'name' => 'My updated token', 'expires_at' => '', ]); @@ -156,12 +156,12 @@ public function test_token_delete() $this->asAdmin()->post($editor->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $tokenUrl = $editor->getEditUrl('/api-tokens/'.$token->id); + $tokenUrl = $editor->getEditUrl('/api-tokens/' . $token->id); - $resp = $this->get($tokenUrl.'/delete'); + $resp = $this->get($tokenUrl . '/delete'); $resp->assertSeeText('Delete Token'); $resp->assertSeeText($token->name); - $resp->assertElementExists('form[action="'.$tokenUrl.'"]'); + $resp->assertElementExists('form[action="' . $tokenUrl . '"]'); $resp = $this->delete($tokenUrl); $resp->assertRedirect($editor->getEditUrl('#api_tokens')); @@ -178,11 +178,11 @@ public function test_user_manage_can_delete_token_without_api_permission_themsel $this->asAdmin()->post($viewer->getEditUrl('/create-api-token'), $this->testTokenData); $token = ApiToken::query()->latest()->first(); - $resp = $this->actingAs($editor)->get($viewer->getEditUrl('/api-tokens/'.$token->id)); + $resp = $this->actingAs($editor)->get($viewer->getEditUrl('/api-tokens/' . $token->id)); $resp->assertStatus(200); $resp->assertSeeText('Delete Token'); - $resp = $this->actingAs($editor)->delete($viewer->getEditUrl('/api-tokens/'.$token->id)); + $resp = $this->actingAs($editor)->delete($viewer->getEditUrl('/api-tokens/' . $token->id)); $resp->assertRedirect($viewer->getEditUrl('#api_tokens')); $this->assertDatabaseMissing('api_tokens', ['id' => $token->id]); } diff --git a/tests/User/UserManagementTest.php b/tests/User/UserManagementTest.php index 05e54654718..5a36b85df6f 100644 --- a/tests/User/UserManagementTest.php +++ b/tests/User/UserManagementTest.php @@ -19,17 +19,17 @@ public function test_user_creation() $adminRole = Role::getRole('admin'); $resp = $this->asAdmin()->get('/settings/users'); - $resp->assertElementContains('a[href="'.url('/settings/users/create').'"]', 'Add New User'); + $resp->assertElementContains('a[href="' . url('/settings/users/create') . '"]', 'Add New User'); $this->get('/settings/users/create') - ->assertElementContains('form[action="'.url('/settings/users/create').'"]', 'Save'); + ->assertElementContains('form[action="' . url('/settings/users/create') . '"]', 'Save'); $resp = $this->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'password' => $user->password, 'password-confirm' => $user->password, - 'roles['.$adminRole->id.']' => 'true', + 'roles[' . $adminRole->id . ']' => 'true', ]); $resp->assertRedirect('/settings/users'); @@ -47,7 +47,7 @@ public function test_user_updating() $user = $this->getNormalUser(); $password = $user->password; - $resp = $this->asAdmin()->get('/settings/users/'.$user->id); + $resp = $this->asAdmin()->get('/settings/users/' . $user->id); $resp->assertSee($user->email); $this->put($user->getEditUrl(), [ @@ -64,7 +64,7 @@ public function test_user_updating() public function test_user_password_update() { $user = $this->getNormalUser(); - $userProfilePage = '/settings/users/'.$user->id; + $userProfilePage = '/settings/users/' . $user->id; $this->asAdmin()->get($userProfilePage); $this->put($userProfilePage, [ @@ -100,10 +100,10 @@ public function test_user_cannot_be_deleted_if_last_admin() /** @var User $user */ $user = $adminRole->users->first(); - $resp = $this->asAdmin()->delete('/settings/users/'.$user->id); - $resp->assertRedirect('/settings/users/'.$user->id); + $resp = $this->asAdmin()->delete('/settings/users/' . $user->id); + $resp->assertRedirect('/settings/users/' . $user->id); - $resp = $this->get('/settings/users/'.$user->id); + $resp = $this->get('/settings/users/' . $user->id); $resp->assertSee('You cannot delete the only admin'); $this->assertDatabaseHas('users', ['id' => $user->id]); @@ -146,7 +146,7 @@ public function test_delete_with_new_owner_id_changes_ownership() public function test_guest_profile_shows_limited_form() { $guest = User::getDefault(); - $resp = $this->asAdmin()->get('/settings/users/'.$guest->id); + $resp = $this->asAdmin()->get('/settings/users/' . $guest->id); $resp->assertSee('Guest'); $resp->assertElementNotExists('#password'); } @@ -154,13 +154,13 @@ public function test_guest_profile_shows_limited_form() public function test_guest_profile_cannot_be_deleted() { $guestUser = User::getDefault(); - $resp = $this->asAdmin()->get('/settings/users/'.$guestUser->id.'/delete'); + $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete'); $resp->assertSee('Delete User'); $resp->assertSee('Guest'); - $resp->assertElementContains('form[action$="/settings/users/'.$guestUser->id.'"] button', 'Confirm'); + $resp->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm'); - $resp = $this->delete('/settings/users/'.$guestUser->id); - $resp->assertRedirect('/settings/users/'.$guestUser->id); + $resp = $this->delete('/settings/users/' . $guestUser->id); + $resp->assertRedirect('/settings/users/' . $guestUser->id); $resp = $this->followRedirects($resp); $resp->assertSee('cannot delete the guest user'); } diff --git a/tests/User/UserPreferencesTest.php b/tests/User/UserPreferencesTest.php index 651bee26d23..b39c2c47c84 100644 --- a/tests/User/UserPreferencesTest.php +++ b/tests/User/UserPreferencesTest.php @@ -12,18 +12,18 @@ public function test_update_sort_preference() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/books', [ + $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/books', [ 'sort' => 'created_at', 'order' => 'desc', ]); $updateRequest->assertStatus(302); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:'.$editor->id.':books_sort', + 'setting_key' => 'user:' . $editor->id . ':books_sort', 'value' => 'created_at', ]); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:'.$editor->id.':books_sort_order', + 'setting_key' => 'user:' . $editor->id . ':books_sort_order', 'value' => 'desc', ]); $this->assertEquals('created_at', setting()->getForCurrentUser('books_sort')); @@ -35,7 +35,7 @@ public function test_update_sort_preference_defaults() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/bookshelves', [ + $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/bookshelves', [ 'sort' => 'cat', 'order' => 'dog', ]); @@ -50,7 +50,7 @@ public function test_update_sort_bad_entity_type_handled() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/'.$editor->id.'/change-sort/dogs', [ + $updateRequest = $this->patch('/settings/users/' . $editor->id . '/change-sort/dogs', [ 'sort' => 'name', 'order' => 'asc', ]); @@ -65,16 +65,16 @@ public function test_update_expansion_preference() $editor = $this->getEditor(); $this->actingAs($editor); - $updateRequest = $this->patch('/settings/users/'.$editor->id.'/update-expansion-preference/home-details', ['expand' => 'true']); + $updateRequest = $this->patch('/settings/users/' . $editor->id . '/update-expansion-preference/home-details', ['expand' => 'true']); $updateRequest->assertStatus(204); $this->assertDatabaseHas('settings', [ - 'setting_key' => 'user:'.$editor->id.':section_expansion#home-details', + 'setting_key' => 'user:' . $editor->id . ':section_expansion#home-details', 'value' => 'true', ]); $this->assertEquals(true, setting()->getForCurrentUser('section_expansion#home-details')); - $invalidKeyRequest = $this->patch('/settings/users/'.$editor->id.'/update-expansion-preference/my-home-details', ['expand' => 'true']); + $invalidKeyRequest = $this->patch('/settings/users/' . $editor->id . '/update-expansion-preference/my-home-details', ['expand' => 'true']); $invalidKeyRequest->assertStatus(500); } diff --git a/tests/User/UserProfileTest.php b/tests/User/UserProfileTest.php index 34e6443e629..c3888f8c511 100644 --- a/tests/User/UserProfileTest.php +++ b/tests/User/UserProfileTest.php @@ -23,7 +23,7 @@ protected function setUp(): void public function test_profile_page_shows_name() { $this->asAdmin() - ->get('/user/'.$this->user->slug) + ->get('/user/' . $this->user->slug) ->assertSee($this->user->name); } @@ -31,7 +31,7 @@ public function test_profile_page_shows_recent_entities() { $content = $this->createEntityChainBelongingToUser($this->user, $this->user); - $resp = $this->asAdmin()->get('/user/'.$this->user->slug); + $resp = $this->asAdmin()->get('/user/' . $this->user->slug); // Check the recently created page is shown $resp->assertSee($content['page']->name); // Check the recently created chapter is shown @@ -44,7 +44,7 @@ public function test_profile_page_shows_created_content_counts() { $newUser = User::factory()->create(); - $this->asAdmin()->get('/user/'.$newUser->slug) + $this->asAdmin()->get('/user/' . $newUser->slug) ->assertSee($newUser->name) ->assertElementContains('#content-counts', '0 Books') ->assertElementContains('#content-counts', '0 Chapters') @@ -52,7 +52,7 @@ public function test_profile_page_shows_created_content_counts() $this->createEntityChainBelongingToUser($newUser, $newUser); - $this->asAdmin()->get('/user/'.$newUser->slug) + $this->asAdmin()->get('/user/' . $newUser->slug) ->assertSee($newUser->name) ->assertElementContains('#content-counts', '1 Book') ->assertElementContains('#content-counts', '1 Chapter') @@ -67,7 +67,7 @@ public function test_profile_page_shows_recent_activity() Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); Activity::addForEntity($entities['page'], ActivityType::PAGE_CREATE); - $this->asAdmin()->get('/user/'.$newUser->slug) + $this->asAdmin()->get('/user/' . $newUser->slug) ->assertElementContains('#recent-user-activity', 'updated book') ->assertElementContains('#recent-user-activity', 'created page') ->assertElementContains('#recent-user-activity', $entities['page']->name); @@ -81,7 +81,7 @@ public function test_user_activity_has_link_leading_to_profile() Activity::addForEntity($entities['book'], ActivityType::BOOK_UPDATE); Activity::addForEntity($entities['page'], ActivityType::PAGE_CREATE); - $linkSelector = '#recent-activity a[href$="/user/'.$newUser->slug.'"]'; + $linkSelector = '#recent-activity a[href$="/user/' . $newUser->slug . '"]'; $this->asAdmin()->get('/') ->assertElementContains($linkSelector, $newUser->name); } @@ -89,17 +89,17 @@ public function test_user_activity_has_link_leading_to_profile() public function test_profile_has_search_links_in_created_entity_lists() { $user = $this->getEditor(); - $resp = $this->actingAs($this->getAdmin())->get('/user/'.$user->slug); + $resp = $this->actingAs($this->getAdmin())->get('/user/' . $user->slug); $expectedLinks = [ - '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Apage%7D', - '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Achapter%7D', - '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Abook%7D', - '/search?term=%7Bcreated_by%3A'.$user->slug.'%7D+%7Btype%3Abookshelf%7D', + '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Apage%7D', + '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Achapter%7D', + '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abook%7D', + '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abookshelf%7D', ]; foreach ($expectedLinks as $link) { - $resp->assertElementContains('[href$="'.$link.'"]', 'View All'); + $resp->assertElementContains('[href$="' . $link . '"]', 'View All'); } } } From 74f6f21accbd7fa33c3cb491452bd489b9205438 Mon Sep 17 00:00:00 2001 From: Dan Brown Date: Sat, 30 Oct 2021 20:30:35 +0100 Subject: [PATCH 18/19] Reverted config files location --- app/Application.php | 13 ++++++------- {config => app/Config}/api.php | 0 {config => app/Config}/app.php | 0 {config => app/Config}/auth.php | 0 {config => app/Config}/broadcasting.php | 0 {config => app/Config}/cache.php | 0 {config => app/Config}/cors.php | 0 {config => app/Config}/database.php | 0 {config => app/Config}/debugbar.php | 0 {config => app/Config}/dompdf.php | 0 {config => app/Config}/filesystems.php | 0 {config => app/Config}/hashing.php | 0 {config => app/Config}/logging.php | 0 {config => app/Config}/mail.php | 0 {config => app/Config}/oidc.php | 0 {config => app/Config}/queue.php | 0 {config => app/Config}/saml2.php | 0 {config => app/Config}/services.php | 0 {config => app/Config}/session.php | 0 {config => app/Config}/setting-defaults.php | 0 {config => app/Config}/snappy.php | 0 {config => app/Config}/view.php | 0 22 files changed, 6 insertions(+), 7 deletions(-) rename {config => app/Config}/api.php (100%) rename {config => app/Config}/app.php (100%) rename {config => app/Config}/auth.php (100%) rename {config => app/Config}/broadcasting.php (100%) rename {config => app/Config}/cache.php (100%) rename {config => app/Config}/cors.php (100%) rename {config => app/Config}/database.php (100%) rename {config => app/Config}/debugbar.php (100%) rename {config => app/Config}/dompdf.php (100%) rename {config => app/Config}/filesystems.php (100%) rename {config => app/Config}/hashing.php (100%) rename {config => app/Config}/logging.php (100%) rename {config => app/Config}/mail.php (100%) rename {config => app/Config}/oidc.php (100%) rename {config => app/Config}/queue.php (100%) rename {config => app/Config}/saml2.php (100%) rename {config => app/Config}/services.php (100%) rename {config => app/Config}/session.php (100%) rename {config => app/Config}/setting-defaults.php (100%) rename {config => app/Config}/snappy.php (100%) rename {config => app/Config}/view.php (100%) diff --git a/app/Application.php b/app/Application.php index c9117e9803a..d409d14bc26 100644 --- a/app/Application.php +++ b/app/Application.php @@ -13,12 +13,11 @@ class Application extends \Illuminate\Foundation\Application */ public function configPath($path = '') { - return parent::configPath($path); -// return $this->basePath -// . DIRECTORY_SEPARATOR -// . 'app' -// . DIRECTORY_SEPARATOR -// . 'Config' -// . ($path ? DIRECTORY_SEPARATOR . $path : $path); + return $this->basePath + . DIRECTORY_SEPARATOR + . 'app' + . DIRECTORY_SEPARATOR + . 'Config' + . ($path ? DIRECTORY_SEPARATOR . $path : $path); } } diff --git a/config/api.php b/app/Config/api.php similarity index 100% rename from config/api.php rename to app/Config/api.php diff --git a/config/app.php b/app/Config/app.php similarity index 100% rename from config/app.php rename to app/Config/app.php diff --git a/config/auth.php b/app/Config/auth.php similarity index 100% rename from config/auth.php rename to app/Config/auth.php diff --git a/config/broadcasting.php b/app/Config/broadcasting.php similarity index 100% rename from config/broadcasting.php rename to app/Config/broadcasting.php diff --git a/config/cache.php b/app/Config/cache.php similarity index 100% rename from config/cache.php rename to app/Config/cache.php diff --git a/config/cors.php b/app/Config/cors.php similarity index 100% rename from config/cors.php rename to app/Config/cors.php diff --git a/config/database.php b/app/Config/database.php similarity index 100% rename from config/database.php rename to app/Config/database.php diff --git a/config/debugbar.php b/app/Config/debugbar.php similarity index 100% rename from config/debugbar.php rename to app/Config/debugbar.php diff --git a/config/dompdf.php b/app/Config/dompdf.php similarity index 100% rename from config/dompdf.php rename to app/Config/dompdf.php diff --git a/config/filesystems.php b/app/Config/filesystems.php similarity index 100% rename from config/filesystems.php rename to app/Config/filesystems.php diff --git a/config/hashing.php b/app/Config/hashing.php similarity index 100% rename from config/hashing.php rename to app/Config/hashing.php diff --git a/config/logging.php b/app/Config/logging.php similarity index 100% rename from config/logging.php rename to app/Config/logging.php diff --git a/config/mail.php b/app/Config/mail.php similarity index 100% rename from config/mail.php rename to app/Config/mail.php diff --git a/config/oidc.php b/app/Config/oidc.php similarity index 100% rename from config/oidc.php rename to app/Config/oidc.php diff --git a/config/queue.php b/app/Config/queue.php similarity index 100% rename from config/queue.php rename to app/Config/queue.php diff --git a/config/saml2.php b/app/Config/saml2.php similarity index 100% rename from config/saml2.php rename to app/Config/saml2.php diff --git a/config/services.php b/app/Config/services.php similarity index 100% rename from config/services.php rename to app/Config/services.php diff --git a/config/session.php b/app/Config/session.php similarity index 100% rename from config/session.php rename to app/Config/session.php diff --git a/config/setting-defaults.php b/app/Config/setting-defaults.php similarity index 100% rename from config/setting-defaults.php rename to app/Config/setting-defaults.php diff --git a/config/snappy.php b/app/Config/snappy.php similarity index 100% rename from config/snappy.php rename to app/Config/snappy.php diff --git a/config/view.php b/app/Config/view.php similarity index 100% rename from config/view.php rename to app/Config/view.php From 0f86c9e2a3e89909273c12c377e3ca927211f84f Mon Sep 17 00:00:00 2001 From: Dan Brown Date: Sat, 30 Oct 2021 21:26:51 +0100 Subject: [PATCH 19/19] Applied manual changes to Laravel 8 shift --- app/Config/app.php | 13 +- app/Config/auth.php | 109 +-- app/Config/broadcasting.php | 101 +-- app/Config/cors.php | 34 - app/Config/filesystems.php | 78 +-- app/Config/logging.php | 94 ++- app/Config/queue.php | 71 +- .../Middleware/RedirectIfAuthenticated.php | 42 +- app/Providers/AppServiceProvider.php | 4 + app/Providers/RouteServiceProvider.php | 9 + composer.json | 25 +- composer.lock | 629 ++++++++++-------- database/factories/Actions/CommentFactory.php | 11 - database/factories/Actions/TagFactory.php | 11 - database/factories/Auth/RoleFactory.php | 11 - database/factories/Auth/UserFactory.php | 11 - .../factories/Entities/Models/BookFactory.php | 11 - .../Entities/Models/BookshelfFactory.php | 11 - .../Entities/Models/ChapterFactory.php | 11 - .../factories/Entities/Models/PageFactory.php | 11 - database/factories/Uploads/ImageFactory.php | 11 - public/index.php | 53 +- routes/api.php | 18 +- tests/Entity/TagTest.php | 24 +- 24 files changed, 611 insertions(+), 792 deletions(-) delete mode 100644 app/Config/cors.php diff --git a/app/Config/app.php b/app/Config/app.php index 3e40259817a..44e382cdcb5 100644 --- a/app/Config/app.php +++ b/app/Config/app.php @@ -143,9 +143,6 @@ // Class aliases, Registered on application start 'aliases' => [ - 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, - 'Date' => Illuminate\Support\Facades\Date::class, - // Laravel 'App' => Illuminate\Support\Facades\App::class, 'Arr' => Illuminate\Support\Arr::class, @@ -157,21 +154,23 @@ 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, + 'Date' => Illuminate\Support\Facades\Date::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, + 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, - 'Input' => Illuminate\Support\Facades\Input::class, - 'Inspiring' => Illuminate\Foundation\Inspiring::class, + 'Http' => Illuminate\Support\Facades\Http::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, + 'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, - 'Redis' => Illuminate\Support\Facades\Redis::class, + // 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, @@ -182,6 +181,8 @@ 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, + + // Laravel Packages 'Socialite' => Laravel\Socialite\Facades\Socialite::class, // Third Party diff --git a/app/Config/auth.php b/app/Config/auth.php index 1c3bb3edddf..1e1a9d3507c 100644 --- a/app/Config/auth.php +++ b/app/Config/auth.php @@ -1,86 +1,57 @@ env('AUTH_METHOD', 'standard'), - /* - |-------------------------------------------------------------------------- - | Authentication Defaults - |-------------------------------------------------------------------------- - | - | This option controls the default authentication "guard" and password - | reset options for your application. You may change these defaults - | as required, but they're a perfect start for most applications. - | - */ - + // Authentication Defaults + // This option controls the default authentication "guard" and password + // reset options for your application. 'defaults' => [ 'guard' => env('AUTH_METHOD', 'standard'), 'passwords' => 'users', ], - /* - |-------------------------------------------------------------------------- - | Authentication Guards - |-------------------------------------------------------------------------- - | - | Next, you may define every authentication guard for your application. - | Of course, a great default configuration has been defined for you - | here which uses session storage and the Eloquent user provider. - | - | All authentication drivers have a user provider. This defines how the - | users are actually retrieved out of your database or other storage - | mechanisms used by this application to persist your user's data. - | - | Supported: "session" - | - */ - + // Authentication Guards + // All authentication drivers have a user provider. This defines how the + // users are actually retrieved out of your database or other storage + // mechanisms used by this application to persist your user's data. + // Supported drivers: "session", "api-token", "ldap-session", "async-external-session" 'guards' => [ 'standard' => [ 'driver' => 'session', 'provider' => 'users', ], - 'ldap' => [ 'driver' => 'ldap-session', 'provider' => 'external', ], - 'saml2' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], - 'oidc' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], - - 'web' => [ - 'driver' => 'session', - 'provider' => 'users', + 'api' => [ + 'driver' => 'api-token', ], ], - /* - |-------------------------------------------------------------------------- - | User Providers - |-------------------------------------------------------------------------- - | - | All authentication drivers have a user provider. This defines how the - | users are actually retrieved out of your database or other storage - | mechanisms used by this application to persist your user's data. - | - | If you have multiple user tables or models you may configure multiple - | sources which represent each model / table. These sources may then - | be assigned to any extra authentication guards you have defined. - | - | Supported: "database", "eloquent" - | - */ - + // User Providers + // All authentication drivers have a user provider. This defines how the + // users are actually retrieved out of your database or other storage + // mechanisms used by this application to persist your user's data. 'providers' => [ 'users' => [ 'driver' => 'eloquent', @@ -98,21 +69,10 @@ // ], ], - /* - |-------------------------------------------------------------------------- - | Resetting Passwords - |-------------------------------------------------------------------------- - | - | You may specify multiple password reset configurations if you have more - | than one user table or model in the application and you want to have - | separate password reset settings based on the specific user types. - | - | The expire time is the number of minutes that the reset token should be - | considered valid. This security feature keeps tokens short-lived so - | they have less time to be guessed. You may change this as needed. - | - */ - + // Resetting Passwords + // The expire time is the number of minutes that the reset token should be + // considered valid. This security feature keeps tokens short-lived so + // they have less time to be guessed. You may change this as needed. 'passwords' => [ 'users' => [ 'provider' => 'users', @@ -123,17 +83,10 @@ ], ], - /* - |-------------------------------------------------------------------------- - | Password Confirmation Timeout - |-------------------------------------------------------------------------- - | - | Here you may define the amount of seconds before a password confirmation - | times out and the user is prompted to re-enter their password via the - | confirmation screen. By default, the timeout lasts for three hours. - | - */ - + // Password Confirmation Timeout + // Here you may define the amount of seconds before a password confirmation + // times out and the user is prompted to re-enter their password via the + // confirmation screen. By default, the timeout lasts for three hours. 'password_timeout' => 10800, ]; diff --git a/app/Config/broadcasting.php b/app/Config/broadcasting.php index 59bccd52243..be0d7376c7f 100644 --- a/app/Config/broadcasting.php +++ b/app/Config/broadcasting.php @@ -1,64 +1,79 @@ $memcachedServer) { + $memcachedServerDetails = explode(':', $memcachedServer); + if (count($memcachedServerDetails) < 2) { + $memcachedServerDetails[] = '11211'; + } + if (count($memcachedServerDetails) < 3) { + $memcachedServerDetails[] = '100'; + } + $memcachedServers[$index] = array_combine($memcachedServerKeys, $memcachedServerDetails); + } +} + return [ - /* - |-------------------------------------------------------------------------- - | Default Broadcaster - |-------------------------------------------------------------------------- - | - | This option controls the default broadcaster that will be used by the - | framework when an event needs to be broadcast. You may set this to - | any of the connections defined in the "connections" array below. - | - | Supported: "pusher", "ably", "redis", "log", "null" - | - */ + // Default cache store to use + // Can be overridden at cache call-time + 'default' => env('CACHE_DRIVER', 'file'), - 'default' => env('BROADCAST_DRIVER', 'null'), + // Available caches stores + 'stores' => [ - /* - |-------------------------------------------------------------------------- - | Broadcast Connections - |-------------------------------------------------------------------------- - | - | Here you may define all of the broadcast connections that will be used - | to broadcast events to other systems or over websockets. Samples of - | each available type of connection are provided inside this array. - | - */ + 'apc' => [ + 'driver' => 'apc', + ], - 'connections' => [ + 'array' => [ + 'driver' => 'array', + 'serialize' => false, + ], - 'pusher' => [ - 'driver' => 'pusher', - 'key' => env('PUSHER_APP_KEY'), - 'secret' => env('PUSHER_APP_SECRET'), - 'app_id' => env('PUSHER_APP_ID'), - 'options' => [ - 'cluster' => env('PUSHER_APP_CLUSTER'), - 'useTLS' => true, - ], + 'database' => [ + 'driver' => 'database', + 'table' => 'cache', + 'connection' => null, + 'lock_connection' => null, ], - 'ably' => [ - 'driver' => 'ably', - 'key' => env('ABLY_KEY'), + 'file' => [ + 'driver' => 'file', + 'path' => storage_path('framework/cache'), ], - 'redis' => [ - 'driver' => 'redis', - 'connection' => 'default', + 'memcached' => [ + 'driver' => 'memcached', + 'servers' => env('CACHE_DRIVER') === 'memcached' ? $memcachedServers : [], + 'options' => [], ], - 'log' => [ - 'driver' => 'log', + 'redis' => [ + 'driver' => 'redis', + 'connection' => 'default', + 'lock_connection' => 'default', ], - 'null' => [ - 'driver' => 'null', + 'octane' => [ + 'driver' => 'octane', ], ], + // Cache key prefix + // Used to prevent collisions in shared cache systems. + 'prefix' => env('CACHE_PREFIX', 'bookstack_cache'), + ]; diff --git a/app/Config/cors.php b/app/Config/cors.php deleted file mode 100644 index 8a39e6daa63..00000000000 --- a/app/Config/cors.php +++ /dev/null @@ -1,34 +0,0 @@ - ['api/*', 'sanctum/csrf-cookie'], - - 'allowed_methods' => ['*'], - - 'allowed_origins' => ['*'], - - 'allowed_origins_patterns' => [], - - 'allowed_headers' => ['*'], - - 'exposed_headers' => [], - - 'max_age' => 0, - - 'supports_credentials' => false, - -]; diff --git a/app/Config/filesystems.php b/app/Config/filesystems.php index b3fa5fc2577..4d59ba9192d 100644 --- a/app/Config/filesystems.php +++ b/app/Config/filesystems.php @@ -1,44 +1,38 @@ env('FILESYSTEM_DRIVER', 'local'), + // Default Filesystem Disk + // Options: local, local_secure, s3 + 'default' => env('STORAGE_TYPE', 'local'), + // Filesystem to use specifically for image uploads. 'images' => env('STORAGE_IMAGE_TYPE', env('STORAGE_TYPE', 'local')), + // Filesystem to use specifically for file attachments. 'attachments' => env('STORAGE_ATTACHMENT_TYPE', env('STORAGE_TYPE', 'local')), + // Storage URL + // This is the url to where the storage is located for when using an external + // file storage service, such as s3, to store publicly accessible assets. 'url' => env('STORAGE_URL', false), - /* - |-------------------------------------------------------------------------- - | Filesystem Disks - |-------------------------------------------------------------------------- - | - | Here you may configure as many filesystem "disks" as you wish, and you - | may even configure multiple disks of the same driver. Defaults have - | been setup for each driver as an example of the required options. - | - | Supported Drivers: "local", "ftp", "sftp", "s3" - | - */ - + // Available filesystem disks + // Only local, local_secure & s3 are supported by BookStack 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => public_path(), + 'visibility' => 'public', ], 'local_secure_attachments' => [ @@ -49,39 +43,25 @@ 'local_secure_images' => [ 'driver' => 'local', 'root' => storage_path('uploads/images/'), - ], - - 'public' => [ - 'driver' => 'local', - 'root' => storage_path('app/public'), - 'url' => env('APP_URL') . '/storage', 'visibility' => 'public', ], 's3' => [ 'driver' => 's3', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION'), - 'bucket' => env('AWS_BUCKET'), - 'url' => env('AWS_URL'), - 'endpoint' => env('AWS_ENDPOINT'), - 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), + 'key' => env('STORAGE_S3_KEY', 'your-key'), + 'secret' => env('STORAGE_S3_SECRET', 'your-secret'), + 'region' => env('STORAGE_S3_REGION', 'your-region'), + 'bucket' => env('STORAGE_S3_BUCKET', 'your-bucket'), + 'endpoint' => env('STORAGE_S3_ENDPOINT', null), + 'use_path_style_endpoint' => env('STORAGE_S3_ENDPOINT', null) !== null, ], ], - /* - |-------------------------------------------------------------------------- - | Symbolic Links - |-------------------------------------------------------------------------- - | - | Here you may configure the symbolic links that will be created when the - | `storage:link` Artisan command is executed. The array keys should be - | the locations of the links and the values should be their targets. - | - */ - + // Symbolic Links + // Here you may configure the symbolic links that will be created when the + // `storage:link` Artisan command is executed. The array keys should be + // the locations of the links and the values should be their targets. 'links' => [ public_path('storage') => storage_path('app/public'), ], diff --git a/app/Config/logging.php b/app/Config/logging.php index 48022940555..2b80147c8c7 100644 --- a/app/Config/logging.php +++ b/app/Config/logging.php @@ -1,39 +1,33 @@ env('LOG_CHANNEL', 'stack'), - - /* - |-------------------------------------------------------------------------- - | Log Channels - |-------------------------------------------------------------------------- - | - | Here you may configure the log channels for your application. Out of - | the box, Laravel uses the Monolog PHP logging library. This gives - | you a variety of powerful log handlers / formatters to utilize. - | - | Available Drivers: "single", "daily", "slack", "syslog", - | "errorlog", "monolog", - | "custom", "stack" - | - */ +return [ + // Default Log Channel + // This option defines the default log channel that gets used when writing + // messages to the logs. The name specified in this option should match + // one of the channels defined in the "channels" configuration array. + 'default' => env('LOG_CHANNEL', 'single'), + + // Log Channels + // Here you may configure the log channels for your application. Out of + // the box, Laravel uses the Monolog PHP logging library. This gives + // you a variety of powerful log handlers / formatters to utilize. + // Available Drivers: "single", "daily", "slack", "syslog", + // "errorlog", "monolog", + // "custom", "stack" 'channels' => [ 'stack' => [ 'driver' => 'stack', @@ -44,55 +38,38 @@ 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => 'debug', 'days' => 14, ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => 'debug', 'days' => 7, ], - 'slack' => [ - 'driver' => 'slack', - 'url' => env('LOG_SLACK_WEBHOOK_URL'), - 'username' => 'Laravel Log', - 'emoji' => ':boom:', - 'level' => env('LOG_LEVEL', 'critical'), - ], - - 'papertrail' => [ - 'driver' => 'monolog', - 'level' => env('LOG_LEVEL', 'debug'), - 'handler' => SyslogUdpHandler::class, - 'handler_with' => [ - 'host' => env('PAPERTRAIL_URL'), - 'port' => env('PAPERTRAIL_PORT'), - ], - ], - 'stderr' => [ - 'driver' => 'monolog', - 'level' => env('LOG_LEVEL', 'debug'), - 'handler' => StreamHandler::class, - 'formatter' => env('LOG_STDERR_FORMATTER'), - 'with' => [ + 'driver' => 'monolog', + 'level' => 'debug', + 'handler' => StreamHandler::class, + 'with' => [ 'stream' => 'php://stderr', ], ], 'syslog' => [ 'driver' => 'syslog', - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => 'debug', ], 'errorlog' => [ 'driver' => 'errorlog', - 'level' => env('LOG_LEVEL', 'debug'), + 'level' => 'debug', ], + // Custom errorlog implementation that logs out a plain, + // non-formatted message intended for the webserver log. 'errorlog_plain_webserver' => [ 'driver' => 'monolog', 'level' => 'debug', @@ -109,6 +86,9 @@ 'handler' => NullHandler::class, ], + // Testing channel + // Uses a shared testing instance during tests + // so that logs can be checked against. 'testing' => [ 'driver' => 'testing', ], @@ -118,6 +98,8 @@ ], ], + // Failed Login Message + // Allows a configurable message to be logged when a login request fails. 'failed_login' => [ 'message' => env('LOG_FAILED_LOGIN_MESSAGE', null), 'channel' => env('LOG_FAILED_LOGIN_CHANNEL', 'errorlog_plain_webserver'), diff --git a/app/Config/queue.php b/app/Config/queue.php index 84f74388b23..0f5ee3ce594 100644 --- a/app/Config/queue.php +++ b/app/Config/queue.php @@ -1,33 +1,20 @@ env('QUEUE_CONNECTION', 'sync'), - /* - |-------------------------------------------------------------------------- - | Queue Connections - |-------------------------------------------------------------------------- - | - | Here you may configure the connection information for each server that - | is used by your application. A default configuration has been added - | for each back-end shipped with Laravel. You are free to add more. - | - | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" - | - */ - + // Queue connection configuration 'connections' => [ 'sync' => [ @@ -42,26 +29,6 @@ 'after_commit' => false, ], - 'beanstalkd' => [ - 'driver' => 'beanstalkd', - 'host' => 'localhost', - 'queue' => 'default', - 'retry_after' => 90, - 'block_for' => 0, - 'after_commit' => false, - ], - - 'sqs' => [ - 'driver' => 'sqs', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), - 'queue' => env('SQS_QUEUE', 'default'), - 'suffix' => env('SQS_SUFFIX'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - 'after_commit' => false, - ], - 'redis' => [ 'driver' => 'redis', 'connection' => 'default', @@ -73,20 +40,10 @@ ], - /* - |-------------------------------------------------------------------------- - | Failed Queue Jobs - |-------------------------------------------------------------------------- - | - | These options configure the behavior of failed queue job logging so you - | can control which database and table are used to store the jobs that - | have failed. You may change them to any database / table you wish. - | - */ - + // Failed queue job logging 'failed' => [ - 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), - 'database' => env('DB_CONNECTION', 'mysql'), + 'driver' => 'database-uuids', + 'database' => 'mysql', 'table' => 'failed_jobs', ], diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 6853809ea9d..76e64a3b9d6 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -2,45 +2,31 @@ namespace BookStack\Http\Middleware; +use BookStack\Providers\RouteServiceProvider; use Closure; -use Illuminate\Contracts\Auth\Guard; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; class RedirectIfAuthenticated { - /** - * The Guard implementation. - * - * @var Guard - */ - protected $auth; - - /** - * Create a new filter instance. - * - * @param Guard $auth - * - * @return void - */ - public function __construct(Guard $auth) - { - $this->auth = $auth; - } - /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null ...$guards * @return mixed */ - public function handle($request, Closure $next) + public function handle(Request $request, Closure $next, ...$guards) { - $requireConfirmation = setting('registration-confirmation'); - if ($this->auth->check() && (!$requireConfirmation || ($requireConfirmation && $this->auth->user()->email_confirmed))) { - return redirect('/'); + $guards = empty($guards) ? [null] : $guards; + + foreach ($guards as $guard) { + if (Auth::guard($guard)->check()) { + return redirect(RouteServiceProvider::HOME); + } } return $next($request); } -} +} \ No newline at end of file diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 34a3a290f0c..fc712632e9b 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -16,6 +16,7 @@ use GuzzleHttp\Client; use Illuminate\Contracts\Cache\Repository; use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\URL; @@ -60,6 +61,9 @@ public function boot() // View Composers View::composer('entities.breadcrumbs', BreadcrumbsViewComposer::class); + + // Set paginator to use bootstrap-style pagination + Paginator::useBootstrap(); } /** diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 82d57703fad..ac3307f2ded 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -10,6 +10,15 @@ class RouteServiceProvider extends ServiceProvider { + /** + * The path to the "home" route for your application. + * + * This is used by Laravel authentication to redirect users after login. + * + * @var string + */ + public const HOME = '/'; + /** * This namespace is applied to the controller routes in your routes file. * diff --git a/composer.json b/composer.json index 9256b6e96cf..c1d5c1e4b77 100644 --- a/composer.json +++ b/composer.json @@ -21,9 +21,12 @@ "barryvdh/laravel-snappy": "^0.4.8", "doctrine/dbal": "^3.1", "filp/whoops": "^2.14", + "guzzlehttp/guzzle": "^7.4", "intervention/image": "^2.7", "laravel/framework": "^8.68", "laravel/socialite": "^5.2", + "laravel/tinker": "^2.5", + "laravel/ui": "^3.3", "league/commonmark": "^1.5", "league/flysystem-aws-s3-v3": "^1.0.29", "league/html-to-markdown": "^5.0.0", @@ -31,18 +34,14 @@ "onelogin/php-saml": "^4.0", "phpseclib/phpseclib": "~3.0", "pragmarx/google2fa": "^8.0", - "predis/predis": "^1.1.6", + "predis/predis": "^1.1", "socialiteproviders/discord": "^4.1", "socialiteproviders/gitlab": "^4.1", "socialiteproviders/microsoft-azure": "^4.1", "socialiteproviders/okta": "^4.1", "socialiteproviders/slack": "^4.1", "socialiteproviders/twitch": "^5.3", - "ssddanbrown/htmldiff": "^1.0.1", - "laravel/ui": "^3.3", - "guzzlehttp/guzzle": "^7.4.0", - "laravel/tinker": "^2.5", - "fruitcake/laravel-cors": "^2.0" + "ssddanbrown/htmldiff": "^1.0.1" }, "require-dev": { "barryvdh/laravel-debugbar": "^3.6", @@ -50,8 +49,7 @@ "mockery/mockery": "^1.4.2", "phpunit/phpunit": "^9.5.3", "symfony/dom-crawler": "^5.3", - "nunomaduro/collision": "^5.0", - "facade/ignition": "^2.5" + "nunomaduro/collision": "^5.0" }, "autoload": { "psr-4": { @@ -69,6 +67,10 @@ } }, "scripts": { + "post-autoload-dump": [ + "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", + "@php artisan package:discover --ansi" + ], "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], @@ -82,16 +84,9 @@ "@php artisan cache:clear", "@php artisan view:clear" ], - "post-autoload-dump": [ - "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", - "@php artisan package:discover --ansi" - ], "refresh-test-database": [ "@php artisan migrate:refresh --database=mysql_testing", "@php artisan db:seed --class=DummyContentSeeder --database=mysql_testing" - ], - "post-update-cmd": [ - "@php artisan vendor:publish --tag=laravel-assets --ansi" ] }, "config": { diff --git a/composer.lock b/composer.lock index f07d6106274..17e57df7109 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": "491a3de7d49182613d0c81032a7001e1", + "content-hash": "9a5d92382b2955dd7de41de5fa9f86b5", "packages": [ { "name": "aws/aws-crt-php", @@ -58,16 +58,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.199.4", + "version": "3.199.7", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "047f6ce04b1de9320ca00bf393d6f03b9d036fa5" + "reference": "fda176884d2952cffc7e67209470bff49609339c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/047f6ce04b1de9320ca00bf393d6f03b9d036fa5", - "reference": "047f6ce04b1de9320ca00bf393d6f03b9d036fa5", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/fda176884d2952cffc7e67209470bff49609339c", + "reference": "fda176884d2952cffc7e67209470bff49609339c", "shasum": "" }, "require": { @@ -143,9 +143,9 @@ "support": { "forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80", "issues": "https://github.com/aws/aws-sdk-php/issues", - "source": "https://github.com/aws/aws-sdk-php/tree/3.199.4" + "source": "https://github.com/aws/aws-sdk-php/tree/3.199.7" }, - "time": "2021-10-26T18:14:35+00:00" + "time": "2021-10-29T18:25:02+00:00" }, { "name": "bacon/bacon-qr-code", @@ -1101,30 +1101,32 @@ }, { "name": "dragonmantank/cron-expression", - "version": "v2.3.1", + "version": "v3.1.0", "source": { "type": "git", "url": "https://github.com/dragonmantank/cron-expression.git", - "reference": "65b2d8ee1f10915efb3b55597da3404f096acba2" + "reference": "7a8c6e56ab3ffcc538d05e8155bb42269abf1a0c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/65b2d8ee1f10915efb3b55597da3404f096acba2", - "reference": "65b2d8ee1f10915efb3b55597da3404f096acba2", + "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/7a8c6e56ab3ffcc538d05e8155bb42269abf1a0c", + "reference": "7a8c6e56ab3ffcc538d05e8155bb42269abf1a0c", "shasum": "" }, "require": { - "php": "^7.0|^8.0" + "php": "^7.2|^8.0", + "webmozart/assert": "^1.7.0" + }, + "replace": { + "mtdowling/cron-expression": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^6.4|^7.0|^8.0|^9.0" + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-webmozart-assert": "^0.12.7", + "phpunit/phpunit": "^7.0|^8.0|^9.0" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.3-dev" - } - }, "autoload": { "psr-4": { "Cron\\": "src/Cron/" @@ -1135,11 +1137,6 @@ "MIT" ], "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, { "name": "Chris Tankersley", "email": "chris@ctankersley.com", @@ -1153,7 +1150,7 @@ ], "support": { "issues": "https://github.com/dragonmantank/cron-expression/issues", - "source": "https://github.com/dragonmantank/cron-expression/tree/v2.3.1" + "source": "https://github.com/dragonmantank/cron-expression/tree/v3.1.0" }, "funding": [ { @@ -1161,7 +1158,7 @@ "type": "github" } ], - "time": "2020-10-13T00:52:37+00:00" + "time": "2020-11-24T19:55:57+00:00" }, { "name": "egulias/email-validator", @@ -1231,64 +1228,6 @@ ], "time": "2020-12-29T14:50:06+00:00" }, - { - "name": "fideloper/proxy", - "version": "4.4.1", - "source": { - "type": "git", - "url": "https://github.com/fideloper/TrustedProxy.git", - "reference": "c073b2bd04d1c90e04dc1b787662b558dd65ade0" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/fideloper/TrustedProxy/zipball/c073b2bd04d1c90e04dc1b787662b558dd65ade0", - "reference": "c073b2bd04d1c90e04dc1b787662b558dd65ade0", - "shasum": "" - }, - "require": { - "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0", - "php": ">=5.4.0" - }, - "require-dev": { - "illuminate/http": "^5.0|^6.0|^7.0|^8.0|^9.0", - "mockery/mockery": "^1.0", - "phpunit/phpunit": "^6.0" - }, - "type": "library", - "extra": { - "laravel": { - "providers": [ - "Fideloper\\Proxy\\TrustedProxyServiceProvider" - ] - } - }, - "autoload": { - "psr-4": { - "Fideloper\\Proxy\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Chris Fidao", - "email": "fideloper@gmail.com" - } - ], - "description": "Set trusted proxies for Laravel", - "keywords": [ - "load balancing", - "proxy", - "trusted proxy" - ], - "support": { - "issues": "https://github.com/fideloper/TrustedProxy/issues", - "source": "https://github.com/fideloper/TrustedProxy/tree/4.4.1" - }, - "time": "2020-10-22T13:48:01+00:00" - }, { "name": "filp/whoops", "version": "2.14.4", @@ -1360,6 +1299,67 @@ ], "time": "2021-10-03T12:00:00+00:00" }, + { + "name": "graham-campbell/result-type", + "version": "v1.0.3", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "296c015dc30ec4322168c5ad3ee5cc11dae827ac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/296c015dc30ec4322168c5ad3ee5cc11dae827ac", + "reference": "296c015dc30ec4322168c5ad3ee5cc11dae827ac", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "phpoption/phpoption": "^1.8" + }, + "require-dev": { + "phpunit/phpunit": "^6.5.14 || ^7.5.20 || ^8.5.19 || ^9.5.8" + }, + "type": "library", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.0.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "time": "2021-10-17T19:48:54+00:00" + }, { "name": "guzzlehttp/guzzle", "version": "7.4.0", @@ -1843,60 +1843,63 @@ }, { "name": "laravel/framework", - "version": "v7.30.4", + "version": "v8.68.1", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "9dd38140dc2924daa1a020a3d7a45f9ceff03df3" + "reference": "abe985ff1fb82dd04aab03bc1dc56e83fe61a59f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/9dd38140dc2924daa1a020a3d7a45f9ceff03df3", - "reference": "9dd38140dc2924daa1a020a3d7a45f9ceff03df3", + "url": "https://api.github.com/repos/laravel/framework/zipball/abe985ff1fb82dd04aab03bc1dc56e83fe61a59f", + "reference": "abe985ff1fb82dd04aab03bc1dc56e83fe61a59f", "shasum": "" }, "require": { "doctrine/inflector": "^1.4|^2.0", - "dragonmantank/cron-expression": "^2.3.1", + "dragonmantank/cron-expression": "^3.0.2", "egulias/email-validator": "^2.1.10", "ext-json": "*", "ext-mbstring": "*", "ext-openssl": "*", - "league/commonmark": "^1.3", + "laravel/serializable-closure": "^1.0", + "league/commonmark": "^1.3|^2.0.2", "league/flysystem": "^1.1", "monolog/monolog": "^2.0", - "nesbot/carbon": "^2.31", + "nesbot/carbon": "^2.53.1", "opis/closure": "^3.6", - "php": "^7.2.5|^8.0", + "php": "^7.3|^8.0", "psr/container": "^1.0", + "psr/log": "^1.0 || ^2.0", "psr/simple-cache": "^1.0", - "ramsey/uuid": "^3.7|^4.0", - "swiftmailer/swiftmailer": "^6.0", - "symfony/console": "^5.0", - "symfony/error-handler": "^5.0", - "symfony/finder": "^5.0", - "symfony/http-foundation": "^5.0", - "symfony/http-kernel": "^5.0", - "symfony/mime": "^5.0", - "symfony/polyfill-php73": "^1.17", - "symfony/process": "^5.0", - "symfony/routing": "^5.0", - "symfony/var-dumper": "^5.0", + "ramsey/uuid": "^4.2.2", + "swiftmailer/swiftmailer": "^6.3", + "symfony/console": "^5.1.4", + "symfony/error-handler": "^5.1.4", + "symfony/finder": "^5.1.4", + "symfony/http-foundation": "^5.1.4", + "symfony/http-kernel": "^5.1.4", + "symfony/mime": "^5.1.4", + "symfony/process": "^5.1.4", + "symfony/routing": "^5.1.4", + "symfony/var-dumper": "^5.1.4", "tijsverkoyen/css-to-inline-styles": "^2.2.2", - "vlucas/phpdotenv": "^4.0", + "vlucas/phpdotenv": "^5.2", "voku/portable-ascii": "^1.4.8" }, "conflict": { "tightenco/collect": "<5.5.33" }, "provide": { - "psr/container-implementation": "1.0" + "psr/container-implementation": "1.0", + "psr/simple-cache-implementation": "1.0" }, "replace": { "illuminate/auth": "self.version", "illuminate/broadcasting": "self.version", "illuminate/bus": "self.version", "illuminate/cache": "self.version", + "illuminate/collections": "self.version", "illuminate/config": "self.version", "illuminate/console": "self.version", "illuminate/container": "self.version", @@ -1909,6 +1912,7 @@ "illuminate/hashing": "self.version", "illuminate/http": "self.version", "illuminate/log": "self.version", + "illuminate/macroable": "self.version", "illuminate/mail": "self.version", "illuminate/notifications": "self.version", "illuminate/pagination": "self.version", @@ -1924,22 +1928,23 @@ "illuminate/view": "self.version" }, "require-dev": { - "aws/aws-sdk-php": "^3.155", - "doctrine/dbal": "^2.6", - "filp/whoops": "^2.8", - "guzzlehttp/guzzle": "^6.3.1|^7.0.1", + "aws/aws-sdk-php": "^3.198.1", + "doctrine/dbal": "^2.13.3|^3.1.2", + "filp/whoops": "^2.14.3", + "guzzlehttp/guzzle": "^6.5.5|^7.0.1", "league/flysystem-cached-adapter": "^1.0", - "mockery/mockery": "~1.3.3|^1.4.2", - "moontoast/math": "^1.1", - "orchestra/testbench-core": "^5.8", + "mockery/mockery": "^1.4.4", + "orchestra/testbench-core": "^6.23", "pda/pheanstalk": "^4.0", - "phpunit/phpunit": "^8.4|^9.3.3", - "predis/predis": "^1.1.1", - "symfony/cache": "^5.0" + "phpunit/phpunit": "^8.5.19|^9.5.8", + "predis/predis": "^1.1.9", + "symfony/cache": "^5.1.4" }, "suggest": { - "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.155).", - "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.6).", + "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.198.1).", + "brianium/paratest": "Required to run tests in parallel (^6.0).", + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.2).", + "ext-bcmath": "Required to use the multiple_of validation rule.", "ext-ftp": "Required to use the Flysystem FTP driver.", "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", "ext-memcached": "Required to use the memcache cache driver.", @@ -1947,38 +1952,43 @@ "ext-posix": "Required to use all features of the queue worker.", "ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).", "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", - "filp/whoops": "Required for friendly error pages in development (^2.8).", - "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.3.1|^7.0.1).", + "filp/whoops": "Required for friendly error pages in development (^2.14.3).", + "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.5.5|^7.0.1).", "laravel/tinker": "Required to use the tinker console command (^2.0).", "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", - "mockery/mockery": "Required to use mocking (~1.3.3|^1.4.2).", - "moontoast/math": "Required to use ordered UUIDs (^1.1).", + "mockery/mockery": "Required to use mocking (^1.4.4).", "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", "pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).", - "phpunit/phpunit": "Required to use assertions and run tests (^8.4|^9.3.3).", - "predis/predis": "Required to use the predis connector (^1.1.2).", + "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8).", + "predis/predis": "Required to use the predis connector (^1.1.9).", "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", - "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0).", - "symfony/cache": "Required to PSR-6 cache bridge (^5.0).", - "symfony/filesystem": "Required to create relative storage directory symbolic links (^5.0).", + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^5.1.4).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.1.4).", "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).", "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." }, "type": "library", "extra": { "branch-alias": { - "dev-master": "7.x-dev" + "dev-master": "8.x-dev" } }, "autoload": { "files": [ + "src/Illuminate/Collections/helpers.php", + "src/Illuminate/Events/functions.php", "src/Illuminate/Foundation/helpers.php", "src/Illuminate/Support/helpers.php" ], "psr-4": { - "Illuminate\\": "src/Illuminate/" + "Illuminate\\": "src/Illuminate/", + "Illuminate\\Support\\": [ + "src/Illuminate/Macroable/", + "src/Illuminate/Collections/" + ] } }, "notification-url": "https://packagist.org/downloads/", @@ -2001,7 +2011,66 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2021-01-21T14:10:48+00:00" + "time": "2021-10-27T12:31:46+00:00" + }, + { + "name": "laravel/serializable-closure", + "version": "v1.0.3", + "source": { + "type": "git", + "url": "https://github.com/laravel/serializable-closure.git", + "reference": "6cfc678735f22ccedad761b8cae2bab14c3d8e5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/6cfc678735f22ccedad761b8cae2bab14c3d8e5b", + "reference": "6cfc678735f22ccedad761b8cae2bab14c3d8e5b", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "pestphp/pest": "^1.18", + "phpstan/phpstan": "^0.12.98", + "symfony/var-dumper": "^5.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": [ + "closure", + "laravel", + "serializable" + ], + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "time": "2021-10-07T14:00:57+00:00" }, { "name": "laravel/socialite", @@ -2142,26 +2211,30 @@ }, { "name": "laravel/ui", - "version": "v2.5.0", + "version": "v3.3.0", "source": { "type": "git", "url": "https://github.com/laravel/ui.git", - "reference": "d01a705763c243b07be795e9d1bb47f89260f73d" + "reference": "07d725813350c695c779382cbd6dac0ab8665537" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/ui/zipball/d01a705763c243b07be795e9d1bb47f89260f73d", - "reference": "d01a705763c243b07be795e9d1bb47f89260f73d", + "url": "https://api.github.com/repos/laravel/ui/zipball/07d725813350c695c779382cbd6dac0ab8665537", + "reference": "07d725813350c695c779382cbd6dac0ab8665537", "shasum": "" }, "require": { - "illuminate/console": "^7.0", - "illuminate/filesystem": "^7.0", - "illuminate/support": "^7.0", - "php": "^7.2.5|^8.0" + "illuminate/console": "^8.42", + "illuminate/filesystem": "^8.42", + "illuminate/support": "^8.42", + "illuminate/validation": "^8.42", + "php": "^7.3|^8.0" }, "type": "library", "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + }, "laravel": { "providers": [ "Laravel\\Ui\\UiServiceProvider" @@ -2190,10 +2263,9 @@ "ui" ], "support": { - "issues": "https://github.com/laravel/ui/issues", - "source": "https://github.com/laravel/ui/tree/v2.5.0" + "source": "https://github.com/laravel/ui/tree/v3.3.0" }, - "time": "2020-11-03T19:45:19+00:00" + "time": "2021-05-25T16:45:33+00:00" }, { "name": "league/commonmark", @@ -3436,16 +3508,16 @@ }, { "name": "phpseclib/phpseclib", - "version": "3.0.10", + "version": "3.0.11", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "62fcc5a94ac83b1506f52d7558d828617fac9187" + "reference": "6e794226a35159eb06f355efe59a0075a16551dd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/62fcc5a94ac83b1506f52d7558d828617fac9187", - "reference": "62fcc5a94ac83b1506f52d7558d828617fac9187", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/6e794226a35159eb06f355efe59a0075a16551dd", + "reference": "6e794226a35159eb06f355efe59a0075a16551dd", "shasum": "" }, "require": { @@ -3527,7 +3599,7 @@ ], "support": { "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/3.0.10" + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.11" }, "funding": [ { @@ -3543,7 +3615,7 @@ "type": "tidelift" } ], - "time": "2021-08-16T04:24:45+00:00" + "time": "2021-10-27T03:01:46+00:00" }, { "name": "pragmarx/google2fa", @@ -4851,16 +4923,16 @@ }, { "name": "symfony/console", - "version": "v5.3.7", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "8b1008344647462ae6ec57559da166c2bfa5e16a" + "reference": "d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/8b1008344647462ae6ec57559da166c2bfa5e16a", - "reference": "8b1008344647462ae6ec57559da166c2bfa5e16a", + "url": "https://api.github.com/repos/symfony/console/zipball/d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3", + "reference": "d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3", "shasum": "" }, "require": { @@ -4930,7 +5002,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v5.3.7" + "source": "https://github.com/symfony/console/tree/v5.3.10" }, "funding": [ { @@ -4946,7 +5018,7 @@ "type": "tidelift" } ], - "time": "2021-08-25T20:02:16+00:00" + "time": "2021-10-26T09:30:15+00:00" }, { "name": "symfony/css-selector", @@ -5455,16 +5527,16 @@ }, { "name": "symfony/http-foundation", - "version": "v5.3.7", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "e36c8e5502b4f3f0190c675f1c1f1248a64f04e5" + "reference": "9f34f02e8a5fdc7a56bafe011cea1ce97300e54c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/e36c8e5502b4f3f0190c675f1c1f1248a64f04e5", - "reference": "e36c8e5502b4f3f0190c675f1c1f1248a64f04e5", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/9f34f02e8a5fdc7a56bafe011cea1ce97300e54c", + "reference": "9f34f02e8a5fdc7a56bafe011cea1ce97300e54c", "shasum": "" }, "require": { @@ -5508,7 +5580,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v5.3.7" + "source": "https://github.com/symfony/http-foundation/tree/v5.3.10" }, "funding": [ { @@ -5524,20 +5596,20 @@ "type": "tidelift" } ], - "time": "2021-08-27T11:20:35+00:00" + "time": "2021-10-11T15:41:55+00:00" }, { "name": "symfony/http-kernel", - "version": "v5.3.9", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "ceaf46a992f60e90645e7279825a830f733a17c5" + "reference": "703e4079920468e9522b72cf47fd76ce8d795e86" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/ceaf46a992f60e90645e7279825a830f733a17c5", - "reference": "ceaf46a992f60e90645e7279825a830f733a17c5", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/703e4079920468e9522b72cf47fd76ce8d795e86", + "reference": "703e4079920468e9522b72cf47fd76ce8d795e86", "shasum": "" }, "require": { @@ -5620,7 +5692,7 @@ "description": "Provides a structured process for converting a Request into a Response", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-kernel/tree/v5.3.9" + "source": "https://github.com/symfony/http-kernel/tree/v5.3.10" }, "funding": [ { @@ -5636,7 +5708,7 @@ "type": "tidelift" } ], - "time": "2021-09-28T10:25:11+00:00" + "time": "2021-10-29T08:36:48+00:00" }, { "name": "symfony/mime", @@ -6762,16 +6834,16 @@ }, { "name": "symfony/string", - "version": "v5.3.7", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "8d224396e28d30f81969f083a58763b8b9ceb0a5" + "reference": "d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/8d224396e28d30f81969f083a58763b8b9ceb0a5", - "reference": "8d224396e28d30f81969f083a58763b8b9ceb0a5", + "url": "https://api.github.com/repos/symfony/string/zipball/d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c", + "reference": "d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c", "shasum": "" }, "require": { @@ -6825,7 +6897,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v5.3.7" + "source": "https://github.com/symfony/string/tree/v5.3.10" }, "funding": [ { @@ -6841,20 +6913,20 @@ "type": "tidelift" } ], - "time": "2021-08-26T08:00:08+00:00" + "time": "2021-10-27T18:21:46+00:00" }, { "name": "symfony/translation", - "version": "v5.3.9", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "6e69f3551c1a3356cf6ea8d019bf039a0f8b6886" + "reference": "6ef197aea2ac8b9cd63e0da7522b3771714035aa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/6e69f3551c1a3356cf6ea8d019bf039a0f8b6886", - "reference": "6e69f3551c1a3356cf6ea8d019bf039a0f8b6886", + "url": "https://api.github.com/repos/symfony/translation/zipball/6ef197aea2ac8b9cd63e0da7522b3771714035aa", + "reference": "6ef197aea2ac8b9cd63e0da7522b3771714035aa", "shasum": "" }, "require": { @@ -6920,7 +6992,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v5.3.9" + "source": "https://github.com/symfony/translation/tree/v5.3.10" }, "funding": [ { @@ -6936,7 +7008,7 @@ "type": "tidelift" } ], - "time": "2021-08-26T08:22:53+00:00" + "time": "2021-10-10T06:43:24+00:00" }, { "name": "symfony/translation-contracts", @@ -7018,16 +7090,16 @@ }, { "name": "symfony/var-dumper", - "version": "v5.3.8", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "eaaea4098be1c90c8285543e1356a09c8aa5c8da" + "reference": "875432adb5f5570fff21036fd22aee244636b7d1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/eaaea4098be1c90c8285543e1356a09c8aa5c8da", - "reference": "eaaea4098be1c90c8285543e1356a09c8aa5c8da", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/875432adb5f5570fff21036fd22aee244636b7d1", + "reference": "875432adb5f5570fff21036fd22aee244636b7d1", "shasum": "" }, "require": { @@ -7086,7 +7158,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v5.3.8" + "source": "https://github.com/symfony/var-dumper/tree/v5.3.10" }, "funding": [ { @@ -7102,7 +7174,7 @@ "type": "tidelift" } ], - "time": "2021-09-24T15:59:58+00:00" + "time": "2021-10-26T09:30:15+00:00" }, { "name": "tijsverkoyen/css-to-inline-styles", @@ -7159,37 +7231,39 @@ }, { "name": "vlucas/phpdotenv", - "version": "v4.2.1", + "version": "v5.3.1", "source": { "type": "git", "url": "https://github.com/vlucas/phpdotenv.git", - "reference": "d38f4d1edcbe32515a0ad593cbd4c858e337263c" + "reference": "accaddf133651d4b5cf81a119f25296736ffc850" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/d38f4d1edcbe32515a0ad593cbd4c858e337263c", - "reference": "d38f4d1edcbe32515a0ad593cbd4c858e337263c", + "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/accaddf133651d4b5cf81a119f25296736ffc850", + "reference": "accaddf133651d4b5cf81a119f25296736ffc850", "shasum": "" }, "require": { - "php": "^5.5.9 || ^7.0 || ^8.0", - "phpoption/phpoption": "^1.7.3", - "symfony/polyfill-ctype": "^1.17" + "ext-pcre": "*", + "graham-campbell/result-type": "^1.0.2", + "php": "^7.1.3 || ^8.0", + "phpoption/phpoption": "^1.8", + "symfony/polyfill-ctype": "^1.23", + "symfony/polyfill-mbstring": "^1.23.1", + "symfony/polyfill-php80": "^1.23.1" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.4.1", "ext-filter": "*", - "ext-pcre": "*", - "phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.21" + "phpunit/phpunit": "^7.5.20 || ^8.5.21 || ^9.5.10" }, "suggest": { - "ext-filter": "Required to use the boolean validator.", - "ext-pcre": "Required to use most of the library." + "ext-filter": "Required to use the boolean validator." }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "5.3-dev" } }, "autoload": { @@ -7219,7 +7293,7 @@ ], "support": { "issues": "https://github.com/vlucas/phpdotenv/issues", - "source": "https://github.com/vlucas/phpdotenv/tree/v4.2.1" + "source": "https://github.com/vlucas/phpdotenv/tree/v5.3.1" }, "funding": [ { @@ -7231,7 +7305,7 @@ "type": "tidelift" } ], - "time": "2021-10-02T19:17:08+00:00" + "time": "2021-10-02T19:24:42+00:00" }, { "name": "voku/portable-ascii", @@ -7306,6 +7380,64 @@ } ], "time": "2020-11-12T00:07:28+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.10.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/6964c76c7804814a842473e0c8fd15bab0f18e25", + "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0", + "symfony/polyfill-ctype": "^1.8" + }, + "conflict": { + "phpstan/phpstan": "<0.12.20", + "vimeo/psalm": "<4.6.1 || 4.6.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/1.10.0" + }, + "time": "2021-03-09T10:59:23+00:00" } ], "packages-dev": [ @@ -7829,35 +7961,34 @@ }, { "name": "nunomaduro/collision", - "version": "v4.3.0", + "version": "v5.10.0", "source": { "type": "git", "url": "https://github.com/nunomaduro/collision.git", - "reference": "7c125dc2463f3e144ddc7e05e63077109508c94e" + "reference": "3004cfa49c022183395eabc6d0e5207dfe498d00" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nunomaduro/collision/zipball/7c125dc2463f3e144ddc7e05e63077109508c94e", - "reference": "7c125dc2463f3e144ddc7e05e63077109508c94e", + "url": "https://api.github.com/repos/nunomaduro/collision/zipball/3004cfa49c022183395eabc6d0e5207dfe498d00", + "reference": "3004cfa49c022183395eabc6d0e5207dfe498d00", "shasum": "" }, "require": { "facade/ignition-contracts": "^1.0", - "filp/whoops": "^2.4", - "php": "^7.2.5 || ^8.0", + "filp/whoops": "^2.14.3", + "php": "^7.3 || ^8.0", "symfony/console": "^5.0" }, "require-dev": { - "facade/ignition": "^2.0", - "fideloper/proxy": "^4.2", - "friendsofphp/php-cs-fixer": "^2.16", - "fruitcake/laravel-cors": "^1.0", - "laravel/framework": "^7.0", - "laravel/tinker": "^2.0", - "nunomaduro/larastan": "^0.6", - "orchestra/testbench": "^5.0", - "phpstan/phpstan": "^0.12.3", - "phpunit/phpunit": "^8.5.1 || ^9.0" + "brianium/paratest": "^6.1", + "fideloper/proxy": "^4.4.1", + "fruitcake/laravel-cors": "^2.0.3", + "laravel/framework": "8.x-dev", + "nunomaduro/larastan": "^0.6.2", + "nunomaduro/mock-final-classes": "^1.0", + "orchestra/testbench": "^6.0", + "phpstan/phpstan": "^0.12.64", + "phpunit/phpunit": "^9.5.0" }, "type": "library", "extra": { @@ -7913,7 +8044,7 @@ "type": "patreon" } ], - "time": "2020-10-29T15:12:23+00:00" + "time": "2021-09-20T15:06:32+00:00" }, { "name": "phar-io/manifest", @@ -8255,23 +8386,23 @@ }, { "name": "phpunit/php-code-coverage", - "version": "9.2.7", + "version": "9.2.8", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "d4c798ed8d51506800b441f7a13ecb0f76f12218" + "reference": "cf04e88a2e3c56fc1a65488afd493325b4c1bc3e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/d4c798ed8d51506800b441f7a13ecb0f76f12218", - "reference": "d4c798ed8d51506800b441f7a13ecb0f76f12218", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/cf04e88a2e3c56fc1a65488afd493325b4c1bc3e", + "reference": "cf04e88a2e3c56fc1a65488afd493325b4c1bc3e", "shasum": "" }, "require": { "ext-dom": "*", "ext-libxml": "*", "ext-xmlwriter": "*", - "nikic/php-parser": "^4.12.0", + "nikic/php-parser": "^4.13.0", "php": ">=7.3", "phpunit/php-file-iterator": "^3.0.3", "phpunit/php-text-template": "^2.0.2", @@ -8320,7 +8451,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.7" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.8" }, "funding": [ { @@ -8328,7 +8459,7 @@ "type": "github" } ], - "time": "2021-09-17T05:39:03+00:00" + "time": "2021-10-30T08:01:38+00:00" }, { "name": "phpunit/php-file-iterator", @@ -9830,64 +9961,6 @@ } ], "time": "2021-07-28T10:34:58+00:00" - }, - { - "name": "webmozart/assert", - "version": "1.10.0", - "source": { - "type": "git", - "url": "https://github.com/webmozarts/assert.git", - "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/webmozarts/assert/zipball/6964c76c7804814a842473e0c8fd15bab0f18e25", - "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25", - "shasum": "" - }, - "require": { - "php": "^7.2 || ^8.0", - "symfony/polyfill-ctype": "^1.8" - }, - "conflict": { - "phpstan/phpstan": "<0.12.20", - "vimeo/psalm": "<4.6.1 || 4.6.2" - }, - "require-dev": { - "phpunit/phpunit": "^8.5.13" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.10-dev" - } - }, - "autoload": { - "psr-4": { - "Webmozart\\Assert\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Bernhard Schussek", - "email": "bschussek@gmail.com" - } - ], - "description": "Assertions to validate method input/output with nice error messages.", - "keywords": [ - "assert", - "check", - "validate" - ], - "support": { - "issues": "https://github.com/webmozarts/assert/issues", - "source": "https://github.com/webmozarts/assert/tree/1.10.0" - }, - "time": "2021-03-09T10:59:23+00:00" } ], "aliases": [], diff --git a/database/factories/Actions/CommentFactory.php b/database/factories/Actions/CommentFactory.php index 06b69d31c6c..e81f3fe2c54 100644 --- a/database/factories/Actions/CommentFactory.php +++ b/database/factories/Actions/CommentFactory.php @@ -4,17 +4,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class CommentFactory extends Factory { /** diff --git a/database/factories/Actions/TagFactory.php b/database/factories/Actions/TagFactory.php index 1d282d68006..8d5c77e09bf 100644 --- a/database/factories/Actions/TagFactory.php +++ b/database/factories/Actions/TagFactory.php @@ -4,17 +4,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class TagFactory extends Factory { /** diff --git a/database/factories/Auth/RoleFactory.php b/database/factories/Auth/RoleFactory.php index cde5256f046..a952e0487f1 100644 --- a/database/factories/Auth/RoleFactory.php +++ b/database/factories/Auth/RoleFactory.php @@ -4,17 +4,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class RoleFactory extends Factory { /** diff --git a/database/factories/Auth/UserFactory.php b/database/factories/Auth/UserFactory.php index 19dc01de5ad..77d63ac68cd 100644 --- a/database/factories/Auth/UserFactory.php +++ b/database/factories/Auth/UserFactory.php @@ -5,17 +5,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class UserFactory extends Factory { /** diff --git a/database/factories/Entities/Models/BookFactory.php b/database/factories/Entities/Models/BookFactory.php index ecebdd5a181..0613800a143 100644 --- a/database/factories/Entities/Models/BookFactory.php +++ b/database/factories/Entities/Models/BookFactory.php @@ -5,17 +5,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class BookFactory extends Factory { /** diff --git a/database/factories/Entities/Models/BookshelfFactory.php b/database/factories/Entities/Models/BookshelfFactory.php index fa884662264..66dd1c11185 100644 --- a/database/factories/Entities/Models/BookshelfFactory.php +++ b/database/factories/Entities/Models/BookshelfFactory.php @@ -5,17 +5,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class BookshelfFactory extends Factory { /** diff --git a/database/factories/Entities/Models/ChapterFactory.php b/database/factories/Entities/Models/ChapterFactory.php index 0a94889c3d3..4fcd69c392d 100644 --- a/database/factories/Entities/Models/ChapterFactory.php +++ b/database/factories/Entities/Models/ChapterFactory.php @@ -5,17 +5,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class ChapterFactory extends Factory { /** diff --git a/database/factories/Entities/Models/PageFactory.php b/database/factories/Entities/Models/PageFactory.php index 3ced0ad631e..c83e0f828c4 100644 --- a/database/factories/Entities/Models/PageFactory.php +++ b/database/factories/Entities/Models/PageFactory.php @@ -5,17 +5,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class PageFactory extends Factory { /** diff --git a/database/factories/Uploads/ImageFactory.php b/database/factories/Uploads/ImageFactory.php index f7c700917d8..c6d0e080128 100644 --- a/database/factories/Uploads/ImageFactory.php +++ b/database/factories/Uploads/ImageFactory.php @@ -4,17 +4,6 @@ use Illuminate\Database\Eloquent\Factories\Factory; -/* -|-------------------------------------------------------------------------- -| Model Factories -|-------------------------------------------------------------------------- -| -| Here you may define all of your model factories. Model factories give -| you a convenient way to create models for testing and seeding your -| database. Just tell the factory how a default model should look. -| -*/ - class ImageFactory extends Factory { /** diff --git a/public/index.php b/public/index.php index 7e4ef97c707..c2f34d4bf27 100644 --- a/public/index.php +++ b/public/index.php @@ -1,59 +1,56 @@ - */ +use Illuminate\Contracts\Http\Kernel; +use BookStack\Http\Request; + define('LARAVEL_START', microtime(true)); /* |-------------------------------------------------------------------------- -| Register The Auto Loader +| Check If The Application Is Under Maintenance |-------------------------------------------------------------------------- | -| Composer provides a convenient, automatically generated class loader for -| our application. We just need to utilize it! We'll simply require it -| into the script here so that we don't have to worry about manual -| loading any of our classes later on. It feels great to relax. +| If the application is in maintenance / demo mode via the "down" command +| we will load this file so that any pre-rendered content can be shown +| instead of starting the framework, which could cause an exception. | */ -require __DIR__ . '/../vendor/autoload.php'; +if (file_exists(__DIR__ . '/../storage/framework/maintenance.php')) { + require __DIR__ . '/../storage/framework/maintenance.php'; +} /* |-------------------------------------------------------------------------- -| Turn On The Lights +| Register The Auto Loader |-------------------------------------------------------------------------- | -| We need to illuminate PHP development, so let us turn on the lights. -| This bootstraps the framework and gets it ready for use, then it -| will load up this application so that we can run it and send -| the responses back to the browser and delight our users. +| Composer provides a convenient, automatically generated class loader for +| this application. We just need to utilize it! We'll simply require it +| into the script here so we don't need to manually load our classes. | */ -$app = require_once __DIR__ . '/../bootstrap/app.php'; -$app->alias('request', \BookStack\Http\Request::class); +require __DIR__ . '/../vendor/autoload.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | -| Once we have the application, we can handle the incoming request -| through the kernel, and send the associated response back to -| the client's browser allowing them to enjoy the creative -| and wonderful application we have prepared for them. +| Once we have the application, we can handle the incoming request using +| the application's HTTP kernel. Then, we will send the response back +| to this client's browser, allowing them to enjoy our application. | */ -$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); +$app = require_once __DIR__ . '/../bootstrap/app.php'; +$app->alias('request', Request::class); -$response = $kernel->handle( - $request = \BookStack\Http\Request::capture() -); +$kernel = $app->make(Kernel::class); -$response->send(); +$response = tap($kernel->handle( + $request = Request::capture() +))->send(); -$kernel->terminate($request, $response); +$kernel->terminate($request, $response); \ No newline at end of file diff --git a/routes/api.php b/routes/api.php index 9742f9f49c3..4ba49946247 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,14 +1,14 @@ merge(Tag::factory()->count(5)->make(['name' => 'plans'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); - $this->asAdmin()->get('/ajax/tags/suggest/names?search=dog')->assertExactJson([]); - $this->get('/ajax/tags/suggest/names?search=co')->assertExactJson(['color', 'country', 'county']); - $this->get('/ajax/tags/suggest/names?search=cou')->assertExactJson(['country', 'county']); - $this->get('/ajax/tags/suggest/names?search=pla')->assertExactJson(['planet', 'plans']); + $this->asAdmin()->get('/ajax/tags/suggest/names?search=dog')->assertSimilarJson([]); + $this->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country', 'county']); + $this->get('/ajax/tags/suggest/names?search=cou')->assertSimilarJson(['country', 'county']); + $this->get('/ajax/tags/suggest/names?search=pla')->assertSimilarJson(['planet', 'plans']); } public function test_tag_value_suggestions() @@ -57,10 +57,10 @@ public function test_tag_value_suggestions() $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'plans', 'value' => 'dodgy'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); - $this->asAdmin()->get('/ajax/tags/suggest/values?search=ora')->assertExactJson([]); - $this->get('/ajax/tags/suggest/values?search=cat')->assertExactJson(['cats', 'cattery', 'catapult']); - $this->get('/ajax/tags/suggest/values?search=do')->assertExactJson(['dog', 'dodgy']); - $this->get('/ajax/tags/suggest/values?search=cas')->assertExactJson(['castle']); + $this->asAdmin()->get('/ajax/tags/suggest/values?search=ora')->assertSimilarJson([]); + $this->get('/ajax/tags/suggest/values?search=cat')->assertSimilarJson(['cats', 'cattery', 'catapult']); + $this->get('/ajax/tags/suggest/values?search=do')->assertSimilarJson(['dog', 'dodgy']); + $this->get('/ajax/tags/suggest/values?search=cas')->assertSimilarJson(['castle']); } public function test_entity_permissions_effect_tag_suggestions() @@ -71,16 +71,16 @@ public function test_entity_permissions_effect_tag_suggestions() $attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color'])); $page = $this->getEntityWithTags(Page::class, $attrs->all()); - $this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertExactJson(['color', 'country']); - $this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertExactJson(['color', 'country']); + $this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']); + $this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']); // Set restricted permission the page $page->restricted = true; $page->save(); $page->rebuildPermissions(); - $this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertExactJson(['color', 'country']); - $this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertExactJson([]); + $this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']); + $this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson([]); } public function test_tags_shown_on_search_listing()