From d97a148be17ebb024ec445d99303aa2042d6a037 Mon Sep 17 00:00:00 2001 From: Allon Moritz Date: Fri, 13 Dec 2024 10:04:14 +0100 Subject: [PATCH 01/13] Add rector --- build/rector.php | 74 +++++++++++++++++++++++++++++++++++++++++ composer.json | 5 +-- composer.lock | 85 ++++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 149 insertions(+), 15 deletions(-) create mode 100644 build/rector.php diff --git a/build/rector.php b/build/rector.php new file mode 100644 index 0000000000000..b8eb202253d98 --- /dev/null +++ b/build/rector.php @@ -0,0 +1,74 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL + */ + +declare(strict_types=1); + +use Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector; +use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector; +use Rector\CodingStyle\Rector\Use_\SeparateMultiUseImportsRector; +use Rector\Config\RectorConfig; +use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector; +use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector; +use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector; +use Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector; +use Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector; +use Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector; +use Rector\Set\ValueObject\LevelSetList; +use Rector\Set\ValueObject\SetList; +use Rector\ValueObject\PhpVersion; + +return static function (RectorConfig $rectorConfig): void { + // Min version + $rectorConfig->phpVersion(PhpVersion::PHP_81); + + // No short class import + $rectorConfig->importShortClasses(false); + + // Tabs for indentation + $rectorConfig->indent(' ', 4); + + // Complete sets with rules + $rectorConfig->sets([ + //LevelSetList::UP_TO_PHP_81, + //SetList::CODE_QUALITY, + //SetList::CODING_STYLE, + //SetList::DEAD_CODE, + //SetList::EARLY_RETURN, + //SetList::INSTANCEOF, + //SetList::NAMING, + //SetList::PRIVATIZATION, + //SetList::STRICT_BOOLEANS, + //SetList::TYPE_DECLARATION, + ]); + + // Skip some rules and folders/files + $rectorConfig->skip([ + // Keep Joomla version compare + UnwrapFutureCompatibleIfPhpVersionRector::class, + // Keep docs + RemoveUselessParamTagRector::class, + RemoveUselessReturnTagRector::class, + // Keep ['*Component.php'], + + // Ignore vendor + '*/vendor/*', + ]); + + // The bootstrap file, which finds the core classes and loads the extension namespace + $rectorConfig->bootstrapFiles([__DIR__ . '/phpstan/joomla-bootstrap.php']); +}; diff --git a/composer.json b/composer.json index b0689ad9e7298..4ea53a8d5454a 100644 --- a/composer.json +++ b/composer.json @@ -116,8 +116,9 @@ "dealerdirect/phpcodesniffer-composer-installer": "^0.7.2", "joomla/mediawiki": "^3.0", "joomla/test": "~3.0", - "phpstan/phpstan": "^2.0", - "phpstan/phpstan-deprecation-rules": "^2.0" + "phpstan/phpstan": "^2.0.3", + "phpstan/phpstan-deprecation-rules": "^2.0.1", + "rector/rector": "^2.0.0" }, "replace": { "paragonie/random_compat": "9.99.99", diff --git a/composer.lock b/composer.lock index 8fdae5799e8f2..5368d76499b51 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": "0f1f9d337d9ee7e6f717bf13b606a359", + "content-hash": "7aab883320e8c54da83d86a7320e7b05", "packages": [ { "name": "algo26-matthias/idna-convert", @@ -7682,16 +7682,16 @@ }, { "name": "phpstan/phpstan", - "version": "2.0.0", + "version": "2.0.3", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "72115ab2bf1e40af1f9b238938d493ba7f3221e7" + "reference": "46b4d3529b12178112d9008337beda0cc2a1a6b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/72115ab2bf1e40af1f9b238938d493ba7f3221e7", - "reference": "72115ab2bf1e40af1f9b238938d493ba7f3221e7", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/46b4d3529b12178112d9008337beda0cc2a1a6b4", + "reference": "46b4d3529b12178112d9008337beda0cc2a1a6b4", "shasum": "" }, "require": { @@ -7736,20 +7736,20 @@ "type": "github" } ], - "time": "2024-11-11T07:06:55+00:00" + "time": "2024-11-28T22:19:37+00:00" }, { "name": "phpstan/phpstan-deprecation-rules", - "version": "2.0.0", + "version": "2.0.1", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan-deprecation-rules.git", - "reference": "81833b5787e2e8f451b31218875e29e4ed600ab2" + "reference": "1cc1259cb91ee4cfbb5c39bca9f635f067c910b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan-deprecation-rules/zipball/81833b5787e2e8f451b31218875e29e4ed600ab2", - "reference": "81833b5787e2e8f451b31218875e29e4ed600ab2", + "url": "https://api.github.com/repos/phpstan/phpstan-deprecation-rules/zipball/1cc1259cb91ee4cfbb5c39bca9f635f067c910b4", + "reference": "1cc1259cb91ee4cfbb5c39bca9f635f067c910b4", "shasum": "" }, "require": { @@ -7781,9 +7781,9 @@ "description": "PHPStan rules for detecting usage of deprecated classes, methods, properties, constants and traits.", "support": { "issues": "https://github.com/phpstan/phpstan-deprecation-rules/issues", - "source": "https://github.com/phpstan/phpstan-deprecation-rules/tree/2.0.0" + "source": "https://github.com/phpstan/phpstan-deprecation-rules/tree/2.0.1" }, - "time": "2024-10-26T16:04:11+00:00" + "time": "2024-11-28T21:56:36+00:00" }, { "name": "phpunit/php-code-coverage", @@ -8737,6 +8737,65 @@ ], "time": "2024-06-11T12:45:25+00:00" }, + { + "name": "rector/rector", + "version": "2.0.3", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "3f27091368bd935dbbaa8387099792fb20f65f68" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/3f27091368bd935dbbaa8387099792fb20f65f68", + "reference": "3f27091368bd935dbbaa8387099792fb20f65f68", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.0.1" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.0.3" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2024-12-12T15:22:19+00:00" + }, { "name": "sebastian/cli-parser", "version": "1.0.2", @@ -10254,7 +10313,7 @@ "ext-gd": "*", "ext-dom": "*" }, - "platform-dev": [], + "platform-dev": {}, "platform-overrides": { "php": "8.1.0" }, From 9caaa38151013dc27c2aa2c0e03f6a3cdc780a5a Mon Sep 17 00:00:00 2001 From: Allon Moritz Date: Fri, 13 Dec 2024 10:11:02 +0100 Subject: [PATCH 02/13] Upgrade code to PHP 8.1 --- .../src/Controller/ActionlogsController.php | 2 +- .../src/Field/UserlogtypeField.php | 2 +- .../src/Helper/ActionlogsHelper.php | 6 +- .../src/Model/ActionlogModel.php | 4 +- .../src/Model/ActionlogsModel.php | 10 +- .../src/Plugin/ActionLogPlugin.php | 4 +- administrator/components/com_admin/script.php | 6 +- .../com_admin/src/Model/HelpModel.php | 2 +- .../com_admin/src/Model/SysinfoModel.php | 22 +- .../src/Service/HTML/Configuration.php | 2 +- .../com_admin/tmpl/sysinfo/default_system.php | 2 +- .../src/Controller/AssociationController.php | 6 +- .../src/Controller/AssociationsController.php | 2 +- .../src/Dispatcher/Dispatcher.php | 2 +- .../src/Field/ItemlanguageField.php | 2 +- .../src/Helper/AssociationsHelper.php | 6 +- .../src/Model/AssociationsModel.php | 12 +- .../src/View/Association/HtmlView.php | 4 +- .../src/View/Associations/HtmlView.php | 2 +- .../com_banners/src/Field/ClicksField.php | 2 +- .../com_banners/src/Field/ImpmadeField.php | 2 +- .../com_banners/src/Field/ImptotalField.php | 2 +- .../com_banners/src/Model/BannerModel.php | 4 +- .../com_banners/src/Model/BannersModel.php | 6 +- .../com_banners/src/Model/ClientsModel.php | 2 +- .../com_banners/tmpl/banners/default.php | 2 +- .../com_cache/src/Model/CacheModel.php | 16 +- .../joomla/form/field/categoryedit.php | 2 +- .../src/Field/CategoryeditField.php | 15 +- .../src/Field/ComponentsCategoryField.php | 2 +- .../src/Field/Modal/CategoryField.php | 4 +- .../src/Model/CategoriesModel.php | 10 +- .../src/Model/CategoryModel.php | 12 +- .../src/View/Categories/HtmlView.php | 6 +- .../src/View/Category/HtmlView.php | 4 +- .../tmpl/categories/default.php | 8 +- .../com_checkin/src/Model/CheckinModel.php | 10 +- .../src/Controller/ApplicationController.php | 14 +- .../src/Controller/ComponentController.php | 8 +- .../src/Controller/DisplayController.php | 2 +- .../com_config/src/Dispatcher/Dispatcher.php | 2 +- .../com_config/src/Field/FiltersField.php | 4 +- .../com_config/src/Model/ApplicationModel.php | 32 +- .../src/Field/Modal/ContactField.php | 4 +- .../com_contact/src/Model/ContactModel.php | 4 +- .../com_contact/src/Model/ContactsModel.php | 8 +- .../com_contact/tmpl/contacts/default.php | 2 +- .../src/Event/Model/FeatureEvent.php | 6 +- .../src/Extension/ContentComponent.php | 2 +- .../src/Field/Modal/ArticleField.php | 4 +- .../com_content/src/Helper/ContentHelper.php | 4 +- .../com_content/src/Model/ArticleModel.php | 16 +- .../com_content/src/Model/ArticlesModel.php | 18 +- .../com_content/tmpl/articles/default.php | 8 +- .../com_content/tmpl/featured/default.php | 8 +- .../src/Helper/ContenthistoryHelper.php | 4 +- .../src/Model/HistoryModel.php | 8 +- .../src/Controller/DisplayController.php | 2 +- .../com_cpanel/src/View/Cpanel/HtmlView.php | 2 +- .../com_fields/src/Field/FieldLayoutField.php | 10 +- .../src/Field/FieldcontextsField.php | 2 +- .../com_fields/src/Field/SubfieldsField.php | 4 +- .../com_fields/src/Field/TypeField.php | 4 +- .../com_fields/src/Helper/FieldsHelper.php | 8 +- .../com_fields/src/Model/FieldModel.php | 12 +- .../com_fields/src/Model/FieldsModel.php | 14 +- .../com_fields/src/Model/GroupModel.php | 2 +- .../com_fields/src/Model/GroupsModel.php | 6 +- .../com_fields/src/Plugin/FieldsPlugin.php | 2 +- .../com_fields/src/View/Field/HtmlView.php | 4 +- .../com_fields/src/View/Fields/HtmlView.php | 4 +- .../com_fields/src/View/Group/HtmlView.php | 4 +- .../com_fields/src/View/Groups/HtmlView.php | 4 +- .../com_fields/tmpl/fields/default.php | 4 +- .../com_fields/tmpl/groups/default.php | 4 +- .../src/Controller/IndexerController.php | 8 +- .../com_finder/src/Field/ContentmapField.php | 2 +- .../com_finder/src/Indexer/Adapter.php | 2 +- .../com_finder/src/Indexer/DebugAdapter.php | 18 +- .../com_finder/src/Indexer/Indexer.php | 4 +- .../com_finder/src/Indexer/Language.php | 18 +- .../com_finder/src/Indexer/Parser.php | 2 +- .../com_finder/src/Indexer/Parser/Html.php | 2 +- .../com_finder/src/Indexer/Parser/Rtf.php | 2 +- .../com_finder/src/Indexer/Query.php | 6 +- .../com_finder/src/Indexer/Taxonomy.php | 12 +- .../com_finder/src/Indexer/Token.php | 4 +- .../com_finder/src/Model/FiltersModel.php | 2 +- .../com_finder/src/Model/IndexModel.php | 2 +- .../com_finder/src/Model/MapsModel.php | 2 +- .../com_finder/src/Model/SearchesModel.php | 2 +- .../com_finder/src/Response/Response.php | 2 +- .../com_finder/src/Service/HTML/Filter.php | 12 +- .../com_finder/src/Service/HTML/Finder.php | 2 +- .../com_finder/tmpl/maps/default.php | 2 +- .../src/Helper/GuidedtoursHelper.php | 2 +- .../com_guidedtours/src/Model/StepModel.php | 4 +- .../com_guidedtours/src/Model/StepsModel.php | 10 +- .../com_guidedtours/src/Model/TourModel.php | 10 +- .../com_guidedtours/src/Model/ToursModel.php | 12 +- .../com_guidedtours/tmpl/step/edit.php | 4 +- .../com_guidedtours/tmpl/steps/default.php | 2 +- .../com_guidedtours/tmpl/tour/edit.php | 4 +- .../com_guidedtours/tmpl/tours/default.php | 4 +- .../src/Helper/InstallerHelper.php | 24 +- .../com_installer/src/Model/DatabaseModel.php | 6 +- .../com_installer/src/Model/DiscoverModel.php | 6 +- .../com_installer/src/Model/InstallModel.php | 6 +- .../src/Model/InstallerModel.php | 4 +- .../src/Model/LanguagesModel.php | 10 +- .../com_installer/src/Model/ManageModel.php | 8 +- .../com_installer/src/Model/UpdateModel.php | 26 +- .../src/Model/UpdatesiteModel.php | 2 +- .../src/Model/UpdatesitesModel.php | 4 +- .../com_installer/src/Model/WarningsModel.php | 20 +- .../src/View/Update/HtmlView.php | 2 +- .../com_installer/tmpl/languages/default.php | 2 +- .../com_installer/tmpl/manage/default.php | 2 +- .../components/com_joomlaupdate/extract.php | 10 +- .../com_joomlaupdate/finalisation.php | 16 +- .../src/Controller/UpdateController.php | 4 +- .../src/Model/UpdateModel.php | 44 +- .../src/Helper/LanguagesHelper.php | 2 +- .../src/Model/InstalledModel.php | 8 +- .../src/Model/LanguagesModel.php | 2 +- .../com_languages/src/Model/OverrideModel.php | 6 +- .../src/Model/OverridesModel.php | 14 +- .../com_languages/src/Model/StringsModel.php | 2 +- .../com_languages/tmpl/installed/default.php | 2 +- .../com_languages/tmpl/languages/default.php | 2 +- .../src/Controller/DisplayController.php | 2 +- .../com_login/src/Model/LoginModel.php | 6 +- .../src/Controller/TemplateController.php | 4 +- .../src/Field/MailtemplateLayoutField.php | 4 +- .../com_mails/src/Helper/MailsHelper.php | 2 +- .../com_mails/src/Model/TemplateModel.php | 4 +- .../com_mails/src/Model/TemplatesModel.php | 2 +- .../com_mails/src/View/Template/HtmlView.php | 2 +- .../com_mails/tmpl/template/edit.php | 2 +- .../com_mails/tmpl/templates/default.php | 2 +- .../src/Controller/ApiController.php | 6 +- .../com_media/src/Model/ApiModel.php | 12 +- .../com_media/src/Model/FileModel.php | 2 +- .../src/Provider/ProviderManager.php | 2 +- .../Provider/ProviderManagerHelperTrait.php | 2 +- .../com_media/tmpl/file/default.php | 8 +- .../com_media/tmpl/media/default.php | 8 +- .../src/Controller/ItemController.php | 4 +- .../src/Controller/ItemsController.php | 2 +- .../src/Controller/MenuController.php | 4 +- .../src/Field/MenuItemByComponentField.php | 2 +- .../src/Field/MenuItemByTypeField.php | 16 +- .../com_menus/src/Field/Modal/MenuField.php | 4 +- .../com_menus/src/Helper/MenusHelper.php | 14 +- .../com_menus/src/Model/ItemModel.php | 18 +- .../com_menus/src/Model/ItemsModel.php | 6 +- .../com_menus/src/Model/MenusModel.php | 2 +- .../com_menus/src/Model/MenutypesModel.php | 18 +- .../com_menus/src/Service/HTML/Menus.php | 2 +- .../com_menus/src/View/Items/HtmlView.php | 2 +- .../com_menus/tmpl/items/default.php | 6 +- .../com_menus/tmpl/menus/default.php | 2 +- .../com_messages/src/Model/MessageModel.php | 4 +- .../com_messages/src/Model/MessagesModel.php | 2 +- .../src/Controller/ModuleController.php | 2 +- .../src/Field/ModulesModuleField.php | 10 +- .../src/Field/ModulesPositionField.php | 10 +- .../src/Field/ModulesPositioneditField.php | 10 +- .../com_modules/src/Helper/ModulesHelper.php | 2 +- .../com_modules/src/Model/ModuleModel.php | 4 +- .../com_modules/src/Model/ModulesModel.php | 6 +- .../com_modules/src/Model/PositionsModel.php | 2 +- .../com_modules/tmpl/module/edit.php | 2 +- .../com_modules/tmpl/modules/default.php | 2 +- .../src/Field/Modal/NewsfeedField.php | 4 +- .../com_newsfeeds/src/Model/NewsfeedModel.php | 4 +- .../src/Model/NewsfeedsModel.php | 6 +- .../com_newsfeeds/tmpl/newsfeeds/default.php | 2 +- .../com_plugins/src/Model/PluginsModel.php | 8 +- .../com_plugins/tmpl/plugin/edit.php | 2 +- .../com_plugins/tmpl/plugins/default.php | 2 +- .../src/Helper/PostinstallHelper.php | 4 +- .../src/Model/MessagesModel.php | 4 +- .../src/Controller/RequestController.php | 39 +- .../com_privacy/src/Model/ConsentsModel.php | 12 +- .../com_privacy/src/Model/RequestModel.php | 2 +- .../com_privacy/src/Model/RequestsModel.php | 4 +- .../src/Controller/LinksController.php | 2 +- .../com_redirect/src/Model/LinksModel.php | 8 +- .../com_scheduler/src/Field/CronField.php | 8 +- .../com_scheduler/src/Field/TaskTypeField.php | 2 +- .../src/Helper/ExecRuleHelper.php | 6 +- .../com_scheduler/src/Model/LogsModel.php | 8 +- .../com_scheduler/src/Model/TaskModel.php | 30 +- .../com_scheduler/src/Model/TasksModel.php | 12 +- .../com_scheduler/src/Scheduler/Scheduler.php | 6 +- .../com_scheduler/src/Task/Task.php | 8 +- .../com_scheduler/src/Task/TaskOption.php | 2 +- .../src/Traits/TaskPluginTrait.php | 14 +- .../com_scheduler/tmpl/task/edit.php | 2 +- .../com_scheduler/tmpl/tasks/default.php | 4 +- .../com_tags/src/Model/TagModel.php | 2 +- .../com_tags/src/Model/TagsModel.php | 8 +- .../components/com_tags/tmpl/tags/default.php | 8 +- .../src/Controller/TemplateController.php | 16 +- .../src/Helper/TemplateHelper.php | 10 +- .../com_templates/src/Model/StylesModel.php | 4 +- .../com_templates/src/Model/TemplateModel.php | 104 +- .../src/Model/TemplatesModel.php | 4 +- .../src/View/Template/HtmlView.php | 14 +- .../com_templates/tmpl/style/edit.php | 2 +- .../com_templates/tmpl/styles/default.php | 2 +- .../com_templates/tmpl/template/default.php | 2 +- .../src/Controller/CaptiveController.php | 6 +- .../src/Controller/DisplayController.php | 18 +- .../src/Controller/MethodsController.php | 6 +- .../src/Controller/UserController.php | 4 +- .../src/DataShape/DataShapeObject.php | 10 +- .../com_users/src/Dispatcher/Dispatcher.php | 4 +- .../components/com_users/src/Helper/Mfa.php | 2 +- .../com_users/src/Model/CaptiveModel.php | 6 +- .../com_users/src/Model/DebuggroupModel.php | 2 +- .../com_users/src/Model/DebuguserModel.php | 2 +- .../com_users/src/Model/GroupsModel.php | 6 +- .../com_users/src/Model/LevelModel.php | 2 +- .../com_users/src/Model/LevelsModel.php | 6 +- .../com_users/src/Model/MailModel.php | 2 +- .../com_users/src/Model/MethodModel.php | 13 +- .../com_users/src/Model/MethodsModel.php | 2 +- .../com_users/src/Model/NotesModel.php | 10 +- .../com_users/src/Model/UsersModel.php | 16 +- .../com_users/src/Service/Encrypt.php | 4 +- .../com_users/src/Service/HTML/Users.php | 8 +- .../com_users/src/Table/MfaTable.php | 12 +- .../com_users/src/View/Method/HtmlView.php | 4 +- .../com_users/src/View/SiteTemplateTrait.php | 2 +- .../com_users/src/View/User/HtmlView.php | 2 +- .../com_users/tmpl/captive/default.php | 2 +- .../com_users/tmpl/levels/default.php | 2 +- .../components/com_users/tmpl/method/edit.php | 2 +- .../com_users/tmpl/methods/list.php | 4 +- .../src/Field/WorkflowcontextsField.php | 2 +- .../com_workflow/src/Model/StageModel.php | 8 +- .../com_workflow/src/Model/StagesModel.php | 2 +- .../src/Model/TransitionModel.php | 6 +- .../src/Model/TransitionsModel.php | 4 +- .../com_workflow/src/Model/WorkflowModel.php | 6 +- .../com_workflow/src/Model/WorkflowsModel.php | 6 +- .../com_workflow/src/View/Stage/HtmlView.php | 2 +- .../src/View/Transition/HtmlView.php | 2 +- .../src/View/Workflow/HtmlView.php | 2 +- .../src/View/Workflows/HtmlView.php | 2 +- .../com_workflow/tmpl/stages/default.php | 2 +- .../com_workflow/tmpl/transitions/default.php | 2 +- .../com_workflow/tmpl/workflows/default.php | 4 +- administrator/includes/framework.php | 2 +- administrator/index.php | 4 +- .../mod_feed/src/Helper/FeedHelper.php | 2 +- .../src/Dispatcher/Dispatcher.php | 2 +- .../modules/mod_guidedtours/tmpl/default.php | 2 +- .../mod_login/src/Helper/LoginHelper.php | 4 +- .../modules/mod_login/tmpl/default.php | 4 +- .../modules/mod_menu/src/Menu/CssMenu.php | 20 +- .../modules/mod_menu/tmpl/default_submenu.php | 4 +- .../src/Helper/PrivacyDashboardHelper.php | 2 +- .../src/Helper/StatsAdminHelper.php | 4 +- .../modules/mod_submenu/src/Menu/Menu.php | 8 +- .../modules/mod_submenu/tmpl/default.php | 10 +- administrator/templates/atum/component.php | 8 +- administrator/templates/atum/error_full.php | 12 +- administrator/templates/atum/error_login.php | 14 +- .../atum/html/layouts/chromes/body.php | 4 +- .../atum/html/layouts/chromes/well.php | 8 +- .../templates/atum/html/layouts/status.php | 2 +- administrator/templates/atum/index.php | 16 +- administrator/templates/atum/login.php | 12 +- .../src/Controller/ContactController.php | 2 +- .../src/Controller/ArticlesController.php | 2 +- .../src/Controller/MediaController.php | 4 +- .../com_media/src/Model/AdapterModel.php | 2 +- .../com_media/src/Model/MediaModel.php | 2 +- .../com_media/src/Model/MediumModel.php | 32 +- api/includes/framework.php | 2 +- api/index.php | 2 +- build/build.php | 20 +- build/bump.php | 32 +- build/check_ruleset_xml.php | 6 +- build/convert_or_die.php | 8 +- build/deleted_file_check.php | 2 +- build/github_rebase.php | 2 +- build/github_update_title.php | 12 +- build/helpTOC.php | 8 +- build/layouts/github.php | 22 +- .../DynamicReturnType/ControllerLoader.php | 2 +- .../src/DynamicReturnType/ViewModelLoader.php | 4 +- .../src/Reflection/FormFieldProperty.php | 4 +- build/psr12/clean_errors.php | 8 +- build/psr12/convert_pull_requests.php | 2 +- build/psr12/phpcs.joomla.report.php | 16 +- build/psr12/psr12_converter.php | 12 +- build/rector.php | 5 +- build/stubGenerator.php | 22 +- build/update_fido_cache.php | 2 +- components/com_ajax/ajax.php | 26 +- .../com_banners/src/Model/BannerModel.php | 2 +- .../com_banners/src/Model/BannersModel.php | 2 +- components/com_banners/src/Service/Router.php | 2 +- .../src/Controller/ModulesController.php | 16 +- .../com_config/src/Dispatcher/Dispatcher.php | 2 +- .../com_config/src/Model/ModulesModel.php | 2 +- .../com_config/src/View/Config/HtmlView.php | 4 +- .../src/View/Templates/HtmlView.php | 6 +- .../com_contact/layouts/fields/render.php | 2 +- .../src/Controller/ContactController.php | 6 +- .../src/Helper/AssociationHelper.php | 2 +- .../com_contact/src/Model/CategoryModel.php | 4 +- .../com_contact/src/Model/FeaturedModel.php | 4 +- .../com_contact/src/Model/FormModel.php | 4 +- .../src/Rule/ContactEmailMessageRule.php | 2 +- .../com_contact/src/Rule/ContactEmailRule.php | 2 +- .../src/Rule/ContactEmailSubjectRule.php | 2 +- components/com_contact/src/Service/Router.php | 39 +- .../com_contact/src/View/Contact/HtmlView.php | 2 +- .../src/View/Featured/HtmlView.php | 2 +- .../com_contact/src/View/Form/HtmlView.php | 2 +- .../tmpl/contact/default_links.php | 2 +- .../src/Controller/ArticleController.php | 4 +- .../src/Helper/AssociationHelper.php | 2 +- .../com_content/src/Helper/QueryHelper.php | 47 +- .../com_content/src/Model/ArticlesModel.php | 2 +- .../com_content/src/Model/CategoryModel.php | 4 +- .../com_content/src/Model/FormModel.php | 4 +- components/com_content/src/Service/Router.php | 39 +- .../com_content/src/View/Archive/HtmlView.php | 2 +- .../com_content/src/View/Article/HtmlView.php | 2 +- .../src/View/Featured/HtmlView.php | 2 +- .../com_content/src/View/Form/HtmlView.php | 2 +- .../tmpl/article/default_links.php | 16 +- .../tmpl/category/default_articles.php | 17 +- .../com_fields/layouts/fields/render.php | 4 +- .../com_finder/src/Model/SearchModel.php | 13 +- .../com_finder/src/View/Search/FeedView.php | 2 +- .../com_finder/src/View/Search/HtmlView.php | 4 +- .../com_finder/tmpl/search/default_result.php | 2 +- .../src/Helper/AssociationHelper.php | 2 +- .../com_newsfeeds/src/Model/CategoryModel.php | 2 +- .../com_newsfeeds/src/Service/Router.php | 39 +- .../src/View/Newsfeed/HtmlView.php | 6 +- .../com_privacy/src/Model/ConfirmModel.php | 2 +- .../com_privacy/src/Model/RemindModel.php | 2 +- .../com_privacy/src/View/Confirm/HtmlView.php | 2 +- .../com_privacy/src/View/Remind/HtmlView.php | 2 +- .../com_privacy/src/View/Request/HtmlView.php | 2 +- .../src/Controller/TagsController.php | 4 +- components/com_tags/src/Model/TagModel.php | 24 +- components/com_tags/src/Service/Router.php | 25 +- components/com_tags/src/View/Tag/FeedView.php | 2 +- components/com_tags/src/View/Tag/HtmlView.php | 2 +- .../com_tags/src/View/Tags/FeedView.php | 2 +- .../com_tags/src/View/Tags/HtmlView.php | 4 +- .../com_tags/tmpl/tags/default_items.php | 2 +- .../src/Controller/UserController.php | 4 +- components/com_users/src/Model/LoginModel.php | 4 +- .../com_users/src/Model/ProfileModel.php | 4 +- .../src/Rule/LoginUniqueFieldRule.php | 4 +- .../src/Rule/LogoutUniqueFieldRule.php | 4 +- .../com_users/src/View/Login/HtmlView.php | 2 +- .../com_users/src/View/Profile/HtmlView.php | 2 +- .../src/View/Registration/HtmlView.php | 2 +- .../com_users/src/View/Remind/HtmlView.php | 2 +- .../com_users/src/View/Reset/HtmlView.php | 2 +- components/com_users/tmpl/captive/default.php | 2 +- .../com_users/tmpl/login/default_login.php | 10 +- .../com_users/tmpl/login/default_logout.php | 4 +- components/com_users/tmpl/method/edit.php | 2 +- components/com_users/tmpl/methods/list.php | 4 +- .../com_wrapper/src/View/Wrapper/HtmlView.php | 10 +- includes/framework.php | 2 +- index.php | 4 +- installation/index.php | 4 +- installation/joomla.php | 2 +- .../CliInstallationApplication.php | 20 +- .../Application/InstallationApplication.php | 4 +- installation/src/Console/InstallCommand.php | 4 +- .../Form/Field/Installation/LanguageField.php | 2 +- .../Form/Field/Installation/PrefixField.php | 2 +- installation/src/Form/Rule/UsernameRule.php | 2 +- installation/src/Helper/DatabaseHelper.php | 2 +- installation/src/Model/ConfigurationModel.php | 2 +- installation/src/Model/DatabaseModel.php | 14 +- .../src/Service/Provider/Application.php | 10 +- language/en-GB/localise.php | 14 +- layouts/chromes/html5.php | 10 +- layouts/chromes/table.php | 2 +- layouts/joomla/content/category_default.php | 2 +- layouts/joomla/content/emptystate.php | 2 +- layouts/joomla/edit/frontediting_modules.php | 8 +- layouts/joomla/edit/params.php | 2 +- layouts/joomla/editors/buttons/button.php | 14 +- layouts/joomla/editors/buttons/modal.php | 8 +- layouts/joomla/form/field/color/simple.php | 2 +- .../form/field/groupedlist-fancy-select.php | 2 +- layouts/joomla/form/field/groupedlist.php | 2 +- .../joomla/form/field/list-fancy-select.php | 2 +- layouts/joomla/form/field/list.php | 2 +- layouts/joomla/form/field/media.php | 18 +- layouts/joomla/form/field/number.php | 2 +- layouts/joomla/form/field/radio/buttons.php | 20 +- layouts/joomla/form/field/range.php | 2 +- .../form/field/subform/repeatable-table.php | 2 +- .../joomla/form/field/subform/repeatable.php | 2 +- layouts/joomla/form/field/tag.php | 2 +- layouts/joomla/icon/iconclass.php | 2 +- layouts/joomla/mail/mailtemplate.php | 4 +- layouts/joomla/toolbar/basic.php | 2 +- layouts/joomla/toolbar/link.php | 2 +- layouts/joomla/toolbar/popup.php | 2 +- layouts/joomla/toolbar/standard.php | 2 +- layouts/joomla/toolbar/title.php | 2 +- .../libraries/html/bootstrap/modal/iframe.php | 4 +- .../libraries/html/bootstrap/modal/main.php | 2 +- .../libraries/html/bootstrap/tab/addtab.php | 8 +- .../html/bootstrap/tab/starttabset.php | 2 +- layouts/plugins/system/webauthn/manage.php | 4 +- libraries/bootstrap.php | 6 +- libraries/cms.php | 6 +- libraries/loader.php | 18 +- libraries/namespacemap.php | 16 +- libraries/php-encryption/Crypto.php | 36 +- libraries/phpass/PasswordHash.php | 29 +- libraries/src/Access/Access.php | 10 +- libraries/src/Access/Rule.php | 6 +- libraries/src/Access/Rules.php | 6 +- libraries/src/Adapter/Adapter.php | 18 +- .../Application/AdministratorApplication.php | 2 +- libraries/src/Application/ApiApplication.php | 4 +- .../src/Application/ApplicationHelper.php | 2 +- libraries/src/Application/CLI/ColorStyle.php | 4 +- libraries/src/Application/CMSApplication.php | 18 +- .../src/Application/ConsoleApplication.php | 2 +- .../src/Application/DaemonApplication.php | 4 +- libraries/src/Application/EventAware.php | 6 +- .../MultiFactorAuthenticationHandler.php | 14 +- libraries/src/Application/SiteApplication.php | 2 +- libraries/src/Application/WebApplication.php | 20 +- .../AssociationExtensionHelper.php | 4 +- .../Authentication/Password/MD5Handler.php | 2 +- libraries/src/Autoload/ClassLoader.php | 18 +- libraries/src/Button/ActionButton.php | 2 +- libraries/src/Button/TransitionButton.php | 2 +- libraries/src/Cache/Cache.php | 4 +- libraries/src/Cache/CacheController.php | 4 +- .../src/Cache/CacheControllerFactory.php | 2 +- .../CacheControllerFactoryAwareTrait.php | 2 +- libraries/src/Cache/CacheStorage.php | 4 +- .../Cache/Controller/CallbackController.php | 4 +- .../src/Cache/Controller/OutputController.php | 2 +- .../src/Cache/Controller/PageController.php | 4 +- .../src/Cache/Controller/ViewController.php | 4 +- libraries/src/Cache/Storage/ApcuStorage.php | 6 +- .../src/Cache/Storage/CacheStorageHelper.php | 18 +- .../src/Cache/Storage/MemcachedStorage.php | 2 +- libraries/src/Cache/Storage/RedisStorage.php | 6 +- libraries/src/Captcha/Captcha.php | 23 +- .../Google/HttpBridgePostRequestMethod.php | 2 +- libraries/src/Categories/Categories.php | 17 +- libraries/src/Categories/CategoryFactory.php | 18 +- libraries/src/Changelog/Changelog.php | 2 +- libraries/src/Client/ClientHelper.php | 27 +- libraries/src/Client/FtpClient.php | 14 +- libraries/src/Component/ComponentHelper.php | 4 +- .../src/Component/Router/RouterFactory.php | 52 +- .../src/Component/Router/RouterLegacy.php | 20 +- libraries/src/Component/Router/RouterView.php | 2 +- .../Router/RouterViewConfiguration.php | 18 +- .../src/Component/Router/Rules/MenuRules.php | 2 +- .../Component/Router/Rules/NomenuRules.php | 6 +- .../Router/Rules/PreprocessRules.php | 42 +- libraries/src/Console/AddUserCommand.php | 19 +- .../src/Console/AddUserToGroupCommand.php | 2 +- .../src/Console/CoreUpdateChannelCommand.php | 13 +- .../src/Console/ExtensionRemoveCommand.php | 4 +- .../src/Console/ExtensionsListCommand.php | 2 +- libraries/src/Console/FinderIndexCommand.php | 18 +- libraries/src/Console/ListUserCommand.php | 6 +- .../Loader/WritableContainerLoader.php | 33 +- .../Console/MaintenanceDatabaseCommand.php | 2 +- .../Console/RemoveUserFromGroupCommand.php | 2 +- .../src/Console/SessionMetadataGcCommand.php | 29 +- .../src/Console/SetConfigurationCommand.php | 20 +- .../Console/SiteCreatePublicFolderCommand.php | 4 +- libraries/src/Console/UpdateCoreCommand.php | 12 +- libraries/src/Crypt/Cipher/CryptoCipher.php | 14 +- libraries/src/Date/Date.php | 89 +- libraries/src/Dispatcher/ApiDispatcher.php | 2 +- .../src/Dispatcher/ComponentDispatcher.php | 6 +- .../Dispatcher/ComponentDispatcherFactory.php | 16 +- .../Dispatcher/LegacyComponentDispatcher.php | 18 +- .../Dispatcher/ModuleDispatcherFactory.php | 20 +- libraries/src/Document/Document.php | 23 +- libraries/src/Document/DocumentAwareTrait.php | 2 +- libraries/src/Document/Factory.php | 4 +- libraries/src/Document/HtmlDocument.php | 10 +- libraries/src/Document/ImageDocument.php | 18 +- libraries/src/Document/JsonapiDocument.php | 6 +- .../Document/Renderer/Feed/AtomRenderer.php | 2 +- .../Document/Renderer/Feed/RssRenderer.php | 4 +- .../Document/Renderer/Html/ModuleRenderer.php | 2 +- .../Renderer/Html/ScriptsRenderer.php | 4 +- .../Document/Renderer/Html/StylesRenderer.php | 6 +- libraries/src/Editor/Button/Button.php | 29 +- .../src/Editor/Button/ButtonsRegistry.php | 4 +- libraries/src/Editor/Editor.php | 8 +- libraries/src/Encrypt/Base32.php | 12 +- libraries/src/Encrypt/Totp.php | 49 +- libraries/src/Environment/Browser.php | 78 +- .../AuthenticationFailedExceptionHandler.php | 2 +- .../CheckinCheckoutExceptionHandler.php | 2 +- .../InvalidParameterExceptionHandler.php | 2 +- .../JsonApi/InvalidRouteExceptionHandler.php | 2 +- .../JsonApi/NotAcceptableExceptionHandler.php | 2 +- .../JsonApi/NotAllowedExceptionHandler.php | 2 +- .../ResourceNotFoundExceptionHandler.php | 2 +- .../Error/JsonApi/SaveExceptionHandler.php | 2 +- .../JsonApi/SendEmailExceptionHandler.php | 2 +- libraries/src/Event/AbstractEvent.php | 12 +- .../Event/Menu/PreprocessMenuItemsEvent.php | 4 +- .../src/Event/Model/PrepareDataEvent.php | 2 +- .../Event/Module/AfterRenderModulesEvent.php | 2 +- .../src/Event/Module/ModuleListEvent.php | 6 +- .../src/Event/MultiFactor/NotifyActionLog.php | 2 +- libraries/src/Event/Plugin/AjaxEvent.php | 2 +- .../src/Event/Privacy/CanRemoveDataEvent.php | 2 +- .../src/Event/Privacy/ExportRequestEvent.php | 4 +- libraries/src/Event/Result/ResultAware.php | 6 +- libraries/src/Event/View/DisplayEvent.php | 6 +- .../src/Event/Workflow/AbstractEvent.php | 8 +- libraries/src/Exception/ExceptionHandler.php | 8 +- libraries/src/Extension/Component.php | 20 +- .../src/Extension/ExtensionManagerTrait.php | 4 +- libraries/src/Extension/LegacyComponent.php | 2 +- libraries/src/Extension/Module.php | 37 +- .../Service/Provider/CategoryFactory.php | 18 +- .../Provider/ComponentDispatcherFactory.php | 24 +- .../Service/Provider/HelperFactory.php | 20 +- .../Extension/Service/Provider/MVCFactory.php | 20 +- .../src/Extension/Service/Provider/Module.php | 10 +- .../Provider/ModuleDispatcherFactory.php | 24 +- .../Service/Provider/RouterFactory.php | 20 +- libraries/src/Factory.php | 18 +- libraries/src/Feed/Feed.php | 10 +- libraries/src/Feed/FeedEntry.php | 10 +- libraries/src/Feed/FeedFactory.php | 2 +- libraries/src/Feed/FeedLink.php | 73 +- libraries/src/Feed/FeedParser.php | 2 +- libraries/src/Feed/FeedPerson.php | 63 +- libraries/src/Feed/Parser/RssParser.php | 4 +- libraries/src/Filesystem/File.php | 4 +- libraries/src/Filesystem/FilesystemHelper.php | 6 +- libraries/src/Filesystem/Folder.php | 2 +- libraries/src/Filesystem/Patcher.php | 12 +- .../src/Filesystem/Streams/StreamString.php | 12 +- libraries/src/Filter/InputFilter.php | 36 +- libraries/src/Filter/OutputFilter.php | 4 +- .../src/Form/Field/AccessiblemediaField.php | 13 +- libraries/src/Form/Field/AliastagField.php | 4 +- libraries/src/Form/Field/CalendarField.php | 49 +- libraries/src/Form/Field/CaptchaField.php | 13 +- libraries/src/Form/Field/CheckboxesField.php | 11 +- libraries/src/Form/Field/ChromestyleField.php | 4 +- libraries/src/Form/Field/ColorField.php | 39 +- .../src/Form/Field/ComponentlayoutField.php | 12 +- libraries/src/Form/Field/ContenttypeField.php | 2 +- libraries/src/Form/Field/EditorField.php | 19 +- libraries/src/Form/Field/FilelistField.php | 17 +- libraries/src/Form/Field/FolderlistField.php | 15 +- libraries/src/Form/Field/LanguageField.php | 4 +- libraries/src/Form/Field/MediaField.php | 32 +- libraries/src/Form/Field/MenuitemField.php | 16 +- libraries/src/Form/Field/MeterField.php | 13 +- libraries/src/Form/Field/ModalSelectField.php | 48 +- .../src/Form/Field/ModulelayoutField.php | 10 +- libraries/src/Form/Field/NumberField.php | 12 +- libraries/src/Form/Field/OrderingField.php | 2 +- libraries/src/Form/Field/PasswordField.php | 14 +- libraries/src/Form/Field/RulesField.php | 12 +- .../Field/SchemaorgComponentSectionsField.php | 2 +- .../src/Form/Field/SessionhandlerField.php | 2 +- libraries/src/Form/Field/SqlField.php | 16 +- libraries/src/Form/Field/SubformField.php | 17 +- libraries/src/Form/Field/TagField.php | 6 +- .../src/Form/Field/TemplatestyleField.php | 11 +- libraries/src/Form/Field/TextField.php | 19 +- libraries/src/Form/Field/TextareaField.php | 15 +- libraries/src/Form/Field/TimeField.php | 12 +- libraries/src/Form/Field/TimezoneField.php | 4 +- libraries/src/Form/Field/TransitionField.php | 4 +- libraries/src/Form/Field/UserField.php | 2 +- .../src/Form/Field/UsergrouplistField.php | 2 +- .../Field/WorkflowComponentSectionsField.php | 2 +- libraries/src/Form/Filter/TelFilter.php | 6 +- libraries/src/Form/Filter/UrlFilter.php | 6 +- libraries/src/Form/Form.php | 85 +- libraries/src/Form/FormFactoryAwareTrait.php | 2 +- libraries/src/Form/FormField.php | 32 +- libraries/src/Form/FormHelper.php | 6 +- libraries/src/Form/FormRule.php | 6 +- libraries/src/Form/Rule/CalendarRule.php | 4 +- libraries/src/Form/Rule/ColorRule.php | 2 +- libraries/src/Form/Rule/CssIdentifierRule.php | 2 +- .../Form/Rule/CssIdentifierSubstringRule.php | 2 +- libraries/src/Form/Rule/EmailRule.php | 2 +- libraries/src/Form/Rule/EqualsRule.php | 6 +- libraries/src/Form/Rule/ExistsRule.php | 2 +- libraries/src/Form/Rule/FilePathRule.php | 4 +- .../src/Form/Rule/FolderPathExistsRule.php | 2 +- libraries/src/Form/Rule/NotequalsRule.php | 4 +- libraries/src/Form/Rule/PasswordRule.php | 12 +- libraries/src/Form/Rule/ShowOnRule.php | 2 +- libraries/src/Form/Rule/TelRule.php | 6 +- libraries/src/Form/Rule/TimeRule.php | 2 +- libraries/src/Form/Rule/UrlRule.php | 2 +- libraries/src/HTML/HTMLHelper.php | 72 +- libraries/src/HTML/HTMLRegistryAwareTrait.php | 2 +- libraries/src/HTML/Helpers/Access.php | 2 +- libraries/src/HTML/Helpers/Bootstrap.php | 12 +- libraries/src/HTML/Helpers/Dropdown.php | 2 +- libraries/src/HTML/Helpers/Icons.php | 2 +- libraries/src/HTML/Helpers/JGrid.php | 6 +- libraries/src/HTML/Helpers/Links.php | 4 +- libraries/src/HTML/Helpers/Number.php | 8 +- libraries/src/HTML/Helpers/Select.php | 22 +- libraries/src/HTML/Helpers/StringHelper.php | 12 +- libraries/src/HTML/Helpers/UiTab.php | 2 +- libraries/src/Helper/AuthenticationHelper.php | 4 +- libraries/src/Helper/HelperFactory.php | 20 +- .../src/Helper/HelperFactoryAwareTrait.php | 2 +- libraries/src/Helper/LibraryHelper.php | 2 +- libraries/src/Helper/MediaHelper.php | 33 +- libraries/src/Helper/ModuleHelper.php | 12 +- .../Helper/PublicFolderGeneratorHelper.php | 4 +- libraries/src/Helper/TagsHelper.php | 27 +- libraries/src/Http/HttpFactory.php | 4 +- .../src/Http/Transport/CurlTransport.php | 4 +- .../src/Http/Transport/StreamTransport.php | 2 +- libraries/src/Image/Image.php | 73 +- libraries/src/Image/ImageFilter.php | 2 +- libraries/src/Input/Cli.php | 22 +- libraries/src/Input/Cookie.php | 20 +- libraries/src/Input/Input.php | 8 +- .../Installer/Adapter/ComponentAdapter.php | 43 +- .../src/Installer/Adapter/FileAdapter.php | 4 +- .../src/Installer/Adapter/LanguageAdapter.php | 2 +- .../src/Installer/Adapter/LibraryAdapter.php | 2 +- .../src/Installer/Adapter/ModuleAdapter.php | 6 +- .../src/Installer/Adapter/PackageAdapter.php | 8 +- .../src/Installer/Adapter/TemplateAdapter.php | 4 +- libraries/src/Installer/Installer.php | 24 +- libraries/src/Installer/InstallerAdapter.php | 8 +- libraries/src/Installer/InstallerHelper.php | 8 +- libraries/src/Installer/InstallerScript.php | 4 +- .../src/Installer/LegacyInstallerScript.php | 16 +- libraries/src/Language/Language.php | 12 +- libraries/src/Language/LanguageAwareTrait.php | 2 +- libraries/src/Language/LanguageHelper.php | 12 +- libraries/src/Language/Text.php | 6 +- libraries/src/Log/DelegatingPsrLogger.php | 18 +- libraries/src/Log/Log.php | 4 +- libraries/src/Log/LogEntry.php | 2 +- libraries/src/Log/Logger/CallbackLogger.php | 2 +- .../src/MVC/Controller/ApiController.php | 2 +- .../src/MVC/Controller/BaseController.php | 32 +- .../src/MVC/Controller/FormController.php | 12 +- libraries/src/MVC/Factory/LegacyFactory.php | 2 +- libraries/src/MVC/Factory/MVCFactory.php | 59 +- .../src/MVC/Factory/MVCFactoryAwareTrait.php | 2 +- .../MVC/Factory/MVCFactoryServiceTrait.php | 2 +- libraries/src/MVC/Model/AdminModel.php | 10 +- libraries/src/MVC/Model/BaseDatabaseModel.php | 10 +- libraries/src/MVC/Model/BaseModel.php | 2 +- .../src/MVC/Model/DatabaseAwareTrait.php | 2 +- libraries/src/MVC/Model/FormBehaviorTrait.php | 4 +- libraries/src/MVC/Model/FormModel.php | 2 +- .../src/MVC/Model/LegacyModelLoaderTrait.php | 8 +- libraries/src/MVC/Model/ListModel.php | 16 +- libraries/src/MVC/Model/State.php | 8 +- libraries/src/MVC/View/AbstractView.php | 12 +- libraries/src/MVC/View/CanDo.php | 8 +- libraries/src/MVC/View/CategoriesView.php | 2 +- libraries/src/MVC/View/CategoryFeedView.php | 4 +- libraries/src/MVC/View/CategoryView.php | 2 +- libraries/src/MVC/View/HtmlView.php | 19 +- .../Mail/Exception/MailDisabledException.php | 17 +- libraries/src/Mail/Mail.php | 2 +- libraries/src/Mail/MailHelper.php | 37 +- libraries/src/Mail/MailTemplate.php | 54 +- libraries/src/Mail/MailerFactory.php | 38 +- .../src/Mail/MailerFactoryAwareTrait.php | 2 +- libraries/src/Menu/MenuItem.php | 2 +- libraries/src/Menu/SiteMenu.php | 4 +- libraries/src/Object/CMSObject.php | 6 +- .../Object/LegacyPropertyManagementTrait.php | 8 +- libraries/src/Pagination/Pagination.php | 14 +- libraries/src/Pagination/PaginationObject.php | 58 +- libraries/src/Pathway/SitePathway.php | 2 +- libraries/src/Plugin/CMSPlugin.php | 2 +- libraries/src/Plugin/PluginHelper.php | 4 +- libraries/src/Profiler/Profiler.php | 12 +- libraries/src/Response/JsonResponse.php | 33 +- libraries/src/Router/ApiRouter.php | 10 +- libraries/src/Router/Route.php | 8 +- libraries/src/Router/Router.php | 4 +- libraries/src/Router/SiteRouter.php | 40 +- libraries/src/Router/SiteRouterAwareTrait.php | 2 +- libraries/src/Schema/ChangeItem.php | 48 +- .../ChangeItem/PostgresqlChangeItem.php | 14 +- libraries/src/Schema/ChangeSet.php | 32 +- .../src/Service/Provider/Application.php | 10 +- .../src/Service/Provider/Authentication.php | 12 +- .../src/Service/Provider/CacheController.php | 4 +- libraries/src/Service/Provider/Console.php | 80 +- libraries/src/Service/Provider/Database.php | 2 +- libraries/src/Service/Provider/Dispatcher.php | 4 +- .../src/Service/Provider/HTMLRegistry.php | 4 +- libraries/src/Service/Provider/Input.php | 4 +- libraries/src/Service/Provider/Language.php | 4 +- libraries/src/Service/Provider/Logger.php | 4 +- libraries/src/Service/Provider/Mailer.php | 4 +- libraries/src/Service/Provider/Pathway.php | 8 +- libraries/src/Service/Provider/Router.php | 12 +- libraries/src/Service/Provider/Session.php | 4 +- libraries/src/Service/Provider/User.php | 4 +- .../EventListener/MetadataManagerListener.php | 33 +- libraries/src/Session/MetadataManager.php | 45 +- libraries/src/Session/Session.php | 8 +- libraries/src/Session/SessionManager.php | 18 +- .../src/Session/Storage/JoomlaStorage.php | 20 +- libraries/src/String/PunycodeHelper.php | 6 +- libraries/src/TUF/TufFetcher.php | 80 +- libraries/src/Table/Content.php | 4 +- libraries/src/Table/ContentHistory.php | 2 +- libraries/src/Table/ContentType.php | 4 +- libraries/src/Table/MenuType.php | 12 +- libraries/src/Table/Nested.php | 45 +- libraries/src/Table/Table.php | 42 +- libraries/src/Table/Usergroup.php | 2 +- libraries/src/Toolbar/Button/HelpButton.php | 2 +- .../src/Toolbar/Button/InlinehelpButton.php | 4 +- libraries/src/Toolbar/Button/PopupButton.php | 8 +- .../src/Toolbar/Button/StandardButton.php | 32 +- libraries/src/Toolbar/Toolbar.php | 23 +- libraries/src/Toolbar/ToolbarButton.php | 11 +- libraries/src/UCM/UCMContent.php | 2 +- .../src/Updater/Adapter/CollectionAdapter.php | 6 +- .../src/Updater/Adapter/ExtensionAdapter.php | 6 +- libraries/src/Updater/Adapter/TufAdapter.php | 8 +- libraries/src/Updater/ConstraintChecker.php | 4 +- libraries/src/Updater/Update.php | 6 +- libraries/src/Updater/UpdateAdapter.php | 14 +- libraries/src/Updater/Updater.php | 8 +- libraries/src/Uri/Uri.php | 12 +- libraries/src/User/User.php | 2 +- libraries/src/User/UserFactory.php | 15 +- libraries/src/User/UserFactoryAwareTrait.php | 2 +- libraries/src/User/UserHelper.php | 12 +- libraries/src/Utility/BufferStreamHandler.php | 32 +- libraries/src/Version.php | 2 +- libraries/src/WebAsset/WebAssetItem.php | 4 +- libraries/src/WebAsset/WebAssetManager.php | 38 +- libraries/src/WebAsset/WebAssetRegistry.php | 2 +- libraries/src/WebAuthn/Server.php | 61 +- libraries/src/Workflow/Workflow.php | 10 +- .../src/Workflow/WorkflowServiceTrait.php | 4 +- .../src/Helper/ArticlesHelper.php | 2 +- .../src/Helper/ArticlesArchiveHelper.php | 2 +- .../src/Helper/ArticlesCategoryHelper.php | 6 +- .../src/Helper/ArticlesNewsHelper.php | 4 +- .../mod_banners/src/Dispatcher/Dispatcher.php | 4 +- modules/mod_banners/tmpl/default.php | 2 +- .../src/Helper/BreadcrumbsHelper.php | 2 +- modules/mod_feed/src/Helper/FeedHelper.php | 2 +- modules/mod_feed/tmpl/default.php | 4 +- modules/mod_finder/tmpl/default.php | 2 +- modules/mod_login/tmpl/default.php | 4 +- modules/mod_menu/mod_menu.php | 2 +- modules/mod_menu/src/Helper/MenuHelper.php | 16 +- modules/mod_menu/tmpl/default.php | 16 +- modules/mod_random_image/tmpl/default.php | 2 +- .../src/Helper/RelatedItemsHelper.php | 6 +- modules/mod_stats/src/Helper/StatsHelper.php | 6 +- .../src/Dispatcher/Dispatcher.php | 2 +- .../src/Helper/TagsPopularHelper.php | 2 +- .../src/Helper/TagsSimilarHelper.php | 2 +- .../src/Helper/UsersLatestHelper.php | 2 +- .../src/Helper/WhosonlineHelper.php | 4 +- .../mod_wrapper/src/Dispatcher/Dispatcher.php | 8 +- .../mod_wrapper/src/Helper/WrapperHelper.php | 4 +- .../actionlog/joomla/src/Extension/Joomla.php | 27 +- .../token/src/Extension/Token.php | 35 +- .../cookie/src/Extension/Cookie.php | 14 +- .../ldap/src/Extension/Ldap.php | 19 +- .../compat/src/classmap/classmap.php | 1018 ++++++++--------- .../src/classmap/extensions.classmap.php | 48 +- .../taggable/src/Extension/Taggable.php | 2 +- .../versionable/src/Extension/Versionable.php | 31 +- .../src/Field/ConsentBoxField.php | 4 +- .../content/fields/src/Extension/Fields.php | 8 +- .../content/joomla/src/Extension/Joomla.php | 21 +- .../loadmodule/src/Extension/LoadModule.php | 4 +- .../pagebreak/src/Extension/PageBreak.php | 10 +- .../src/Extension/PageNavigation.php | 66 +- plugins/content/vote/tmpl/rating.php | 4 +- .../editors-xtd/image/src/Extension/Image.php | 10 +- .../src/Provider/CodeMirrorProvider.php | 29 +- .../none/src/Provider/EditorNoneProvider.php | 29 +- .../editors/tinymce/src/Extension/TinyMCE.php | 2 +- .../tinymce/src/Field/UploaddirsField.php | 4 +- .../src/PluginTraits/ActiveSiteTemplate.php | 2 +- .../tinymce/src/PluginTraits/DisplayTrait.php | 29 +- .../tinymce/src/PluginTraits/XTDButtons.php | 10 +- .../extension/finder/src/Extension/Finder.php | 2 +- .../src/Extension/NamespaceMap.php | 16 +- plugins/fields/calendar/tmpl/calendar.php | 2 +- plugins/fields/imagelist/tmpl/imagelist.php | 4 +- plugins/fields/sql/tmpl/sql.php | 2 +- plugins/fields/subform/tmpl/subform.php | 6 +- .../local/src/Adapter/LocalAdapter.php | 60 +- .../filesystem/local/src/Extension/Local.php | 16 +- .../override/src/Extension/Override.php | 2 +- .../src/Extension/WebInstaller.php | 2 +- .../resize/src/Extension/Resize.php | 23 +- .../email/src/Extension/Email.php | 8 +- .../fixed/services/provider.php | 4 +- .../webauthn/src/Extension/Webauthn.php | 6 +- .../webauthn/src/Helper/Credentials.php | 8 +- .../yubikey/src/Extension/Yubikey.php | 22 +- .../downloadkey/src/Extension/Downloadkey.php | 2 +- .../src/Extension/Joomlaupdate.php | 19 +- .../multilang/src/Extension/MultiLanguage.php | 14 +- .../schemaorg/custom/src/Extension/Custom.php | 4 +- .../actionlogs/src/Extension/ActionLogs.php | 16 +- plugins/system/cache/src/Extension/Cache.php | 69 +- plugins/system/debug/services/provider.php | 14 +- .../debug/src/DataCollector/InfoCollector.php | 17 +- .../LanguageStringsCollector.php | 2 +- .../src/DataCollector/ProfileCollector.php | 10 +- .../src/DataCollector/QueryCollector.php | 48 +- .../DataCollector/RequestDataCollector.php | 2 +- plugins/system/debug/src/DataFormatter.php | 12 +- plugins/system/debug/src/Extension/Debug.php | 32 +- .../system/debug/src/JavascriptRenderer.php | 2 +- plugins/system/debug/src/JoomlaHttpDriver.php | 15 +- .../system/debug/src/Storage/FileStorage.php | 8 +- .../system/fields/src/Extension/Fields.php | 2 +- .../guidedtours/src/Extension/GuidedTours.php | 4 +- .../highlight/src/Extension/Highlight.php | 4 +- .../httpheaders/src/Extension/Httpheaders.php | 14 +- .../src/Extension/LanguageCode.php | 4 +- .../src/Extension/LanguageFilter.php | 33 +- plugins/system/log/src/Extension/Log.php | 2 +- plugins/system/logout/services/provider.php | 12 +- .../src/Extension/PrivacyConsent.php | 12 +- .../redirect/src/Extension/Redirect.php | 6 +- .../src/Extension/ScheduleRunner.php | 4 +- .../schemaorg/src/Extension/Schemaorg.php | 4 +- plugins/system/sef/src/Extension/Sef.php | 45 +- plugins/system/stats/layouts/stats.php | 2 +- plugins/system/stats/src/Extension/Stats.php | 16 +- .../src/Extension/TaskNotification.php | 6 +- .../system/webauthn/src/Authentication.php | 85 +- .../webauthn/src/CredentialRepository.php | 34 +- .../webauthn/src/Extension/Webauthn.php | 2 +- .../webauthn/src/MetadataRepository.php | 26 +- .../PluginTraits/AdditionalLoginButtons.php | 4 +- .../webauthn/src/PluginTraits/AjaxHandler.php | 51 +- .../src/PluginTraits/AjaxHandlerChallenge.php | 6 +- .../src/PluginTraits/AjaxHandlerDelete.php | 6 +- .../src/PluginTraits/AjaxHandlerLogin.php | 4 +- .../src/PluginTraits/AjaxHandlerSaveLabel.php | 6 +- .../src/PluginTraits/UserDeletion.php | 2 +- .../src/PluginTraits/UserProfileFields.php | 6 +- .../checkfiles/src/Extension/Checkfiles.php | 19 +- .../src/Extension/DeleteActionLogs.php | 2 +- .../src/Extension/Globalcheckin.php | 4 +- .../src/Extension/PrivacyConsent.php | 10 +- .../task/requests/src/Extension/Requests.php | 35 +- .../rotatelogs/src/Extension/RotateLogs.php | 6 +- .../sessiongc/src/Extension/SessionGC.php | 19 +- .../sitestatus/src/Extension/SiteStatus.php | 33 +- .../src/Extension/UpdateNotification.php | 10 +- .../src/Extension/ContactCreator.php | 2 +- plugins/user/joomla/src/Extension/Joomla.php | 12 +- .../user/profile/src/Extension/Profile.php | 14 +- plugins/user/token/src/Extension/Token.php | 12 +- .../user/token/src/Field/JoomlatokenField.php | 4 +- .../featuring/src/Extension/Featuring.php | 4 +- .../src/Extension/Notification.php | 17 +- .../publishing/src/Extension/Publishing.php | 2 +- templates/cassiopeia/component.php | 4 +- templates/cassiopeia/error.php | 12 +- .../cassiopeia/html/layouts/chromes/card.php | 8 +- .../html/layouts/chromes/noCard.php | 6 +- .../html/mod_menu/dropdown-metismenu.php | 15 +- templates/cassiopeia/index.php | 12 +- templates/cassiopeia/offline.php | 14 +- templates/system/offline.php | 4 +- tests/Integration/DBTestHelper.php | 2 +- .../Administrator/Indexer/ResultTest.php | 2 +- .../Libraries/Cms/Feed/FeedFactoryTest.php | 8 +- .../Libraries/Cms/Feed/FeedParserTest.php | 8 +- .../Cms/Feed/Parser/AtomParserTest.php | 4 +- .../Cms/Feed/Parser/RssParserTest.php | 64 +- tests/Unit/Libraries/Cms/Image/ImageTest.php | 18 +- .../Cms/MVC/Controller/BaseControllerTest.php | 4 +- .../Libraries/Cms/Plugin/CMSPluginTest.php | 2 +- .../Authentication/Ldap/LdapPluginTest.php | 23 +- .../Extension/CheckfilesPluginTest.php | 12 +- .../Requests/Extension/RequestsPluginTest.php | 2 +- .../Extension/SiteStatusPluginTest.php | 2 +- tests/Unit/bootstrap.php | 2 +- 920 files changed, 4335 insertions(+), 5697 deletions(-) diff --git a/administrator/components/com_actionlogs/src/Controller/ActionlogsController.php b/administrator/components/com_actionlogs/src/Controller/ActionlogsController.php index 80873249fb37a..1b6bc1abf7c45 100644 --- a/administrator/components/com_actionlogs/src/Controller/ActionlogsController.php +++ b/administrator/components/com_actionlogs/src/Controller/ActionlogsController.php @@ -87,7 +87,7 @@ public function exportLogs() if (\count($data)) { try { $rows = ActionlogsHelper::getCsvData($data); - } catch (\InvalidArgumentException $exception) { + } catch (\InvalidArgumentException) { $this->setMessage(Text::_('COM_ACTIONLOGS_ERROR_COULD_NOT_EXPORT_DATA'), 'error'); $this->setRedirect(Route::_('index.php?option=com_actionlogs&view=actionlogs', false)); diff --git a/administrator/components/com_actionlogs/src/Field/UserlogtypeField.php b/administrator/components/com_actionlogs/src/Field/UserlogtypeField.php index c821e5fb67a4e..5d381cfb62caa 100644 --- a/administrator/components/com_actionlogs/src/Field/UserlogtypeField.php +++ b/administrator/components/com_actionlogs/src/Field/UserlogtypeField.php @@ -57,7 +57,7 @@ public function getOptions() $globalExt = $params->get('loggable_extensions', []); if (!empty($extensions)) { - $userExt = substr($extensions[0], 2); + $userExt = substr((string) $extensions[0], 2); $userExt = substr($userExt, 0, -2); $userExt = explode('","', $userExt); } diff --git a/administrator/components/com_actionlogs/src/Helper/ActionlogsHelper.php b/administrator/components/com_actionlogs/src/Helper/ActionlogsHelper.php index 68cab09bbc17a..ecb6ed750b438 100644 --- a/administrator/components/com_actionlogs/src/Helper/ActionlogsHelper.php +++ b/administrator/components/com_actionlogs/src/Helper/ActionlogsHelper.php @@ -56,7 +56,7 @@ public static function getCsvData($data): \Generator \sprintf( '%s() requires an array or object implementing the Traversable interface, a %s was given.', __METHOD__, - \is_object($data) ? \get_class($data) : \gettype($data) + get_debug_type($data) ) ); } @@ -208,7 +208,7 @@ public static function getHumanReadableLogMessage($log, $generateLinks = true) foreach ($messageData as $key => $value) { // Escape any markup in the values to prevent XSS attacks - $value = $value !== null ? htmlspecialchars($value, ENT_QUOTES, 'UTF-8') : ''; + $value = $value !== null ? htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8') : ''; // Convert relative url to absolute url so that it is clickable in action logs notification email if ($generateLinks && StringHelper::strpos($value, 'index.php?') === 0) { @@ -310,7 +310,7 @@ public static function loadActionLogPluginsLanguage() try { $rows = $db->loadObjectList(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { $rows = []; } diff --git a/administrator/components/com_actionlogs/src/Model/ActionlogModel.php b/administrator/components/com_actionlogs/src/Model/ActionlogModel.php index f11c3bf87c034..2a746b1f210b3 100644 --- a/administrator/components/com_actionlogs/src/Model/ActionlogModel.php +++ b/administrator/components/com_actionlogs/src/Model/ActionlogModel.php @@ -85,7 +85,7 @@ public function addLog($messages, $messageLanguageKey, $context, $userId = 0) try { $db->insertObject('#__action_logs', $logMessage); $loggedMessages[] = $logMessage; - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // Ignore it } } @@ -93,7 +93,7 @@ public function addLog($messages, $messageLanguageKey, $context, $userId = 0) try { // Send notification email to users who choose to be notified about the action logs $this->sendNotificationEmails($loggedMessages, $user->name, $context); - } catch (MailDisabledException | phpMailerException $e) { + } catch (MailDisabledException | phpMailerException) { // Ignore it } } diff --git a/administrator/components/com_actionlogs/src/Model/ActionlogsModel.php b/administrator/components/com_actionlogs/src/Model/ActionlogsModel.php index f3883d9e06245..e94aea21c6f35 100644 --- a/administrator/components/com_actionlogs/src/Model/ActionlogsModel.php +++ b/administrator/components/com_actionlogs/src/Model/ActionlogsModel.php @@ -147,12 +147,12 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $ids = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :id') ->bind(':id', $ids, ParameterType::INTEGER); - } elseif (stripos($search, 'item_id:') === 0) { - $ids = (int) substr($search, 8); + } elseif (stripos((string) $search, 'item_id:') === 0) { + $ids = (int) substr((string) $search, 8); $query->where($db->quoteName('a.item_id') . ' = :itemid') ->bind(':itemid', $ids, ParameterType::INTEGER); } else { @@ -363,7 +363,7 @@ public function purge() { try { $this->getDatabase()->truncateTable('#__action_logs'); - } catch (\Exception $e) { + } catch (\Exception) { return false; } diff --git a/administrator/components/com_actionlogs/src/Plugin/ActionLogPlugin.php b/administrator/components/com_actionlogs/src/Plugin/ActionLogPlugin.php index 946ec21d2a156..6a355fa8bc090 100644 --- a/administrator/components/com_actionlogs/src/Plugin/ActionLogPlugin.php +++ b/administrator/components/com_actionlogs/src/Plugin/ActionLogPlugin.php @@ -84,11 +84,11 @@ protected function addLog($messages, $messageLanguageKey, $context, $userId = nu } if (\array_key_exists('type', $message)) { - $message['type'] = strtoupper($message['type']); + $message['type'] = strtoupper((string) $message['type']); } if (\array_key_exists('app', $message)) { - $message['app'] = strtoupper($message['app']); + $message['app'] = strtoupper((string) $message['app']); } $messages[$index] = $message; diff --git a/administrator/components/com_admin/script.php b/administrator/components/com_admin/script.php index c480ed3e7f6c6..a78503f5c4753 100644 --- a/administrator/components/com_admin/script.php +++ b/administrator/components/com_admin/script.php @@ -187,7 +187,7 @@ protected function clearStatsCache() return; } - $params = json_decode($params, true); + $params = json_decode((string) $params, true); // Reset the last run parameter if (isset($params['lastrun'])) { @@ -2960,7 +2960,7 @@ private function migrateTinymceConfiguration(): bool return false; } - $params = json_decode($params, true); + $params = json_decode((string) $params, true); // If there are no toolbars there is nothing to migrate if (!isset($params['configuration']['toolbars'])) { @@ -3196,7 +3196,7 @@ protected function fixFilesystemPermissions() try { // Using hard-coded string because a new language string would not be available in all cases Log::add('Fixing permissions for files and folders.', Log::INFO, 'Update'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } diff --git a/administrator/components/com_admin/src/Model/HelpModel.php b/administrator/components/com_admin/src/Model/HelpModel.php index 2198e6430e801..b1373f97ea5fb 100644 --- a/administrator/components/com_admin/src/Model/HelpModel.php +++ b/administrator/components/com_admin/src/Model/HelpModel.php @@ -171,7 +171,7 @@ public function &getToc() $title = Text::_($title); // Strip the extension - $file = preg_replace('#\.xml$|\.html$#', '', $file); + $file = preg_replace('#\.xml$|\.html$#', '', (string) $file); if ($help_search && StringHelper::strpos(StringHelper::strtolower(strip_tags($buffer)), StringHelper::strtolower($help_search)) === false) { continue; diff --git a/administrator/components/com_admin/src/Model/SysinfoModel.php b/administrator/components/com_admin/src/Model/SysinfoModel.php index 2bd59bc01ee70..17aa2a431b97d 100644 --- a/administrator/components/com_admin/src/Model/SysinfoModel.php +++ b/administrator/components/com_admin/src/Model/SysinfoModel.php @@ -216,15 +216,15 @@ protected function cleanPrivateData(array $dataArray, string $dataType = 'other' protected function cleanSectionPrivateData($sectionValues) { if (!\is_array($sectionValues)) { - if (strstr($sectionValues, JPATH_ROOT)) { + if (strstr((string) $sectionValues, JPATH_ROOT)) { $sectionValues = 'xxxxxx'; } - return \strlen($sectionValues) ? 'xxxxxx' : ''; + return \strlen((string) $sectionValues) ? 'xxxxxx' : ''; } foreach ($sectionValues as $setting => $value) { - $sectionValues[$setting] = \strlen($value) ? 'xxxxxx' : ''; + $sectionValues[$setting] = \strlen((string) $value) ? 'xxxxxx' : ''; } return $sectionValues; @@ -411,12 +411,12 @@ public function &getPHPInfo(): string date_default_timezone_set('UTC'); phpinfo(INFO_GENERAL | INFO_CONFIGURATION | INFO_MODULES); $phpInfo = ob_get_clean(); - preg_match_all('#]*>(.*)#siU', $phpInfo, $output); - $output = preg_replace('#]*>#', '', $output[1][0]); - $output = preg_replace('#(\w),(\w)#', '\1, \2', $output); + preg_match_all('#]*>(.*)#siU', (string) $phpInfo, $output); + $output = preg_replace('#]*>#', '
', (string) $output[1][0]); + $output = preg_replace('#(\w),(\w)#', '\1, \2', (string) $output); $output = str_replace('
', '', $output); $output = str_replace('
', '', $output); - $output = preg_replace('#
(.*)#', '$1', $output); + $output = preg_replace('#(.*)#', '$1', (string) $output); $output = str_replace('
', '', $output); $output = str_replace('', '', $output); $this->php_info = $output; @@ -466,7 +466,7 @@ public function getExtensions(): array } catch (\Exception $e) { try { Log::add(Text::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { Factory::getApplication()->enqueueMessage( Text::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()), 'warning' @@ -636,7 +636,7 @@ public function getDirectory(bool $public = false): array $this->addDirectory('configuration.php', JPATH_CONFIGURATION . '/configuration.php'); // Is there a cache path in configuration.php? - if ($cache_path = trim($registry->get('cache_path', ''))) { + if ($cache_path = trim((string) $registry->get('cache_path', ''))) { // Frontend and backend use same directory for caching. $this->addDirectory($cache_path, $cache_path, 'COM_ADMIN_CACHE_DIRECTORY'); } else { @@ -721,8 +721,8 @@ protected function parsePhpInfo(string $html): array { $html = strip_tags($html, '

'); $html = preg_replace('/]*>([^<]+)<\/th>/', '\1', $html); - $html = preg_replace('/]*>([^<]+)<\/td>/', '\1', $html); - $t = preg_split('/(]*>[^<]+<\/h2>)/', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + $html = preg_replace('/]*>([^<]+)<\/td>/', '\1', (string) $html); + $t = preg_split('/(]*>[^<]+<\/h2>)/', (string) $html, -1, PREG_SPLIT_DELIM_CAPTURE); $r = []; $count = \count($t); $p1 = '([^<]+)<\/info>'; diff --git a/administrator/components/com_admin/src/Service/HTML/Configuration.php b/administrator/components/com_admin/src/Service/HTML/Configuration.php index bc9058b9f6831..d3a223742c3ea 100644 --- a/administrator/components/com_admin/src/Service/HTML/Configuration.php +++ b/administrator/components/com_admin/src/Service/HTML/Configuration.php @@ -40,6 +40,6 @@ public function value($value): string $value = implode(', ', $value); } - return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); + return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); } } diff --git a/administrator/components/com_admin/tmpl/sysinfo/default_system.php b/administrator/components/com_admin/tmpl/sysinfo/default_system.php index 06e1bdb41f60a..4e1486f2bd850 100644 --- a/administrator/components/com_admin/tmpl/sysinfo/default_system.php +++ b/administrator/components/com_admin/tmpl/sysinfo/default_system.php @@ -133,7 +133,7 @@ - info['useragent'], ENT_COMPAT, 'UTF-8'); ?> + info['useragent'], ENT_COMPAT, 'UTF-8'); ?> diff --git a/administrator/components/com_associations/src/Controller/AssociationController.php b/administrator/components/com_associations/src/Controller/AssociationController.php index 54db9cba3e9e1..ba176cbab3d45 100644 --- a/administrator/components/com_associations/src/Controller/AssociationController.php +++ b/administrator/components/com_associations/src/Controller/AssociationController.php @@ -39,7 +39,7 @@ class AssociationController extends FormController */ public function edit($key = null, $urlVar = null) { - list($extensionName, $typeName) = explode('.', $this->input->get('itemtype', '', 'string'), 2); + [$extensionName, $typeName] = explode('.', (string) $this->input->get('itemtype', '', 'string'), 2); $id = $this->input->get('id', 0, 'int'); @@ -67,7 +67,7 @@ public function cancel($key = null) { $this->checkToken(); - list($extensionName, $typeName) = explode('.', $this->input->get('itemtype', '', 'string'), 2); + [$extensionName, $typeName] = explode('.', (string) $this->input->get('itemtype', '', 'string'), 2); // Only check in, if component item type allows to check out. if (AssociationsHelper::typeSupportsCheckout($extensionName, $typeName)) { @@ -75,7 +75,7 @@ public function cancel($key = null) $targetId = $this->input->get('target-id', '', 'string'); if ($targetId !== '') { - $ids = array_unique(explode(',', $targetId)); + $ids = array_unique(explode(',', (string) $targetId)); } $ids[] = $this->input->get('id', 0, 'int'); diff --git a/administrator/components/com_associations/src/Controller/AssociationsController.php b/administrator/components/com_associations/src/Controller/AssociationsController.php index dd24dad3cd972..bc417cad76f05 100644 --- a/administrator/components/com_associations/src/Controller/AssociationsController.php +++ b/administrator/components/com_associations/src/Controller/AssociationsController.php @@ -94,7 +94,7 @@ public function checkin() $this->setRedirect(Route::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false)); // Figure out if the item supports checking and check it in - list($extensionName, $typeName) = explode('.', $this->input->get('itemtype')); + [$extensionName, $typeName] = explode('.', (string) $this->input->get('itemtype')); $extension = AssociationsHelper::getSupportedExtension($extensionName); $types = $extension->get('types'); diff --git a/administrator/components/com_associations/src/Dispatcher/Dispatcher.php b/administrator/components/com_associations/src/Dispatcher/Dispatcher.php index 4875f196e2110..d62e262eb59f2 100644 --- a/administrator/components/com_associations/src/Dispatcher/Dispatcher.php +++ b/administrator/components/com_associations/src/Dispatcher/Dispatcher.php @@ -43,7 +43,7 @@ protected function checkAccess() $itemType = $this->input->get('itemtype', '', 'string'); if ($itemType !== '') { - list($extensionName, $typeName) = explode('.', $itemType); + [$extensionName, $typeName] = explode('.', (string) $itemType); if (!AssociationsHelper::hasSupport($extensionName)) { throw new \Exception( diff --git a/administrator/components/com_associations/src/Field/ItemlanguageField.php b/administrator/components/com_associations/src/Field/ItemlanguageField.php index 9c7d24754f4f7..91804a81f91e2 100644 --- a/administrator/components/com_associations/src/Field/ItemlanguageField.php +++ b/administrator/components/com_associations/src/Field/ItemlanguageField.php @@ -46,7 +46,7 @@ protected function getOptions() { $input = Factory::getApplication()->getInput(); - list($extensionName, $typeName) = explode('.', $input->get('itemtype', '', 'string'), 2); + [$extensionName, $typeName] = explode('.', (string) $input->get('itemtype', '', 'string'), 2); // Get the extension specific helper method $helper = AssociationsHelper::getExtensionHelper($extensionName); diff --git a/administrator/components/com_associations/src/Helper/AssociationsHelper.php b/administrator/components/com_associations/src/Helper/AssociationsHelper.php index b185c9907e73f..86f734c533082 100644 --- a/administrator/components/com_associations/src/Helper/AssociationsHelper.php +++ b/administrator/components/com_associations/src/Helper/AssociationsHelper.php @@ -193,7 +193,7 @@ private static function getExtensionHelperClassName($extensionName) */ private static function getExtensionRealName($extensionName) { - return strpos($extensionName, 'com_') === false ? $extensionName : substr($extensionName, 4); + return !str_contains($extensionName, 'com_') ? $extensionName : substr($extensionName, 4); } /** @@ -317,7 +317,7 @@ public static function getAssociationHtmlList($extensionName, $typeName, $itemId $text = $language->lang_code; $tooltip = '' . htmlspecialchars($language->title, ENT_QUOTES, 'UTF-8') . '
' - . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '

' . $additional; + . htmlspecialchars((string) $title, ENT_QUOTES, 'UTF-8') . '

' . $additional; $classes = 'badge ' . $labelClass; $items[$langCode]['link'] = '' . $text . '' @@ -409,7 +409,7 @@ public static function getSupportedExtension($extensionName) $title = $helper->getTypeTitle($typeName); $languageKey = $typeName; - $typeNameExploded = explode('.', $typeName); + $typeNameExploded = explode('.', (string) $typeName); if (array_pop($typeNameExploded) === 'category') { $languageKey = strtoupper($extensionName) . '_CATEGORIES'; diff --git a/administrator/components/com_associations/src/Model/AssociationsModel.php b/administrator/components/com_associations/src/Model/AssociationsModel.php index 8f16fc2ddafd9..4de600b88ce88 100644 --- a/administrator/components/com_associations/src/Model/AssociationsModel.php +++ b/administrator/components/com_associations/src/Model/AssociationsModel.php @@ -154,7 +154,7 @@ protected function getListQuery() { $type = null; - list($extensionName, $typeName) = explode('.', $this->state->get('itemtype'), 2); + [$extensionName, $typeName] = explode('.', (string) $this->state->get('itemtype'), 2); $extension = AssociationsHelper::getSupportedExtension($extensionName); $types = $extension->get('types'); @@ -423,12 +423,12 @@ protected function getListQuery() // Filter by search in name. if ($search = $this->getState('filter.search')) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName($fields['id']) . ' = :searchid') ->bind(':searchid', $search, ParameterType::INTEGER); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where('(' . $db->quoteName($fields['title']) . ' LIKE :title' . ' OR ' . $db->quoteName($fields['alias']) . ' LIKE :alias)') ->bind(':title', $search) @@ -480,7 +480,7 @@ public function purge($context = '', $key = '') try { $db->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { $app->enqueueMessage(Text::_('COM_ASSOCIATIONS_PURGE_FAILED'), 'error'); return false; @@ -543,7 +543,7 @@ public function clean($context = '', $key = '') try { $db->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { $app->enqueueMessage(Text::_('COM_ASSOCIATIONS_DELETE_ORPHANS_FAILED'), 'error'); return false; diff --git a/administrator/components/com_associations/src/View/Association/HtmlView.php b/administrator/components/com_associations/src/View/Association/HtmlView.php index d0e662e404d84..f01660655b3a1 100644 --- a/administrator/components/com_associations/src/View/Association/HtmlView.php +++ b/administrator/components/com_associations/src/View/Association/HtmlView.php @@ -235,7 +235,7 @@ public function display($tpl = null): void $input = $this->app->getInput(); $this->referenceId = $input->get('id', 0, 'int'); - [$extensionName, $typeName] = explode('.', $input->get('itemtype', '', 'string'), 2); + [$extensionName, $typeName] = explode('.', (string) $input->get('itemtype', '', 'string'), 2); /** @var Registry $extension */ $extension = AssociationsHelper::getSupportedExtension($extensionName); @@ -305,7 +305,7 @@ public function display($tpl = null): void $this->targetTitle = ''; if ($target = $input->get('target', '', 'string')) { - $matches = preg_split("#[\:]+#", $target); + $matches = preg_split("#[\:]+#", (string) $target); $this->targetAction = $matches[2]; $this->targetId = $matches[1]; $this->targetLanguage = $matches[0]; diff --git a/administrator/components/com_associations/src/View/Associations/HtmlView.php b/administrator/components/com_associations/src/View/Associations/HtmlView.php index 179ed3e1e745f..fbf16b94f33e3 100644 --- a/administrator/components/com_associations/src/View/Associations/HtmlView.php +++ b/administrator/components/com_associations/src/View/Associations/HtmlView.php @@ -140,7 +140,7 @@ public function display($tpl = null) } elseif ($this->state->get('itemtype') != '' && $this->state->get('language') != '') { $type = null; - list($extensionName, $typeName) = explode('.', $this->state->get('itemtype'), 2); + [$extensionName, $typeName] = explode('.', (string) $this->state->get('itemtype'), 2); $extension = AssociationsHelper::getSupportedExtension($extensionName); diff --git a/administrator/components/com_banners/src/Field/ClicksField.php b/administrator/components/com_banners/src/Field/ClicksField.php index 80d34d4046515..e1a257be757dc 100644 --- a/administrator/components/com_banners/src/Field/ClicksField.php +++ b/administrator/components/com_banners/src/Field/ClicksField.php @@ -44,7 +44,7 @@ protected function getInput() $onclick = ' onclick="document.getElementById(\'' . $this->id . '\').value=\'0\';"'; return '
' + . htmlspecialchars((string) $this->value, ENT_COMPAT, 'UTF-8') . '" readonly="readonly">' . '
'; } diff --git a/administrator/components/com_banners/src/Field/ImpmadeField.php b/administrator/components/com_banners/src/Field/ImpmadeField.php index 3cf5a25574a80..d7fc08bf8cae5 100644 --- a/administrator/components/com_banners/src/Field/ImpmadeField.php +++ b/administrator/components/com_banners/src/Field/ImpmadeField.php @@ -44,7 +44,7 @@ protected function getInput() $onclick = ' onclick="document.getElementById(\'' . $this->id . '\').value=\'0\';"'; return '
' + . htmlspecialchars((string) $this->value, ENT_COMPAT, 'UTF-8') . '" readonly="readonly">' . '
'; } diff --git a/administrator/components/com_banners/src/Field/ImptotalField.php b/administrator/components/com_banners/src/Field/ImptotalField.php index 2fc6b6c53cf5e..54c969d0d9877 100644 --- a/administrator/components/com_banners/src/Field/ImptotalField.php +++ b/administrator/components/com_banners/src/Field/ImptotalField.php @@ -49,7 +49,7 @@ protected function getInput() $value = empty($this->value) ? '' : $this->value; $checked = empty($this->value) ? ' checked="checked"' : ''; - return '' . '
' . '
'; diff --git a/administrator/components/com_banners/src/Model/BannerModel.php b/administrator/components/com_banners/src/Model/BannerModel.php index b03de8fd0eb8f..e83c65008401c 100644 --- a/administrator/components/com_banners/src/Model/BannerModel.php +++ b/administrator/components/com_banners/src/Model/BannerModel.php @@ -418,7 +418,7 @@ public function save($data) if ($createCategory && $this->canCreateCategory()) { $category = [ // Remove #new# prefix, if exists. - 'title' => strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'], + 'title' => str_starts_with((string) $data['catid'], '#new#') ? substr((string) $data['catid'], 5) : $data['catid'], 'parent_id' => 1, 'extension' => 'com_banners', 'language' => $data['language'], @@ -447,7 +447,7 @@ public function save($data) $origTable->load($input->getInt('id')); if ($data['name'] == $origTable->name) { - list($name, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); + [$name, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); $data['name'] = $name; $data['alias'] = $alias; } else { diff --git a/administrator/components/com_banners/src/Model/BannersModel.php b/administrator/components/com_banners/src/Model/BannersModel.php index a835d5bb23f5a..44a2ac2702800 100644 --- a/administrator/components/com_banners/src/Model/BannersModel.php +++ b/administrator/components/com_banners/src/Model/BannersModel.php @@ -178,12 +178,12 @@ protected function getListQuery() // Filter by search in title if ($search = $this->getState('filter.search')) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where('(' . $db->quoteName('a.name') . ' LIKE :search1 OR ' . $db->quoteName('a.alias') . ' LIKE :search2)') ->bind([':search1', ':search2'], $search); } diff --git a/administrator/components/com_banners/src/Model/ClientsModel.php b/administrator/components/com_banners/src/Model/ClientsModel.php index 54216dd4f553e..05e1881c3fe78 100644 --- a/administrator/components/com_banners/src/Model/ClientsModel.php +++ b/administrator/components/com_banners/src/Model/ClientsModel.php @@ -164,7 +164,7 @@ protected function getListQuery() ); // Filter by search in title - if ($search = trim($this->getState('filter.search', ''))) { + if ($search = trim((string) $this->getState('filter.search', ''))) { if (stripos($search, 'id:') === 0) { $search = (int) substr($search, 3); $query->where($db->quoteName('a.id') . ' = :search') diff --git a/administrator/components/com_banners/tmpl/banners/default.php b/administrator/components/com_banners/tmpl/banners/default.php index 7b24a58ff792c..82e7638d3cd89 100644 --- a/administrator/components/com_banners/tmpl/banners/default.php +++ b/administrator/components/com_banners/tmpl/banners/default.php @@ -92,7 +92,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="true" class="js-draggable" data-url="" data-direction="" data-nested="true"> items as $i => $item) : $ordering = ($listOrder == 'ordering'); diff --git a/administrator/components/com_cache/src/Model/CacheModel.php b/administrator/components/com_cache/src/Model/CacheModel.php index cae0a8d60401c..efbfaab09d3f9 100644 --- a/administrator/components/com_cache/src/Model/CacheModel.php +++ b/administrator/components/com_cache/src/Model/CacheModel.php @@ -130,7 +130,7 @@ public function getData() // Process filter by search term. if ($search = $this->getState('filter.search')) { foreach ($data as $key => $cacheItem) { - if (stripos($cacheItem->group, $search) === false) { + if (stripos($cacheItem->group, (string) $search) === false) { unset($data[$key]); } } @@ -140,7 +140,7 @@ public function getData() $listOrder = $this->getState('list.ordering', 'group'); $listDirn = $this->getState('list.direction', 'ASC'); - $this->_data = ArrayHelper::sortObjects($data, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true); + $this->_data = ArrayHelper::sortObjects($data, $listOrder, strtolower((string) $listDirn) === 'desc' ? -1 : 1, true, true); // Process pagination. $limit = (int) $this->getState('list.limit', 25); @@ -153,10 +153,10 @@ public function getData() } else { $this->_data = []; } - } catch (CacheConnectingException $exception) { + } catch (CacheConnectingException) { $this->setError(Text::_('COM_CACHE_ERROR_CACHE_CONNECTION_FAILED')); $this->_data = []; - } catch (UnsupportedCacheException $exception) { + } catch (UnsupportedCacheException) { $this->setError(Text::_('COM_CACHE_ERROR_CACHE_DRIVER_UNSUPPORTED')); $this->_data = []; } @@ -224,9 +224,7 @@ public function clean($group = '') { try { $this->getCache()->clean($group); - } catch (CacheConnectingException $exception) { - return false; - } catch (UnsupportedCacheException $exception) { + } catch (CacheConnectingException|UnsupportedCacheException) { return false; } @@ -264,9 +262,7 @@ public function purge() { try { Factory::getCache('')->gc(); - } catch (CacheConnectingException $exception) { - return false; - } catch (UnsupportedCacheException $exception) { + } catch (CacheConnectingException|UnsupportedCacheException) { return false; } diff --git a/administrator/components/com_categories/layouts/joomla/form/field/categoryedit.php b/administrator/components/com_categories/layouts/joomla/form/field/categoryedit.php index 7e2fd4ea0fab5..f9d8edd041039 100644 --- a/administrator/components/com_categories/layouts/joomla/form/field/categoryedit.php +++ b/administrator/components/com_categories/layouts/joomla/form/field/categoryedit.php @@ -141,4 +141,4 @@ ->useScript('webcomponent.field-fancy-select'); ?> -> +> diff --git a/administrator/components/com_categories/src/Field/CategoryeditField.php b/administrator/components/com_categories/src/Field/CategoryeditField.php index c824639799c3b..64e6530e22533 100644 --- a/administrator/components/com_categories/src/Field/CategoryeditField.php +++ b/administrator/components/com_categories/src/Field/CategoryeditField.php @@ -97,14 +97,11 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) */ public function __get($name) { - switch ($name) { - case 'allowAdd': - return (bool) $this->$name; - case 'customPrefix': - return $this->$name; - } - - return parent::__get($name); + return match ($name) { + 'allowAdd' => (bool) $this->$name, + 'customPrefix' => $this->$name, + default => parent::__get($name), + }; } /** @@ -196,7 +193,7 @@ protected function getOptions() // Filter language if (!empty($this->element['language'])) { - if (strpos($this->element['language'], ',') !== false) { + if (str_contains($this->element['language'], ',')) { $language = explode(',', $this->element['language']); } else { $language = $this->element['language']; diff --git a/administrator/components/com_categories/src/Field/ComponentsCategoryField.php b/administrator/components/com_categories/src/Field/ComponentsCategoryField.php index c6599b83b6127..d3205e0e25254 100644 --- a/administrator/components/com_categories/src/Field/ComponentsCategoryField.php +++ b/administrator/components/com_categories/src/Field/ComponentsCategoryField.php @@ -60,7 +60,7 @@ protected function getOptions() $option->value = $categoryType; // Extract the component name and optional section name - $parts = explode('.', $categoryType); + $parts = explode('.', (string) $categoryType); $component = $parts[0]; $section = (\count($parts) > 1) ? $parts[1] : null; diff --git a/administrator/components/com_categories/src/Field/Modal/CategoryField.php b/administrator/components/com_categories/src/Field/Modal/CategoryField.php index ba48fdcc64355..d9f042c8b399e 100644 --- a/administrator/components/com_categories/src/Field/Modal/CategoryField.php +++ b/administrator/components/com_categories/src/Field/Modal/CategoryField.php @@ -53,8 +53,8 @@ class CategoryField extends ModalSelectField public function setup(\SimpleXMLElement $element, $value, $group = null) { // Check if the value consist with id:alias, extract the id only - if ($value && str_contains($value, ':')) { - [$id] = explode(':', $value, 2); + if ($value && str_contains((string) $value, ':')) { + [$id] = explode(':', (string) $value, 2); $value = (int) $id; } diff --git a/administrator/components/com_categories/src/Model/CategoriesModel.php b/administrator/components/com_categories/src/Model/CategoriesModel.php index defbc31c0aa84..2f0437b0ffc72 100644 --- a/administrator/components/com_categories/src/Model/CategoriesModel.php +++ b/administrator/components/com_categories/src/Model/CategoriesModel.php @@ -109,7 +109,7 @@ protected function populateState($ordering = 'a.lft', $direction = 'asc') $extension = $app->getUserStateFromRequest($this->context . '.filter.extension', 'extension', 'com_content', 'cmd'); $this->setState('filter.extension', $extension); - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); // Extract the component name $this->setState('filter.component', $parts[0]); @@ -296,12 +296,12 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->extendWhere( 'AND', [ @@ -418,7 +418,7 @@ public function getAssoc() $extension = $this->getState('filter.extension'); $this->hasAssociation = Associations::isEnabled(); - $extension = explode('.', $extension); + $extension = explode('.', (string) $extension); $component = array_shift($extension); $cname = str_replace('com_', '', $component); diff --git a/administrator/components/com_categories/src/Model/CategoryModel.php b/administrator/components/com_categories/src/Model/CategoryModel.php index f9e516ee0bddb..f6954ff510f31 100644 --- a/administrator/components/com_categories/src/Model/CategoryModel.php +++ b/administrator/components/com_categories/src/Model/CategoryModel.php @@ -182,7 +182,7 @@ protected function populateState() $extension = $app->getInput()->get('extension', 'com_content'); $this->setState('category.extension', $extension); - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); // Extract the component name $this->setState('category.component', $parts[0]); @@ -254,7 +254,7 @@ public function getForm($data = [], $loadData = true) // A workaround to get the extension into the model for save requests. if (empty($extension) && isset($data['extension'])) { $extension = $data['extension']; - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); $this->setState('category.extension', $extension); $this->setState('category.component', $parts[0]); @@ -274,7 +274,7 @@ public function getForm($data = [], $loadData = true) } $categoryId = $jinput->get('id'); - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); $assetKey = $categoryId ? $extension . '.category.' . $categoryId : $parts[0]; if (!$this->getCurrentUser()->authorise('core.edit.state', $assetKey)) { @@ -334,7 +334,7 @@ protected function loadFormData() // Pre-select some filters (Status, Language, Access) in edit form if those have been selected in Category Manager if (!$data->id) { // Check for which extension the Category Manager is used and get selected fields - $extension = substr($app->getUserState('com_categories.categories.filter.extension', ''), 4); + $extension = substr((string) $app->getUserState('com_categories.categories.filter.extension', ''), 4); $filters = (array) $app->getUserState('com_categories.categories.' . $extension . '.filter'); $data->set( @@ -438,7 +438,7 @@ protected function preprocessForm(Form $form, $data, $group = 'content') $path = Path::clean(JPATH_ADMINISTRATOR . "/components/$component/helpers/category.php"); if (file_exists($path)) { - $cName = ucfirst($eName) . ucfirst($section) . 'HelperCategory'; + $cName = ucfirst($eName) . ucfirst((string) $section) . 'HelperCategory'; \JLoader::register($cName, $path); @@ -1283,7 +1283,7 @@ public function getAssoc() $extension = $this->getState('category.extension', ''); $this->hasAssociation = Associations::isEnabled(); - $extension = explode('.', $extension); + $extension = explode('.', (string) $extension); $component = array_shift($extension); $cname = str_replace('com_', '', $component); diff --git a/administrator/components/com_categories/src/View/Categories/HtmlView.php b/administrator/components/com_categories/src/View/Categories/HtmlView.php index aa012b5052633..a51f4b9cc86e2 100644 --- a/administrator/components/com_categories/src/View/Categories/HtmlView.php +++ b/administrator/components/com_categories/src/View/Categories/HtmlView.php @@ -215,7 +215,7 @@ protected function addToolbar() } // Prepare the toolbar. - ToolbarHelper::title($title, 'folder categories ' . substr($component, 4) . ($section ? "-$section" : '') . '-categories'); + ToolbarHelper::title($title, 'folder categories ' . substr((string) $component, 4) . ($section ? "-$section" : '') . '-categories'); if ($canDo->get('core.create') || \count($user->getAuthorisedCategories($component, 'core.create')) > 0) { $toolbar->addNew('category.add'); @@ -309,7 +309,7 @@ protected function addToolbar() if ($lang->hasKey($languageKey)) { $ref_key = $languageKey; } else { - $languageKey = 'JHELP_COMPONENTS_' . strtoupper(substr($component, 4) . ($section ? "_$section" : '')) . '_CATEGORIES'; + $languageKey = 'JHELP_COMPONENTS_' . strtoupper(substr((string) $component, 4) . ($section ? "_$section" : '')) . '_CATEGORIES'; if ($lang->hasKey($languageKey)) { $ref_key = $languageKey; @@ -325,7 +325,7 @@ protected function addToolbar() * -remotely searching in a component URL if helpURL param exists in the component and is NOT set to '' */ if (!$url) { - if ($lang->hasKey($lang_help_url = strtoupper($component) . '_HELP_URL')) { + if ($lang->hasKey($lang_help_url = strtoupper((string) $component) . '_HELP_URL')) { $debug = $lang->setDebug(false); $url = Text::_($lang_help_url); $lang->setDebug($debug); diff --git a/administrator/components/com_categories/src/View/Category/HtmlView.php b/administrator/components/com_categories/src/View/Category/HtmlView.php index 7e54e36d6af94..8a54441c42b58 100644 --- a/administrator/components/com_categories/src/View/Category/HtmlView.php +++ b/administrator/components/com_categories/src/View/Category/HtmlView.php @@ -178,7 +178,7 @@ protected function addToolbar() } // The extension can be in the form com_foo.section - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); $component = $parts[0]; $section = (\count($parts) > 1) ? $parts[1] : null; $componentParams = ComponentHelper::getParams($component); @@ -357,7 +357,7 @@ protected function addModalToolbar() } // The extension can be in the form com_foo.section - $parts = explode('.', $extension); + $parts = explode('.', (string) $extension); $component = $parts[0]; // Need to load the menu language file as mod_menu hasn't been loaded yet. diff --git a/administrator/components/com_categories/tmpl/categories/default.php b/administrator/components/com_categories/tmpl/categories/default.php index 1535e9eeeb213..c210dc55053b3 100644 --- a/administrator/components/com_categories/tmpl/categories/default.php +++ b/administrator/components/com_categories/tmpl/categories/default.php @@ -30,8 +30,8 @@ $extension = $this->escape($this->state->get('filter.extension')); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); -$saveOrder = ($listOrder == 'a.lft' && strtolower($listDirn) == 'asc'); -$parts = explode('.', $extension, 2); +$saveOrder = ($listOrder == 'a.lft' && strtolower((string) $listDirn) == 'asc'); +$parts = explode('.', (string) $extension, 2); $component = $parts[0]; $section = null; @@ -127,7 +127,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="false" class="js-draggable" data-url="" data-direction="" data-nested="false" > items as $i => $item) : ?> ordering as $k => $v) { $v = implode('-', $v); $v = '-' . $v . '-'; - if (strpos($v, '-' . $_currentParentId . '-') !== false) { + if (str_contains($v, '-' . $_currentParentId . '-')) { $parentsStr .= ' ' . $k; $_currentParentId = $k; break; diff --git a/administrator/components/com_checkin/src/Model/CheckinModel.php b/administrator/components/com_checkin/src/Model/CheckinModel.php index 50e663de3accb..103763f200938 100644 --- a/administrator/components/com_checkin/src/Model/CheckinModel.php +++ b/administrator/components/com_checkin/src/Model/CheckinModel.php @@ -96,7 +96,7 @@ public function checkin($ids = []) foreach ($ids as $tn) { // Make sure we get the right tables based on prefix. - if (stripos($tn, $app->get('dbprefix')) !== 0) { + if (stripos((string) $tn, (string) $app->get('dbprefix')) !== 0) { continue; } @@ -173,11 +173,11 @@ public function getItems() foreach ($tables as $tn) { // Make sure we get the right tables based on prefix. - if (stripos($tn, $prefix) !== 0) { + if (stripos((string) $tn, (string) $prefix) !== 0) { continue; } - if ($this->getState('filter.search') && stripos($tn, $this->getState('filter.search')) === false) { + if ($this->getState('filter.search') && stripos((string) $tn, (string) $this->getState('filter.search')) === false) { continue; } @@ -209,14 +209,14 @@ public function getItems() // Order items by table if ($this->getState('list.ordering') == 'table') { - if (strtolower($this->getState('list.direction')) == 'asc') { + if (strtolower((string) $this->getState('list.direction')) == 'asc') { ksort($results); } else { krsort($results); } } else { // Order items by number of items - if (strtolower($this->getState('list.direction')) == 'asc') { + if (strtolower((string) $this->getState('list.direction')) == 'asc') { asort($results); } else { arsort($results); diff --git a/administrator/components/com_config/src/Controller/ApplicationController.php b/administrator/components/com_config/src/Controller/ApplicationController.php index eb33421783efb..a36f9c8b4004d 100644 --- a/administrator/components/com_config/src/Controller/ApplicationController.php +++ b/administrator/components/com_config/src/Controller/ApplicationController.php @@ -181,16 +181,10 @@ public function save() $this->app->enqueueMessage(Text::_('COM_CONFIG_SAVE_SUCCESS'), 'message'); // Set the redirect based on the task. - switch ($this->input->getCmd('task')) { - case 'apply': - $this->setRedirect(Route::_('index.php?option=com_config', false)); - break; - - case 'save': - default: - $this->setRedirect(Route::_('index.php', false)); - break; - } + match ($this->input->getCmd('task')) { + 'apply' => $this->setRedirect(Route::_('index.php?option=com_config', false)), + default => $this->setRedirect(Route::_('index.php', false)), + }; } /** diff --git a/administrator/components/com_config/src/Controller/ComponentController.php b/administrator/components/com_config/src/Controller/ComponentController.php index f7abd791c87c2..03b6b93e103c6 100644 --- a/administrator/components/com_config/src/Controller/ComponentController.php +++ b/administrator/components/com_config/src/Controller/ComponentController.php @@ -76,7 +76,7 @@ public function save($key = null, $urlVar = null) $form = $model->getForm(); // Make sure com_joomlaupdate and com_privacy can only be accessed by SuperUser - if (\in_array(strtolower($option), ['com_joomlaupdate', 'com_privacy'], true) && !$user->authorise('core.admin')) { + if (\in_array(strtolower((string) $option), ['com_joomlaupdate', 'com_privacy'], true) && !$user->authorise('core.admin')) { $this->setRedirect(Route::_('index.php', false), Text::_('JERROR_ALERTNOAUTHOR'), 'error'); } @@ -95,7 +95,7 @@ public function save($key = null, $urlVar = null) $redirect = ''; if (!empty($returnUri)) { - $redirect = '&return=' . urlencode($returnUri); + $redirect = '&return=' . urlencode((string) $returnUri); } // Validate the posted data. @@ -162,7 +162,7 @@ public function save($key = null, $urlVar = null) $redirect = 'index.php?option=' . $option; if (!empty($returnUri)) { - $redirect = base64_decode($returnUri); + $redirect = base64_decode((string) $returnUri); } // Don't redirect to an external URL. @@ -198,7 +198,7 @@ public function cancel($key = null) $redirect = 'index.php?option=' . $component; if (!empty($returnUri)) { - $redirect = base64_decode($returnUri); + $redirect = base64_decode((string) $returnUri); } // Don't redirect to an external URL. diff --git a/administrator/components/com_config/src/Controller/DisplayController.php b/administrator/components/com_config/src/Controller/DisplayController.php index 008a20deff0f5..894f6fddb31ed 100644 --- a/administrator/components/com_config/src/Controller/DisplayController.php +++ b/administrator/components/com_config/src/Controller/DisplayController.php @@ -55,7 +55,7 @@ public function display($cachable = false, $urlparams = []) // Make sure com_joomlaupdate and com_privacy can only be accessed by SuperUser if ( - \in_array(strtolower($component), ['com_joomlaupdate', 'com_privacy']) + \in_array(strtolower((string) $component), ['com_joomlaupdate', 'com_privacy']) && !$this->app->getIdentity()->authorise('core.admin') ) { $this->setRedirect(Route::_('index.php'), Text::_('JERROR_ALERTNOAUTHOR'), 'error'); diff --git a/administrator/components/com_config/src/Dispatcher/Dispatcher.php b/administrator/components/com_config/src/Dispatcher/Dispatcher.php index 18c901eb88288..936d080467705 100644 --- a/administrator/components/com_config/src/Dispatcher/Dispatcher.php +++ b/administrator/components/com_config/src/Dispatcher/Dispatcher.php @@ -45,7 +45,7 @@ protected function checkAccess(): void $view = $this->input->getCmd('view'); $component = $this->input->getCmd('component'); - if ($component && (substr($task, 0, 10) === 'component.' || $view === 'component')) { + if ($component && (str_starts_with($task, 'component.') || $view === 'component')) { // User is changing component settings, check if he has permission to do that $canAccess = ConfigHelper::canChangeComponentConfig($component); } else { diff --git a/administrator/components/com_config/src/Field/FiltersField.php b/administrator/components/com_config/src/Field/FiltersField.php index d2b5a6a9cc2e5..8ae3c46699c11 100644 --- a/administrator/components/com_config/src/Field/FiltersField.php +++ b/administrator/components/com_config/src/Field/FiltersField.php @@ -125,7 +125,7 @@ protected function getInput() . ' name="' . $this->name . '[' . $group->value . '][filter_tags]"' . ' type="text"' . ' id="' . $this->id . $group->value . '_filter_tags" class="novalidate form-control"' - . ' value="' . htmlspecialchars($group_filter['filter_tags'], ENT_QUOTES) . '"' + . ' value="' . htmlspecialchars((string) $group_filter['filter_tags'], ENT_QUOTES) . '"' . '>'; $html[] = ' '; $html[] = ' '; @@ -135,7 +135,7 @@ protected function getInput() . ' name="' . $this->name . '[' . $group->value . '][filter_attributes]"' . ' type="text"' . ' id="' . $this->id . $group->value . '_filter_attributes" class="novalidate form-control"' - . ' value="' . htmlspecialchars($group_filter['filter_attributes'], ENT_QUOTES) . '"' + . ' value="' . htmlspecialchars((string) $group_filter['filter_attributes'], ENT_QUOTES) . '"' . '>'; $html[] = ' '; $html[] = ' '; diff --git a/administrator/components/com_config/src/Model/ApplicationModel.php b/administrator/components/com_config/src/Model/ApplicationModel.php index a362c9523c808..9ab5eea418202 100644 --- a/administrator/components/com_config/src/Model/ApplicationModel.php +++ b/administrator/components/com_config/src/Model/ApplicationModel.php @@ -167,7 +167,7 @@ public function validateDbConnection($data) } } else { // Check localhost - if (strtolower($data['host']) === 'localhost') { + if (strtolower((string) $data['host']) === 'localhost') { Factory::getApplication()->enqueueMessage(Text::_('COM_CONFIG_ERROR_DATABASE_ENCRYPTION_LOCALHOST'), 'error'); return false; @@ -306,7 +306,7 @@ public function save($data) ]; foreach (['cipher', 'ca', 'key', 'cert'] as $value) { - $confVal = trim($data['dbssl' . $value]); + $confVal = trim((string) $data['dbssl' . $value]); if ($confVal !== '') { $options['ssl'][$value] = $confVal; @@ -475,7 +475,7 @@ public function save($data) } else { $revisedDbo->truncateTable('#__session'); } - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { /* * The database API logs errors on failures so we don't need to add any error handling mechanisms here. * Also, this data won't be added or checked anymore once the configuration is saved, so it'll purge itself @@ -506,7 +506,7 @@ public function save($data) Log::WARNING, 'jerror' ); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage( Text::sprintf( 'COM_CONFIG_ERROR_CUSTOM_SESSION_FILESYSTEM_PATH_NOTWRITABLE_USING_DEFAULT', @@ -583,7 +583,7 @@ public function save($data) Log::WARNING, 'jerror' ); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage( Text::sprintf('COM_CONFIG_ERROR_CUSTOM_CACHE_PATH_NOTWRITABLE_USING_DEFAULT', $path, JPATH_CACHE), 'warning' @@ -599,7 +599,7 @@ public function save($data) if ($error) { try { Log::add(Text::sprintf('COM_CONFIG_ERROR_CACHE_PATH_NOTWRITABLE', $path), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { $app->enqueueMessage(Text::sprintf('COM_CONFIG_ERROR_CACHE_PATH_NOTWRITABLE', $path), 'warning'); } @@ -616,16 +616,16 @@ public function save($data) if ((!$data['caching'] && $prev['caching']) || $data['cache_handler'] !== $prev['cache_handler']) { try { Factory::getCache()->clean(); - } catch (CacheConnectingException $exception) { + } catch (CacheConnectingException) { try { Log::add(Text::_('COM_CONFIG_ERROR_CACHE_CONNECTION_FAILED'), Log::WARNING, 'jerror'); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage(Text::_('COM_CONFIG_ERROR_CACHE_CONNECTION_FAILED'), 'warning'); } - } catch (UnsupportedCacheException $exception) { + } catch (UnsupportedCacheException) { try { Log::add(Text::_('COM_CONFIG_ERROR_CACHE_DRIVER_UNSUPPORTED'), Log::WARNING, 'jerror'); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage(Text::_('COM_CONFIG_ERROR_CACHE_DRIVER_UNSUPPORTED'), 'warning'); } } @@ -659,7 +659,7 @@ public function save($data) Log::WARNING, 'jerror' ); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage( Text::sprintf('COM_CONFIG_ERROR_CUSTOM_TEMP_PATH_NOTWRITABLE_USING_DEFAULT', $path, $defaultTmpPath), 'warning' @@ -674,7 +674,7 @@ public function save($data) if ($error) { try { Log::add(Text::sprintf('COM_CONFIG_ERROR_TMP_PATH_NOTWRITABLE', $path), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { $app->enqueueMessage(Text::sprintf('COM_CONFIG_ERROR_TMP_PATH_NOTWRITABLE', $path), 'warning'); } } @@ -708,7 +708,7 @@ public function save($data) Log::WARNING, 'jerror' ); - } catch (\RuntimeException $logException) { + } catch (\RuntimeException) { $app->enqueueMessage( Text::sprintf('COM_CONFIG_ERROR_CUSTOM_LOG_PATH_NOTWRITABLE_USING_DEFAULT', $path, $defaultLogPath), 'warning' @@ -722,7 +722,7 @@ public function save($data) if ($error) { try { Log::add(Text::sprintf('COM_CONFIG_ERROR_LOG_PATH_NOTWRITABLE', $path), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { $app->enqueueMessage(Text::sprintf('COM_CONFIG_ERROR_LOG_PATH_NOTWRITABLE', $path), 'warning'); } } @@ -871,7 +871,7 @@ public function storePermissions($permission = null) } // We are creating a new item so we don't have an item id so don't allow. - if (substr($permission['component'], -6) === '.false') { + if (str_ends_with((string) $permission['component'], '.false')) { $app->enqueueMessage(Text::_('JLIB_RULES_SAVE_BEFORE_CHANGE_PERMISSIONS'), 'error'); return false; @@ -946,7 +946,7 @@ public function storePermissions($permission = null) /** @var Asset $parentAsset */ $parentAsset = Table::getInstance('Asset'); - if (strpos($asset->name, '.') !== false) { + if (str_contains($asset->name, '.')) { $assetParts = explode('.', $asset->name); $parentAsset->loadByName($assetParts[0]); $parentAssetId = $parentAsset->id; diff --git a/administrator/components/com_contact/src/Field/Modal/ContactField.php b/administrator/components/com_contact/src/Field/Modal/ContactField.php index 7dc872ac6db99..c7d7658bf3cd4 100644 --- a/administrator/components/com_contact/src/Field/Modal/ContactField.php +++ b/administrator/components/com_contact/src/Field/Modal/ContactField.php @@ -53,8 +53,8 @@ class ContactField extends ModalSelectField public function setup(\SimpleXMLElement $element, $value, $group = null) { // Check if the value consist with id:alias, extract the id only - if ($value && str_contains($value, ':')) { - [$id] = explode(':', $value, 2); + if ($value && str_contains((string) $value, ':')) { + [$id] = explode(':', (string) $value, 2); $value = (int) $id; } diff --git a/administrator/components/com_contact/src/Model/ContactModel.php b/administrator/components/com_contact/src/Model/ContactModel.php index 7344f38bd7ee3..b5ebac640c48d 100644 --- a/administrator/components/com_contact/src/Model/ContactModel.php +++ b/administrator/components/com_contact/src/Model/ContactModel.php @@ -292,7 +292,7 @@ public function save($data) if ($createCategory && $this->canCreateCategory()) { $category = [ // Remove #new# prefix, if exists. - 'title' => strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'], + 'title' => str_starts_with((string) $data['catid'], '#new#') ? substr((string) $data['catid'], 5) : $data['catid'], 'parent_id' => 1, 'extension' => 'com_contact', 'language' => $data['language'], @@ -320,7 +320,7 @@ public function save($data) $origTable->load($input->getInt('id')); if ($data['name'] == $origTable->name) { - list($name, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); + [$name, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); $data['name'] = $name; $data['alias'] = $alias; } else { diff --git a/administrator/components/com_contact/src/Model/ContactsModel.php b/administrator/components/com_contact/src/Model/ContactsModel.php index cbacd0635e8c0..f74f38eaf7338 100644 --- a/administrator/components/com_contact/src/Model/ContactsModel.php +++ b/administrator/components/com_contact/src/Model/ContactsModel.php @@ -154,7 +154,7 @@ protected function getListQuery() $db->quoteName( explode( ', ', - $this->getState( + (string) $this->getState( 'list.select', 'a.id, a.name, a.alias, a.checked_out, a.checked_out_time, a.catid, a.user_id' . ', a.published, a.access, a.created, a.created_by, a.ordering, a.featured, a.language' . @@ -254,12 +254,12 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :id'); $query->bind(':id', $search, ParameterType::INTEGER); } else { - $search = '%' . trim($search) . '%'; + $search = '%' . trim((string) $search) . '%'; $query->where( '(' . $db->quoteName('a.name') . ' LIKE :name OR ' . $db->quoteName('a.alias') . ' LIKE :alias)' ); diff --git a/administrator/components/com_contact/tmpl/contacts/default.php b/administrator/components/com_contact/tmpl/contacts/default.php index 83049cc92f6be..4f64b23805ff5 100644 --- a/administrator/components/com_contact/tmpl/contacts/default.php +++ b/administrator/components/com_contact/tmpl/contacts/default.php @@ -93,7 +93,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="true" class="js-draggable" data-url="" data-direction="" data-nested="true"> items); diff --git a/administrator/components/com_content/src/Event/Model/FeatureEvent.php b/administrator/components/com_content/src/Event/Model/FeatureEvent.php index 226a56203a3c7..79235d684cff4 100644 --- a/administrator/components/com_content/src/Event/Model/FeatureEvent.php +++ b/administrator/components/com_content/src/Event/Model/FeatureEvent.php @@ -42,15 +42,15 @@ public function __construct($name, array $arguments = []) throw new \BadMethodCallException("Argument 'extension' of event $this->name is not of type 'string'"); } - if (strpos($arguments['extension'], '.') === false) { + if (!str_contains($arguments['extension'], '.')) { throw new \BadMethodCallException("Argument 'extension' of event $this->name has wrong format. Valid format: 'component.section'"); } if (!\array_key_exists('extensionName', $arguments) || !\array_key_exists('section', $arguments)) { $parts = explode('.', $arguments['extension']); - $arguments['extensionName'] = $arguments['extensionName'] ?? $parts[0]; - $arguments['section'] = $arguments['section'] ?? $parts[1]; + $arguments['extensionName'] ??= $parts[0]; + $arguments['section'] ??= $parts[1]; } if (!isset($arguments['pks']) || !\is_array($arguments['pks'])) { diff --git a/administrator/components/com_content/src/Extension/ContentComponent.php b/administrator/components/com_content/src/Extension/ContentComponent.php index bd2861e1fa467..191c3e25c4585 100644 --- a/administrator/components/com_content/src/Extension/ContentComponent.php +++ b/administrator/components/com_content/src/Extension/ContentComponent.php @@ -293,7 +293,7 @@ public function getModelName($context): string return 'Article'; } - return ucfirst($modelname); + return ucfirst((string) $modelname); } /** diff --git a/administrator/components/com_content/src/Field/Modal/ArticleField.php b/administrator/components/com_content/src/Field/Modal/ArticleField.php index c173321bbf6c0..337bd46e29985 100644 --- a/administrator/components/com_content/src/Field/Modal/ArticleField.php +++ b/administrator/components/com_content/src/Field/Modal/ArticleField.php @@ -53,8 +53,8 @@ class ArticleField extends ModalSelectField public function setup(\SimpleXMLElement $element, $value, $group = null) { // Check if the value consist with id:alias, extract the id only - if ($value && str_contains($value, ':')) { - [$id] = explode(':', $value, 2); + if ($value && str_contains((string) $value, ':')) { + [$id] = explode(':', (string) $value, 2); $value = (int) $id; } diff --git a/administrator/components/com_content/src/Helper/ContentHelper.php b/administrator/components/com_content/src/Helper/ContentHelper.php index 46aa32889767d..e0255918aa172 100644 --- a/administrator/components/com_content/src/Helper/ContentHelper.php +++ b/administrator/components/com_content/src/Helper/ContentHelper.php @@ -69,9 +69,7 @@ public static function filterTransitions(array $transitions, int $pk, int $workf return array_values( array_filter( $transitions, - function ($var) use ($pk, $workflowId) { - return \in_array($var['from_stage_id'], [-1, $pk]) && $workflowId == $var['workflow_id']; - } + fn($var) => \in_array($var['from_stage_id'], [-1, $pk]) && $workflowId == $var['workflow_id'] ) ); } diff --git a/administrator/components/com_content/src/Model/ArticleModel.php b/administrator/components/com_content/src/Model/ArticleModel.php index 6474be7a2753f..c255133e0ebfd 100644 --- a/administrator/components/com_content/src/Model/ArticleModel.php +++ b/administrator/components/com_content/src/Model/ArticleModel.php @@ -106,7 +106,7 @@ class ArticleModel extends AdminModel implements WorkflowModelInterface */ public function __construct($config = [], ?MVCFactoryInterface $factory = null, ?FormFactoryInterface $formFactory = null) { - $config['events_map'] = $config['events_map'] ?? []; + $config['events_map'] ??= []; $config['events_map'] = array_merge( ['featured' => 'content'], @@ -117,9 +117,9 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null, // Set the featured status change events $this->event_before_change_featured = $config['event_before_change_featured'] ?? $this->event_before_change_featured; - $this->event_before_change_featured = $this->event_before_change_featured ?? 'onContentBeforeChangeFeatured'; + $this->event_before_change_featured ??= 'onContentBeforeChangeFeatured'; $this->event_after_change_featured = $config['event_after_change_featured'] ?? $this->event_after_change_featured; - $this->event_after_change_featured = $this->event_after_change_featured ?? 'onContentAfterChangeFeatured'; + $this->event_after_change_featured ??= 'onContentAfterChangeFeatured'; $this->setUpWorkflow('com_content.article'); } @@ -202,7 +202,7 @@ protected function batchMove($value, $pks, $contexts) // Set some needed variables. $this->user = $this->getCurrentUser(); $this->table = $this->getTable(); - $this->tableClassName = \get_class($this->table); + $this->tableClassName = $this->table::class; $this->contentType = new UCMType(); $this->type = $this->contentType->getTypeByTable($this->tableClassName); } @@ -682,7 +682,7 @@ public function save($data) if ($createCategory && $this->canCreateCategory()) { $category = [ // Remove #new# prefix, if exists. - 'title' => strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'], + 'title' => str_starts_with((string) $data['catid'], '#new#') ? substr((string) $data['catid'], 5) : $data['catid'], 'parent_id' => 1, 'extension' => 'com_content', 'language' => $data['language'], @@ -709,7 +709,7 @@ public function save($data) foreach ($data['urls'] as $i => $url) { if ($url != false && ($i == 'urla' || $i == 'urlb' || $i == 'urlc')) { - if (preg_match('~^#[a-zA-Z]{1}[a-zA-Z0-9-_:.]*$~', $check['urls'][$i]) == 1) { + if (preg_match('~^#[a-zA-Z]{1}[a-zA-Z0-9-_:.]*$~', (string) $check['urls'][$i]) == 1) { $data['urls'][$i] = $check['urls'][$i]; } else { $data['urls'][$i] = PunycodeHelper::urlToPunycode($url); @@ -745,7 +745,7 @@ public function save($data) } if ($data['title'] == $origTable->title) { - list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); + [$title, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); $data['title'] = $title; $data['alias'] = $alias; } elseif ($data['alias'] == $origTable->alias) { @@ -768,7 +768,7 @@ public function save($data) $msg = Text::_('COM_CONTENT_SAVE_WARNING'); } - list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); + [$title, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); $data['alias'] = $alias; if (isset($msg)) { diff --git a/administrator/components/com_content/src/Model/ArticlesModel.php b/administrator/components/com_content/src/Model/ArticlesModel.php index ac02ff4299142..f761f4389b3bb 100644 --- a/administrator/components/com_content/src/Model/ArticlesModel.php +++ b/administrator/components/com_content/src/Model/ArticlesModel.php @@ -418,25 +418,25 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); - } elseif (stripos($search, 'author:') === 0) { - $search = '%' . substr($search, 7) . '%'; + } elseif (stripos((string) $search, 'author:') === 0) { + $search = '%' . substr((string) $search, 7) . '%'; $query->where('(' . $db->quoteName('ua.name') . ' LIKE :search1 OR ' . $db->quoteName('ua.username') . ' LIKE :search2)') ->bind([':search1', ':search2'], $search); - } elseif (stripos($search, 'content:') === 0) { - $search = '%' . substr($search, 8) . '%'; + } elseif (stripos((string) $search, 'content:') === 0) { + $search = '%' . substr((string) $search, 8) . '%'; $query->where('(' . $db->quoteName('a.introtext') . ' LIKE :search1 OR ' . $db->quoteName('a.fulltext') . ' LIKE :search2)') ->bind([':search1', ':search2'], $search); - } elseif (stripos($search, 'checkedout:') === 0) { - $search = '%' . substr($search, 11) . '%'; + } elseif (stripos((string) $search, 'checkedout:') === 0) { + $search = '%' . substr((string) $search, 11) . '%'; $query->where('(' . $db->quoteName('uc.name') . ' LIKE :search1 OR ' . $db->quoteName('uc.username') . ' LIKE :search2)' . ' AND ' . $db->quoteName('a.checked_out') . ' IS NOT NULL') ->bind([':search1', ':search2'], $search); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where( '(' . $db->quoteName('a.title') . ' LIKE :search1 OR ' . $db->quoteName('a.alias') . ' LIKE :search2' . ' OR ' . $db->quoteName('a.note') . ' LIKE :search3)' diff --git a/administrator/components/com_content/tmpl/articles/default.php b/administrator/components/com_content/tmpl/articles/default.php index 862896a10057c..54519c3f62a60 100644 --- a/administrator/components/com_content/tmpl/articles/default.php +++ b/administrator/components/com_content/tmpl/articles/default.php @@ -39,11 +39,11 @@ $listDirn = $this->escape($this->state->get('list.direction')); $saveOrder = $listOrder == 'a.ordering'; -if (strpos($listOrder, 'publish_up') !== false) { +if (str_contains((string) $listOrder, 'publish_up')) { $orderingColumn = 'publish_up'; -} elseif (strpos($listOrder, 'publish_down') !== false) { +} elseif (str_contains((string) $listOrder, 'publish_down')) { $orderingColumn = 'publish_down'; -} elseif (strpos($listOrder, 'modified') !== false) { +} elseif (str_contains((string) $listOrder, 'modified')) { $orderingColumn = 'modified'; } else { $orderingColumn = 'created'; @@ -152,7 +152,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="true" class="js-draggable" data-url="" data-direction="" data-nested="true"> items as $i => $item) : $item->max_ordering = 0; diff --git a/administrator/components/com_content/tmpl/featured/default.php b/administrator/components/com_content/tmpl/featured/default.php index df58b6aa66b58..4ab80b31bb814 100644 --- a/administrator/components/com_content/tmpl/featured/default.php +++ b/administrator/components/com_content/tmpl/featured/default.php @@ -39,11 +39,11 @@ $listDirn = $this->escape($this->state->get('list.direction')); $saveOrder = $listOrder == 'fp.ordering'; -if (strpos($listOrder, 'publish_up') !== false) { +if (str_contains((string) $listOrder, 'publish_up')) { $orderingColumn = 'publish_up'; -} elseif (strpos($listOrder, 'publish_down') !== false) { +} elseif (str_contains((string) $listOrder, 'publish_down')) { $orderingColumn = 'publish_down'; -} elseif (strpos($listOrder, 'modified') !== false) { +} elseif (str_contains((string) $listOrder, 'modified')) { $orderingColumn = 'modified'; } else { $orderingColumn = 'created'; @@ -152,7 +152,7 @@ class="js-draggable" data-url="" data-direction="" class="js-draggable" data-url="" data-direction=""> items); ?> items as $i => $item) : diff --git a/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php b/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php index 6dcab10af041b..738939e8f41ad 100644 --- a/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php +++ b/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php @@ -76,7 +76,7 @@ public static function decodeFields($jsonString) if (\is_object($object)) { foreach ($object as $name => $value) { - if (!\is_null($value) && $subObject = json_decode($value)) { + if (!\is_null($value) && $subObject = json_decode((string) $value)) { $object->$name = $subObject; } } @@ -201,7 +201,7 @@ public static function getLookupValue($lookup, $value) try { $result = $db->loadResult(); - } catch (\Exception $e) { + } catch (\Exception) { // Ignore any errors and just return false return false; } diff --git a/administrator/components/com_contenthistory/src/Model/HistoryModel.php b/administrator/components/com_contenthistory/src/Model/HistoryModel.php index 73470f5645422..fa06f07b33773 100644 --- a/administrator/components/com_contenthistory/src/Model/HistoryModel.php +++ b/administrator/components/com_contenthistory/src/Model/HistoryModel.php @@ -152,7 +152,7 @@ public function delete(&$pks) if ($error) { try { Log::add($error, Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { Factory::getApplication()->enqueueMessage($error, 'warning'); } @@ -161,7 +161,7 @@ public function delete(&$pks) try { Log::add(Text::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { Factory::getApplication()->enqueueMessage(Text::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), 'warning'); } @@ -259,7 +259,7 @@ public function keep(&$pks) if ($error) { try { Log::add($error, Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { Factory::getApplication()->enqueueMessage($error, 'warning'); } @@ -268,7 +268,7 @@ public function keep(&$pks) try { Log::add(Text::_('COM_CONTENTHISTORY_ERROR_KEEP_NOT_PERMITTED'), Log::WARNING, 'jerror'); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { Factory::getApplication()->enqueueMessage(Text::_('COM_CONTENTHISTORY_ERROR_KEEP_NOT_PERMITTED'), 'warning'); } diff --git a/administrator/components/com_cpanel/src/Controller/DisplayController.php b/administrator/components/com_cpanel/src/Controller/DisplayController.php index b9ede3f88e7a4..4d9a05ab6e4f0 100644 --- a/administrator/components/com_cpanel/src/Controller/DisplayController.php +++ b/administrator/components/com_cpanel/src/Controller/DisplayController.php @@ -75,7 +75,7 @@ public function addModule() $appendLink .= '&function=' . $function; } - if (substr($position, 0, 6) != 'cpanel') { + if (!str_starts_with((string) $position, 'cpanel')) { $position = 'cpanel'; } diff --git a/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php b/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php index 1d5a34a7e5a0c..3e8bc11296dd2 100644 --- a/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php +++ b/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php @@ -69,7 +69,7 @@ public function display($tpl = null) $parts = explode('.', $dashboard); $component = $parts[0]; - if (strpos($component, 'com_') === false) { + if (!str_contains($component, 'com_')) { $component = 'com_' . $component; } diff --git a/administrator/components/com_fields/src/Field/FieldLayoutField.php b/administrator/components/com_fields/src/Field/FieldLayoutField.php index 95216b097eadb..3eeb1c16b8798 100644 --- a/administrator/components/com_fields/src/Field/FieldLayoutField.php +++ b/administrator/components/com_fields/src/Field/FieldLayoutField.php @@ -45,7 +45,7 @@ class FieldLayoutField extends FormField */ protected function getInput() { - $extension = explode('.', $this->form->getValue('context')); + $extension = explode('.', (string) $this->form->getValue('context')); $extension = $extension[0]; if ($extension) { @@ -86,7 +86,7 @@ protected function getInput() foreach ($component_layouts as $i => $file) { // Add an option to the component group - $value = basename($file, '.php'); + $value = basename((string) $file, '.php'); $component_layouts[$i] = $value; if ($value === 'render') { @@ -115,7 +115,7 @@ protected function getInput() } foreach ($files as $i => $file) { - $value = basename($file, '.php'); + $value = basename((string) $file, '.php'); // Remove the default "render.php" or layout files that exist in the component folder if ($value === 'render' || \in_array($value, $component_layouts)) { @@ -132,7 +132,7 @@ protected function getInput() foreach ($files as $file) { // Add an option to the template group - $value = basename($file, '.php'); + $value = basename((string) $file, '.php'); $groups[$template->name]['items'][] = HTMLHelper::_('select.option', $value, $value); } } @@ -157,7 +157,7 @@ protected function getInput() ['id' => $this->id, 'group.id' => 'id', 'list.attr' => $attr, 'list.select' => $selected] ); - return implode($html); + return implode('', $html); } return ''; diff --git a/administrator/components/com_fields/src/Field/FieldcontextsField.php b/administrator/components/com_fields/src/Field/FieldcontextsField.php index 4d049efc6a83e..892652b4fe313 100644 --- a/administrator/components/com_fields/src/Field/FieldcontextsField.php +++ b/administrator/components/com_fields/src/Field/FieldcontextsField.php @@ -54,7 +54,7 @@ protected function getInput() */ protected function getOptions() { - $parts = explode('.', $this->value); + $parts = explode('.', (string) $this->value); $component = Factory::getApplication()->bootComponent($parts[0]); diff --git a/administrator/components/com_fields/src/Field/SubfieldsField.php b/administrator/components/com_fields/src/Field/SubfieldsField.php index c8dc4cfeba751..2c9d757188c89 100644 --- a/administrator/components/com_fields/src/Field/SubfieldsField.php +++ b/administrator/components/com_fields/src/Field/SubfieldsField.php @@ -85,9 +85,7 @@ protected function getOptions() // Sorting the fields based on the text which is displayed usort( $options, - function ($a, $b) { - return strcmp($a->text, $b->text); - } + fn($a, $b) => strcmp($a->text, $b->text) ); if (\count($options) == 0) { diff --git a/administrator/components/com_fields/src/Field/TypeField.php b/administrator/components/com_fields/src/Field/TypeField.php index 4514da0b584a8..703f9902990a3 100644 --- a/administrator/components/com_fields/src/Field/TypeField.php +++ b/administrator/components/com_fields/src/Field/TypeField.php @@ -73,9 +73,7 @@ protected function getOptions() // Sorting the fields based on the text which is displayed usort( $options, - function ($a, $b) { - return strcmp($a->text, $b->text); - } + fn($a, $b) => strcmp($a->text, $b->text) ); // Load scripts diff --git a/administrator/components/com_fields/src/Helper/FieldsHelper.php b/administrator/components/com_fields/src/Helper/FieldsHelper.php index 96b05e66eb986..4bb515e879b0f 100644 --- a/administrator/components/com_fields/src/Helper/FieldsHelper.php +++ b/administrator/components/com_fields/src/Helper/FieldsHelper.php @@ -175,9 +175,7 @@ public static function getFields( PluginHelper::importPlugin('fields', null, true, $dispatcher); $fieldIds = array_map( - function ($f) { - return $f->id; - }, + fn($f) => $f->id, $fields ); @@ -226,9 +224,7 @@ function ($f) { ]))->getArgument('result', []); if (\is_array($value)) { - $value = array_filter($value, function ($v) { - return $v !== '' && $v !== null; - }); + $value = array_filter($value, fn($v) => $v !== '' && $v !== null); $value = $value ? implode(' ', $value) : ''; } diff --git a/administrator/components/com_fields/src/Model/FieldModel.php b/administrator/components/com_fields/src/Model/FieldModel.php index 1b8031d1042b7..4c5107ba57eae 100644 --- a/administrator/components/com_fields/src/Model/FieldModel.php +++ b/administrator/components/com_fields/src/Model/FieldModel.php @@ -144,7 +144,7 @@ public function save($data) $origTable->load($input->getInt('id')); if ($data['title'] == $origTable->title) { - list($title, $name) = $this->generateNewTitle($data['group_id'], $data['name'], $data['title']); + [$title, $name] = $this->generateNewTitle($data['group_id'], $data['name'], $data['title']); $data['title'] = $title; $data['label'] = $title; $data['name'] = $name; @@ -329,7 +329,7 @@ private function checkDefaultValue($data) if ($rule instanceof DatabaseAwareInterface) { try { $rule->setDatabase($this->getDatabase()); - } catch (DatabaseNotFoundException $e) { + } catch (DatabaseNotFoundException) { @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); $rule->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } @@ -340,7 +340,7 @@ private function checkDefaultValue($data) $value = $data['default_value']; if ($data['type'] === 'checkboxes') { - $value = explode(',', $value); + $value = explode(',', (string) $value); } elseif ($element['multiple'] && \is_string($value) && \is_array(json_decode($value, true))) { $value = (array)json_decode($value); } @@ -1060,11 +1060,11 @@ function () use ($component, $section) { // Try to get the categories for this component and section try { $cat = $componentObject->getCategory([], $section ?: ''); - } catch (SectionNotFoundException $e) { + } catch (SectionNotFoundException) { // Not found for component and section -> Now try once more without the section, so only component try { $cat = $componentObject->getCategory(); - } catch (SectionNotFoundException $e) { + } catch (SectionNotFoundException) { // If we haven't found it now, return (no categories available for this component) return null; } @@ -1225,7 +1225,7 @@ protected function batchMove($value, $pks, $contexts) // Set the variables $user = $this->getCurrentUser(); $table = $this->getTable(); - $context = explode('.', Factory::getApplication()->getUserState('com_fields.fields.context')); + $context = explode('.', (string) Factory::getApplication()->getUserState('com_fields.fields.context')); $value = (int) $value; foreach ($pks as $pk) { diff --git a/administrator/components/com_fields/src/Model/FieldsModel.php b/administrator/components/com_fields/src/Model/FieldsModel.php index aa6b8c112edc3..b270b75313b27 100644 --- a/administrator/components/com_fields/src/Model/FieldsModel.php +++ b/administrator/components/com_fields/src/Model/FieldsModel.php @@ -213,11 +213,11 @@ function () use ($parts) { // Try to get the categories for this component and section try { $cat = $componentObject->getCategory([], $parts[1] ?: ''); - } catch (SectionNotFoundException $e) { + } catch (SectionNotFoundException) { // Not found for component and section -> Now try once more without the section, so only component try { $cat = $componentObject->getCategory(); - } catch (SectionNotFoundException $e) { + } catch (SectionNotFoundException) { // If we haven't found it now, return (no categories available for this component) return null; } @@ -336,12 +336,12 @@ function () use ($parts) { $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :id') ->bind(':id', $search, ParameterType::INTEGER); - } elseif (stripos($search, 'author:') === 0) { - $search = '%' . substr($search, 7) . '%'; + } elseif (stripos((string) $search, 'author:') === 0) { + $search = '%' . substr((string) $search, 7) . '%'; $query->where( '(' . $db->quoteName('ua.name') . ' LIKE :name OR ' . @@ -351,7 +351,7 @@ function () use ($parts) { ->bind(':name', $search) ->bind(':username', $search); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where( '(' . $db->quoteName('a.title') . ' LIKE :title OR ' . diff --git a/administrator/components/com_fields/src/Model/GroupModel.php b/administrator/components/com_fields/src/Model/GroupModel.php index 69caf97134ff0..90f40cc6d8971 100644 --- a/administrator/components/com_fields/src/Model/GroupModel.php +++ b/administrator/components/com_fields/src/Model/GroupModel.php @@ -312,7 +312,7 @@ protected function loadFormData() // Pre-select some filters (Status, Language, Access) in edit form if those have been selected in Field Group Manager if (!$data->id) { // Check for which context the Field Group Manager is used and get selected fields - $context = substr($app->getUserState('com_fields.groups.filter.context', ''), 4); + $context = substr((string) $app->getUserState('com_fields.groups.filter.context', ''), 4); $filters = (array) $app->getUserState('com_fields.groups.' . $context . '.filter'); $data->set( diff --git a/administrator/components/com_fields/src/Model/GroupsModel.php b/administrator/components/com_fields/src/Model/GroupsModel.php index 5ad10277f1c23..1366aa9ddd29c 100644 --- a/administrator/components/com_fields/src/Model/GroupsModel.php +++ b/administrator/components/com_fields/src/Model/GroupsModel.php @@ -187,12 +187,12 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where($db->quoteName('a.title') . ' LIKE :search') ->bind(':search', $search); } diff --git a/administrator/components/com_fields/src/Plugin/FieldsPlugin.php b/administrator/components/com_fields/src/Plugin/FieldsPlugin.php index 4aa87df598cfc..d5cbbdcd2fa33 100644 --- a/administrator/components/com_fields/src/Plugin/FieldsPlugin.php +++ b/administrator/components/com_fields/src/Plugin/FieldsPlugin.php @@ -343,7 +343,7 @@ public function onContentPrepareForm(Form $form, $data) protected function getFormPath(Form $form, $data) { // Check if the field form is calling us - if (strpos($form->getName(), 'com_fields.field') !== 0) { + if (!str_starts_with($form->getName(), 'com_fields.field')) { return null; } diff --git a/administrator/components/com_fields/src/View/Field/HtmlView.php b/administrator/components/com_fields/src/View/Field/HtmlView.php index 788807326a21b..f6c82c1d68d2b 100644 --- a/administrator/components/com_fields/src/View/Field/HtmlView.php +++ b/administrator/components/com_fields/src/View/Field/HtmlView.php @@ -114,12 +114,12 @@ protected function addToolbar() $lang->load($component, JPATH_ADMINISTRATOR) || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); - $title = Text::sprintf('COM_FIELDS_VIEW_FIELD_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper($component))); + $title = Text::sprintf('COM_FIELDS_VIEW_FIELD_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper((string) $component))); // Prepare the toolbar. ToolbarHelper::title( $title, - 'puzzle field-' . ($isNew ? 'add' : 'edit') . ' ' . substr($component, 4) . ($section ? "-$section" : '') . '-field-' . + 'puzzle field-' . ($isNew ? 'add' : 'edit') . ' ' . substr((string) $component, 4) . ($section ? "-$section" : '') . '-field-' . ($isNew ? 'add' : 'edit') ); diff --git a/administrator/components/com_fields/src/View/Fields/HtmlView.php b/administrator/components/com_fields/src/View/Fields/HtmlView.php index 35c6e2608139e..c6a53217be412 100644 --- a/administrator/components/com_fields/src/View/Fields/HtmlView.php +++ b/administrator/components/com_fields/src/View/Fields/HtmlView.php @@ -142,10 +142,10 @@ protected function addToolbar() $lang->load($component, JPATH_ADMINISTRATOR) || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); - $title = Text::sprintf('COM_FIELDS_VIEW_FIELDS_TITLE', Text::_(strtoupper($component))); + $title = Text::sprintf('COM_FIELDS_VIEW_FIELDS_TITLE', Text::_(strtoupper((string) $component))); // Prepare the toolbar. - ToolbarHelper::title($title, 'puzzle-piece fields ' . substr($component, 4) . ($section ? "-$section" : '') . '-fields'); + ToolbarHelper::title($title, 'puzzle-piece fields ' . substr((string) $component, 4) . ($section ? "-$section" : '') . '-fields'); if ($canDo->get('core.create')) { $toolbar->addNew('field.add'); diff --git a/administrator/components/com_fields/src/View/Group/HtmlView.php b/administrator/components/com_fields/src/View/Group/HtmlView.php index b6ebc8d9bd778..fe79b3298bd94 100644 --- a/administrator/components/com_fields/src/View/Group/HtmlView.php +++ b/administrator/components/com_fields/src/View/Group/HtmlView.php @@ -134,12 +134,12 @@ protected function addToolbar() $lang->load($component, JPATH_ADMINISTRATOR) || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); - $title = Text::sprintf('COM_FIELDS_VIEW_GROUP_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper($component))); + $title = Text::sprintf('COM_FIELDS_VIEW_GROUP_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper((string) $component))); // Prepare the toolbar. ToolbarHelper::title( $title, - 'puzzle-piece field-' . ($isNew ? 'add' : 'edit') . ' ' . substr($component, 4) . '-group-' . + 'puzzle-piece field-' . ($isNew ? 'add' : 'edit') . ' ' . substr((string) $component, 4) . '-group-' . ($isNew ? 'add' : 'edit') ); diff --git a/administrator/components/com_fields/src/View/Groups/HtmlView.php b/administrator/components/com_fields/src/View/Groups/HtmlView.php index be2bf889e2050..3130cb02905af 100644 --- a/administrator/components/com_fields/src/View/Groups/HtmlView.php +++ b/administrator/components/com_fields/src/View/Groups/HtmlView.php @@ -144,10 +144,10 @@ protected function addToolbar() $lang->load($component, JPATH_ADMINISTRATOR) || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); - $title = Text::sprintf('COM_FIELDS_VIEW_GROUPS_TITLE', Text::_(strtoupper($component))); + $title = Text::sprintf('COM_FIELDS_VIEW_GROUPS_TITLE', Text::_(strtoupper((string) $component))); // Prepare the toolbar. - ToolbarHelper::title($title, 'puzzle-piece fields ' . substr($component, 4) . '-groups'); + ToolbarHelper::title($title, 'puzzle-piece fields ' . substr((string) $component, 4) . '-groups'); if ($canDo->get('core.create')) { $toolbar->addNew('group.add'); diff --git a/administrator/components/com_fields/tmpl/fields/default.php b/administrator/components/com_fields/tmpl/fields/default.php index 77b27cce1aa81..6336da4cb3ef1 100644 --- a/administrator/components/com_fields/tmpl/fields/default.php +++ b/administrator/components/com_fields/tmpl/fields/default.php @@ -36,7 +36,7 @@ $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $ordering = ($listOrder == 'a.ordering'); -$saveOrder = ($listOrder == 'a.ordering' && strtolower($listDirn) == 'asc'); +$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) == 'asc'); // The category object of the component $category = Categories::getInstance(str_replace('com_', '', $component) . '.' . $section); @@ -110,7 +110,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="true" class="js-draggable" data-url="" data-direction="" data-nested="true"> items as $i => $item) : ?> diff --git a/administrator/components/com_fields/tmpl/groups/default.php b/administrator/components/com_fields/tmpl/groups/default.php index d72ad1d5cb4c9..9b668be8151d6 100644 --- a/administrator/components/com_fields/tmpl/groups/default.php +++ b/administrator/components/com_fields/tmpl/groups/default.php @@ -40,7 +40,7 @@ $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $ordering = ($listOrder == 'a.ordering'); -$saveOrder = ($listOrder == 'a.ordering' && strtolower($listDirn) == 'asc'); +$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) == 'asc'); if ($saveOrder && !empty($this->items)) { $saveOrderingUrl = 'index.php?option=com_fields&task=groups.saveOrderAjax&tmpl=component&' . Session::getFormToken() . '=1'; @@ -102,7 +102,7 @@ class="js-draggable" data-url="" data-direction="" data-nested="true" class="js-draggable" data-url="" data-direction="" data-nested="true"> items as $i => $item) : ?> diff --git a/administrator/components/com_finder/src/Controller/IndexerController.php b/administrator/components/com_finder/src/Controller/IndexerController.php index ce5696d82b2e5..3adbf1b9b832e 100644 --- a/administrator/components/com_finder/src/Controller/IndexerController.php +++ b/administrator/components/com_finder/src/Controller/IndexerController.php @@ -65,7 +65,7 @@ public function start() // Log the start try { Log::add('Starting the indexer', Log::INFO); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } @@ -137,7 +137,7 @@ public function batch() // Log the start try { Log::add('Starting the indexer batch process', Log::INFO); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } @@ -196,7 +196,7 @@ public function batch() // Log batch completion and memory high-water mark. try { Log::add('Batch completed, peak memory usage: ' . number_format(memory_get_peak_usage(true)) . ' bytes', Log::INFO); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } @@ -293,7 +293,7 @@ public static function sendResponse($data = null) if ($data instanceof \Exception) { try { Log::add($data->getMessage(), Log::ERROR); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } diff --git a/administrator/components/com_finder/src/Field/ContentmapField.php b/administrator/components/com_finder/src/Field/ContentmapField.php index e35a26205d31a..ea005dc8e581d 100644 --- a/administrator/components/com_finder/src/Field/ContentmapField.php +++ b/administrator/components/com_finder/src/Field/ContentmapField.php @@ -63,7 +63,7 @@ protected function getGroups() try { $contentMap = $db->loadObjectList(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return []; } diff --git a/administrator/components/com_finder/src/Indexer/Adapter.php b/administrator/components/com_finder/src/Indexer/Adapter.php index d554f0c5b6799..e7ea5bd4b4db3 100644 --- a/administrator/components/com_finder/src/Indexer/Adapter.php +++ b/administrator/components/com_finder/src/Indexer/Adapter.php @@ -804,7 +804,7 @@ protected function getItemMenuTitle($url) } // Instantiate the params. - $params = json_decode($params); + $params = json_decode((string) $params); // Get the page title if it is set. if (isset($params->page_title) && $params->page_title) { diff --git a/administrator/components/com_finder/src/Indexer/DebugAdapter.php b/administrator/components/com_finder/src/Indexer/DebugAdapter.php index 11f5ea49d0f7d..0770dc7ddbe54 100644 --- a/administrator/components/com_finder/src/Indexer/DebugAdapter.php +++ b/administrator/components/com_finder/src/Indexer/DebugAdapter.php @@ -804,7 +804,7 @@ protected function getItemMenuTitle($url) } // Instantiate the params. - $params = json_decode($params); + $params = json_decode((string) $params); // Get the page title if it is set. if (isset($params->page_title) && $params->page_title) { @@ -919,16 +919,12 @@ protected function translateState($item, $category = null) } // Translate the state - switch ($item) { - case 1: - case 2: - // Published and archived items only should return a published state - return 1; - - default: - // All other states should return an unpublished state - return 0; - } + return match ($item) { + // Published and archived items only should return a published state + 1, 2 => 1, + // All other states should return an unpublished state + default => 0, + }; } /** diff --git a/administrator/components/com_finder/src/Indexer/Indexer.php b/administrator/components/com_finder/src/Indexer/Indexer.php index 13a9823d724f1..6aec4b6572342 100644 --- a/administrator/components/com_finder/src/Indexer/Indexer.php +++ b/administrator/components/com_finder/src/Indexer/Indexer.php @@ -186,7 +186,7 @@ public static function getState() */ $memory_table_limit = (int) ($heapsize->Value / 800); $data->options->set('memory_table_limit', $memory_table_limit); - } catch (\Exception $e) { + } catch (\Exception) { // Something failed. We fall back to a reasonable guess. $data->options->set('memory_table_limit', 7500); } @@ -1008,7 +1008,7 @@ protected function toggleTables($memory) // Set the tokens aggregate table to Memory. $db->setQuery('ALTER TABLE ' . $db->quoteName('#__finder_tokens_aggregate') . ' ENGINE = MEMORY'); $db->execute(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { $supported = false; return true; diff --git a/administrator/components/com_finder/src/Indexer/Language.php b/administrator/components/com_finder/src/Indexer/Language.php index 805ad349a2ece..0b58d3da6e1bc 100644 --- a/administrator/components/com_finder/src/Indexer/Language.php +++ b/administrator/components/com_finder/src/Indexer/Language.php @@ -81,7 +81,7 @@ public function __construct($locale = null) break; } } - } catch (NotFoundException $e) { + } catch (NotFoundException) { // We don't have a stemmer for the language } } @@ -147,14 +147,14 @@ public function tokenise($input) */ $input = StringHelper::strtolower($input); $input = preg_replace('#[^\pL\pM\pN\p{Pi}\p{Pf}\'+-.,]+#mui', ' ', $input); - $input = preg_replace('#(^|\s)[+-,]+([\pL\pM]+)#mui', ' $1', $input); - $input = preg_replace('#([\pL\pM\pN]+)[+-.,]+(\s|$)#mui', '$1 ', $input); - $input = preg_replace('#([\pL\pM]+)[+.,]+([\pL\pM]+)#muiU', '$1 $2', $input); - $input = preg_replace('#(^|\s)[\'+-.,]+(\s|$)#mui', ' ', $input); - $input = preg_replace('#(^|\s)[\p{Pi}\p{Pf}]+(\s|$)#mui', ' ', $input); - $input = preg_replace('#[' . $quotes . ']+#mui', '\'', $input); - $input = preg_replace('#\s+#mui', ' ', $input); - $input = trim($input); + $input = preg_replace('#(^|\s)[+-,]+([\pL\pM]+)#mui', ' $1', (string) $input); + $input = preg_replace('#([\pL\pM\pN]+)[+-.,]+(\s|$)#mui', '$1 ', (string) $input); + $input = preg_replace('#([\pL\pM]+)[+.,]+([\pL\pM]+)#muiU', '$1 $2', (string) $input); + $input = preg_replace('#(^|\s)[\'+-.,]+(\s|$)#mui', ' ', (string) $input); + $input = preg_replace('#(^|\s)[\p{Pi}\p{Pf}]+(\s|$)#mui', ' ', (string) $input); + $input = preg_replace('#[' . $quotes . ']+#mui', '\'', (string) $input); + $input = preg_replace('#\s+#mui', ' ', (string) $input); + $input = trim((string) $input); // Explode the normalized string to get the terms. $terms = explode(' ', $input); diff --git a/administrator/components/com_finder/src/Indexer/Parser.php b/administrator/components/com_finder/src/Indexer/Parser.php index 76b58e3b70bdb..6e55d9953ddfd 100644 --- a/administrator/components/com_finder/src/Indexer/Parser.php +++ b/administrator/components/com_finder/src/Indexer/Parser.php @@ -52,7 +52,7 @@ public static function getInstance($format) } // Setup the adapter for the parser. - $class = '\\Joomla\\Component\\Finder\\Administrator\\Indexer\\Parser\\' . ucfirst($format); + $class = '\\Joomla\\Component\\Finder\\Administrator\\Indexer\\Parser\\' . ucfirst((string) $format); // Check if a parser exists for the format. if (class_exists($class)) { diff --git a/administrator/components/com_finder/src/Indexer/Parser/Html.php b/administrator/components/com_finder/src/Indexer/Parser/Html.php index ac569bbe45117..5241823d852b4 100644 --- a/administrator/components/com_finder/src/Indexer/Parser/Html.php +++ b/administrator/components/com_finder/src/Indexer/Parser/Html.php @@ -77,7 +77,7 @@ public function parse($input) ')\b/i', ' $1$2', $input); // Strip HTML tags. - $input = strip_tags($input); + $input = strip_tags((string) $input); return parent::parse($input); } diff --git a/administrator/components/com_finder/src/Indexer/Parser/Rtf.php b/administrator/components/com_finder/src/Indexer/Parser/Rtf.php index 2fcbdbf3e097e..c3c77dd72043d 100644 --- a/administrator/components/com_finder/src/Indexer/Parser/Rtf.php +++ b/administrator/components/com_finder/src/Indexer/Parser/Rtf.php @@ -40,7 +40,7 @@ protected function process($input) // Remove control characters. $input = str_replace(['{', '}', "\\\n"], [' ', ' ', "\n"], $input); $input = preg_replace('#\\\([^;]+?);#m', ' ', $input); - $input = preg_replace('#\\\[\'a-zA-Z0-9]+#mi', ' ', $input); + $input = preg_replace('#\\\[\'a-zA-Z0-9]+#mi', ' ', (string) $input); return $input; } diff --git a/administrator/components/com_finder/src/Indexer/Query.php b/administrator/components/com_finder/src/Indexer/Query.php index 61b1bd4cd9b5f..807ad2d550c09 100644 --- a/administrator/components/com_finder/src/Indexer/Query.php +++ b/administrator/components/com_finder/src/Indexer/Query.php @@ -741,7 +741,7 @@ protected function processString($input, $lang, $mode) $input = html_entity_decode($input, ENT_QUOTES, 'UTF-8'); $input = StringHelper::strtolower($input); $input = preg_replace('#\s+#mi', ' ', $input); - $input = trim($input); + $input = trim((string) $input); $debug = Factory::getApplication()->get('debug_lang'); $params = ComponentHelper::getParams('com_finder'); @@ -847,7 +847,7 @@ protected function processString($input, $lang, $mode) // Clean up the input string again. $input = str_replace($matches[0], '', $input); $input = preg_replace('#\s+#mi', ' ', $input); - $input = trim($input); + $input = trim((string) $input); } } @@ -880,7 +880,7 @@ protected function processString($input, $lang, $mode) // Clean up the input string again. $input = preg_replace('#\s+#mi', ' ', $input); - $input = trim($input); + $input = trim((string) $input); // Get the number of words in the phrase. $parts = explode(' ', $match); diff --git a/administrator/components/com_finder/src/Indexer/Taxonomy.php b/administrator/components/com_finder/src/Indexer/Taxonomy.php index 6808f23dacc23..e6e175c1dffde 100644 --- a/administrator/components/com_finder/src/Indexer/Taxonomy.php +++ b/administrator/components/com_finder/src/Indexer/Taxonomy.php @@ -481,11 +481,7 @@ public static function getTaxonomy($id = 0) return self::$taxonomies; } - if (isset(self::$taxonomies[$id])) { - return self::$taxonomies[$id]; - } - - return false; + return self::$taxonomies[$id] ?? false; } /** @@ -513,10 +509,6 @@ public static function getBranch($title = '') return self::$branches; } - if (isset(self::$branches[$title])) { - return self::$branches[$title]; - } - - return false; + return self::$branches[$title] ?? false; } } diff --git a/administrator/components/com_finder/src/Indexer/Token.php b/administrator/components/com_finder/src/Indexer/Token.php index cc4147dd60a2b..73b64f2ef9a85 100644 --- a/administrator/components/com_finder/src/Indexer/Token.php +++ b/administrator/components/com_finder/src/Indexer/Token.php @@ -146,7 +146,7 @@ public function __construct($term, $lang, $spacer = ' ') // Populate the token instance. $langs = array_fill(0, \count($term), $lang); $this->term = implode($spacer, $term); - $this->stem = implode($spacer, array_map([Helper::class, 'stem'], $term, $langs)); + $this->stem = implode($spacer, array_map(Helper::stem(...), $term, $langs)); $this->numeric = false; $this->common = false; $this->phrase = true; @@ -164,7 +164,7 @@ public function __construct($term, $lang, $spacer = ' ') // Populate the token instance. $this->term = $term; $this->stem = Helper::stem($this->term, $lang); - $this->numeric = (is_numeric($this->term) || (bool) preg_match('#^[0-9,.\-\+]+$#', $this->term)); + $this->numeric = (is_numeric($this->term) || (bool) preg_match('#^[0-9,.\-\+]+$#', (string) $this->term)); $this->common = $this->numeric ? false : Helper::isCommon($this->term, $lang); $this->phrase = false; $this->length = StringHelper::strlen($this->term); diff --git a/administrator/components/com_finder/src/Model/FiltersModel.php b/administrator/components/com_finder/src/Model/FiltersModel.php index ec05f535ba67e..acf14008c3235 100644 --- a/administrator/components/com_finder/src/Model/FiltersModel.php +++ b/administrator/components/com_finder/src/Model/FiltersModel.php @@ -77,7 +77,7 @@ protected function getListQuery() // Check for a search filter. if ($search = $this->getState('filter.search')) { - $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%')); + $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim((string) $search), true) . '%')); $query->where($db->quoteName('a.title') . ' LIKE ' . $search); } diff --git a/administrator/components/com_finder/src/Model/IndexModel.php b/administrator/components/com_finder/src/Model/IndexModel.php index e6dbe7da260fc..69024578ed071 100644 --- a/administrator/components/com_finder/src/Model/IndexModel.php +++ b/administrator/components/com_finder/src/Model/IndexModel.php @@ -223,7 +223,7 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%')); + $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim((string) $search), true) . '%')); $orSearchSql = $db->quoteName('l.title') . ' LIKE ' . $search . ' OR ' . $db->quoteName('l.url') . ' LIKE ' . $search; // Filter by indexdate only if $search doesn't contains non-ascii characters diff --git a/administrator/components/com_finder/src/Model/MapsModel.php b/administrator/components/com_finder/src/Model/MapsModel.php index 98231c4d188bf..2315b0453ae4f 100644 --- a/administrator/components/com_finder/src/Model/MapsModel.php +++ b/administrator/components/com_finder/src/Model/MapsModel.php @@ -210,7 +210,7 @@ protected function getListQuery() // Filter the maps over the search string if set. if ($search = $this->getState('filter.search')) { - $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%')); + $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim((string) $search), true) . '%')); $query->where('a.title LIKE ' . $search); } diff --git a/administrator/components/com_finder/src/Model/SearchesModel.php b/administrator/components/com_finder/src/Model/SearchesModel.php index 5cdff1385b1c2..9c7f02998cb63 100644 --- a/administrator/components/com_finder/src/Model/SearchesModel.php +++ b/administrator/components/com_finder/src/Model/SearchesModel.php @@ -118,7 +118,7 @@ protected function getListQuery() // Filter by search in title if ($search = $this->getState('filter.search')) { - $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%')); + $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim((string) $search), true) . '%')); $query->where($db->quoteName('a.searchterm') . ' LIKE ' . $search); } diff --git a/administrator/components/com_finder/src/Response/Response.php b/administrator/components/com_finder/src/Response/Response.php index 28dc80ffeb5e5..39691a8520f84 100644 --- a/administrator/components/com_finder/src/Response/Response.php +++ b/administrator/components/com_finder/src/Response/Response.php @@ -152,7 +152,7 @@ public function __construct($state) // Log the error try { Log::add($state->getMessage(), Log::ERROR); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { // Informational log only } diff --git a/administrator/components/com_finder/src/Service/HTML/Filter.php b/administrator/components/com_finder/src/Service/HTML/Filter.php index 7e511918dd9c1..0d238cca30ad3 100644 --- a/administrator/components/com_finder/src/Service/HTML/Filter.php +++ b/administrator/components/com_finder/src/Service/HTML/Filter.php @@ -69,7 +69,7 @@ public function slider($options = []) try { $filter = $db->loadObject(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } @@ -100,7 +100,7 @@ public function slider($options = []) try { $branches = $db->loadObjectList('id'); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } @@ -141,7 +141,7 @@ public function slider($options = []) try { $nodes = $db->loadObjectList('id'); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } @@ -238,7 +238,7 @@ public function select($idxQuery, $options) try { $filter = $db->loadObject(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } @@ -273,7 +273,7 @@ public function select($idxQuery, $options) try { $branches = $db->loadObjectList('id'); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } @@ -321,7 +321,7 @@ public function select($idxQuery, $options) try { $bv->nodes = $db->loadObjectList('id'); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return null; } diff --git a/administrator/components/com_finder/src/Service/HTML/Finder.php b/administrator/components/com_finder/src/Service/HTML/Finder.php index 642fcf86f5846..fa62a601879e0 100644 --- a/administrator/components/com_finder/src/Service/HTML/Finder.php +++ b/administrator/components/com_finder/src/Service/HTML/Finder.php @@ -50,7 +50,7 @@ public function typeslist() try { $rows = $db->loadObjectList(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return []; } diff --git a/administrator/components/com_finder/tmpl/maps/default.php b/administrator/components/com_finder/tmpl/maps/default.php index 2b9ca870ffecc..0cc87fc036e0e 100644 --- a/administrator/components/com_finder/tmpl/maps/default.php +++ b/administrator/components/com_finder/tmpl/maps/default.php @@ -103,7 +103,7 @@ ?> —', $item->level - 1); ?> escape($title); ?> - escape(trim($title, '*')) === 'Language' && Multilanguage::isEnabled()) : ?> + escape(trim((string) $title, '*')) === 'Language' && Multilanguage::isEnabled()) : ?>
diff --git a/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php b/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php index f3b6198b99b47..004b94dac33fa 100644 --- a/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php +++ b/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php @@ -46,7 +46,7 @@ public static function loadTranslationFiles($uid, bool $steps = false) // The uid has an extension separator so we need to check the extension language files if (strpos($uid, '.') > 0) { - list($extension, $tourid) = explode('.', $uid, 2); + [$extension, $tourid] = explode('.', $uid, 2); $source = ''; diff --git a/administrator/components/com_guidedtours/src/Model/StepModel.php b/administrator/components/com_guidedtours/src/Model/StepModel.php index 62533efa4d150..437abb1042a00 100644 --- a/administrator/components/com_guidedtours/src/Model/StepModel.php +++ b/administrator/components/com_guidedtours/src/Model/StepModel.php @@ -81,8 +81,8 @@ public function save($data) $tour->load($data['tour_id']); // Language keys must include GUIDEDTOUR to prevent save issues - if (strpos($data['description'], 'GUIDEDTOUR') !== false) { - $data['description'] = strip_tags($data['description']); + if (str_contains((string) $data['description'], 'GUIDEDTOUR')) { + $data['description'] = strip_tags((string) $data['description']); } // Make sure we use the correct extension when editing an existing tour diff --git a/administrator/components/com_guidedtours/src/Model/StepsModel.php b/administrator/components/com_guidedtours/src/Model/StepsModel.php index d3daaa4685b81..58cfdbaafbac0 100644 --- a/administrator/components/com_guidedtours/src/Model/StepsModel.php +++ b/administrator/components/com_guidedtours/src/Model/StepsModel.php @@ -193,16 +193,16 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); - } elseif (stripos($search, 'description:') === 0) { - $search = '%' . substr($search, 12) . '%'; + } elseif (stripos((string) $search, 'description:') === 0) { + $search = '%' . substr((string) $search, 12) . '%'; $query->where('(' . $db->quoteName('a.description') . ' LIKE :search1)') ->bind([':search1'], $search); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where( '(' . $db->quoteName('a.title') . ' LIKE :search1' . ' OR ' . $db->quoteName('a.description') . ' LIKE :search2' diff --git a/administrator/components/com_guidedtours/src/Model/TourModel.php b/administrator/components/com_guidedtours/src/Model/TourModel.php index 1bc1e6512c6b1..0ab944a5dc228 100644 --- a/administrator/components/com_guidedtours/src/Model/TourModel.php +++ b/administrator/components/com_guidedtours/src/Model/TourModel.php @@ -63,8 +63,8 @@ public function save($data) $input = Factory::getApplication()->getInput(); // Language keys must include GUIDEDTOUR to prevent save issues - if (strpos($data['description'], 'GUIDEDTOUR') !== false) { - $data['description'] = strip_tags($data['description']); + if (str_contains((string) $data['description'], 'GUIDEDTOUR')) { + $data['description'] = strip_tags((string) $data['description']); } if ($input->get('task') == 'save2copy') { @@ -562,7 +562,7 @@ public function isAutostart($pk): bool if ($result === null) { return false; } - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return false; } @@ -597,7 +597,7 @@ public function saveTourUserState($id, $state = ''): bool try { $result = $db->setQuery($query)->loadResult(); - } catch (\Exception $e) { + } catch (\Exception) { return false; } @@ -616,7 +616,7 @@ public function saveTourUserState($id, $state = ''): bool ]; if (!\is_null($result)) { - $values = json_decode($result, true); + $values = json_decode((string) $result, true); // The profile is updated only when delayed. 'Completed' and 'Skipped' are final if (!empty($values) && $values['state'] === 'delayed') { diff --git a/administrator/components/com_guidedtours/src/Model/ToursModel.php b/administrator/components/com_guidedtours/src/Model/ToursModel.php index 3179b7d79f91c..010abda576683 100644 --- a/administrator/components/com_guidedtours/src/Model/ToursModel.php +++ b/administrator/components/com_guidedtours/src/Model/ToursModel.php @@ -207,16 +207,16 @@ public function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $search = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $search = (int) substr((string) $search, 3); $query->where($db->quoteName('a.id') . ' = :search') ->bind(':search', $search, ParameterType::INTEGER); - } elseif (stripos($search, 'description:') === 0) { - $search = '%' . substr($search, 12) . '%'; + } elseif (stripos((string) $search, 'description:') === 0) { + $search = '%' . substr((string) $search, 12) . '%'; $query->where('(' . $db->quoteName('a.description') . ' LIKE :search1)') ->bind([':search1'], $search); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where( '(' . $db->quoteName('a.title') . ' LIKE :search1' . ' OR ' . $db->quoteName('a.description') . ' LIKE :search2' @@ -228,7 +228,7 @@ public function getListQuery() // Add the list ordering clause. $orderCol = $this->state->get('list.ordering', 'a.ordering'); - $orderDirn = strtoupper($this->state->get('list.direction', 'ASC')); + $orderDirn = strtoupper((string) $this->state->get('list.direction', 'ASC')); $query->order($db->escape($orderCol) . ' ' . ($orderDirn === 'DESC' ? 'DESC' : 'ASC')); diff --git a/administrator/components/com_guidedtours/tmpl/step/edit.php b/administrator/components/com_guidedtours/tmpl/step/edit.php index c47a6d07209ba..b7b9f55487b05 100644 --- a/administrator/components/com_guidedtours/tmpl/step/edit.php +++ b/administrator/components/com_guidedtours/tmpl/step/edit.php @@ -38,7 +38,7 @@ - item->id != 0 && strpos($this->item->title, 'GUIDEDTOUR') !== false) : ?> + item->id != 0 && str_contains($this->item->title, 'GUIDEDTOUR')) : ?>
form->setFieldAttribute('title_translation', 'label', Text::sprintf('COM_GUIDEDTOURS_STEP_TITLE_TRANSLATION', $lang)); ?> @@ -55,7 +55,7 @@
form->renderField('description'); ?> - item->id != 0 && strpos($this->item->description, 'GUIDEDTOUR') !== false) : ?> + item->id != 0 && str_contains($this->item->description, 'GUIDEDTOUR')) : ?> form->setFieldAttribute('description_translation', 'label', Text::sprintf('COM_GUIDEDTOURS_STEP_DESCRIPTION_TRANSLATION', $lang)); ?> form->renderField('description_translation'); ?> diff --git a/administrator/components/com_guidedtours/tmpl/steps/default.php b/administrator/components/com_guidedtours/tmpl/steps/default.php index 97a0217a49c86..2f287ca45a8c0 100644 --- a/administrator/components/com_guidedtours/tmpl/steps/default.php +++ b/administrator/components/com_guidedtours/tmpl/steps/default.php @@ -136,7 +136,7 @@ - class="js-draggable" data-url="" data-direction="" data-nested="true" " data-direction="" data-nested="true" > items as $i => $item) : $canEditOwn = $canEditOwnTour && $item->created_by == $userId; diff --git a/administrator/components/com_guidedtours/tmpl/tour/edit.php b/administrator/components/com_guidedtours/tmpl/tour/edit.php index 5bef1f3549f89..ce857b0b3dc76 100644 --- a/administrator/components/com_guidedtours/tmpl/tour/edit.php +++ b/administrator/components/com_guidedtours/tmpl/tour/edit.php @@ -41,7 +41,7 @@
- item->id != 0 && strpos($this->item->title, 'GUIDEDTOUR') !== false) : ?> + item->id != 0 && str_contains($this->item->title, 'GUIDEDTOUR')) : ?>
form->setFieldAttribute('title_translation', 'label', Text::sprintf('COM_GUIDEDTOURS_TITLE_TRANSLATION', $lang)); ?> @@ -59,7 +59,7 @@ form->renderField('url'); ?> form->renderField('description'); ?> - item->id != 0 && strpos($this->item->description, 'GUIDEDTOUR') !== false) : ?> + item->id != 0 && str_contains($this->item->description, 'GUIDEDTOUR')) : ?> form->setFieldAttribute('description_translation', 'label', Text::sprintf('COM_GUIDEDTOURS_DESCRIPTION_TRANSLATION', $lang)); ?> form->renderField('description_translation'); ?> diff --git a/administrator/components/com_guidedtours/tmpl/tours/default.php b/administrator/components/com_guidedtours/tmpl/tours/default.php index 6b1f349b562f2..4999cef8aee09 100644 --- a/administrator/components/com_guidedtours/tmpl/tours/default.php +++ b/administrator/components/com_guidedtours/tmpl/tours/default.php @@ -29,7 +29,7 @@ try { $app = Factory::getApplication(); -} catch (Exception $e) { +} catch (Exception) { die('Failed to get app'); } @@ -149,7 +149,7 @@ - class="js-draggable" data-url="" data-direction="" data-nested="true" " data-direction="" data-nested="true" > items as $i => $item) : $canEditOwn = $canEditOwnTour && $item->created_by == $userId; diff --git a/administrator/components/com_installer/src/Helper/InstallerHelper.php b/administrator/components/com_installer/src/Helper/InstallerHelper.php index f0899df2e4045..80be7c5fe4fa6 100644 --- a/administrator/components/com_installer/src/Helper/InstallerHelper.php +++ b/administrator/components/com_installer/src/Helper/InstallerHelper.php @@ -47,7 +47,7 @@ public static function getExtensionTypes() $options = []; foreach ($types as $type) { - $options[] = HTMLHelper::_('select.option', $type, Text::_('COM_INSTALLER_TYPE_' . strtoupper($type))); + $options[] = HTMLHelper::_('select.option', $type, Text::_('COM_INSTALLER_TYPE_' . strtoupper((string) $type))); } return $options; @@ -159,9 +159,7 @@ function (object $entry) use ($language): string { $extensions ); $arrayValues = array_map( - function (object $entry): int { - return $entry->extension_id; - }, + fn(object $entry): int => $entry->extension_id, $extensions ); @@ -264,7 +262,7 @@ public static function getDownloadKey(CMSObject $extension): array $prefix = (string) $installXmlFile->dlid['prefix']; $suffix = (string) $installXmlFile->dlid['suffix']; - $value = substr($extension->get('extra_query'), \strlen($prefix)); + $value = substr((string) $extension->get('extra_query'), \strlen($prefix)); if ($suffix) { $value = substr($value, 0, -\strlen($suffix)); @@ -302,7 +300,7 @@ public static function getExtensionDownloadKey( // Get the database driver. If it fails we cannot report whether the extension supports download keys. try { $db = Factory::getDbo(); - } catch (\Exception $e) { + } catch (\Exception) { return [ 'supported' => false, 'valid' => false, @@ -324,7 +322,7 @@ public static function getExtensionDownloadKey( try { $extension = new CMSObject($db->setQuery($query)->loadAssoc()); - } catch (\Exception $e) { + } catch (\Exception) { return [ 'supported' => false, 'valid' => false, @@ -362,9 +360,7 @@ public static function getDownloadKeySupportedSites($onlyEnabled = false): array }; $extensions = array_filter($extensions, $filterClosure); - $mapClosure = function (CMSObject $extension) { - return $extension->get('update_site_id'); - }; + $mapClosure = (fn(CMSObject $extension) => $extension->get('update_site_id')); return array_map($mapClosure, $extensions); } @@ -403,9 +399,7 @@ public static function getDownloadKeyExistsSites(bool $exists = true, $onlyEnabl $extensions = array_filter($extensions, $filterClosure); // Return only the update site IDs - $mapClosure = function (CMSObject $extension) { - return $extension->get('update_site_id'); - }; + $mapClosure = (fn(CMSObject $extension) => $extension->get('update_site_id')); return array_map($mapClosure, $extensions); } @@ -423,7 +417,7 @@ protected static function getUpdateSitesInformation(bool $onlyEnabled): array { try { $db = Factory::getDbo(); - } catch (\Exception $e) { + } catch (\Exception) { return []; } @@ -481,7 +475,7 @@ protected static function getUpdateSitesInformation(bool $onlyEnabled): array } return $items; - } catch (\Exception $e) { + } catch (\Exception) { return []; } } diff --git a/administrator/components/com_installer/src/Model/DatabaseModel.php b/administrator/components/com_installer/src/Model/DatabaseModel.php index 0c7f2caa199e5..bc1ad0d3b719e 100644 --- a/administrator/components/com_installer/src/Model/DatabaseModel.php +++ b/administrator/components/com_installer/src/Model/DatabaseModel.php @@ -380,8 +380,8 @@ protected function getListQuery() // Process search filter (update site id). $search = $this->getState('filter.search'); - if (!empty($search) && stripos($search, 'id:') === 0) { - $ids = (int) substr($search, 3); + if (!empty($search) && stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); $query->where($db->quoteName('schemas.extension_id') . ' = :eid') ->bind(':eid', $ids, ParameterType::INTEGER); } @@ -479,7 +479,7 @@ public function fixSchemaVersion($changeSet, $extensionId) try { $db->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { return false; } diff --git a/administrator/components/com_installer/src/Model/DiscoverModel.php b/administrator/components/com_installer/src/Model/DiscoverModel.php index eeb5fec3b761b..85f07f10172d1 100644 --- a/administrator/components/com_installer/src/Model/DiscoverModel.php +++ b/administrator/components/com_installer/src/Model/DiscoverModel.php @@ -121,8 +121,8 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'id:') === 0) { - $ids = (int) substr($search, 3); + if (stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); $query->where($db->quoteName('extension_id') . ' = :eid') ->bind(':eid', $ids, ParameterType::INTEGER); } @@ -260,7 +260,7 @@ public function purge() try { $db->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { $this->_message = Text::_('COM_INSTALLER_MSG_DISCOVER_FAILEDTOPURGEEXTENSIONS'); return false; diff --git a/administrator/components/com_installer/src/Model/InstallModel.php b/administrator/components/com_installer/src/Model/InstallModel.php index 953e90d38fbf5..e302ff3c8262e 100644 --- a/administrator/components/com_installer/src/Model/InstallModel.php +++ b/administrator/components/com_installer/src/Model/InstallModel.php @@ -214,7 +214,7 @@ public function install() // Install the package. if (!$installer->install($package['dir'])) { // There was an error installing the package. - $msg = Text::sprintf('COM_INSTALLER_INSTALL_ERROR', Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type']))); + $msg = Text::sprintf('COM_INSTALLER_INSTALL_ERROR', Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper((string) $package['type']))); $result = false; $msgType = 'error'; } else { @@ -329,8 +329,8 @@ protected function _getPackageFromUpload() // Move uploaded file. try { - File::upload($tmp_src, $tmp_dest, false, true); - } catch (FilesystemException $exception) { + File::upload($tmp_src, $tmp_dest, false); + } catch (FilesystemException) { Factory::getApplication()->enqueueMessage(Text::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR'), 'error'); return false; diff --git a/administrator/components/com_installer/src/Model/InstallerModel.php b/administrator/components/com_installer/src/Model/InstallerModel.php index 1ba176c78eff1..183eb62c4dd11 100644 --- a/administrator/components/com_installer/src/Model/InstallerModel.php +++ b/administrator/components/com_installer/src/Model/InstallerModel.php @@ -101,7 +101,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) $found = 0; foreach ($searchFields as $key => $field) { - if (!$found && preg_match('/' . $escapedSearchString . '/i', $item->{$field})) { + if (!$found && preg_match('/' . $escapedSearchString . '/i', (string) $item->{$field})) { $found = 1; } } @@ -115,7 +115,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) // Process ordering. // Sort array object by selected ordering and selected direction. Sort is case insensitive and using locale sorting. - $result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) == 'desc' ? -1 : 1, false, true); + $result = ArrayHelper::sortObjects($result, $listOrder, strtolower((string) $listDirn) == 'desc' ? -1 : 1, false, true); // Process pagination. $total = \count($result); diff --git a/administrator/components/com_installer/src/Model/LanguagesModel.php b/administrator/components/com_installer/src/Model/LanguagesModel.php index 3bf548db3dfb2..103741a67a6e6 100644 --- a/administrator/components/com_installer/src/Model/LanguagesModel.php +++ b/administrator/components/com_installer/src/Model/LanguagesModel.php @@ -136,7 +136,7 @@ protected function getLanguages() try { $response = HttpFactory::getHttp()->get($updateSite); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { $response = null; } @@ -155,7 +155,7 @@ protected function getLanguages() } $languages = []; - $search = strtolower($this->getState('filter.search', '')); + $search = strtolower((string) $this->getState('filter.search', '')); foreach ($updateSiteXML->extension as $extension) { $language = new \stdClass(); @@ -166,8 +166,8 @@ protected function getLanguages() if ($search) { if ( - strpos(strtolower($language->name), $search) === false - && strpos(strtolower($language->element), $search) === false + !str_contains(strtolower($language->name), $search) + && !str_contains(strtolower($language->element), $search) ) { continue; } @@ -185,7 +185,7 @@ protected function getLanguages() function ($a, $b) use ($that) { $ordering = $that->getState('list.ordering', 'name'); - if (strtolower($that->getState('list.direction', 'asc')) === 'asc') { + if (strtolower((string) $that->getState('list.direction', 'asc')) === 'asc') { return StringHelper::strcmp($a->$ordering, $b->$ordering); } diff --git a/administrator/components/com_installer/src/Model/ManageModel.php b/administrator/components/com_installer/src/Model/ManageModel.php index 841a20c16d773..b67eb77bad7f3 100644 --- a/administrator/components/com_installer/src/Model/ManageModel.php +++ b/administrator/components/com_installer/src/Model/ManageModel.php @@ -239,7 +239,7 @@ public function remove($eid = []) $result = false; foreach ($eid as $id) { - $id = trim($id); + $id = trim((string) $id); $row->load($id); $result = false; @@ -253,7 +253,7 @@ public function remove($eid = []) $langstring = 'COM_INSTALLER_TYPE_TYPE_' . strtoupper($row->type); $rowtype = Text::_($langstring); - if (strpos($rowtype, $langstring) !== false) { + if (str_contains($rowtype, $langstring)) { $rowtype = $row->type; } @@ -369,8 +369,8 @@ protected function getListQuery() // Process search filter (extension id). $search = $this->getState('filter.search'); - if (!empty($search) && stripos($search, 'id:') === 0) { - $ids = (int) substr($search, 3); + if (!empty($search) && stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); $query->where($db->quoteName('extension_id') . ' = :eid') ->bind(':eid', $ids, ParameterType::INTEGER); } diff --git a/administrator/components/com_installer/src/Model/UpdateModel.php b/administrator/components/com_installer/src/Model/UpdateModel.php index 2cd000b8ca4a0..dd61954f0f809 100644 --- a/administrator/components/com_installer/src/Model/UpdateModel.php +++ b/administrator/components/com_installer/src/Model/UpdateModel.php @@ -145,21 +145,21 @@ protected function getListQuery() $search = $this->getState('filter.search'); if (!empty($search)) { - if (stripos($search, 'eid:') !== false) { - $sid = (int) substr($search, 4); + if (stripos((string) $search, 'eid:') !== false) { + $sid = (int) substr((string) $search, 4); $query->where($db->quoteName('u.extension_id') . ' = :sid') ->bind(':sid', $sid, ParameterType::INTEGER); } else { - if (stripos($search, 'uid:') !== false) { - $suid = (int) substr($search, 4); + if (stripos((string) $search, 'uid:') !== false) { + $suid = (int) substr((string) $search, 4); $query->where($db->quoteName('u.update_site_id') . ' = :suid') ->bind(':suid', $suid, ParameterType::INTEGER); - } elseif (stripos($search, 'id:') !== false) { - $uid = (int) substr($search, 3); + } elseif (stripos((string) $search, 'id:') !== false) { + $uid = (int) substr((string) $search, 3); $query->where($db->quoteName('u.update_id') . ' = :uid') ->bind(':uid', $uid, ParameterType::INTEGER); } else { - $search = '%' . str_replace(' ', '%', trim($search)) . '%'; + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; $query->where($db->quoteName('u.name') . ' LIKE :search') ->bind(':search', $search); } @@ -215,7 +215,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) $db->setQuery($query); $result = $db->loadObjectList(); $this->translate($result); - $result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true); + $result = ArrayHelper::sortObjects($result, $listOrder, strtolower((string) $listDirn) === 'desc' ? -1 : 1, true, true); $total = \count($result); if ($total < $limitstart) { @@ -286,7 +286,7 @@ public function purge() try { $db->truncateTable('#__updates'); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { $this->_message = Text::_('JLIB_INSTALLER_FAILED_TO_PURGE_UPDATES'); return false; @@ -421,7 +421,7 @@ private function install($update) $sources = $update->get('downloadSources', []); if ($extra_query = $update->get('extra_query')) { - $url .= (strpos($url, '?') === false) ? '?' : '&'; + $url .= (!str_contains($url, '?')) ? '?' : '&'; $url .= $extra_query; } @@ -432,7 +432,7 @@ private function install($update) $url = trim($name->url); if ($extra_query) { - $url .= (strpos($url, '?') === false) ? '?' : '&'; + $url .= (!str_contains($url, '?')) ? '?' : '&'; $url .= $extra_query; } @@ -481,7 +481,7 @@ private function install($update) $app->enqueueMessage( Text::sprintf( 'COM_INSTALLER_MSG_UPDATE_ERROR', - Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])) + Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper((string) $package['type'])) ), 'error' ); @@ -491,7 +491,7 @@ private function install($update) $app->enqueueMessage( Text::sprintf( 'COM_INSTALLER_MSG_UPDATE_SUCCESS', - Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])) + Text::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper((string) $package['type'])) ), 'success' ); diff --git a/administrator/components/com_installer/src/Model/UpdatesiteModel.php b/administrator/components/com_installer/src/Model/UpdatesiteModel.php index cdb5f0528eaaa..5b2efd737254c 100644 --- a/administrator/components/com_installer/src/Model/UpdatesiteModel.php +++ b/administrator/components/com_installer/src/Model/UpdatesiteModel.php @@ -161,7 +161,7 @@ public function save($data): bool try { $db->setQuery($query)->execute(); - } catch (\Exception $e) { + } catch (\Exception) { // No problem if this fails for any reason. } diff --git a/administrator/components/com_installer/src/Model/UpdatesitesModel.php b/administrator/components/com_installer/src/Model/UpdatesitesModel.php index b8b48d027f701..6dc50e798afc1 100644 --- a/administrator/components/com_installer/src/Model/UpdatesitesModel.php +++ b/administrator/components/com_installer/src/Model/UpdatesitesModel.php @@ -585,8 +585,8 @@ protected function getListQuery() // Process search filter (update site id). $search = $this->getState('filter.search'); - if (!empty($search) && stripos($search, 'id:') === 0) { - $uid = (int) substr($search, 3); + if (!empty($search) && stripos((string) $search, 'id:') === 0) { + $uid = (int) substr((string) $search, 3); $query->where($db->quoteName('s.update_site_id') . ' = :siteId') ->bind(':siteId', $uid, ParameterType::INTEGER); } diff --git a/administrator/components/com_installer/src/Model/WarningsModel.php b/administrator/components/com_installer/src/Model/WarningsModel.php index 1c596941b65b1..3d54ab120cc0c 100644 --- a/administrator/components/com_installer/src/Model/WarningsModel.php +++ b/administrator/components/com_installer/src/Model/WarningsModel.php @@ -60,20 +60,12 @@ public function return_bytes($val) $val = (int) $matches[1]; } - switch (strtolower($last)) { - case 'g': - case 'gb': - $val *= (1024 * 1024 * 1024); - break; - case 'm': - case 'mb': - $val *= (1024 * 1024); - break; - case 'k': - case 'kb': - $val *= 1024; - break; - } + match (strtolower($last)) { + 'g', 'gb' => $val *= (1024 * 1024 * 1024), + 'm', 'mb' => $val *= (1024 * 1024), + 'k', 'kb' => $val *= 1024, + default => (int) $val, + }; return (int) $val; } diff --git a/administrator/components/com_installer/src/View/Update/HtmlView.php b/administrator/components/com_installer/src/View/Update/HtmlView.php index 819a80eeb4d57..8c061935d747a 100644 --- a/administrator/components/com_installer/src/View/Update/HtmlView.php +++ b/administrator/components/com_installer/src/View/Update/HtmlView.php @@ -100,7 +100,7 @@ public function display($tpl = null) } // Find if there are any updates which require but are missing a Download Key - if (!class_exists('Joomla\Component\Installer\Administrator\Helper\InstallerHelper')) { + if (!class_exists(\Joomla\Component\Installer\Administrator\Helper\InstallerHelper::class)) { require_once JPATH_COMPONENT_ADMINISTRATOR . '/Helper/InstallerHelper.php'; } diff --git a/administrator/components/com_installer/tmpl/languages/default.php b/administrator/components/com_installer/tmpl/languages/default.php index bc9575f3e1b62..c14f26da718fe 100644 --- a/administrator/components/com_installer/tmpl/languages/default.php +++ b/administrator/components/com_installer/tmpl/languages/default.php @@ -92,7 +92,7 @@ class="" - version, $minorVersion) !== 0 || strpos($language->version, $currentShortVersion) !== 0) : ?> + version, $minorVersion) || !str_starts_with($language->version, (string) $currentShortVersion)) : ?> version; ?>
params->get('logout_redirect_url')) : ?> - + - + diff --git a/components/com_users/tmpl/method/edit.php b/components/com_users/tmpl/method/edit.php index e3c4952c2d44f..8b66b5bea89d0 100644 --- a/components/com_users/tmpl/method/edit.php +++ b/components/com_users/tmpl/method/edit.php @@ -145,7 +145,7 @@ class="form-control" $this->renderOptions['input_attributes'] ); - if (strpos($attributes['class'], 'form-control') === false) { + if (!str_contains((string) $attributes['class'], 'form-control')) { $attributes['class'] .= ' form-control'; } ?> diff --git a/components/com_users/tmpl/methods/list.php b/components/com_users/tmpl/methods/list.php index 6188cd44131a3..433f38a161915 100644 --- a/components/com_users/tmpl/methods/list.php +++ b/components/com_users/tmpl/methods/list.php @@ -34,7 +34,7 @@ ?>
methods as $methodName => $method) : - $methodClass = 'com-users-methods-list-method-name-' . htmlentities($method['name']) + $methodClass = 'com-users-methods-list-method-name-' . htmlentities((string) $method['name']) . ($this->defaultMethod == $methodName ? ' com-users-methods-list-method-default' : ''); ?>
@@ -128,7 +128,7 @@ class="text-warning me-1 hasTooltip"
- diff --git a/components/com_wrapper/src/View/Wrapper/HtmlView.php b/components/com_wrapper/src/View/Wrapper/HtmlView.php index 8b1da760f87f4..c6adf00651d31 100644 --- a/components/com_wrapper/src/View/Wrapper/HtmlView.php +++ b/components/com_wrapper/src/View/Wrapper/HtmlView.php @@ -88,13 +88,13 @@ public function display($tpl = null) if ($params->def('add_scheme', 1)) { // Adds 'http://' or 'https://' if none is set - if (strpos($url, '//') === 0) { + if (str_starts_with((string) $url, '//')) { // URL without scheme in component. Prepend current scheme. - $wrapper->url = Uri::getInstance()->toString(['scheme']) . substr($url, 2); - } elseif (strpos($url, '/') === 0) { + $wrapper->url = Uri::getInstance()->toString(['scheme']) . substr((string) $url, 2); + } elseif (str_starts_with((string) $url, '/')) { // Relative URL in component. Use scheme + host + port. $wrapper->url = Uri::getInstance()->toString(['scheme', 'host', 'port']) . $url; - } elseif (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) { + } elseif (!str_starts_with((string) $url, 'http://') && !str_starts_with((string) $url, 'https://')) { // URL doesn't start with either 'http://' or 'https://'. Add current scheme. $wrapper->url = Uri::getInstance()->toString(['scheme']) . $url; } else { @@ -106,7 +106,7 @@ public function display($tpl = null) } // Escape strings for HTML output - $this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx', '')); + $this->pageclass_sfx = htmlspecialchars((string) $params->get('pageclass_sfx', '')); $this->params = &$params; $this->wrapper = &$wrapper; diff --git a/includes/framework.php b/includes/framework.php index 35de688cce0f0..3ba0f0125f9cb 100644 --- a/includes/framework.php +++ b/includes/framework.php @@ -88,7 +88,7 @@ set_error_handler(null, E_USER_DEPRECATED); } else { // Make sure handler for E_USER_DEPRECATED is registered - set_error_handler(['Joomla\CMS\Exception\ExceptionHandler', 'handleUserDeprecatedErrors'], E_USER_DEPRECATED); + set_error_handler(\Joomla\CMS\Exception\ExceptionHandler::handleUserDeprecatedErrors(...), E_USER_DEPRECATED); } if (JDEBUG || $config->error_reporting === 'maximum') { diff --git a/index.php b/index.php index 85daa024dce05..20269d962ef26 100644 --- a/index.php +++ b/index.php @@ -17,7 +17,7 @@ str_replace( '{{phpversion}}', JOOMLA_MINIMUM_PHP, - file_get_contents(dirname(__FILE__) . '/includes/incompatible.html') + file_get_contents(__DIR__ . '/includes/incompatible.html') ) ); } @@ -29,4 +29,4 @@ define('_JEXEC', 1); // Run the application - All executable code should be triggered through this file -require_once dirname(__FILE__) . '/includes/app.php'; +require_once __DIR__ . '/includes/app.php'; diff --git a/installation/index.php b/installation/index.php index 163297bc31829..3c80e6d04e74b 100644 --- a/installation/index.php +++ b/installation/index.php @@ -17,7 +17,7 @@ str_replace( '{{phpversion}}', JOOMLA_MINIMUM_PHP, - file_get_contents(\dirname(__FILE__) . '/../templates/system/incompatible.html') + file_get_contents(__DIR__ . '/../templates/system/incompatible.html') ) ); } @@ -29,4 +29,4 @@ \define('_JEXEC', 1); // Run the application - All executable code should be triggered through this file -require_once \dirname(__FILE__) . '/includes/app.php'; +require_once __DIR__ . '/includes/app.php'; diff --git a/installation/joomla.php b/installation/joomla.php index 137e042651c57..6a3e8db46c2a6 100644 --- a/installation/joomla.php +++ b/installation/joomla.php @@ -36,4 +36,4 @@ \define('_JCLI_INSTALLATION', 1); // Run the application - All executable code should be triggered through this file -require_once \dirname(__FILE__) . '/includes/cli.php'; +require_once __DIR__ . '/includes/cli.php'; diff --git a/installation/src/Application/CliInstallationApplication.php b/installation/src/Application/CliInstallationApplication.php index 56f704874f473..ad0f6534f92cb 100644 --- a/installation/src/Application/CliInstallationApplication.php +++ b/installation/src/Application/CliInstallationApplication.php @@ -54,14 +54,6 @@ final class CliInstallationApplication extends Application implements CMSApplica */ public $input; - /** - * The application language object. - * - * @var Language - * @since 4.3.0 - */ - protected $language; - /** * @var MVCFactory * @since 4.3.0 @@ -104,7 +96,12 @@ public function __construct( ?InputInterface $input = null, ?OutputInterface $output = null, ?Registry $config = null, - ?Language $language = null + /** + * The application language object. + * + * @since 4.3.0 + */ + protected ?Language $language = null ) { // Register the application name. $this->setName('Joomla CLI installation'); @@ -113,7 +110,6 @@ public function __construct( // Register the client ID. $this->clientId = 2; - $this->language = $language; // Run the parent constructor. parent::__construct($input, $output, $config); @@ -127,7 +123,7 @@ public function __construct( // Register the config to Factory. Factory::$config = $this->config; - Factory::$language = $language; + Factory::$language = $this->language; } /** @@ -140,7 +136,7 @@ public function __construct( * * @since 4.3.0 */ - public function enqueueMessage($msg, $type = 'info') + public function enqueueMessage($msg, $type = 'info'): never { throw new \Exception($msg); } diff --git a/installation/src/Application/InstallationApplication.php b/installation/src/Application/InstallationApplication.php index 8f65c113e9bec..a05c073b03502 100644 --- a/installation/src/Application/InstallationApplication.php +++ b/installation/src/Application/InstallationApplication.php @@ -153,7 +153,7 @@ public function debugLanguage() $key = strtoupper(trim($key)); $key = preg_replace('#\s+#', '_', $key); - $key = preg_replace('#\W#', '', $key); + $key = preg_replace('#\W#', '', (string) $key); // Prepare the text. $guesses[] = $key . '="' . $guess . '"'; @@ -294,7 +294,7 @@ private function executeController() // Parse task in format controller.task if ($task !== '') { - list($controllerName, $task) = explode('.', $task, 2); + [$controllerName, $task] = explode('.', $task, 2); } $factory = new MVCFactory('Joomla\\CMS', $this->getLogger()); diff --git a/installation/src/Console/InstallCommand.php b/installation/src/Console/InstallCommand.php index 9ba642657c97a..1f2a52be75a33 100644 --- a/installation/src/Console/InstallCommand.php +++ b/installation/src/Console/InstallCommand.php @@ -232,7 +232,7 @@ protected function getCLIOptions() foreach ($conditions as $cond) { // remove jform[] from the name - $f = rtrim(substr($cond['field'], 6), ']'); + $f = rtrim(substr((string) $cond['field'], 6), ']'); $temp = false; if ($cond['sign'] == '=' && \in_array($cfg[$f], $cond['values'])) { @@ -355,7 +355,7 @@ protected function getStringFromOption($option, $question, FormField $field): st $answer = null; foreach ($_SERVER['argv'] as $arg) { - if ($arg == '--' . $option || strpos($arg, $option . '=')) { + if ($arg == '--' . $option || strpos((string) $arg, $option . '=')) { $givenOption = true; } } diff --git a/installation/src/Form/Field/Installation/LanguageField.php b/installation/src/Form/Field/Installation/LanguageField.php index 20b86e57b132e..32b519a0e319a 100644 --- a/installation/src/Form/Field/Installation/LanguageField.php +++ b/installation/src/Form/Field/Installation/LanguageField.php @@ -99,7 +99,7 @@ protected function getOptions() */ protected function _sortLanguages($a, $b) { - return strcmp($a['text'], $b['text']); + return strcmp((string) $a['text'], (string) $b['text']); } /** diff --git a/installation/src/Form/Field/Installation/PrefixField.php b/installation/src/Form/Field/Installation/PrefixField.php index f29acdab035fb..d69d9c4b5fe70 100644 --- a/installation/src/Form/Field/Installation/PrefixField.php +++ b/installation/src/Form/Field/Installation/PrefixField.php @@ -83,7 +83,7 @@ protected function getInput() $onchange = $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; return ''; } } diff --git a/installation/src/Form/Rule/UsernameRule.php b/installation/src/Form/Rule/UsernameRule.php index 4e12fa1177943..d65a277f39b80 100644 --- a/installation/src/Form/Rule/UsernameRule.php +++ b/installation/src/Form/Rule/UsernameRule.php @@ -43,7 +43,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $filterInput = InputFilter::getInstance(); if ( - preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $value) + preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', (string) $value) || \strlen(mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8')) < 2 || $filterInput->clean($value, 'TRIM') !== $value || \strlen(mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8')) > $element['size'] diff --git a/installation/src/Helper/DatabaseHelper.php b/installation/src/Helper/DatabaseHelper.php index aa4f1351a7fb1..a3047ce73f213 100644 --- a/installation/src/Helper/DatabaseHelper.php +++ b/installation/src/Helper/DatabaseHelper.php @@ -95,7 +95,7 @@ public static function getDbo($driver, $host, $user, $password, $database, $pref ]; foreach (['cipher', 'ca', 'key', 'cert'] as $value) { - $confVal = trim($ssl['dbssl' . $value]); + $confVal = trim((string) $ssl['dbssl' . $value]); if ($confVal !== '') { $options['ssl'][$value] = $confVal; diff --git a/installation/src/Model/ConfigurationModel.php b/installation/src/Model/ConfigurationModel.php index e92ea8708d532..23326e72f8bda 100644 --- a/installation/src/Model/ConfigurationModel.php +++ b/installation/src/Model/ConfigurationModel.php @@ -142,7 +142,7 @@ public function setup($options) // This is needed because the installer loads the extension table in constructor, needs to be refactored in 5.0 // It doesn't honor the DatabaseAware interface - Factory::getContainer()->set('\Joomla\CMS\Table\Extension', new \Joomla\CMS\Table\Extension($db)); + Factory::getContainer()->set(\Joomla\CMS\Table\Extension::class, new \Joomla\CMS\Table\Extension($db)); $installer = Installer::getInstance(); diff --git a/installation/src/Model/DatabaseModel.php b/installation/src/Model/DatabaseModel.php index 2b3038eeaa538..a2bb67313ccc3 100644 --- a/installation/src/Model/DatabaseModel.php +++ b/installation/src/Model/DatabaseModel.php @@ -204,7 +204,7 @@ public function createDatabase(array $options) } // @internal Check for asc(00) Null in name. - if (strpos($options->db_name, \chr(00)) !== false) { + if (str_contains($options->db_name, \chr(00))) { throw new \RuntimeException(Text::_('INSTL_DATABASE_NAME_INVALID_CHAR')); } @@ -226,7 +226,7 @@ public function createDatabase(array $options) // Set the character set to UTF-8 for pre-existing databases. try { $db->alterDbCharacterSet($options->db_name); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // Continue Anyhow } @@ -270,7 +270,7 @@ public function handleOldDatabase(array $options) // Set the character set to UTF-8 for pre-existing databases. try { $db->alterDbCharacterSet($options['db_name']); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // Continue Anyhow } @@ -339,7 +339,7 @@ public function backupDatabase($db, $prefix) if ($tables) { foreach ($tables as $table) { // If the table uses the given prefix, back it up. - if (strpos($table, $prefix) === 0) { + if (str_starts_with((string) $table, $prefix)) { // Backup table name. $backupTable = str_replace($prefix, $backup, $table); @@ -385,7 +385,7 @@ public function createDb($db, $options, $utf) try { // Run the create database query. $db->createDatabase($options, $utf); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // If an error occurred return false. return false; } @@ -419,7 +419,7 @@ public function populateDatabase($db, $schema) foreach ($queries as $query) { // Trim any whitespace. - $query = trim($query); + $query = trim((string) $query); // If the query isn't empty and is not a MySQL or PostgreSQL comment, execute it. if (!empty($query) && ($query[0] != '#') && ($query[0] != '-')) { @@ -464,7 +464,7 @@ protected function splitQueries($query) $query = preg_replace("/\n\--[^\n]*/", '', "\n" . $query); // Find function. - $funct = explode('CREATE OR REPLACE FUNCTION', $query); + $funct = explode('CREATE OR REPLACE FUNCTION', (string) $query); // Save sql before function and parse it. $query = $funct[0]; diff --git a/installation/src/Service/Provider/Application.php b/installation/src/Service/Provider/Application.php index b8da47fb3b480..8a487865c6b97 100644 --- a/installation/src/Service/Provider/Application.php +++ b/installation/src/Service/Provider/Application.php @@ -48,12 +48,12 @@ public function register(Container $container) InstallationApplication::class, function (Container $container) { $app = new InstallationApplication($container->get(CMSInput::class), $container->get('config'), null, $container); - $app->setDispatcher($container->get('Joomla\Event\DispatcherInterface')); + $app->setDispatcher($container->get(\Joomla\Event\DispatcherInterface::class)); $app->setLogger($container->get(LoggerInterface::class)); $app->setSession($container->get(SessionInterface::class)); // Ensure that session purging is configured now we have a dispatcher - $app->getDispatcher()->addListener(SessionEvents::START, [$app, 'afterSessionStart'], Priority::HIGH); + $app->getDispatcher()->addListener(SessionEvents::START, $app->afterSessionStart(...), Priority::HIGH); return $app; }, @@ -67,7 +67,7 @@ function (Container $container) { $app = new CliInstallationApplication(null, null, $container->get('config'), $lang); - $app->setDispatcher($container->get('Joomla\Event\DispatcherInterface')); + $app->setDispatcher($container->get(\Joomla\Event\DispatcherInterface::class)); $app->setLogger($container->get(LoggerInterface::class)); $app->setSession($container->get(SessionInterface::class)); @@ -79,9 +79,7 @@ function (Container $container) { // Inject a custom JSON error renderer $container->share( JsonRenderer::class, - function (Container $container) { - return new \Joomla\CMS\Installation\Error\Renderer\JsonRenderer(); - } + fn(Container $container) => new \Joomla\CMS\Installation\Error\Renderer\JsonRenderer() ); } } diff --git a/language/en-GB/localise.php b/language/en-GB/localise.php index 68338c3391ef7..0ad9efa5a2fa6 100644 --- a/language/en-GB/localise.php +++ b/language/en-GB/localise.php @@ -33,14 +33,10 @@ abstract class En_GBLocalise */ public static function getPluralSuffixes($count) { - switch ($count) { - case 0: - return ['0']; - - case 1: - return ['ONE', '1']; - } - - return ['OTHER', 'MORE']; + return match ($count) { + 0 => ['0'], + 1 => ['ONE', '1'], + default => ['OTHER', 'MORE'], + }; } } diff --git a/layouts/chromes/html5.php b/layouts/chromes/html5.php index af2d0f4101895..63407b8ab3040 100644 --- a/layouts/chromes/html5.php +++ b/layouts/chromes/html5.php @@ -22,13 +22,13 @@ return; } -$moduleTag = htmlspecialchars($params->get('module_tag', 'div'), ENT_QUOTES, 'UTF-8'); +$moduleTag = htmlspecialchars((string) $params->get('module_tag', 'div'), ENT_QUOTES, 'UTF-8'); $moduleAttribs = []; -$moduleAttribs['class'] = 'moduletable ' . htmlspecialchars($params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); +$moduleAttribs['class'] = 'moduletable ' . htmlspecialchars((string) $params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); $bootstrapSize = (int) $params->get('bootstrap_size', 0); $moduleAttribs['class'] .= $bootstrapSize !== 0 ? ' col-md-' . $bootstrapSize : ''; -$headerTag = htmlspecialchars($params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); -$headerClass = htmlspecialchars($params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); +$headerTag = htmlspecialchars((string) $params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); +$headerClass = htmlspecialchars((string) $params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); $headerAttribs = []; // Only output a header class if one is set @@ -38,7 +38,7 @@ // Add class from attributes if any if (!empty($attribs['class'])) { - $moduleAttribs['class'] .= ' ' . htmlspecialchars($attribs['class'], ENT_QUOTES, 'UTF-8'); + $moduleAttribs['class'] .= ' ' . htmlspecialchars((string) $attribs['class'], ENT_QUOTES, 'UTF-8'); } // Only add aria if the moduleTag is not a div diff --git a/layouts/chromes/table.php b/layouts/chromes/table.php index 2176625b876a4..0d40f7c27556d 100644 --- a/layouts/chromes/table.php +++ b/layouts/chromes/table.php @@ -16,7 +16,7 @@ $params = $displayData['params']; ?> + class="moduletable get('moduleclass_sfx', ''), ENT_COMPAT, 'UTF-8'); ?>"> showtitle) : ?> - + - + diff --git a/plugins/system/stats/src/Extension/Stats.php b/plugins/system/stats/src/Extension/Stats.php index 13f6cb16248d7..f9c6f922cdd1f 100644 --- a/plugins/system/stats/src/Extension/Stats.php +++ b/plugins/system/stats/src/Extension/Stats.php @@ -405,7 +405,7 @@ private function isUpdateRequired() */ private function isAjaxRequest() { - return strtolower($this->getApplication()->getInput()->server->get('HTTP_X_REQUESTED_WITH', '')) === 'xmlhttprequest'; + return strtolower((string) $this->getApplication()->getInput()->server->get('HTTP_X_REQUESTED_WITH', '')) === 'xmlhttprequest'; } /** @@ -454,7 +454,7 @@ private function saveParams() try { // Lock the tables to prevent multiple plugin executions causing a race condition $db->lockTable('#__extensions'); - } catch (\Exception $e) { + } catch (\Exception) { // If we can't lock the tables it's too risky to continue execution return false; } @@ -464,7 +464,7 @@ private function saveParams() $result = $db->setQuery($query)->execute(); $this->clearCacheGroups(['com_plugins']); - } catch (\Exception $exc) { + } catch (\Exception) { // If we failed to execute $db->unlockTables(); $result = false; @@ -473,7 +473,7 @@ private function saveParams() try { // Unlock the tables after writing $db->unlockTables(); - } catch (\Exception $e) { + } catch (\Exception) { // If we can't lock the tables assume we have somehow failed $result = false; } @@ -551,7 +551,7 @@ private function clearCacheGroups(array $clearGroups) $cache = Cache::getInstance('callback', $options); $cache->clean(); - } catch (\Exception $e) { + } catch (\Exception) { // Ignore it } } @@ -579,7 +579,7 @@ private function disablePlugin() try { // Lock the tables to prevent multiple plugin executions causing a race condition $db->lockTable('#__extensions'); - } catch (\Exception $e) { + } catch (\Exception) { // If we can't lock the tables it's too risky to continue execution return false; } @@ -589,7 +589,7 @@ private function disablePlugin() $result = $db->setQuery($query)->execute(); $this->clearCacheGroups(['com_plugins']); - } catch (\Exception $exc) { + } catch (\Exception) { // If we failed to execute $db->unlockTables(); $result = false; @@ -598,7 +598,7 @@ private function disablePlugin() try { // Unlock the tables after writing $db->unlockTables(); - } catch (\Exception $e) { + } catch (\Exception) { // If we can't lock the tables assume we have somehow failed $result = false; } diff --git a/plugins/system/tasknotification/src/Extension/TaskNotification.php b/plugins/system/tasknotification/src/Extension/TaskNotification.php index 6be75dec3dade..6a031e40b600c 100644 --- a/plugins/system/tasknotification/src/Extension/TaskNotification.php +++ b/plugins/system/tasknotification/src/Extension/TaskNotification.php @@ -97,7 +97,7 @@ public function injectTaskNotificationFieldset(Model\PrepareFormEvent $event): b try { $formFile = Path::check($formFile); - } catch (\Exception $e) { + } catch (\Exception) { // Log? return false; } @@ -298,7 +298,7 @@ private function sendMail(string $template, array $data, string $attachment = '' try { $users = $db->loadObjectList(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return; } @@ -331,7 +331,7 @@ private function sendMail(string $template, array $data, string $attachment = '' $mailer->send(); $mailSent = true; - } catch (MailerException $exception) { + } catch (MailerException) { Log::add($this->getApplication()->getLanguage()->_('PLG_SYSTEM_TASK_NOTIFICATION_NOTIFY_SEND_EMAIL_FAIL'), Log::ERROR); } } diff --git a/plugins/system/webauthn/src/Authentication.php b/plugins/system/webauthn/src/Authentication.php index c8b12f620ad5a..2f931283f0c26 100644 --- a/plugins/system/webauthn/src/Authentication.php +++ b/plugins/system/webauthn/src/Authentication.php @@ -43,38 +43,6 @@ */ final class Authentication { - /** - * The credentials repository - * - * @var CredentialRepository - * @since 4.2.0 - */ - private $credentialsRepository; - - /** - * The application we are running in. - * - * @var CMSApplication - * @since 4.2.0 - */ - private $app; - - /** - * The application session - * - * @var SessionInterface - * @since 4.2.0 - */ - private $session; - - /** - * A simple metadata statement repository - * - * @var MetadataStatementRepository - * @since 4.2.0 - */ - private $metadataRepository; - /** * Should I permit attestation support if a Metadata Statement Repository object is present and * non-empty? @@ -89,21 +57,38 @@ final class Authentication * * @param ?ApplicationInterface $app The app we are running in * @param ?SessionInterface $session The app session object - * @param ?PublicKeyCredentialSourceRepository $credRepo Credentials repo - * @param ?MetadataStatementRepository $mdsRepo Authenticator metadata repo + * @param ?PublicKeyCredentialSourceRepository $credentialsRepository Credentials repo + * @param ?MetadataStatementRepository $metadataRepository Authenticator metadata repo * * @since 4.2.0 */ public function __construct( - ?ApplicationInterface $app = null, - ?SessionInterface $session = null, - ?PublicKeyCredentialSourceRepository $credRepo = null, - ?MetadataStatementRepository $mdsRepo = null - ) { - $this->app = $app; - $this->session = $session; - $this->credentialsRepository = $credRepo; - $this->metadataRepository = $mdsRepo; + /** + * The application we are running in. + * + * @since 4.2.0 + */ + private readonly ?ApplicationInterface $app = null, + /** + * The application session + * + * @since 4.2.0 + */ + private readonly ?SessionInterface $session = null, + /** + * The credentials repository + * + * @since 4.2.0 + */ + private readonly ?PublicKeyCredentialSourceRepository $credentialsRepository = null, + /** + * A simple metadata statement repository + * + * @since 4.2.0 + */ + private readonly ?MetadataStatementRepository $metadataRepository = null + ) + { } /** @@ -120,7 +105,7 @@ public function getKnownAuthenticators(): array // Add a generic authenticator entry $image = HTMLHelper::_('image', 'plg_system_webauthn/fido.png', '', '', true, true); - $image = $image ? JPATH_ROOT . substr($image, \strlen(Uri::root(true))) : (JPATH_BASE . '/media/plg_system_webauthn/images/fido.png'); + $image = $image ? JPATH_ROOT . substr((string) $image, \strlen(Uri::root(true))) : (JPATH_BASE . '/media/plg_system_webauthn/images/fido.png'); $image = file_exists($image) ? file_get_contents($image) : ''; $return[''] = (object) [ @@ -249,7 +234,7 @@ public function validateAssertionResponse(string $data, User $user): PublicKeyCr { // Make sure the public key credential request options in the session are valid $encodedPkOptions = $this->session->get('plg_system_webauthn.publicKeyCredentialRequestOptions', null); - $serializedOptions = base64_decode($encodedPkOptions); + $serializedOptions = base64_decode((string) $encodedPkOptions); $publicKeyCredentialRequestOptions = unserialize($serializedOptions); if ( @@ -307,8 +292,8 @@ public function validateAttestationResponse(string $data): PublicKeyCredentialSo /** @var PublicKeyCredentialCreationOptions|null $publicKeyCredentialCreationOptions */ try { - $publicKeyCredentialCreationOptions = unserialize(base64_decode($encodedOptions)); - } catch (\Exception $e) { + $publicKeyCredentialCreationOptions = unserialize(base64_decode((string) $encodedOptions)); + } catch (\Exception) { Log::add('The plg_system_webauthn.publicKeyCredentialCreationOptions in the session is invalid', Log::NOTICE, 'webauthn.system'); $publicKeyCredentialCreationOptions = null; } @@ -392,7 +377,7 @@ private function getSiteIcon(): ?string '/templates/', '/templates/' . $this->app->getTemplate(), ]; - } catch (\Exception $e) { + } catch (\Exception) { return null; } @@ -501,8 +486,8 @@ private function getPKCredentialRequestOptions(): PublicKeyCredentialRequestOpti } try { - $publicKeyCredentialRequestOptions = unserialize(base64_decode($encodedOptions)); - } catch (\Exception $e) { + $publicKeyCredentialRequestOptions = unserialize(base64_decode((string) $encodedOptions)); + } catch (\Exception) { Log::add('Invalid plg_system_webauthn.publicKeyCredentialRequestOptions in the session', Log::NOTICE, 'webauthn.system'); throw new \RuntimeException(Text::_('PLG_SYSTEM_WEBAUTHN_ERR_CREATE_INVALID_LOGIN_REQUEST')); diff --git a/plugins/system/webauthn/src/CredentialRepository.php b/plugins/system/webauthn/src/CredentialRepository.php index e23a3e34f0870..2c8351d835d02 100644 --- a/plugins/system/webauthn/src/CredentialRepository.php +++ b/plugins/system/webauthn/src/CredentialRepository.php @@ -79,7 +79,7 @@ public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKey try { return PublicKeyCredentialSource::createFromArray(json_decode($json, true)); - } catch (\Throwable $e) { + } catch (\Throwable) { return null; } } @@ -107,7 +107,7 @@ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCre try { $records = $db->setQuery($query)->loadAssocList(); - } catch (\Exception $e) { + } catch (\Exception) { return []; } @@ -126,7 +126,7 @@ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCre try { $json = $this->decryptCredential($record['credential']); $data = json_decode($json, true); - } catch (\JsonException $e) { + } catch (\JsonException) { return null; } @@ -136,7 +136,7 @@ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCre try { return PublicKeyCredentialSource::createFromArray($data); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return null; } }; @@ -155,9 +155,7 @@ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCre * * @return boolean */ - $filterClosure = function ($record) { - return !\is_null($record) && \is_object($record) && ($record instanceof PublicKeyCredentialSource); - }; + $filterClosure = (fn($record) => !\is_null($record) && \is_object($record) && ($record instanceof PublicKeyCredentialSource)); return array_filter($records, $filterClosure); } @@ -222,7 +220,7 @@ public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredent $o->user_id = $oldRecord->user_id; $o->label = $oldRecord->label; $update = true; - } catch (\Exception $e) { + } catch (\Exception) { } $o->credential = $this->encryptCredential($o->credential); @@ -268,7 +266,7 @@ public function getAll(int $userId): array try { $results = $db->setQuery($query)->loadAssocList(); - } catch (\Exception $e) { + } catch (\Exception) { return []; } @@ -288,7 +286,7 @@ public function getAll(int $userId): array try { $json = $this->decryptCredential($record['credential']); $data = json_decode($json, true); - } catch (\JsonException $e) { + } catch (\JsonException) { $record['credential'] = null; return $record; @@ -304,7 +302,7 @@ public function getAll(int $userId): array $record['credential'] = PublicKeyCredentialSource::createFromArray($data); return $record; - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { $record['credential'] = null; return $record; @@ -338,7 +336,7 @@ public function has(string $credentialId): bool $count = $db->setQuery($query)->loadResult(); return $count > 0; - } catch (\Exception $e) { + } catch (\Exception) { return false; } } @@ -473,7 +471,7 @@ public function getUserIdFromHandle(?string $userHandle): ?int try { $numRecords = $db->setQuery($query)->loadResult(); - } catch (\Exception $e) { + } catch (\Exception) { return null; } @@ -501,7 +499,7 @@ public function getUserIdFromHandle(?string $userHandle): ?int while (true) { try { $ids = $db->setQuery($query, $start, $limit)->loadColumn(); - } catch (\Exception $e) { + } catch (\Exception) { return null; } @@ -562,7 +560,7 @@ private function decryptCredential(string $credential): string } // Was the credential stored unencrypted (e.g. the site's secret was empty)? - if ((strpos($credential, '{') !== false) && (strpos($credential, '"publicKeyCredentialId"') !== false)) { + if ((str_contains($credential, '{')) && (str_contains($credential, '"publicKeyCredentialId"'))) { return $credential; } @@ -585,7 +583,7 @@ private function getEncryptionKey(): string /** @var Registry $config */ $config = $app->getConfig(); $secret = $config->get('secret', ''); - } catch (\Exception $e) { + } catch (\Exception) { $secret = ''; } @@ -621,7 +619,7 @@ private function formatDate($date, ?string $format = null, bool $tzAware = true) try { $tzDefault = Factory::getApplication()->get('offset'); - } catch (\Exception $e) { + } catch (\Exception) { $tzDefault = 'GMT'; } @@ -634,7 +632,7 @@ private function formatDate($date, ?string $format = null, bool $tzAware = true) $userTimeZone = new \DateTimeZone($tz); $jDate->setTimezone($userTimeZone); - } catch (\Exception $e) { + } catch (\Exception) { // Nothing. Fall back to UTC. } } diff --git a/plugins/system/webauthn/src/Extension/Webauthn.php b/plugins/system/webauthn/src/Extension/Webauthn.php index 876e04cd48971..4f468bdaae40d 100644 --- a/plugins/system/webauthn/src/Extension/Webauthn.php +++ b/plugins/system/webauthn/src/Extension/Webauthn.php @@ -155,7 +155,7 @@ public static function getSubscribedEvents(): array { try { $app = Factory::getApplication(); - } catch (\Exception $e) { + } catch (\Exception) { return []; } diff --git a/plugins/system/webauthn/src/MetadataRepository.php b/plugins/system/webauthn/src/MetadataRepository.php index 4d61056780c13..6f523825846f3 100644 --- a/plugins/system/webauthn/src/MetadataRepository.php +++ b/plugins/system/webauthn/src/MetadataRepository.php @@ -81,22 +81,16 @@ public function getKnownAuthenticators(): array { $this->load(); - $mapKeys = function (MetadataStatement $meta) { - return $meta->getAaguid(); - }; - $mapvalues = function (MetadataStatement $meta) { - return $meta->getAaguid() ? (object) [ - 'description' => $meta->getDescription(), - 'icon' => $meta->getIcon(), - ] : null; - }; + $mapKeys = (fn(MetadataStatement $meta) => $meta->getAaguid()); + $mapvalues = (fn(MetadataStatement $meta) => $meta->getAaguid() ? (object) [ + 'description' => $meta->getDescription(), + 'icon' => $meta->getIcon(), + ] : null); $keys = array_map($mapKeys, $this->mdsCache); $values = array_map($mapvalues, $this->mdsCache); $return = array_combine($keys, $values) ?: []; - $filter = function ($x) { - return !empty($x); - }; + $filter = (fn($x) => !empty($x)); return array_filter($return, $filter); } @@ -128,7 +122,7 @@ private function load(): void try { $jwtConfig = Configuration::forUnsecuredSigner(); $token = $jwtConfig->parser()->parse($rawJwt); - } catch (\Exception $e) { + } catch (\Exception) { return; } @@ -153,7 +147,7 @@ private function load(): void } return MetadataStatement::createFromArray($array); - } catch (\Exception $e) { + } catch (\Exception) { return null; } }; @@ -161,9 +155,7 @@ private function load(): void unset($token); - $entriesFilter = function ($x) { - return !empty($x); - }; + $entriesFilter = (fn($x) => !empty($x)); $this->mdsCache = array_filter($entries, $entriesFilter); foreach ($this->mdsCache as $idx => $meta) { diff --git a/plugins/system/webauthn/src/PluginTraits/AdditionalLoginButtons.php b/plugins/system/webauthn/src/PluginTraits/AdditionalLoginButtons.php index cbf17cd67bfde..c93941568085f 100644 --- a/plugins/system/webauthn/src/PluginTraits/AdditionalLoginButtons.php +++ b/plugins/system/webauthn/src/PluginTraits/AdditionalLoginButtons.php @@ -82,7 +82,7 @@ public function onUserLoginButtons(Event $event): void $image = HTMLHelper::_('image', 'plg_system_webauthn/fido-passkey-black.svg', '', '', true, true); // If you can't find the image then skip it - $image = $image ? JPATH_ROOT . substr($image, \strlen(Uri::root(true))) : ''; + $image = $image ? JPATH_ROOT . substr((string) $image, \strlen(Uri::root(true))) : ''; // Extract image if it exists $image = file_exists($image) ? file_get_contents($image) : ''; @@ -138,7 +138,7 @@ private function mustDisplayButton(): bool */ try { $document = $this->getApplication()->getDocument(); - } catch (\Exception $e) { + } catch (\Exception) { $document = null; } diff --git a/plugins/system/webauthn/src/PluginTraits/AjaxHandler.php b/plugins/system/webauthn/src/PluginTraits/AjaxHandler.php index b9e6556258894..af058cd8173a1 100644 --- a/plugins/system/webauthn/src/PluginTraits/AjaxHandler.php +++ b/plugins/system/webauthn/src/PluginTraits/AjaxHandler.php @@ -85,50 +85,25 @@ public function onAjaxWebauthn(AjaxEvent $event): void // Call the plugin event onAjaxWebauthnSomething where Something is the akaction param. /** @var AbstractEvent|ResultAwareInterface $triggerEvent */ - $eventName = 'onAjaxWebauthn' . ucfirst($akaction); - - switch ($eventName) { - case 'onAjaxWebauthn': - $eventClass = PlgSystemWebauthnAjax::class; - break; - - case 'onAjaxWebauthnChallenge': - $eventClass = PlgSystemWebauthnAjaxChallenge::class; - break; - - case 'onAjaxWebauthnCreate': - $eventClass = PlgSystemWebauthnAjaxCreate::class; - break; - - case 'onAjaxWebauthnDelete': - $eventClass = PlgSystemWebauthnAjaxDelete::class; - break; - - case 'onAjaxWebauthnInitcreate': - $eventClass = PlgSystemWebauthnAjaxInitCreate::class; - break; - - case 'onAjaxWebauthnLogin': - $eventClass = PlgSystemWebauthnAjaxLogin::class; - break; - - case 'onAjaxWebauthnSavelabel': - $eventClass = PlgSystemWebauthnAjaxSaveLabel::class; - break; - - default: - $eventClass = GenericEvent::class; - break; - } + $eventName = 'onAjaxWebauthn' . ucfirst((string) $akaction); + + $eventClass = match ($eventName) { + 'onAjaxWebauthn' => PlgSystemWebauthnAjax::class, + 'onAjaxWebauthnChallenge' => PlgSystemWebauthnAjaxChallenge::class, + 'onAjaxWebauthnCreate' => PlgSystemWebauthnAjaxCreate::class, + 'onAjaxWebauthnDelete' => PlgSystemWebauthnAjaxDelete::class, + 'onAjaxWebauthnInitcreate' => PlgSystemWebauthnAjaxInitCreate::class, + 'onAjaxWebauthnLogin' => PlgSystemWebauthnAjaxLogin::class, + 'onAjaxWebauthnSavelabel' => PlgSystemWebauthnAjaxSaveLabel::class, + default => GenericEvent::class, + }; $triggerEvent = new $eventClass($eventName, []); $result = $this->getApplication()->getDispatcher()->dispatch($eventName, $triggerEvent); $results = ($result instanceof ResultAwareInterface) ? ($result['result'] ?? []) : []; $result = array_reduce( $results, - function ($carry, $result) { - return $carry ?? $result; - }, + fn($carry, $result) => $carry ?? $result, null ); } catch (\Exception $e) { diff --git a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerChallenge.php b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerChallenge.php index 6de8ad4c124f3..b5c0f0aaf5059 100644 --- a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerChallenge.php +++ b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerChallenge.php @@ -57,7 +57,7 @@ public function onAjaxWebauthnChallenge(AjaxChallenge $event): void $session->get('plg_system_webauthn.returnUrl', Uri::current()) ); $returnUrl = $input->getBase64('returnUrl', $returnUrl); - $returnUrl = base64_decode($returnUrl); + $returnUrl = base64_decode((string) $returnUrl); // For security reasons the post-login redirection URL must be internal to the site. if (!Uri::isInternal($returnUrl)) { @@ -77,7 +77,7 @@ public function onAjaxWebauthnChallenge(AjaxChallenge $event): void // Is the username valid? try { $userId = UserHelper::getUserId($username); - } catch (\Exception $e) { + } catch (\Exception) { $userId = 0; } @@ -89,7 +89,7 @@ public function onAjaxWebauthnChallenge(AjaxChallenge $event): void try { $myUser = Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById($userId); - } catch (\Exception $e) { + } catch (\Exception) { $myUser = new User(); } diff --git a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerDelete.php b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerDelete.php index 1a7d0febe33a4..519961ad01495 100644 --- a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerDelete.php +++ b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerDelete.php @@ -53,7 +53,7 @@ public function onAjaxWebauthnDelete(AjaxDelete $event): void return; } - $credentialId = base64_decode($credentialId); + $credentialId = base64_decode((string) $credentialId); if (empty($credentialId) || !$repository->has($credentialId)) { $event->addResult(false); @@ -66,7 +66,7 @@ public function onAjaxWebauthnDelete(AjaxDelete $event): void $user = $this->getApplication()->getIdentity() ?? new User(); $credentialHandle = $repository->getUserHandleFor($credentialId); $myHandle = $repository->getHandleFromUserId($user->id); - } catch (\Exception $e) { + } catch (\Exception) { $event->addResult(false); return; @@ -81,7 +81,7 @@ public function onAjaxWebauthnDelete(AjaxDelete $event): void // Delete the record try { $repository->remove($credentialId); - } catch (\Exception $e) { + } catch (\Exception) { $event->addResult(false); return; diff --git a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerLogin.php b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerLogin.php index f4d339256e63c..2785029ee975a 100644 --- a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerLogin.php +++ b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerLogin.php @@ -144,7 +144,7 @@ public function onAjaxWebauthnLogin(AjaxLogin $event): void private function loginUser(int $userId): void { // Trick the class auto-loader into loading the necessary classes - class_exists('Joomla\\CMS\\Authentication\\Authentication', true); + class_exists(\Joomla\CMS\Authentication\Authentication::class, true); // Fake a successful login message $isAdmin = $this->getApplication()->isClient('administrator'); @@ -260,7 +260,7 @@ class_exists('Joomla\\CMS\\Authentication\\Authentication', true); private function getAuthenticationResponseObject(): AuthenticationResponse { // Force the class auto-loader to load the JAuthentication class - class_exists('Joomla\\CMS\\Authentication\\Authentication', true); + class_exists(\Joomla\CMS\Authentication\Authentication::class, true); return new AuthenticationResponse(); } diff --git a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerSaveLabel.php b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerSaveLabel.php index aa188019d20db..ff327b6917f38 100644 --- a/plugins/system/webauthn/src/PluginTraits/AjaxHandlerSaveLabel.php +++ b/plugins/system/webauthn/src/PluginTraits/AjaxHandlerSaveLabel.php @@ -55,7 +55,7 @@ public function onAjaxWebauthnSavelabel(AjaxSaveLabel $event): void return; } - $credentialId = base64_decode($credentialId); + $credentialId = base64_decode((string) $credentialId); if (empty($credentialId) || !$repository->has($credentialId)) { $event->addResult(false); @@ -68,7 +68,7 @@ public function onAjaxWebauthnSavelabel(AjaxSaveLabel $event): void $credentialHandle = $repository->getUserHandleFor($credentialId); $user = $this->getApplication()->getIdentity() ?? new User(); $myHandle = $repository->getHandleFromUserId($user->id); - } catch (\Exception $e) { + } catch (\Exception) { $event->addResult(false); return; @@ -90,7 +90,7 @@ public function onAjaxWebauthnSavelabel(AjaxSaveLabel $event): void // Save the new label try { $repository->setLabel($credentialId, $newLabel); - } catch (\Exception $e) { + } catch (\Exception) { $event->addResult(false); return; diff --git a/plugins/system/webauthn/src/PluginTraits/UserDeletion.php b/plugins/system/webauthn/src/PluginTraits/UserDeletion.php index 5dd83d6016c69..9a883f5157a80 100644 --- a/plugins/system/webauthn/src/PluginTraits/UserDeletion.php +++ b/plugins/system/webauthn/src/PluginTraits/UserDeletion.php @@ -66,7 +66,7 @@ public function onUserAfterDelete(Event $event): void try { $db->setQuery($query)->execute(); - } catch (\Exception $e) { + } catch (\Exception) { // Don't worry if this fails } diff --git a/plugins/system/webauthn/src/PluginTraits/UserProfileFields.php b/plugins/system/webauthn/src/PluginTraits/UserProfileFields.php index 3ff1fe348e947..4092362a381cd 100644 --- a/plugins/system/webauthn/src/PluginTraits/UserProfileFields.php +++ b/plugins/system/webauthn/src/PluginTraits/UserProfileFields.php @@ -74,9 +74,7 @@ public static function renderWebauthnProfileField($value): string $credentialRepository = $plugin->getAuthenticationHelper()->getCredentialsRepository(); $credentials = $credentialRepository->getAll(self::$userFromFormData->id); $authenticators = array_map( - function (array $credential) { - return $credential['label']; - }, + fn(array $credential) => $credential['label'], $credentials ); @@ -175,7 +173,7 @@ public function onContentPrepareData(Event $event): void self::$userFromFormData = $this->getUserFromData($data); if (!HTMLHelper::isRegistered('users.webauthnWebauthn')) { - HTMLHelper::register('users.webauthn', [__CLASS__, 'renderWebauthnProfileField']); + HTMLHelper::register('users.webauthn', self::renderWebauthnProfileField(...)); } } diff --git a/plugins/task/checkfiles/src/Extension/Checkfiles.php b/plugins/task/checkfiles/src/Extension/Checkfiles.php index 7c1ab16a9cbe0..3fed13a6f8423 100644 --- a/plugins/task/checkfiles/src/Extension/Checkfiles.php +++ b/plugins/task/checkfiles/src/Extension/Checkfiles.php @@ -69,14 +69,6 @@ public static function getSubscribedEvents(): array */ protected $autoloadLanguage = true; - /** - * The root directory path - * - * @var string - * @since 4.2.0 - */ - private $rootDirectory; - /** * Constructor. * @@ -86,11 +78,14 @@ public static function getSubscribedEvents(): array * * @since 4.2.0 */ - public function __construct(DispatcherInterface $dispatcher, array $config, string $rootDirectory) + public function __construct(DispatcherInterface $dispatcher, array $config, /** + * The root directory path + * + * @since 4.2.0 + */ + private string $rootDirectory) { parent::__construct($dispatcher, $config); - - $this->rootDirectory = $rootDirectory; } /** @@ -143,7 +138,7 @@ protected function checkImages(ExecuteTaskEvent $event): int try { $image->resize($newWidth, $newHeight, false); - } catch (\LogicException $e) { + } catch (\LogicException) { $this->logTask($this->getApplication()->getLanguage()->_('PLG_TASK_CHECK_FILES_LOG_RESIZE_FAIL'), 'error'); return TaskStatus::KNOCKOUT; diff --git a/plugins/task/deleteactionlogs/src/Extension/DeleteActionLogs.php b/plugins/task/deleteactionlogs/src/Extension/DeleteActionLogs.php index 1b756739ca27c..0015106b2dfe6 100644 --- a/plugins/task/deleteactionlogs/src/Extension/DeleteActionLogs.php +++ b/plugins/task/deleteactionlogs/src/Extension/DeleteActionLogs.php @@ -94,7 +94,7 @@ private function deleteLogs(ExecuteTaskEvent $event): int try { $db->execute(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // Ignore it return Status::KNOCKOUT; } diff --git a/plugins/task/globalcheckin/src/Extension/Globalcheckin.php b/plugins/task/globalcheckin/src/Extension/Globalcheckin.php index 8f63a9aa035be..669d779e70cde 100644 --- a/plugins/task/globalcheckin/src/Extension/Globalcheckin.php +++ b/plugins/task/globalcheckin/src/Extension/Globalcheckin.php @@ -82,7 +82,7 @@ protected function makeCheckin(ExecuteTaskEvent $event): int foreach ($tables as $tn) { // Make sure we get the right tables based on prefix. - if (stripos($tn, $prefix) !== 0) { + if (stripos((string) $tn, $prefix) !== 0) { continue; } @@ -114,7 +114,7 @@ protected function makeCheckin(ExecuteTaskEvent $event): int try { $db->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { // This failure isn't critical, don't care too much $failed = true; } diff --git a/plugins/task/privacyconsent/src/Extension/PrivacyConsent.php b/plugins/task/privacyconsent/src/Extension/PrivacyConsent.php index 2114be4957825..4ff194dd5d8e5 100644 --- a/plugins/task/privacyconsent/src/Extension/PrivacyConsent.php +++ b/plugins/task/privacyconsent/src/Extension/PrivacyConsent.php @@ -133,7 +133,7 @@ private function remindExpiringConsents($expire, $remind): int try { $users = $db->setQuery($query)->loadObjectList(); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { return Status::KNOCKOUT; } @@ -183,10 +183,10 @@ private function remindExpiringConsents($expire, $remind): int try { $db->execute(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return Status::KNOCKOUT; } - } catch (MailDisabledException | phpmailerException $exception) { + } catch (MailDisabledException | phpmailerException) { return Status::KNOCKOUT; } } @@ -222,7 +222,7 @@ private function invalidateExpiredConsents($expire): int try { $users = $db->loadObjectList(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return Status::KNOCKOUT; } @@ -246,7 +246,7 @@ private function invalidateExpiredConsents($expire): int try { $db->execute(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { return Status::KNOCKOUT; } diff --git a/plugins/task/requests/src/Extension/Requests.php b/plugins/task/requests/src/Extension/Requests.php index 606d1d9a00b9a..0970936aece62 100644 --- a/plugins/task/requests/src/Extension/Requests.php +++ b/plugins/task/requests/src/Extension/Requests.php @@ -68,22 +68,6 @@ public static function getSubscribedEvents(): array */ protected $autoloadLanguage = true; - /** - * The http factory - * - * @var HttpFactory - * @since 4.2.0 - */ - private $httpFactory; - - /** - * The root directory - * - * @var string - * @since 4.2.0 - */ - private $rootDirectory; - /** * Constructor. * @@ -94,12 +78,19 @@ public static function getSubscribedEvents(): array * * @since 4.2.0 */ - public function __construct(DispatcherInterface $dispatcher, array $config, HttpFactory $httpFactory, string $rootDirectory) + public function __construct(DispatcherInterface $dispatcher, array $config, /** + * The http factory + * + * @since 4.2.0 + */ + private HttpFactory $httpFactory, /** + * The root directory + * + * @since 4.2.0 + */ + private string $rootDirectory) { parent::__construct($dispatcher, $config); - - $this->httpFactory = $httpFactory; - $this->rootDirectory = $rootDirectory; } /** @@ -130,7 +121,7 @@ protected function makeGetRequest(ExecuteTaskEvent $event): int try { $response = $this->httpFactory->getHttp([])->get($url, $headers, $timeout); - } catch (\Exception $e) { + } catch (\Exception) { $this->logTask($this->getApplication()->getLanguage()->_('PLG_TASK_REQUESTS_TASK_GET_REQUEST_LOG_TIMEOUT')); return TaskStatus::TIMEOUT; @@ -146,7 +137,7 @@ protected function makeGetRequest(ExecuteTaskEvent $event): int File::write($responseFilename, $responseBody); $this->snapshot['output_file'] = $responseFilename; $responseStatus = 'SAVED'; - } catch (\Exception $e) { + } catch (\Exception) { $this->logTask($this->getApplication()->getLanguage()->_('PLG_TASK_REQUESTS_TASK_GET_REQUEST_LOG_UNWRITEABLE_OUTPUT'), 'error'); $responseStatus = 'NOT_SAVED'; } diff --git a/plugins/task/rotatelogs/src/Extension/RotateLogs.php b/plugins/task/rotatelogs/src/Extension/RotateLogs.php index 542de9e9746a9..09d8db6f373cc 100644 --- a/plugins/task/rotatelogs/src/Extension/RotateLogs.php +++ b/plugins/task/rotatelogs/src/Extension/RotateLogs.php @@ -103,7 +103,7 @@ private function rotateLogs(ExecuteTaskEvent $event): int foreach ($files as $file) { try { File::delete($logPath . '/' . $file); - } catch (FilesystemException $exception) { + } catch (FilesystemException) { } } } else { @@ -146,7 +146,7 @@ private function rotate($path, $filename, $currentVersion) try { File::move($path . '/' . $filename, $rotatedFile); - } catch (FilesystemException $exception) { + } catch (FilesystemException) { } } @@ -165,7 +165,7 @@ private function getLogFiles($path) $files = Folder::files($path, '\.php$'); foreach ($files as $file) { - $parts = explode('.', $file); + $parts = explode('.', (string) $file); /* * Rotated log file has this filename format [VERSION].[FILENAME].php. So if $parts has at least 3 elements diff --git a/plugins/task/sessiongc/src/Extension/SessionGC.php b/plugins/task/sessiongc/src/Extension/SessionGC.php index 0440ef90864e7..c28e425a14477 100644 --- a/plugins/task/sessiongc/src/Extension/SessionGC.php +++ b/plugins/task/sessiongc/src/Extension/SessionGC.php @@ -32,15 +32,6 @@ final class SessionGC extends CMSPlugin implements SubscriberInterface { use TaskPluginTrait; - /** - * The meta data manager - * - * @var MetadataManager - * - * @since 4.4.0 - */ - private $metadataManager; - /** * @var string[] * @since 5.0.0 @@ -68,11 +59,15 @@ final class SessionGC extends CMSPlugin implements SubscriberInterface * * @since 4.4.0 */ - public function __construct(DispatcherInterface $dispatcher, array $config, MetadataManager $metadataManager) + public function __construct(DispatcherInterface $dispatcher, array $config, /** + * The meta data manager + * + * + * @since 4.4.0 + */ + private MetadataManager $metadataManager) { parent::__construct($dispatcher, $config); - - $this->metadataManager = $metadataManager; } /** diff --git a/plugins/task/sitestatus/src/Extension/SiteStatus.php b/plugins/task/sitestatus/src/Extension/SiteStatus.php index da446799f2282..d409548e751b6 100644 --- a/plugins/task/sitestatus/src/Extension/SiteStatus.php +++ b/plugins/task/sitestatus/src/Extension/SiteStatus.php @@ -79,22 +79,6 @@ public static function getSubscribedEvents(): array ]; } - /** - * The old config - * - * @var array - * @since 4.2.0 - */ - private $oldConfig; - - /** - * The config file - * - * @var string - * @since 4.2.0 - */ - private $configFile; - /** * Constructor. * @@ -105,12 +89,19 @@ public static function getSubscribedEvents(): array * * @since 4.2.0 */ - public function __construct(DispatcherInterface $dispatcher, array $config, array $oldConfig, string $configFile) + public function __construct(DispatcherInterface $dispatcher, array $config, /** + * The old config + * + * @since 4.2.0 + */ + private array $oldConfig, /** + * The config file + * + * @since 4.2.0 + */ + private string $configFile) { parent::__construct($dispatcher, $config); - - $this->oldConfig = $oldConfig; - $this->configFile = $configFile; } /** @@ -171,7 +162,7 @@ private function writeConfigFile(Registry $config): int // Attempt to write the configuration file as a PHP class named JConfig. $configuration = $config->toString('PHP', ['class' => 'JConfig', 'closingtag' => false]); File::write($file, $configuration); - } catch (\Exception $e) { + } catch (\Exception) { $this->logTask($this->getApplication()->getLanguage()->_('PLG_TASK_SITE_STATUS_ERROR_WRITE_FAILED'), 'error'); return Status::KNOCKOUT; diff --git a/plugins/task/updatenotification/src/Extension/UpdateNotification.php b/plugins/task/updatenotification/src/Extension/UpdateNotification.php index e845b4840676d..4cef732f07f2f 100644 --- a/plugins/task/updatenotification/src/Extension/UpdateNotification.php +++ b/plugins/task/updatenotification/src/Extension/UpdateNotification.php @@ -127,7 +127,7 @@ private function sendNotification(ExecuteTaskEvent $event): int // If we're here, we have updates. First, get a link to the Joomla! Update component. $baseURL = Uri::base(); $baseURL = rtrim($baseURL, '/'); - $baseURL .= (substr($baseURL, -13) !== 'administrator') ? '/administrator/' : '/'; + $baseURL .= (!str_ends_with($baseURL, 'administrator')) ? '/administrator/' : '/'; $baseURL .= 'index.php?option=com_joomlaupdate'; $uri = new Uri($baseURL); @@ -203,7 +203,7 @@ private function sendNotification(ExecuteTaskEvent $event): int } catch (MailDisabledException | phpMailerException $exception) { try { $this->logTask($jLanguage->_($exception->getMessage())); - } catch (\RuntimeException $exception) { + } catch (\RuntimeException) { return Status::KNOCKOUT; } } @@ -263,7 +263,7 @@ private function getSuperUsers($email = null) if (empty($groups)) { return $ret; } - } catch (\Exception $exc) { + } catch (\Exception) { return $ret; } @@ -280,7 +280,7 @@ private function getSuperUsers($email = null) if (empty($userIDs)) { return $ret; } - } catch (\Exception $exc) { + } catch (\Exception) { return $ret; } @@ -300,7 +300,7 @@ private function getSuperUsers($email = null) $db->setQuery($query); $ret = $db->loadObjectList(); - } catch (\Exception $exc) { + } catch (\Exception) { return $ret; } diff --git a/plugins/user/contactcreator/src/Extension/ContactCreator.php b/plugins/user/contactcreator/src/Extension/ContactCreator.php index 87e0ac4e015ad..803f9dff53cd5 100644 --- a/plugins/user/contactcreator/src/Extension/ContactCreator.php +++ b/plugins/user/contactcreator/src/Extension/ContactCreator.php @@ -91,7 +91,7 @@ public function onUserAfterSave($user, $isnew, $success, $msg): void // Check if the contact already exists to generate new name & alias if required if ($contact->id == 0) { - list($name, $alias) = $this->generateAliasAndName($contact->alias, $contact->name, $categoryId); + [$name, $alias] = $this->generateAliasAndName($contact->alias, $contact->name, $categoryId); $contact->name = $name; $contact->alias = $alias; diff --git a/plugins/user/joomla/src/Extension/Joomla.php b/plugins/user/joomla/src/Extension/Joomla.php index d9dd5cccc01c6..6224829af307f 100644 --- a/plugins/user/joomla/src/Extension/Joomla.php +++ b/plugins/user/joomla/src/Extension/Joomla.php @@ -110,7 +110,7 @@ public function onUserAfterDelete($user, $success, $msg): void ->where($db->quoteName('user_id_from') . ' = :userId') ->bind(':userId', $userId, ParameterType::INTEGER) )->execute(); - } catch (ExecutionFailureException $e) { + } catch (ExecutionFailureException) { // Do nothing. } @@ -125,7 +125,7 @@ public function onUserAfterDelete($user, $success, $msg): void try { $db->setQuery($query)->execute(); - } catch (\Exception $e) { + } catch (\Exception) { // Do nothing } @@ -137,7 +137,7 @@ public function onUserAfterDelete($user, $success, $msg): void try { $db->setQuery($query)->execute(); - } catch (\Exception $e) { + } catch (\Exception) { // Do nothing } } @@ -175,7 +175,7 @@ public function onUserAfterSave($user, $isnew, $success, $msg): void } // Check if we have a sensible from email address, if not bail out as mail would not be sent anyway - if (strpos($app->get('mailfrom'), '@') === false) { + if (!str_contains((string) $app->get('mailfrom'), '@')) { $app->enqueueMessage($language->_('JERROR_SENDING_EMAIL'), 'warning'); return; @@ -318,7 +318,7 @@ public function onUserLogin($user, $options = []) try { $db->setQuery($query)->execute(); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { // The old session is already invalidated, don't let this block logging in } @@ -441,7 +441,7 @@ private function disableMfaOnSilentLogin(array $options): void $silentResponseTypes = array_map( 'trim', - explode(',', $userParams->get('silentresponses', '') ?: '') + explode(',', (string) $userParams->get('silentresponses', '') ?: '') ); $silentResponseTypes = $silentResponseTypes ?: ['cookie', 'passwordless']; diff --git a/plugins/user/profile/src/Extension/Profile.php b/plugins/user/profile/src/Extension/Profile.php index 9f68cf0b4defd..c65cb24685807 100644 --- a/plugins/user/profile/src/Extension/Profile.php +++ b/plugins/user/profile/src/Extension/Profile.php @@ -90,7 +90,7 @@ public function onContentPrepareData($context, $data) foreach ($results as $v) { $k = str_replace('profile.', '', $v[0]); - $data->profile[$k] = json_decode($v[1], true); + $data->profile[$k] = json_decode((string) $v[1], true); if ($data->profile[$k] === null) { $data->profile[$k] = $v[1]; @@ -99,19 +99,19 @@ public function onContentPrepareData($context, $data) } if (!HTMLHelper::isRegistered('users.url')) { - HTMLHelper::register('users.url', [__CLASS__, 'url']); + HTMLHelper::register('users.url', [self::class, 'url']); } if (!HTMLHelper::isRegistered('users.calendar')) { - HTMLHelper::register('users.calendar', [__CLASS__, 'calendar']); + HTMLHelper::register('users.calendar', [self::class, 'calendar']); } if (!HTMLHelper::isRegistered('users.tos')) { - HTMLHelper::register('users.tos', [__CLASS__, 'tos']); + HTMLHelper::register('users.tos', [self::class, 'tos']); } if (!HTMLHelper::isRegistered('users.dob')) { - HTMLHelper::register('users.dob', [__CLASS__, 'dob']); + HTMLHelper::register('users.dob', [self::class, 'dob']); } } @@ -134,7 +134,7 @@ public static function url($value) // Convert website URL to utf8 for display $value = htmlspecialchars(PunycodeHelper::urlToUTF8($value), ENT_QUOTES, 'UTF-8'); - if (strpos($value, 'http') === 0) { + if (str_starts_with($value, 'http')) { return '' . $value . ''; } @@ -307,7 +307,7 @@ public function onUserBeforeSave($user, $isnew, $data) try { $date = new Date($data['profile']['dob']); $this->date = $date->format('Y-m-d H:i:s'); - } catch (\Exception $e) { + } catch (\Exception) { // Throw an exception if date is not valid. throw new \InvalidArgumentException($this->getApplication()->getLanguage()->_('PLG_USER_PROFILE_ERROR_INVALID_DOB')); } diff --git a/plugins/user/token/src/Extension/Token.php b/plugins/user/token/src/Extension/Token.php index 3bd8a06dff386..7b59fd20e11ea 100644 --- a/plugins/user/token/src/Extension/Token.php +++ b/plugins/user/token/src/Extension/Token.php @@ -134,7 +134,7 @@ public function onContentPrepareData(string $context, &$data): bool $data->{$this->profileKeyPrefix}[$k] = $v[1]; } - } catch (\Exception $e) { + } catch (\Exception) { // We suppress any database error. It means we get no token saved by default. } @@ -404,7 +404,7 @@ public function onUserAfterDelete(array $user, bool $success, string $msg): void $query->bind(':profileKey', $profileKey, ParameterType::STRING); $db->setQuery($query)->execute(); - } catch (\Exception $e) { + } catch (\Exception) { // Do nothing. } } @@ -449,7 +449,7 @@ private function getTokenSeedForUser(int $userId): ?string $query->bind(':userId', $userId, ParameterType::INTEGER); return $db->setQuery($query)->loadResult(); - } catch (\Exception $e) { + } catch (\Exception) { return null; } } @@ -529,7 +529,7 @@ private function getTokenForDisplay( try { $siteSecret = $this->getApplication()->get('secret'); - } catch (\Exception $e) { + } catch (\Exception) { $siteSecret = ''; } @@ -539,7 +539,7 @@ private function getTokenForDisplay( } $rawToken = base64_decode($tokenSeed); - $tokenHash = hash_hmac($algorithm, $rawToken, $siteSecret); + $tokenHash = hash_hmac($algorithm, $rawToken, (string) $siteSecret); $message = base64_encode("$algorithm:$userId:$tokenHash"); if ($userId !== $this->getApplication()->getIdentity()->id) { @@ -596,7 +596,7 @@ private function hasTokenProfileFields(?int $userId): bool try { $numRows = $db->setQuery($q)->loadResult() ?? 0; - } catch (\Exception $e) { + } catch (\Exception) { return false; } diff --git a/plugins/user/token/src/Field/JoomlatokenField.php b/plugins/user/token/src/Field/JoomlatokenField.php index 7de4cbc7751ae..776d2f0dfac39 100644 --- a/plugins/user/token/src/Field/JoomlatokenField.php +++ b/plugins/user/token/src/Field/JoomlatokenField.php @@ -104,7 +104,7 @@ private function getTokenForDisplay(string $tokenSeed): string try { $siteSecret = Factory::getApplication()->get('secret'); - } catch (\Exception $e) { + } catch (\Exception) { $siteSecret = ''; } @@ -114,7 +114,7 @@ private function getTokenForDisplay(string $tokenSeed): string } $rawToken = base64_decode($tokenSeed); - $tokenHash = hash_hmac($algorithm, $rawToken, $siteSecret); + $tokenHash = hash_hmac((string) $algorithm, $rawToken, (string) $siteSecret); $userId = $this->form->getData()->get('id'); $message = base64_encode("$algorithm:$userId:$tokenHash"); diff --git a/plugins/workflow/featuring/src/Extension/Featuring.php b/plugins/workflow/featuring/src/Extension/Featuring.php index ed53418123401..d611d7a2f42dd 100644 --- a/plugins/workflow/featuring/src/Extension/Featuring.php +++ b/plugins/workflow/featuring/src/Extension/Featuring.php @@ -269,7 +269,7 @@ public function onWorkflowBeforeTransition(WorkflowTransitionEvent $event) AbstractEvent::create( 'onContentBeforeChangeFeatured', [ - 'eventClass' => 'Joomla\Component\Content\Administrator\Event\Model\FeatureEvent', + 'eventClass' => \Joomla\Component\Content\Administrator\Event\Model\FeatureEvent::class, 'subject' => $this, 'extension' => $context, 'pks' => $pks, @@ -424,7 +424,7 @@ public function onContentVersioningPrepareTable(EventInterface $event) return; } - $parts = explode('.', $context); + $parts = explode('.', (string) $context); $component = $this->getApplication()->bootComponent($parts[0]); diff --git a/plugins/workflow/notification/src/Extension/Notification.php b/plugins/workflow/notification/src/Extension/Notification.php index ff8d83a053fe7..0da03866b952b 100644 --- a/plugins/workflow/notification/src/Extension/Notification.php +++ b/plugins/workflow/notification/src/Extension/Notification.php @@ -46,14 +46,6 @@ final class Notification extends CMSPlugin implements SubscriberInterface */ protected $autoloadLanguage = true; - /** - * The language factory. - * - * @var LanguageFactoryInterface - * @since 4.4.0 - */ - private $languageFactory; - /** * Returns an array of events this subscriber will listen to. * @@ -79,11 +71,14 @@ public static function getSubscribedEvents(): array * * @since 4.2.0 */ - public function __construct(DispatcherInterface $dispatcher, array $config, LanguageFactoryInterface $languageFactory) + public function __construct(DispatcherInterface $dispatcher, array $config, /** + * The language factory. + * + * @since 4.4.0 + */ + private LanguageFactoryInterface $languageFactory) { parent::__construct($dispatcher, $config); - - $this->languageFactory = $languageFactory; } /** diff --git a/plugins/workflow/publishing/src/Extension/Publishing.php b/plugins/workflow/publishing/src/Extension/Publishing.php index 1fdf788b37a3b..12ad765fe5726 100644 --- a/plugins/workflow/publishing/src/Extension/Publishing.php +++ b/plugins/workflow/publishing/src/Extension/Publishing.php @@ -427,7 +427,7 @@ public function onContentVersioningPrepareTable(EventInterface $event) return; } - $parts = explode('.', $context); + $parts = explode('.', (string) $context); $component = $this->getApplication()->bootComponent($parts[0]); diff --git a/templates/cassiopeia/component.php b/templates/cassiopeia/component.php index c0cfba17ff4e2..62c18f528f7ed 100644 --- a/templates/cassiopeia/component.php +++ b/templates/cassiopeia/component.php @@ -28,13 +28,13 @@ $fontStyles = ''; if ($paramsFontScheme) { - if (stripos($paramsFontScheme, 'https://') === 0) { + if (stripos((string) $paramsFontScheme, 'https://') === 0) { $this->getPreloadManager()->preconnect('https://fonts.googleapis.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preconnect('https://fonts.gstatic.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preload($paramsFontScheme, ['as' => 'style', 'crossorigin' => 'anonymous']); $wa->registerAndUseStyle('fontscheme.current', $paramsFontScheme, [], ['rel' => 'lazy-stylesheet', 'crossorigin' => 'anonymous']); - if (preg_match_all('/family=([^?:]*):/i', $paramsFontScheme, $matches) > 0) { + if (preg_match_all('/family=([^?:]*):/i', (string) $paramsFontScheme, $matches) > 0) { $fontStyles = '--cassiopeia-font-family-body: "' . str_replace('+', ' ', $matches[1][0]) . '", sans-serif; --cassiopeia-font-family-headings: "' . str_replace('+', ' ', $matches[1][1] ?? $matches[1][0]) . '", sans-serif; --cassiopeia-font-weight-normal: 400; diff --git a/templates/cassiopeia/error.php b/templates/cassiopeia/error.php index e0fe88ca267fb..3b30773f7b784 100644 --- a/templates/cassiopeia/error.php +++ b/templates/cassiopeia/error.php @@ -27,7 +27,7 @@ $layout = $input->getCmd('layout', ''); $task = $input->getCmd('task', ''); $itemid = $input->getCmd('Itemid', ''); -$sitename = htmlspecialchars($app->get('sitename'), ENT_QUOTES, 'UTF-8'); +$sitename = htmlspecialchars((string) $app->get('sitename'), ENT_QUOTES, 'UTF-8'); $menu = $app->getMenu()->getActive(); $pageclass = $menu !== null ? $menu->getParams()->get('pageclass_sfx', '') : ''; @@ -41,13 +41,13 @@ $fontStyles = ''; if ($paramsFontScheme) { - if (stripos($paramsFontScheme, 'https://') === 0) { + if (stripos((string) $paramsFontScheme, 'https://') === 0) { $this->getPreloadManager()->preconnect('https://fonts.googleapis.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preconnect('https://fonts.gstatic.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preload($paramsFontScheme, ['as' => 'style', 'crossorigin' => 'anonymous']); $wa->registerAndUseStyle('fontscheme.current', $paramsFontScheme, [], ['rel' => 'lazy-stylesheet', 'crossorigin' => 'anonymous']); - if (preg_match_all('/family=([^?:]*):/i', $paramsFontScheme, $matches) > 0) { + if (preg_match_all('/family=([^?:]*):/i', (string) $paramsFontScheme, $matches) > 0) { $fontStyles = '--cassiopeia-font-family-body: "' . str_replace('+', ' ', $matches[1][0]) . '", sans-serif; --cassiopeia-font-family-headings: "' . str_replace('+', ' ', $matches[1][1] ?? $matches[1][0]) . '", sans-serif; --cassiopeia-font-weight-normal: 400; @@ -84,9 +84,9 @@ // Logo file or site title param if ($this->params->get('logoFile')) { - $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars($this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); + $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars((string) $this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); } elseif ($this->params->get('siteTitle')) { - $logo = '' . htmlspecialchars($this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; + $logo = '' . htmlspecialchars((string) $this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; } else { $logo = HTMLHelper::_('image', 'logo.svg', $sitename, ['class' => 'logo d-inline-block', 'loading' => 'eager', 'decoding' => 'async'], true, 0); } @@ -127,7 +127,7 @@ params->get('siteDescription')) : ?> -
params->get('siteDescription')); ?>
+
params->get('siteDescription')); ?>
diff --git a/templates/cassiopeia/html/layouts/chromes/card.php b/templates/cassiopeia/html/layouts/chromes/card.php index f0400ab5d4bbf..3e7b8fd340ab6 100644 --- a/templates/cassiopeia/html/layouts/chromes/card.php +++ b/templates/cassiopeia/html/layouts/chromes/card.php @@ -22,9 +22,9 @@ $moduleTag = $params->get('module_tag', 'div'); $moduleAttribs = []; -$moduleAttribs['class'] = $module->position . ' card ' . htmlspecialchars($params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); -$headerTag = htmlspecialchars($params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); -$headerClass = htmlspecialchars($params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); +$moduleAttribs['class'] = $module->position . ' card ' . htmlspecialchars((string) $params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); +$headerTag = htmlspecialchars((string) $params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); +$headerClass = htmlspecialchars((string) $params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); $headerAttribs = []; $headerAttribs['class'] = $headerClass; @@ -35,7 +35,7 @@ // Add class from attributes if any if (!empty($attribs['class'])) { - $moduleAttribs['class'] .= ' ' . htmlspecialchars($attribs['class'], ENT_QUOTES, 'UTF-8'); + $moduleAttribs['class'] .= ' ' . htmlspecialchars((string) $attribs['class'], ENT_QUOTES, 'UTF-8'); } // Only add aria if the moduleTag is not a div diff --git a/templates/cassiopeia/html/layouts/chromes/noCard.php b/templates/cassiopeia/html/layouts/chromes/noCard.php index 40ccc64370457..6fae3d2567a80 100644 --- a/templates/cassiopeia/html/layouts/chromes/noCard.php +++ b/templates/cassiopeia/html/layouts/chromes/noCard.php @@ -22,9 +22,9 @@ $moduleTag = $params->get('module_tag', 'div'); $moduleAttribs = []; -$moduleAttribs['class'] = $module->position . ' no-card ' . htmlspecialchars($params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); -$headerTag = htmlspecialchars($params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); -$headerClass = htmlspecialchars($params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); +$moduleAttribs['class'] = $module->position . ' no-card ' . htmlspecialchars((string) $params->get('moduleclass_sfx', ''), ENT_QUOTES, 'UTF-8'); +$headerTag = htmlspecialchars((string) $params->get('header_tag', 'h3'), ENT_QUOTES, 'UTF-8'); +$headerClass = htmlspecialchars((string) $params->get('header_class', ''), ENT_QUOTES, 'UTF-8'); $headerAttribs = []; // Only output a header class if one is set diff --git a/templates/cassiopeia/html/mod_menu/dropdown-metismenu.php b/templates/cassiopeia/html/mod_menu/dropdown-metismenu.php index 6c1549e6dbaf9..34a9b45dcb279 100644 --- a/templates/cassiopeia/html/mod_menu/dropdown-metismenu.php +++ b/templates/cassiopeia/html/mod_menu/dropdown-metismenu.php @@ -74,17 +74,10 @@ echo '
  • '; - switch ($item->type) : - case 'separator': - case 'component': - case 'heading': - case 'url': - require ModuleHelper::getLayoutPath('mod_menu', 'dropdown-metismenu_' . $item->type); - break; - - default: - require ModuleHelper::getLayoutPath('mod_menu', 'dropdown-metismenu_url'); - endswitch; + match ($item->type) { + 'separator', 'component', 'heading', 'url' => require ModuleHelper::getLayoutPath('mod_menu', 'dropdown-metismenu_' . $item->type), + default => require ModuleHelper::getLayoutPath('mod_menu', 'dropdown-metismenu_url'), + }; switch (true) : // The next item is deeper. diff --git a/templates/cassiopeia/index.php b/templates/cassiopeia/index.php index c12947be90405..54df181990074 100644 --- a/templates/cassiopeia/index.php +++ b/templates/cassiopeia/index.php @@ -32,7 +32,7 @@ $layout = $input->getCmd('layout', ''); $task = $input->getCmd('task', ''); $itemid = $input->getCmd('Itemid', ''); -$sitename = htmlspecialchars($app->get('sitename'), ENT_QUOTES, 'UTF-8'); +$sitename = htmlspecialchars((string) $app->get('sitename'), ENT_QUOTES, 'UTF-8'); $menu = $app->getMenu()->getActive(); $pageclass = $menu !== null ? $menu->getParams()->get('pageclass_sfx', '') : ''; @@ -45,13 +45,13 @@ $fontStyles = ''; if ($paramsFontScheme) { - if (stripos($paramsFontScheme, 'https://') === 0) { + if (stripos((string) $paramsFontScheme, 'https://') === 0) { $this->getPreloadManager()->preconnect('https://fonts.googleapis.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preconnect('https://fonts.gstatic.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preload($paramsFontScheme, ['as' => 'style', 'crossorigin' => 'anonymous']); $wa->registerAndUseStyle('fontscheme.current', $paramsFontScheme, [], ['rel' => 'lazy-stylesheet', 'crossorigin' => 'anonymous']); - if (preg_match_all('/family=([^?:]*):/i', $paramsFontScheme, $matches) > 0) { + if (preg_match_all('/family=([^?:]*):/i', (string) $paramsFontScheme, $matches) > 0) { $fontStyles = '--cassiopeia-font-family-body: "' . str_replace('+', ' ', $matches[1][0]) . '", sans-serif; --cassiopeia-font-family-headings: "' . str_replace('+', ' ', $matches[1][1] ?? $matches[1][0]) . '", sans-serif; --cassiopeia-font-weight-normal: 400; @@ -96,9 +96,9 @@ // Logo file or site title param if ($this->params->get('logoFile')) { - $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars($this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); + $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars((string) $this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); } elseif ($this->params->get('siteTitle')) { - $logo = '' . htmlspecialchars($this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; + $logo = '' . htmlspecialchars((string) $this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; } else { $logo = HTMLHelper::_('image', 'logo.svg', $sitename, ['class' => 'logo d-inline-block', 'loading' => 'eager', 'decoding' => 'async'], true, 0); } @@ -163,7 +163,7 @@ params->get('siteDescription')) : ?> -
    params->get('siteDescription')); ?>
    +
    params->get('siteDescription')); ?>
    diff --git a/templates/cassiopeia/offline.php b/templates/cassiopeia/offline.php index fb0252ae21884..9c93d2d4f07c3 100644 --- a/templates/cassiopeia/offline.php +++ b/templates/cassiopeia/offline.php @@ -35,13 +35,13 @@ $fontStyles = ''; if ($paramsFontScheme) { - if (stripos($paramsFontScheme, 'https://') === 0) { + if (stripos((string) $paramsFontScheme, 'https://') === 0) { $this->getPreloadManager()->preconnect('https://fonts.googleapis.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preconnect('https://fonts.gstatic.com/', ['crossorigin' => 'anonymous']); $this->getPreloadManager()->preload($paramsFontScheme, ['as' => 'style', 'crossorigin' => 'anonymous']); $wa->registerAndUseStyle('fontscheme.current', $paramsFontScheme, [], ['rel' => 'lazy-stylesheet', 'crossorigin' => 'anonymous']); - if (preg_match_all('/family=([^?:]*):/i', $paramsFontScheme, $matches) > 0) { + if (preg_match_all('/family=([^?:]*):/i', (string) $paramsFontScheme, $matches) > 0) { $fontStyles = '--cassiopeia-font-family-body: "' . str_replace('+', ' ', $matches[1][0]) . '", sans-serif; --cassiopeia-font-family-headings: "' . str_replace('+', ' ', $matches[1][1] ?? $matches[1][0]) . '", sans-serif; --cassiopeia-font-weight-normal: 400; @@ -73,7 +73,7 @@ $wa->registerStyle('template.active', '', [], [], ['template.cassiopeia.' . ($this->direction === 'rtl' ? 'rtl' : 'ltr')]); // Logo file or site title param -$sitename = htmlspecialchars($app->get('sitename'), ENT_QUOTES, 'UTF-8'); +$sitename = htmlspecialchars((string) $app->get('sitename'), ENT_QUOTES, 'UTF-8'); // Browsers support SVG favicons $this->addHeadLink(HTMLHelper::_('image', 'joomla-favicon.svg', '', [], true, 1), 'icon', 'rel', ['type' => 'image/svg+xml']); @@ -81,9 +81,9 @@ $this->addHeadLink(HTMLHelper::_('image', 'joomla-favicon-pinned.svg', '', [], true, 1), 'mask-icon', 'rel', ['color' => '#000']); if ($this->params->get('logoFile')) { - $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars($this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); + $logo = HTMLHelper::_('image', Uri::root(false) . htmlspecialchars((string) $this->params->get('logoFile'), ENT_QUOTES), $sitename, ['loading' => 'eager', 'decoding' => 'async'], false, 0); } elseif ($this->params->get('siteTitle')) { - $logo = '' . htmlspecialchars($this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; + $logo = '' . htmlspecialchars((string) $this->params->get('siteTitle'), ENT_COMPAT, 'UTF-8') . ''; } else { $logo = HTMLHelper::_('image', 'logo.svg', $sitename, ['class' => 'logo d-inline-block', 'loading' => 'eager', 'decoding' => 'async'], true, 0); } @@ -139,9 +139,7 @@ str_starts_with((string) $key, 'data-')); ?>
  • '; $html[] = ' - + @@ -140,7 +140,7 @@ - + - + 0) : ?> $item) : ?> - + 0) : ?> $item) : ?> - + 0) : ?> $item) : ?> hits; ?> diff --git a/administrator/modules/mod_privacy_dashboard/tmpl/default.php b/administrator/modules/mod_privacy_dashboard/tmpl/default.php index 82a0922812dd8..332ee9b8ed1bc 100644 --- a/administrator/modules/mod_privacy_dashboard/tmpl/default.php +++ b/administrator/modules/mod_privacy_dashboard/tmpl/default.php @@ -28,7 +28,7 @@ - + 0) : ?> $item) : ?> status, [0, 1])) : ?> count; ?> @@ -57,7 +57,7 @@
    diff --git a/layouts/joomla/content/category_default.php b/layouts/joomla/content/category_default.php index 8b7fc1f7dfb57..ccbeb27bb6cb5 100644 --- a/layouts/joomla/content/category_default.php +++ b/layouts/joomla/content/category_default.php @@ -45,7 +45,7 @@ * This will work for the core components but not necessarily for other components * that may have different pluralisation rules. */ -if (substr($className, -1) === 's') { +if (str_ends_with($className, 's')) { $className = rtrim($className, 's'); } diff --git a/layouts/joomla/content/emptystate.php b/layouts/joomla/content/emptystate.php index 2abe33d2ab641..b90aaebf76be9 100644 --- a/layouts/joomla/content/emptystate.php +++ b/layouts/joomla/content/emptystate.php @@ -18,7 +18,7 @@ $textPrefix = $displayData['textPrefix'] ?? ''; if (!$textPrefix) { - $textPrefix = strtoupper(Factory::getApplication()->getInput()->get('option')); + $textPrefix = strtoupper((string) Factory::getApplication()->getInput()->get('option')); } $formURL = $displayData['formURL'] ?? ''; diff --git a/layouts/joomla/edit/frontediting_modules.php b/layouts/joomla/edit/frontediting_modules.php index f45d8e09e206b..6462604d6f8b0 100644 --- a/layouts/joomla/edit/frontediting_modules.php +++ b/layouts/joomla/edit/frontediting_modules.php @@ -41,8 +41,8 @@ // Create and add the edit link and tooltip '\\1 ' . Text::_('JGLOBAL_EDIT') . ' - ', - $moduleHtml, + ', + (string) $moduleHtml, 1, $count ); @@ -52,7 +52,7 @@ // find the menu item id $regex = '/\bitem-(\d+)\b/'; - preg_match_all($regex, $moduleHtml, $menuItemids); + preg_match_all($regex, (string) $moduleHtml, $menuItemids); if ($menuItemids) { foreach ($menuItemids[1] as $menuItemid) { $menuitemEditUrl = Uri::base() . 'administrator/index.php?option=com_menus&view=item&client_id=0&layout=edit&id=' . (int) $menuItemid; @@ -62,7 +62,7 @@ // Create and add the edit link '\\1 ', - $moduleHtml + (string) $moduleHtml ); } } diff --git a/layouts/joomla/edit/params.php b/layouts/joomla/edit/params.php index c61e6a5c0b944..d2f222c71eab1 100644 --- a/layouts/joomla/edit/params.php +++ b/layouts/joomla/edit/params.php @@ -62,7 +62,7 @@ } // Check if it is the correct fieldset to ignore - if (strpos($name, 'basic') === 0) { + if (str_starts_with((string) $name, 'basic')) { // Ignore only the fieldsets which are defined by the options not the custom fields ones $ignoreFieldsets[] = $name; } diff --git a/layouts/joomla/editors/buttons/button.php b/layouts/joomla/editors/buttons/button.php index d68472ebd45b5..409adbc9baeb2 100644 --- a/layouts/joomla/editors/buttons/button.php +++ b/layouts/joomla/editors/buttons/button.php @@ -31,19 +31,19 @@ $class = 'btn btn-secondary'; $class .= $button->get('class') ? ' ' . $button->get('class') : null; $class .= $button->get('modal') ? ' modal-button' : null; -$href = '#' . $button->get('editor') . '_' . strtolower($button->get('name', '')) . '_modal'; +$href = '#' . $button->get('editor') . '_' . strtolower((string) $button->get('name', '')) . '_modal'; $link = $button->get('link'); $onclick = $button->get('onclick') ? ' onclick="' . $button->get('onclick') . '"' : ''; -$title = $button->get('title') ? $button->get('title') : $button->get('text', ''); +$title = $button->get('title') ?: $button->get('text', ''); $icon = $button->get('icon'); $action = $button->get('action', ''); $options = (array) $button->get('options'); // Correct the link, check for legacy with & in it, and prepend a base Uri if ($link && $link[0] !== '#') { - $link = str_contains($link, '&') ? htmlspecialchars_decode($link) : $link; + $link = str_contains((string) $link, '&') ? htmlspecialchars_decode((string) $link) : $link; $link = Uri::base(true) . '/' . $link; - $options['src'] = $options['src'] ?? $link; + $options['src'] ??= $link; } // Detect a legacy BS modal, and set action to "modal" for legacy buttons, when possible @@ -54,9 +54,9 @@ $wa->useScript('joomla.dialog'); $legacyModal = false; - $options['popupType'] = $options['popupType'] ?? 'iframe'; - $options['textHeader'] = $options['textHeader'] ?? $title; - $options['iconHeader'] = $options['iconHeader'] ?? 'icon-' . $icon; + $options['popupType'] ??= 'iframe'; + $options['textHeader'] ??= $title; + $options['iconHeader'] ??= 'icon-' . $icon; } $optStr = $options && $action ? json_encode($options, JSON_UNESCAPED_SLASHES) : ''; diff --git a/layouts/joomla/editors/buttons/modal.php b/layouts/joomla/editors/buttons/modal.php index 36e1e0e0c1ba4..7bcba6e0d84ac 100644 --- a/layouts/joomla/editors/buttons/modal.php +++ b/layouts/joomla/editors/buttons/modal.php @@ -21,12 +21,12 @@ return; } -$class = ($button->get('class')) ? $button->get('class') : null; +$class = $button->get('class') ?: null; $class .= ($button->get('modal')) ? ' modal-button' : null; -$href = '#' . $button->get('editor') . '_' . strtolower($button->get('name')) . '_modal'; +$href = '#' . $button->get('editor') . '_' . strtolower((string) $button->get('name')) . '_modal'; $link = ($button->get('link')) ? Uri::base() . $button->get('link') : null; $onclick = ($button->get('onclick')) ? ' onclick="' . $button->get('onclick') . '"' : ''; -$title = ($button->get('title')) ? $button->get('title') : $button->get('text'); +$title = $button->get('title') ?: $button->get('text'); $options = $button->getOptions(); $confirm = ''; @@ -39,7 +39,7 @@ if (null !== $button->get('id')) { $id = str_replace(' ', '', $button->get('id')); } else { - $id = $button->get('editor') . '_' . strtolower($button->get('name')) . '_modal'; + $id = $button->get('editor') . '_' . strtolower((string) $button->get('name')) . '_modal'; } // @todo: J4: Move Make buttons fullscreen on smaller devices per https://github.com/joomla/joomla-cms/pull/23091 diff --git a/layouts/joomla/form/field/color/simple.php b/layouts/joomla/form/field/color/simple.php index 2ed3e632ead10..8f056b5c5ac04 100644 --- a/layouts/joomla/form/field/color/simple.php +++ b/layouts/joomla/form/field/color/simple.php @@ -52,7 +52,7 @@ * @var array $dataAttributes Miscellaneous data attribute for eg, data-*. */ -$class = ' class="form-select ' . trim($class) . '"'; +$class = ' class="form-select ' . trim((string) $class) . '"'; $disabled = $disabled ? ' disabled' : ''; $readonly = $readonly ? ' readonly' : ''; diff --git a/layouts/joomla/form/field/groupedlist-fancy-select.php b/layouts/joomla/form/field/groupedlist-fancy-select.php index 35df462ab80c9..7a37adf2f3896 100644 --- a/layouts/joomla/form/field/groupedlist-fancy-select.php +++ b/layouts/joomla/form/field/groupedlist-fancy-select.php @@ -119,4 +119,4 @@ ?> -> +> diff --git a/layouts/joomla/form/field/groupedlist.php b/layouts/joomla/form/field/groupedlist.php index a70e00cfbe3f7..911da960e62a9 100644 --- a/layouts/joomla/form/field/groupedlist.php +++ b/layouts/joomla/form/field/groupedlist.php @@ -101,4 +101,4 @@ ); } -echo implode($html); +echo implode('', $html); diff --git a/layouts/joomla/form/field/list-fancy-select.php b/layouts/joomla/form/field/list-fancy-select.php index f117d34a9a96b..5370aa0acbd20 100644 --- a/layouts/joomla/form/field/list-fancy-select.php +++ b/layouts/joomla/form/field/list-fancy-select.php @@ -101,4 +101,4 @@ ?> -> +> diff --git a/layouts/joomla/form/field/list.php b/layouts/joomla/form/field/list.php index 224107485943b..d57425e142d79 100644 --- a/layouts/joomla/form/field/list.php +++ b/layouts/joomla/form/field/list.php @@ -92,4 +92,4 @@ $html[] = HTMLHelper::_('select.genericlist', $options, $name, $listoptions); } -echo implode($html); +echo implode('', $html); diff --git a/layouts/joomla/form/field/media.php b/layouts/joomla/form/field/media.php index 03e1978b52cb9..e2a2c082cb930 100644 --- a/layouts/joomla/form/field/media.php +++ b/layouts/joomla/form/field/media.php @@ -60,20 +60,10 @@ // Initialize JavaScript field attributes. $attr .= !empty($onchange) ? ' onchange="' . $onchange . '"' : ''; -switch ($preview) { - case 'no': // Deprecated parameter value - case 'false': - case 'none': - $showPreview = false; - break; - case 'yes': // Deprecated parameter value - case 'true': - case 'show': - case 'tooltip': - default: - $showPreview = true; - break; -} +$showPreview = match ($preview) { + 'no', 'false', 'none' => false, + default => true, +}; // Prefill the contents of the popover if ($showPreview) { diff --git a/layouts/joomla/form/field/number.php b/layouts/joomla/form/field/number.php index 5ac03b8f4c530..d2c4ce80848eb 100644 --- a/layouts/joomla/form/field/number.php +++ b/layouts/joomla/form/field/number.php @@ -74,5 +74,5 @@ inputmode="numeric" name="" id="" - value="" + value="" > diff --git a/layouts/joomla/form/field/radio/buttons.php b/layouts/joomla/form/field/radio/buttons.php index 31109f41469d3..a0e1e3b48ea57 100644 --- a/layouts/joomla/form/field/radio/buttons.php +++ b/layouts/joomla/form/field/radio/buttons.php @@ -44,8 +44,8 @@ */ $alt = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $name); -$isBtnGroup = strpos(trim($class), 'btn-group') !== false; -$isBtnYesNo = strpos(trim($class), 'btn-group-yesno') !== false; +$isBtnGroup = str_contains(trim($class), 'btn-group'); +$isBtnYesNo = str_contains(trim($class), 'btn-group-yesno'); $classToggle = $isBtnGroup ? 'btn-check' : 'form-check-input'; $btnClass = $isBtnGroup ? 'btn btn-outline-secondary' : 'form-check-label'; $blockStart = $isBtnGroup ? '' : '
    '; @@ -90,17 +90,11 @@ // Initialize some option attributes. if ($isBtnYesNo) { // Set the button classes for the yes/no group - switch ($option->value) { - case '0': - $btnClass = 'btn btn-outline-danger'; - break; - case '1': - $btnClass = 'btn btn-outline-success'; - break; - default: - $btnClass = 'btn btn-outline-secondary'; - break; - } + $btnClass = match ($option->value) { + '0' => 'btn btn-outline-danger', + '1' => 'btn btn-outline-success', + default => 'btn btn-outline-secondary', + }; } $optionClass = !empty($option->class) ? $option->class : $btnClass; diff --git a/layouts/joomla/form/field/range.php b/layouts/joomla/form/field/range.php index 4d1c3833ce27b..838ffdd7d43d3 100644 --- a/layouts/joomla/form/field/range.php +++ b/layouts/joomla/form/field/range.php @@ -68,5 +68,5 @@ type="range" name="" id="" - value="" + value="" > diff --git a/layouts/joomla/form/field/subform/repeatable-table.php b/layouts/joomla/form/field/subform/repeatable-table.php index 04ed15b53064e..effb9a97c21b9 100644 --- a/layouts/joomla/form/field/subform/repeatable-table.php +++ b/layouts/joomla/form/field/subform/repeatable-table.php @@ -116,7 +116,7 @@
    diff --git a/layouts/joomla/form/field/subform/repeatable.php b/layouts/joomla/form/field/subform/repeatable.php index 97a8bfb2ea858..3ca33d9663992 100644 --- a/layouts/joomla/form/field/subform/repeatable.php +++ b/layouts/joomla/form/field/subform/repeatable.php @@ -67,7 +67,7 @@ ?> diff --git a/layouts/joomla/form/field/tag.php b/layouts/joomla/form/field/tag.php index ea6c458af2c64..781b874fd9cb9 100644 --- a/layouts/joomla/form/field/tag.php +++ b/layouts/joomla/form/field/tag.php @@ -120,4 +120,4 @@ ?> -> +> diff --git a/layouts/joomla/icon/iconclass.php b/layouts/joomla/icon/iconclass.php index ca2c8c6f6e709..4b797888806fd 100644 --- a/layouts/joomla/icon/iconclass.php +++ b/layouts/joomla/icon/iconclass.php @@ -36,7 +36,7 @@ $icon = str_replace('icon-icon-', 'icon-', $icon); switch ($icon) { - case (strpos($icon, 'icon-') !== false): + case (str_contains($icon, 'icon-')): $iconPrefix = $displayData['prefix'] ?? null; break; diff --git a/layouts/joomla/mail/mailtemplate.php b/layouts/joomla/mail/mailtemplate.php index 209b0ad26f570..b072765f0dcc5 100644 --- a/layouts/joomla/mail/mailtemplate.php +++ b/layouts/joomla/mail/mailtemplate.php @@ -34,7 +34,7 @@ ?> - + @@ -77,7 +77,7 @@
    - <?php echo (isset($extraData['siteName']) ? $extraData['siteName'] . ' ' : '');?>Logo + <?php echo (isset($extraData['siteName']) ? $extraData['siteName'] . ' ' : '');?>Logo

    diff --git a/layouts/joomla/toolbar/basic.php b/layouts/joomla/toolbar/basic.php index 445831a99698e..313c5b6125890 100644 --- a/layouts/joomla/toolbar/basic.php +++ b/layouts/joomla/toolbar/basic.php @@ -39,7 +39,7 @@ ->useScript('core') ->useScript('webcomponent.toolbar-button'); -$tagName = $tagName ?? 'button'; +$tagName ??= 'button'; $taskAttr = ''; $title = ''; diff --git a/layouts/joomla/toolbar/link.php b/layouts/joomla/toolbar/link.php index 6ee810135850b..06c8ae63aa6dc 100644 --- a/layouts/joomla/toolbar/link.php +++ b/layouts/joomla/toolbar/link.php @@ -24,7 +24,7 @@ * @var string $htmlAttributes */ -$margin = (strpos($url ?? '', 'index.php?option=com_config') === false) ? '' : 'ms-auto'; +$margin = (!str_contains($url ?? '', 'index.php?option=com_config')) ? '' : 'ms-auto'; $target = empty($target) ? '' : 'target="' . $target . '"'; ?> diff --git a/layouts/joomla/toolbar/popup.php b/layouts/joomla/toolbar/popup.php index 9b87d767879de..c8dd0f4dd60c2 100644 --- a/layouts/joomla/toolbar/popup.php +++ b/layouts/joomla/toolbar/popup.php @@ -40,7 +40,7 @@ ->useScript('joomla.dialog-autocreate') ->useScript('webcomponent.toolbar-button'); -$tagName = $tagName ?? 'button'; +$tagName ??= 'button'; $modalAttrs = []; // Check for use of Joomla Dialog, otherwise fallback to BS Modal diff --git a/layouts/joomla/toolbar/standard.php b/layouts/joomla/toolbar/standard.php index 3df11db4e8b91..6e7b61360fd7e 100644 --- a/layouts/joomla/toolbar/standard.php +++ b/layouts/joomla/toolbar/standard.php @@ -36,7 +36,7 @@ ->useScript('core') ->useScript('webcomponent.toolbar-button'); -$tagName = $tagName ?? 'button'; +$tagName ??= 'button'; $taskAttr = ''; $idAttr = !empty($id) ? ' id="' . $id . '"' : ''; diff --git a/layouts/joomla/toolbar/title.php b/layouts/joomla/toolbar/title.php index 2f2fb21c0df33..4f1ad6729d2e8 100644 --- a/layouts/joomla/toolbar/title.php +++ b/layouts/joomla/toolbar/title.php @@ -13,7 +13,7 @@ use Joomla\CMS\Layout\LayoutHelper; // Strip extension if given -$icon = empty($displayData['icon']) ? 'dot-circle' : preg_replace('#\.[^ .]*$#', '', $displayData['icon']); +$icon = empty($displayData['icon']) ? 'dot-circle' : preg_replace('#\.[^ .]*$#', '', (string) $displayData['icon']); ?>

    $icon]); ?> diff --git a/layouts/libraries/html/bootstrap/modal/iframe.php b/layouts/libraries/html/bootstrap/modal/iframe.php index d207d7330ee8c..551b028fc5811 100644 --- a/layouts/libraries/html/bootstrap/modal/iframe.php +++ b/layouts/libraries/html/bootstrap/modal/iframe.php @@ -38,8 +38,8 @@ ]; if (isset($params['title'])) { - $iframeAttributes['name'] = addslashes($params['title']); - $iframeAttributes['title'] = addslashes($params['title']); + $iframeAttributes['name'] = addslashes((string) $params['title']); + $iframeAttributes['title'] = addslashes((string) $params['title']); } if (isset($params['height'])) { diff --git a/layouts/libraries/html/bootstrap/modal/main.php b/layouts/libraries/html/bootstrap/modal/main.php index 6ce9aece875fc..ed9170ffabee2 100644 --- a/layouts/libraries/html/bootstrap/modal/main.php +++ b/layouts/libraries/html/bootstrap/modal/main.php @@ -71,7 +71,7 @@ $iframeHtml = htmlspecialchars(LayoutHelper::render('libraries.html.bootstrap.modal.iframe', $displayData), ENT_COMPAT, 'UTF-8'); } ?> -

    diff --git a/administrator/components/com_checkin/src/Controller/DisplayController.php b/administrator/components/com_checkin/src/Controller/DisplayController.php index e267dc566e68c..6248656f6e00d 100644 --- a/administrator/components/com_checkin/src/Controller/DisplayController.php +++ b/administrator/components/com_checkin/src/Controller/DisplayController.php @@ -59,7 +59,7 @@ public function checkin() $ids = (array) $this->input->get('cid', [], 'string'); - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('JLIB_HTML_PLEASE_MAKE_A_SELECTION_FROM_THE_LIST'), 'warning'); } else { // Get the model. diff --git a/administrator/components/com_checkin/src/Model/CheckinModel.php b/administrator/components/com_checkin/src/Model/CheckinModel.php index 103763f200938..46482c20f46ec 100644 --- a/administrator/components/com_checkin/src/Model/CheckinModel.php +++ b/administrator/components/com_checkin/src/Model/CheckinModel.php @@ -147,7 +147,7 @@ public function checkin($ids = []) */ public function getTotal() { - if (!isset($this->total)) { + if ($this->total === null) { $this->getItems(); } @@ -163,7 +163,7 @@ public function getTotal() */ public function getItems() { - if (!isset($this->items)) { + if (!property_exists($this, 'items') || $this->items === null) { $db = $this->getDatabase(); $tables = $db->getTableList(); $prefix = Factory::getApplication()->get('dbprefix'); @@ -209,28 +209,22 @@ public function getItems() // Order items by table if ($this->getState('list.ordering') == 'table') { - if (strtolower((string) $this->getState('list.direction')) == 'asc') { + if (strtolower((string) $this->getState('list.direction')) === 'asc') { ksort($results); } else { krsort($results); } - } else { + } elseif (strtolower((string) $this->getState('list.direction')) === 'asc') { // Order items by number of items - if (strtolower((string) $this->getState('list.direction')) == 'asc') { - asort($results); - } else { - arsort($results); - } + asort($results); + } else { + arsort($results); } // Pagination $limit = (int) $this->getState('list.limit'); - if ($limit !== 0) { - $this->items = \array_slice($results, $this->getState('list.start'), $limit); - } else { - $this->items = $results; - } + $this->items = $limit !== 0 ? \array_slice($results, $this->getState('list.start'), $limit) : $results; } return $this->items; diff --git a/administrator/components/com_config/src/Controller/ApplicationController.php b/administrator/components/com_config/src/Controller/ApplicationController.php index a36f9c8b4004d..e0d4188706259 100644 --- a/administrator/components/com_config/src/Controller/ApplicationController.php +++ b/administrator/components/com_config/src/Controller/ApplicationController.php @@ -66,7 +66,7 @@ public function cancel() /** * Saves the form * - * @return void|boolean Void on success. Boolean false on fail. + * @return bool|null Void on success. Boolean false on fail. * * @since 4.0.0 */ @@ -185,6 +185,7 @@ public function save() 'apply' => $this->setRedirect(Route::_('index.php?option=com_config', false)), default => $this->setRedirect(Route::_('index.php', false)), }; + return null; } /** diff --git a/administrator/components/com_config/src/Field/ConfigComponentsField.php b/administrator/components/com_config/src/Field/ConfigComponentsField.php index 7ec5fb115417f..933304200a838 100644 --- a/administrator/components/com_config/src/Field/ConfigComponentsField.php +++ b/administrator/components/com_config/src/Field/ConfigComponentsField.php @@ -61,8 +61,9 @@ protected function getOptions() if (is_file(JPATH_ADMINISTRATOR . '/components/' . $extension . '/config.xml')) { $source = JPATH_ADMINISTRATOR . '/components/' . $extension; - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) - || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", $source); + } // Translate component name $item->text = Text::_($item->text); diff --git a/administrator/components/com_config/src/Field/FiltersField.php b/administrator/components/com_config/src/Field/FiltersField.php index 8ae3c46699c11..c4b42842e169b 100644 --- a/administrator/components/com_config/src/Field/FiltersField.php +++ b/administrator/components/com_config/src/Field/FiltersField.php @@ -89,8 +89,8 @@ protected function getInput() $group_filter = $this->value[$group->value]; - $group_filter['filter_tags'] = !empty($group_filter['filter_tags']) ? $group_filter['filter_tags'] : ''; - $group_filter['filter_attributes'] = !empty($group_filter['filter_attributes']) ? $group_filter['filter_attributes'] : ''; + $group_filter['filter_tags'] = empty($group_filter['filter_tags']) ? '' : $group_filter['filter_tags']; + $group_filter['filter_attributes'] = empty($group_filter['filter_attributes']) ? '' : $group_filter['filter_attributes']; $html[] = '
    '; diff --git a/administrator/components/com_config/src/Helper/ConfigHelper.php b/administrator/components/com_config/src/Helper/ConfigHelper.php index 115d384402162..5f4c45ea3d1f9 100644 --- a/administrator/components/com_config/src/Helper/ConfigHelper.php +++ b/administrator/components/com_config/src/Helper/ConfigHelper.php @@ -146,7 +146,8 @@ public static function loadLanguageForComponent($component) // Load the core file then // Load extension-local file. - $lang->load($component . '.sys', JPATH_BASE) - || $lang->load($component . '.sys', JPATH_ADMINISTRATOR . '/components/' . $component); + if (!$lang->load($component . '.sys', JPATH_BASE)) { + $lang->load($component . '.sys', JPATH_ADMINISTRATOR . '/components/' . $component); + } } } diff --git a/administrator/components/com_config/src/Model/ApplicationModel.php b/administrator/components/com_config/src/Model/ApplicationModel.php index 9ab5eea418202..da8ed271681bd 100644 --- a/administrator/components/com_config/src/Model/ApplicationModel.php +++ b/administrator/components/com_config/src/Model/ApplicationModel.php @@ -154,7 +154,7 @@ public function validateDbConnection($data) $data['dbsslcert'] = ''; } - if ((bool) $data['dbsslverifyservercert'] === true) { + if ((bool) $data['dbsslverifyservercert']) { $data['dbsslverifyservercert'] = false; } @@ -174,7 +174,7 @@ public function validateDbConnection($data) } // Check CA file and folder depending on database type if server certificate verification - if ((bool) $data['dbsslverifyservercert'] === true) { + if ((bool) $data['dbsslverifyservercert']) { if (empty($data['dbsslca'])) { Factory::getApplication()->enqueueMessage( Text::sprintf( @@ -186,7 +186,6 @@ public function validateDbConnection($data) return false; } - if (!is_file(Path::clean($data['dbsslca']))) { Factory::getApplication()->enqueueMessage( Text::sprintf( @@ -198,11 +197,9 @@ public function validateDbConnection($data) return false; } - } else { + } elseif (!empty($data['dbsslca'])) { // Reset unused option - if (!empty($data['dbsslca'])) { - $data['dbsslca'] = ''; - } + $data['dbsslca'] = ''; } // Check key and certificate if two-way encryption @@ -495,29 +492,26 @@ public function save($data) $data['session_filesystem_path'] = Path::clean($data['session_filesystem_path']); - if ($currentPath !== $data['session_filesystem_path']) { - if (!is_dir(Path::clean($data['session_filesystem_path'])) && !Folder::create($data['session_filesystem_path'])) { - try { - Log::add( - Text::sprintf( - 'COM_CONFIG_ERROR_CUSTOM_SESSION_FILESYSTEM_PATH_NOTWRITABLE_USING_DEFAULT', - $data['session_filesystem_path'] - ), - Log::WARNING, - 'jerror' - ); - } catch (\RuntimeException) { - $app->enqueueMessage( - Text::sprintf( - 'COM_CONFIG_ERROR_CUSTOM_SESSION_FILESYSTEM_PATH_NOTWRITABLE_USING_DEFAULT', - $data['session_filesystem_path'] - ), - 'warning' - ); - } - - $data['session_filesystem_path'] = $currentPath; + if ($currentPath !== $data['session_filesystem_path'] && (!is_dir(Path::clean($data['session_filesystem_path'])) && !Folder::create($data['session_filesystem_path']))) { + try { + Log::add( + Text::sprintf( + 'COM_CONFIG_ERROR_CUSTOM_SESSION_FILESYSTEM_PATH_NOTWRITABLE_USING_DEFAULT', + $data['session_filesystem_path'] + ), + Log::WARNING, + 'jerror' + ); + } catch (\RuntimeException) { + $app->enqueueMessage( + Text::sprintf( + 'COM_CONFIG_ERROR_CUSTOM_SESSION_FILESYSTEM_PATH_NOTWRITABLE_USING_DEFAULT', + $data['session_filesystem_path'] + ), + 'warning' + ); } + $data['session_filesystem_path'] = $currentPath; } } @@ -1099,13 +1093,13 @@ public function storePermissions($permission = null) // Get the group, group parent id, and group global config recursive calculated permission for the chosen action. $inheritedGroupRule = Access::checkGroup($permission['rule'], $permission['action'], $assetId); - if (!empty($parentAssetId)) { + if ($parentAssetId !== null && $parentAssetId !== 0) { $inheritedGroupParentAssetRule = Access::checkGroup($permission['rule'], $permission['action'], $parentAssetId); } else { $inheritedGroupParentAssetRule = null; } - $inheritedParentGroupRule = !empty($parentGroupId) ? Access::checkGroup($parentGroupId, $permission['action'], $assetId) : null; + $inheritedParentGroupRule = $parentGroupId === 0 ? null : Access::checkGroup($parentGroupId, $permission['action'], $assetId); // Current group is a Super User group, so calculated setting is "Allowed (Super User)". if ($isSuperUserGroupAfter) { @@ -1146,7 +1140,7 @@ public function storePermissions($permission = null) // Third part: Overwrite the calculated permissions labels for special cases. // Global configuration with "Not Set" permission. Calculated permission is "Not Allowed (Default)". - if (empty($parentGroupId) && $isGlobalConfig === true && $assetRule === null) { + if ($parentGroupId === 0 && $isGlobalConfig && $assetRule === null) { $result['class'] = 'badge bg-danger'; $result['text'] = Text::_('JLIB_RULES_NOT_ALLOWED_DEFAULT'); } elseif ($inheritedGroupParentAssetRule === false || $inheritedParentGroupRule === false) { diff --git a/administrator/components/com_config/src/Model/ComponentModel.php b/administrator/components/com_config/src/Model/ComponentModel.php index 17554c5791631..64469feacbe25 100644 --- a/administrator/components/com_config/src/Model/ComponentModel.php +++ b/administrator/components/com_config/src/Model/ComponentModel.php @@ -95,8 +95,9 @@ public function getForm($data = [], $loadData = true) } $lang = Factory::getLanguage(); - $lang->load($option, JPATH_BASE) - || $lang->load($option, JPATH_BASE . "/components/$option"); + if (!$lang->load($option, JPATH_BASE)) { + $lang->load($option, JPATH_BASE . "/components/$option"); + } return $form; } @@ -136,8 +137,9 @@ public function getComponent() // Load common and local language files. $lang = Factory::getLanguage(); - $lang->load($option, JPATH_BASE) - || $lang->load($option, JPATH_BASE . "/components/$option"); + if (!$lang->load($option, JPATH_BASE)) { + $lang->load($option, JPATH_BASE . "/components/$option"); + } $result = ComponentHelper::getComponent($option); diff --git a/administrator/components/com_config/src/View/Application/HtmlView.php b/administrator/components/com_config/src/View/Application/HtmlView.php index 6ec11ecb289a1..889a90146019f 100644 --- a/administrator/components/com_config/src/View/Application/HtmlView.php +++ b/administrator/components/com_config/src/View/Application/HtmlView.php @@ -29,6 +29,23 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var \Joomla\CMS\User\User + */ + public $user; + /** + * @var \Joomla\Registry\Registry + */ + public $usersParams; + /** + * @var \Joomla\Registry\Registry + */ + public $mediaParams; + public $components; + /** + * @var bool + */ + public $userIsSuperAdmin; /** * The model state * diff --git a/administrator/components/com_config/src/View/Component/HtmlView.php b/administrator/components/com_config/src/View/Component/HtmlView.php index 486824d9f564d..e39c884e2c307 100644 --- a/administrator/components/com_config/src/View/Component/HtmlView.php +++ b/administrator/components/com_config/src/View/Component/HtmlView.php @@ -28,6 +28,15 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var mixed[] + */ + public $components; + /** + * @var bool + */ + public $userIsSuperAdmin; + public $currentComponent; /** * The model state * @@ -158,9 +167,9 @@ protected function addToolbar() $helpKey = (string) $this->form->getXml()->config->help['key']; // Try with legacy language key - if (!$helpKey) { + if ($helpKey === '' || $helpKey === '0') { $language = Factory::getApplication()->getLanguage(); - $languageKey = 'JHELP_COMPONENTS_' . strtoupper($this->currentComponent) . '_OPTIONS'; + $languageKey = 'JHELP_COMPONENTS_' . strtoupper((string) $this->currentComponent) . '_OPTIONS'; if ($language->hasKey($languageKey)) { $helpKey = $languageKey; diff --git a/administrator/components/com_config/tmpl/component/default.php b/administrator/components/com_config/tmpl/component/default.php index 0ffc394ad285b..096f0a2df447b 100644 --- a/administrator/components/com_config/tmpl/component/default.php +++ b/administrator/components/com_config/tmpl/component/default.php @@ -78,7 +78,7 @@ label); ?>
    - + 1) : ?>
    @@ -117,7 +117,7 @@ - + 1) : ?> diff --git a/administrator/components/com_contact/src/Controller/ContactController.php b/administrator/components/com_contact/src/Controller/ContactController.php index 4e77dec9217b0..c05ca84d6d797 100644 --- a/administrator/components/com_contact/src/Controller/ContactController.php +++ b/administrator/components/com_contact/src/Controller/ContactController.php @@ -63,7 +63,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; // Since there is no asset tracking, fallback to the component permissions. if (!$recordId) { diff --git a/administrator/components/com_contact/src/Controller/ContactsController.php b/administrator/components/com_contact/src/Controller/ContactsController.php index 3c44571dfb671..d99eb669ffddc 100644 --- a/administrator/components/com_contact/src/Controller/ContactsController.php +++ b/administrator/components/com_contact/src/Controller/ContactsController.php @@ -87,7 +87,7 @@ public function featured() } } - if (empty($ids)) { + if ($ids === []) { $message = null; $this->app->enqueueMessage(Text::_('COM_CONTACT_NO_ITEM_SELECTED'), 'warning'); diff --git a/administrator/components/com_contact/src/Field/Modal/ContactField.php b/administrator/components/com_contact/src/Field/Modal/ContactField.php index c7d7658bf3cd4..db718c08d4653 100644 --- a/administrator/components/com_contact/src/Field/Modal/ContactField.php +++ b/administrator/components/com_contact/src/Field/Modal/ContactField.php @@ -70,7 +70,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $language = (string) $this->element['language']; // Prepare enabled actions - $this->canDo['propagate'] = ((string) $this->element['propagate'] == 'true') && \count($languages) > 2; + $this->canDo['propagate'] = ((string) $this->element['propagate'] === 'true') && \count($languages) > 2; // Prepare Urls $linkItems = (new Uri())->setPath(Uri::base(true) . '/index.php'); @@ -91,7 +91,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) Session::getFormToken() => 1, ]); - if ($language) { + if ($language !== '' && $language !== '0') { $linkItems->setVar('forcedLanguage', $language); $linkItem->setVar('forcedLanguage', $language); diff --git a/administrator/components/com_contact/src/Model/ContactModel.php b/administrator/components/com_contact/src/Model/ContactModel.php index b5ebac640c48d..27e23816b8c4e 100644 --- a/administrator/components/com_contact/src/Model/ContactModel.php +++ b/administrator/components/com_contact/src/Model/ContactModel.php @@ -323,10 +323,8 @@ public function save($data) [$name, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']); $data['name'] = $name; $data['alias'] = $alias; - } else { - if ($data['alias'] == $origTable->alias) { - $data['alias'] = ''; - } + } elseif ($data['alias'] == $origTable->alias) { + $data['alias'] = ''; } $data['published'] = 0; diff --git a/administrator/components/com_contact/src/Model/ContactsModel.php b/administrator/components/com_contact/src/Model/ContactsModel.php index f74f38eaf7338..d0ed660ed82c1 100644 --- a/administrator/components/com_contact/src/Model/ContactsModel.php +++ b/administrator/components/com_contact/src/Model/ContactsModel.php @@ -300,7 +300,7 @@ protected function getListQuery() '(' . $subQuery . ') AS ' . $db->quoteName('tagmap'), $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id') ); - } elseif ($tag = (int) $tag) { + } elseif ($tag = (int) $tag !== 0) { $query->join( 'INNER', $db->quoteName('#__contentitem_tag_map', 'tagmap'), @@ -324,7 +324,7 @@ protected function getListQuery() } // Case: Using both categories filter and by level filter - if (\count($categoryId)) { + if ($categoryId !== []) { $categoryId = ArrayHelper::toInteger($categoryId); $categoryTable = Table::getInstance('Category', '\\Joomla\\CMS\\Table\\'); $subCatItemsWhere = []; diff --git a/administrator/components/com_contact/src/Table/ContactTable.php b/administrator/components/com_contact/src/Table/ContactTable.php index c1ba065f60a22..737261885e8f5 100644 --- a/administrator/components/com_contact/src/Table/ContactTable.php +++ b/administrator/components/com_contact/src/Table/ContactTable.php @@ -87,7 +87,7 @@ public function store($updateNulls = true) $userId = $this->getCurrentUser()->id; // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -101,7 +101,7 @@ public function store($updateNulls = true) $this->created_by = $userId; } - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $date; } @@ -164,7 +164,7 @@ public function check() } // Check for valid name - if (trim($this->name) == '') { + if (trim($this->name) === '') { $this->setError(Text::_('COM_CONTACT_WARNING_PROVIDE_VALID_NAME')); return false; @@ -174,7 +174,7 @@ public function check() $this->generateAlias(); // Check for a valid category. - if (!$this->catid = (int) $this->catid) { + if ($this->catid = (int) $this->catid === 0) { $this->setError(Text::_('JLIB_DATABASE_ERROR_CATEGORY_REQUIRED')); return false; @@ -252,7 +252,7 @@ public function generateAlias() $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); - if (trim(str_replace('-', '', $this->alias)) == '') { + if (trim(str_replace('-', '', $this->alias)) === '') { $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } diff --git a/administrator/components/com_contact/src/View/Contact/HtmlView.php b/administrator/components/com_contact/src/View/Contact/HtmlView.php index 5e64cf65aca61..09c6419d7f4ac 100644 --- a/administrator/components/com_contact/src/View/Contact/HtmlView.php +++ b/administrator/components/com_contact/src/View/Contact/HtmlView.php @@ -126,7 +126,7 @@ protected function addToolbar() $user = $this->getCurrentUser(); $userId = $user->id; $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; $toolbar = $this->getDocument()->getToolbar(); // Since we don't track these assets at the item level, use the category id. diff --git a/administrator/components/com_contact/src/View/Contacts/HtmlView.php b/administrator/components/com_contact/src/View/Contacts/HtmlView.php index 02dea42e0211b..53bb15196871e 100644 --- a/administrator/components/com_contact/src/View/Contacts/HtmlView.php +++ b/administrator/components/com_contact/src/View/Contacts/HtmlView.php @@ -105,26 +105,21 @@ public function display($tpl = null) // We don't need toolbar in the modal window. if ($this->getLayout() !== 'modal') { $this->addToolbar(); - // We do not need to filter by language when multilingual is disabled if (!Multilanguage::isEnabled()) { unset($this->activeFilters['language']); $this->filterForm->removeField('language', 'filter'); } - } else { + } elseif ($forcedLanguage = Factory::getApplication()->getInput()->get('forcedLanguage', '', 'CMD')) { // In article associations modal we need to remove language filter if forcing a language. // We also need to change the category filter to show show categories with All or the forced language. - if ($forcedLanguage = Factory::getApplication()->getInput()->get('forcedLanguage', '', 'CMD')) { - // If the language is forced we can't allow to select the language, so transform the language selector filter into a hidden field. - $languageXml = new \SimpleXMLElement(''); - $this->filterForm->setField($languageXml, 'filter', true); - - // Also, unset the active language filter so the search tools is not open by default with this filter. - unset($this->activeFilters['language']); - - // One last changes needed is to change the category filter to just show categories with All language or with the forced language. - $this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter'); - } + // If the language is forced we can't allow to select the language, so transform the language selector filter into a hidden field. + $languageXml = new \SimpleXMLElement(''); + $this->filterForm->setField($languageXml, 'filter', true); + // Also, unset the active language filter so the search tools is not open by default with this filter. + unset($this->activeFilters['language']); + // One last changes needed is to change the category filter to just show categories with All language or with the forced language. + $this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter'); } parent::display($tpl); diff --git a/administrator/components/com_contact/tmpl/contacts/modal.php b/administrator/components/com_contact/tmpl/contacts/modal.php index ed2579532dc83..d823b500347ff 100644 --- a/administrator/components/com_contact/tmpl/contacts/modal.php +++ b/administrator/components/com_contact/tmpl/contacts/modal.php @@ -110,7 +110,7 @@ } $link = RouteHelper::getContactRoute($item->id, $item->catid, $item->language); - $itemHtml = '' . $item->name . ''; + $itemHtml = '' . $item->name . ''; ?>
    diff --git a/administrator/components/com_content/src/Controller/ArticleController.php b/administrator/components/com_content/src/Controller/ArticleController.php index abffcfed2f15b..eb064ad5d2f06 100644 --- a/administrator/components/com_content/src/Controller/ArticleController.php +++ b/administrator/components/com_content/src/Controller/ArticleController.php @@ -159,7 +159,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; $user = $this->app->getIdentity(); // Zero record (id:0), return component edit permission by calling parent controller method diff --git a/administrator/components/com_content/src/Controller/ArticlesController.php b/administrator/components/com_content/src/Controller/ArticlesController.php index dc86b71f090e5..666fbbe6a8305 100644 --- a/administrator/components/com_content/src/Controller/ArticlesController.php +++ b/administrator/components/com_content/src/Controller/ArticlesController.php @@ -90,7 +90,7 @@ public function featured() } } - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('JERROR_NO_ITEMS_SELECTED'), 'error'); $this->setRedirect(Route::_($redirectUrl, false)); diff --git a/administrator/components/com_content/src/Controller/FeaturedController.php b/administrator/components/com_content/src/Controller/FeaturedController.php index 92756c9fc89c6..70a5e1b54dd33 100644 --- a/administrator/components/com_content/src/Controller/FeaturedController.php +++ b/administrator/components/com_content/src/Controller/FeaturedController.php @@ -55,7 +55,7 @@ public function delete() } } - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('JERROR_NO_ITEMS_SELECTED'), 'error'); } else { /** @var \Joomla\Component\Content\Administrator\Model\FeatureModel $model */ diff --git a/administrator/components/com_content/src/Field/Modal/ArticleField.php b/administrator/components/com_content/src/Field/Modal/ArticleField.php index 337bd46e29985..a60fe930e0f76 100644 --- a/administrator/components/com_content/src/Field/Modal/ArticleField.php +++ b/administrator/components/com_content/src/Field/Modal/ArticleField.php @@ -70,7 +70,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $language = (string) $this->element['language']; // Prepare enabled actions - $this->canDo['propagate'] = ((string) $this->element['propagate'] == 'true') && \count($languages) > 2; + $this->canDo['propagate'] = ((string) $this->element['propagate'] === 'true') && \count($languages) > 2; // Prepare Urls $linkArticles = (new Uri())->setPath(Uri::base(true) . '/index.php'); @@ -91,7 +91,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) Session::getFormToken() => 1, ]); - if ($language) { + if ($language !== '' && $language !== '0') { $linkArticles->setVar('forcedLanguage', $language); $linkArticle->setVar('forcedLanguage', $language); diff --git a/administrator/components/com_content/src/Helper/ContentHelper.php b/administrator/components/com_content/src/Helper/ContentHelper.php index e0255918aa172..204e29a906362 100644 --- a/administrator/components/com_content/src/Helper/ContentHelper.php +++ b/administrator/components/com_content/src/Helper/ContentHelper.php @@ -134,7 +134,7 @@ public static function onPrepareForm(Form $form, $data) $option = Text::sprintf('COM_WORKFLOW_INHERIT_WORKFLOW', Text::_($defaulttitle)); - if (!empty($categories)) { + if ($categories !== []) { $categories = array_reverse($categories); $query = $db->getQuery(true); @@ -165,7 +165,7 @@ public static function onPrepareForm(Form $form, $data) break; } - if ($workflow_id = (int) $workflow_id) { + if ($workflow_id = (int) $workflow_id !== 0) { $title = $db->loadResult(); if (!\is_null($title)) { diff --git a/administrator/components/com_content/src/Model/ArticleModel.php b/administrator/components/com_content/src/Model/ArticleModel.php index c255133e0ebfd..3a559fd17bbcb 100644 --- a/administrator/components/com_content/src/Model/ArticleModel.php +++ b/administrator/components/com_content/src/Model/ArticleModel.php @@ -398,7 +398,7 @@ public function getItem($pk = null) $registry = new Registry($item->urls); $item->urls = $registry->toArray(); - $item->articletext = ($item->fulltext !== null && trim($item->fulltext) != '') ? $item->introtext . '
    ' . $item->fulltext : $item->introtext; + $item->articletext = ($item->fulltext !== null && trim($item->fulltext) !== '') ? $item->introtext . '
    ' . $item->fulltext : $item->introtext; if (!empty($item->id)) { $item->tags = new TagsHelper(); @@ -492,7 +492,7 @@ public function getForm($data = [], $loadData = true) : (int) $assignedCatids; // Try to get the category from the category field - if (empty($assignedCatids)) { + if ($assignedCatids === 0) { $assignedCatids = $formField->getAttribute('default', null); if (!$assignedCatids) { @@ -523,7 +523,7 @@ public function getForm($data = [], $loadData = true) ? (int) reset($catIds) : (int) $catIds; - if (!$catId) { + if ($catId === 0) { $catId = (int) $form->getFieldAttribute('catid', 'default', 0); } } @@ -587,15 +587,15 @@ protected function loadFormData() ((isset($filters['published']) && $filters['published'] !== '') ? $filters['published'] : null) ) ); - $data->set('catid', $app->getInput()->getInt('catid', (!empty($filters['category_id']) ? $filters['category_id'] : null))); + $data->set('catid', $app->getInput()->getInt('catid', (empty($filters['category_id']) ? null : $filters['category_id']))); if ($app->isClient('administrator')) { - $data->set('language', $app->getInput()->getString('language', (!empty($filters['language']) ? $filters['language'] : null))); + $data->set('language', $app->getInput()->getString('language', (empty($filters['language']) ? null : $filters['language']))); } $data->set( 'access', - $app->getInput()->getInt('access', (!empty($filters['access']) ? $filters['access'] : $app->get('access'))) + $app->getInput()->getInt('access', (empty($filters['access']) ? $app->get('access') : $filters['access'])) ); } } @@ -625,10 +625,8 @@ protected function loadFormData() */ public function validate($form, $data, $group = null) { - if (!$this->getCurrentUser()->authorise('core.admin', 'com_content')) { - if (isset($data['rules'])) { - unset($data['rules']); - } + if (!$this->getCurrentUser()->authorise('core.admin', 'com_content') && isset($data['rules'])) { + unset($data['rules']); } return parent::validate($form, $data, $group); @@ -731,15 +729,7 @@ public function save($data) if ($app->isClient('site')) { $origTable->load($input->getInt('a_id')); - if ($origTable->title === $data['title']) { - /** - * If title of article is not changed, set alias to original article alias so that Joomla! will generate - * new Title and Alias for the copied article - */ - $data['alias'] = $origTable->alias; - } else { - $data['alias'] = ''; - } + $data['alias'] = $origTable->title === $data['title'] ? $origTable->alias : ''; } else { $origTable->load($input->getInt('id')); } @@ -754,42 +744,32 @@ public function save($data) } // Automatic handling of alias for empty fields - if (\in_array($input->get('task'), ['apply', 'save', 'save2new']) && (!isset($data['id']) || (int) $data['id'] == 0)) { - if ($data['alias'] == null) { - if ($app->get('unicodeslugs') == 1) { - $data['alias'] = OutputFilter::stringUrlUnicodeSlug($data['title']); - } else { - $data['alias'] = OutputFilter::stringURLSafe($data['title']); - } - - $table = $this->getTable(); - - if ($table->load(['alias' => $data['alias'], 'catid' => $data['catid']])) { - $msg = Text::_('COM_CONTENT_SAVE_WARNING'); - } - - [$title, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); - $data['alias'] = $alias; - - if (isset($msg)) { - $app->enqueueMessage($msg, 'warning'); - } + if (\in_array($input->get('task'), ['apply', 'save', 'save2new']) && (!isset($data['id']) || (int) $data['id'] == 0) && $data['alias'] == null) { + if ($app->get('unicodeslugs') == 1) { + $data['alias'] = OutputFilter::stringUrlUnicodeSlug($data['title']); + } else { + $data['alias'] = OutputFilter::stringURLSafe($data['title']); + } + $table = $this->getTable(); + if ($table->load(['alias' => $data['alias'], 'catid' => $data['catid']])) { + $msg = Text::_('COM_CONTENT_SAVE_WARNING'); + } + [$title, $alias] = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); + $data['alias'] = $alias; + if (isset($msg)) { + $app->enqueueMessage($msg, 'warning'); } } if (parent::save($data)) { // Check if featured is set and if not managed by workflow - if (isset($data['featured']) && !$this->bootComponent('com_content')->isFunctionalityUsed('core.featured', 'com_content.article')) { - if ( - !$this->featured( - $this->getState($this->getName() . '.id'), - $data['featured'], - $data['featured_up'] ?? null, - $data['featured_down'] ?? null - ) - ) { - return false; - } + if (isset($data['featured']) && !$this->bootComponent('com_content')->isFunctionalityUsed('core.featured', 'com_content.article') && !$this->featured( + $this->getState($this->getName() . '.id'), + $data['featured'], + $data['featured_up'] ?? null, + $data['featured_down'] ?? null + )) { + return false; } $this->workflowAfterSave($data); @@ -890,7 +870,7 @@ public function featured($pks, $value = 0, $featuredUp = null, $featuredDown = n $oldFeatured = $db->loadColumn(); // Update old featured articles - if (\count($oldFeatured)) { + if (\count($oldFeatured) > 0) { $query = $db->getQuery(true) ->update($db->quoteName('#__content_frontpage')) ->set( @@ -910,7 +890,7 @@ public function featured($pks, $value = 0, $featuredUp = null, $featuredDown = n $newFeatured = array_diff($pks, $oldFeatured); // Featuring. - if ($newFeatured) { + if ($newFeatured !== []) { $query = $db->getQuery(true) ->insert($db->quoteName('#__content_frontpage')) ->columns( diff --git a/administrator/components/com_content/src/Model/ArticlesModel.php b/administrator/components/com_content/src/Model/ArticlesModel.php index f761f4389b3bb..5acdae765c765 100644 --- a/administrator/components/com_content/src/Model/ArticlesModel.php +++ b/administrator/components/com_content/src/Model/ArticlesModel.php @@ -361,7 +361,7 @@ protected function getListQuery() } // Case: Using both categories filter and by level filter - if (\count($categoryId)) { + if ($categoryId !== []) { $categoryId = ArrayHelper::toInteger($categoryId); $categoryTable = Table::getInstance('Category', '\\Joomla\\CMS\\Table\\'); $subCatItemsWhere = []; @@ -372,7 +372,7 @@ protected function getListQuery() // Because values to $query->bind() are passed by reference, using $query->bindArray() here instead to prevent overwriting. $valuesToBind = [$categoryTable->lft, $categoryTable->rgt]; - if ($level) { + if ($level !== 0) { $valuesToBind[] = $level + $categoryTable->level - 1; } @@ -381,7 +381,7 @@ protected function getListQuery() $categoryWhere = $db->quoteName('c.lft') . ' >= ' . $bounded[0] . ' AND ' . $db->quoteName('c.rgt') . ' <= ' . $bounded[1]; - if ($level) { + if ($level !== 0) { $categoryWhere .= ' AND ' . $db->quoteName('c.level') . ' <= ' . $bounded[2]; } @@ -389,7 +389,7 @@ protected function getListQuery() } $query->where('(' . implode(' OR ', $subCatItemsWhere) . ')'); - } elseif ($level = (int) $level) { + } elseif ($level = (int) $level !== 0) { // Case: Using only the by level filter $query->where($db->quoteName('c.level') . ' <= :level') ->bind(':level', $level, ParameterType::INTEGER); @@ -477,7 +477,7 @@ protected function getListQuery() '(' . $subQuery . ') AS ' . $db->quoteName('tagmap'), $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id') ); - } elseif ($tag = (int) $tag) { + } elseif ($tag = (int) $tag !== 0) { $query->join( 'INNER', $db->quoteName('#__contentitem_tag_map', 'tagmap'), @@ -578,11 +578,11 @@ public function getTransitions() $where = []; - if (\count($stage_ids)) { + if ($stage_ids !== []) { $where[] = $db->quoteName('t.from_stage_id') . ' IN (' . implode(',', $query->bindArray($stage_ids)) . ')'; } - if (\count($workflow_ids)) { + if ($workflow_ids !== []) { $where[] = '(' . $db->quoteName('t.from_stage_id') . ' = -1 AND ' . $db->quoteName('t.workflow_id') . ' IN (' . implode(',', $query->bindArray($workflow_ids)) . '))'; } diff --git a/administrator/components/com_content/src/View/Article/HtmlView.php b/administrator/components/com_content/src/View/Article/HtmlView.php index 83f31df49212d..a153afcbc7e15 100644 --- a/administrator/components/com_content/src/View/Article/HtmlView.php +++ b/administrator/components/com_content/src/View/Article/HtmlView.php @@ -163,7 +163,7 @@ protected function addToolbar() $user = $this->getCurrentUser(); $userId = $user->id; $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; $toolbar = $this->getDocument()->getToolbar(); // Built the actions for new and existing records. @@ -273,7 +273,7 @@ protected function addModalToolbar() $user = $this->getCurrentUser(); $userId = $user->id; $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; $toolbar = $this->getDocument()->getToolbar(); // Build the actions for new and existing records. diff --git a/administrator/components/com_content/src/View/Featured/HtmlView.php b/administrator/components/com_content/src/View/Featured/HtmlView.php index 8cf0f4f49dda2..f086a5a0b4bce 100644 --- a/administrator/components/com_content/src/View/Featured/HtmlView.php +++ b/administrator/components/com_content/src/View/Featured/HtmlView.php @@ -33,6 +33,11 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var bool + */ + public $vote; + public $hits; /** * An array of items * diff --git a/administrator/components/com_content/tmpl/articles/default.php b/administrator/components/com_content/tmpl/articles/default.php index 54519c3f62a60..30301e027adde 100644 --- a/administrator/components/com_content/tmpl/articles/default.php +++ b/administrator/components/com_content/tmpl/articles/default.php @@ -268,10 +268,8 @@ $CurrentCatUrl = Route::_('index.php?option=com_categories&task=category.edit&id=' . $item->catid . '&extension=com_content'); $EditCatTxt = Text::_('COM_CONTENT_EDIT_CATEGORY'); echo Text::_('JCATEGORY') . ': '; - if ($item->category_level != '1') : - if ($item->parent_category_level != '1') : - echo ' » '; - endif; + if ($item->category_level != '1' && $item->parent_category_level != '1') : + echo ' » '; endif; if ($this->getLanguage()->isRtl()) { if ($canEditCat || $canEditOwnCat) : diff --git a/administrator/components/com_content/tmpl/articles/modal.php b/administrator/components/com_content/tmpl/articles/modal.php index 1d498b8a16b2a..dd79505539abb 100644 --- a/administrator/components/com_content/tmpl/articles/modal.php +++ b/administrator/components/com_content/tmpl/articles/modal.php @@ -112,7 +112,7 @@ } $link = RouteHelper::getArticleRoute($item->id, $item->catid, $item->language); - $itemHtml = '' . $item->title . ''; + $itemHtml = '' . $item->title . ''; ?>
    diff --git a/administrator/components/com_content/tmpl/featured/default.php b/administrator/components/com_content/tmpl/featured/default.php index 4ab80b31bb814..dffda4b1a0711 100644 --- a/administrator/components/com_content/tmpl/featured/default.php +++ b/administrator/components/com_content/tmpl/featured/default.php @@ -262,10 +262,8 @@ $CurrentCatUrl = Route::_('index.php?option=com_categories&task=category.edit&id=' . $item->catid . '&extension=com_content'); $EditCatTxt = Text::_('COM_CONTENT_EDIT_CATEGORY'); echo Text::_('JCATEGORY') . ': '; - if ($item->category_level != '1') : - if ($item->parent_category_level != '1') : - echo ' » '; - endif; + if ($item->category_level != '1' && $item->parent_category_level != '1') : + echo ' » '; endif; if ($this->getLanguage()->isRtl()) { if ($canEditCat || $canEditOwnCat) : diff --git a/administrator/components/com_contenthistory/src/Controller/HistoryController.php b/administrator/components/com_contenthistory/src/Controller/HistoryController.php index 317fc8e17849c..4d9298efe9551 100644 --- a/administrator/components/com_contenthistory/src/Controller/HistoryController.php +++ b/administrator/components/com_contenthistory/src/Controller/HistoryController.php @@ -59,7 +59,7 @@ public function keep() // Remove zero values resulting from input filter $cid = array_filter($cid); - if (empty($cid)) { + if ($cid === []) { $this->app->enqueueMessage(Text::_('COM_CONTENTHISTORY_NO_ITEM_SELECTED'), 'warning'); } else { // Get the model. diff --git a/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php b/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php index 738939e8f41ad..a0c4ef95ca800 100644 --- a/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php +++ b/administrator/components/com_contenthistory/src/Helper/ContenthistoryHelper.php @@ -107,35 +107,31 @@ public static function getFormValues($object, ContentType $typesTable) $expandedObjectArray = static::createObjectArray($object); static::loadLanguageFiles($typesTable->type_alias); - if ($formFile = static::getFormFile($typesTable)) { - if ($xml = simplexml_load_file($formFile)) { - // Now we need to get all of the labels from the form - $fieldArray = $xml->xpath('//field'); - $fieldArray = array_merge($fieldArray, $xml->xpath('//fields')); - - foreach ($fieldArray as $field) { - if ($label = (string) $field->attributes()->label) { - $labels[(string) $field->attributes()->name] = Text::_($label); - } + if (($formFile = static::getFormFile($typesTable)) && $xml = simplexml_load_file($formFile)) { + // Now we need to get all of the labels from the form + $fieldArray = $xml->xpath('//field'); + $fieldArray = array_merge($fieldArray, $xml->xpath('//fields')); + foreach ($fieldArray as $field) { + $label = (string) $field->attributes()->label; + if ($label !== '' && $label !== '0') { + $labels[(string) $field->attributes()->name] = Text::_($label); } + } + // Get values for any list type fields + $listFieldArray = $xml->xpath('//field[@type="list" or @type="radio"]'); + foreach ($listFieldArray as $field) { + $name = (string) $field->attributes()->name; - // Get values for any list type fields - $listFieldArray = $xml->xpath('//field[@type="list" or @type="radio"]'); - - foreach ($listFieldArray as $field) { - $name = (string) $field->attributes()->name; - - if (isset($expandedObjectArray[$name])) { - $optionFieldArray = $field->xpath('option[@value="' . $expandedObjectArray[$name] . '"]'); - - $valueText = null; + if (isset($expandedObjectArray[$name])) { + $optionFieldArray = $field->xpath('option[@value="' . $expandedObjectArray[$name] . '"]'); - if (\is_array($optionFieldArray) && \count($optionFieldArray)) { - $valueText = trim((string) $optionFieldArray[0]); - } + $valueText = null; - $values[(string) $field->attributes()->name] = Text::_($valueText); + if (\is_array($optionFieldArray) && \count($optionFieldArray)) { + $valueText = trim((string) $optionFieldArray[0]); } + + $values[(string) $field->attributes()->name] = Text::_($valueText); } } } @@ -165,7 +161,7 @@ public static function getFormFile(ContentType $typesTable) $result = JPATH_ROOT . '/' . $options->formFile; } else { $aliasArray = explode('.', $typesTable->type_alias); - $component = ($aliasArray[1] == 'category') ? 'com_categories' : $aliasArray[0]; + $component = ($aliasArray[1] === 'category') ? 'com_categories' : $aliasArray[0]; $path = Folder::makeSafe(JPATH_ADMINISTRATOR . '/components/' . $component . '/models/forms/'); array_shift($aliasArray); $file = File::makeSafe(implode('.', $aliasArray) . '.xml'); @@ -222,11 +218,9 @@ public static function getLookupValue($lookup, $value) */ public static function hideFields($object, ContentType $typeTable) { - if ($options = json_decode($typeTable->content_history_options)) { - if (isset($options->hideFields) && \is_array($options->hideFields)) { - foreach ($options->hideFields as $field) { - unset($object->$field); - } + if (($options = json_decode($typeTable->content_history_options)) && (isset($options->hideFields) && \is_array($options->hideFields))) { + foreach ($options->hideFields as $field) { + unset($object->$field); } } @@ -247,15 +241,16 @@ public static function loadLanguageFiles($typeAlias) $aliasArray = explode('.', $typeAlias); if (\is_array($aliasArray) && \count($aliasArray) == 2) { - $component = ($aliasArray[1] == 'category') ? 'com_categories' : $aliasArray[0]; + $component = ($aliasArray[1] === 'category') ? 'com_categories' : $aliasArray[0]; $lang = Factory::getLanguage(); /** * Loading language file from the administrator/language directory then * loading language file from the administrator/components/extension/language directory */ - $lang->load($component, JPATH_ADMINISTRATOR) - || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + if (!$lang->load($component, JPATH_ADMINISTRATOR)) { + $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + } // Force loading of backend global language file $lang->load('joomla', Path::clean(JPATH_ADMINISTRATOR)); @@ -345,15 +340,13 @@ public static function prepareData(ContentHistory $table) */ public static function processLookupFields($object, ContentType $typesTable) { - if ($options = json_decode($typesTable->content_history_options)) { - if (isset($options->displayLookup) && \is_array($options->displayLookup)) { - foreach ($options->displayLookup as $lookup) { - $sourceColumn = $lookup->sourceColumn ?? false; - $sourceValue = $object->$sourceColumn->value ?? false; - - if ($sourceColumn && $sourceValue && ($lookupValue = static::getLookupValue($lookup, $sourceValue))) { - $object->$sourceColumn->value = $lookupValue; - } + if (($options = json_decode($typesTable->content_history_options)) && (isset($options->displayLookup) && \is_array($options->displayLookup))) { + foreach ($options->displayLookup as $lookup) { + $sourceColumn = $lookup->sourceColumn ?? false; + $sourceValue = $object->$sourceColumn->value ?? false; + + if ($sourceColumn && $sourceValue && ($lookupValue = static::getLookupValue($lookup, $sourceValue))) { + $object->$sourceColumn->value = $lookupValue; } } } diff --git a/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php b/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php index 3e8bc11296dd2..55c2b6ab59c95 100644 --- a/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php +++ b/administrator/components/com_cpanel/src/View/Cpanel/HtmlView.php @@ -75,8 +75,9 @@ public function display($tpl = null) // Need to load the language file $lang = $this->getLanguage(); - $lang->load($component, JPATH_BASE) - || $lang->load($component, JPATH_ADMINISTRATOR . '/components/' . $component); + if (!$lang->load($component, JPATH_BASE)) { + $lang->load($component, JPATH_ADMINISTRATOR . '/components/' . $component); + } $lang->load($component); // Lookup dashboard attributes from component manifest file @@ -101,7 +102,7 @@ public function display($tpl = null) // Try building a title $prefix = strtoupper($component) . '_DASHBOARD'; - $sectionkey = !empty($parts[1]) ? '_' . strtoupper($parts[1]) : ''; + $sectionkey = empty($parts[1]) ? '' : '_' . strtoupper($parts[1]); $key = $prefix . $sectionkey . '_TITLE'; $keyIcon = $prefix . $sectionkey . '_ICON'; diff --git a/administrator/components/com_fields/src/Controller/FieldController.php b/administrator/components/com_fields/src/Controller/FieldController.php index 24682c186ce79..0f70a25c5060a 100644 --- a/administrator/components/com_fields/src/Controller/FieldController.php +++ b/administrator/components/com_fields/src/Controller/FieldController.php @@ -95,7 +95,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; $user = $this->app->getIdentity(); // Zero record (id:0), return component edit permission by calling parent controller method diff --git a/administrator/components/com_fields/src/Controller/GroupController.php b/administrator/components/com_fields/src/Controller/GroupController.php index 6572227d11fe3..bbd5a767d4ae7 100644 --- a/administrator/components/com_fields/src/Controller/GroupController.php +++ b/administrator/components/com_fields/src/Controller/GroupController.php @@ -117,7 +117,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'parent_id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; $user = $this->app->getIdentity(); // Zero record (parent_id:0), return component edit permission by calling parent controller method diff --git a/administrator/components/com_fields/src/Field/ComponentsFieldgroupField.php b/administrator/components/com_fields/src/Field/ComponentsFieldgroupField.php index 0a7f763baf9fc..9a09f68b68c88 100644 --- a/administrator/components/com_fields/src/Field/ComponentsFieldgroupField.php +++ b/administrator/components/com_fields/src/Field/ComponentsFieldgroupField.php @@ -58,7 +58,7 @@ protected function getOptions() $options = []; - if (\count($items)) { + if (\count($items) > 0) { $lang = Factory::getLanguage(); $components = []; @@ -73,8 +73,9 @@ protected function getOptions() if (!empty($availableActions)) { // Load language $source = JPATH_ADMINISTRATOR . '/components/' . $item->value; - $lang->load($item->value . 'sys', JPATH_ADMINISTRATOR) - || $lang->load($item->value . 'sys', $source); + if (!$lang->load($item->value . 'sys', JPATH_ADMINISTRATOR)) { + $lang->load($item->value . 'sys', $source); + } // Translate component name $item->text = Text::_($item->text); @@ -83,7 +84,7 @@ protected function getOptions() } } - if (empty($components)) { + if ($components === []) { return []; } diff --git a/administrator/components/com_fields/src/Field/ComponentsFieldsField.php b/administrator/components/com_fields/src/Field/ComponentsFieldsField.php index fecd3715fd762..744ee45c0eaf2 100644 --- a/administrator/components/com_fields/src/Field/ComponentsFieldsField.php +++ b/administrator/components/com_fields/src/Field/ComponentsFieldsField.php @@ -58,7 +58,7 @@ protected function getOptions() $options = []; - if (\count($items)) { + if (\count($items) > 0) { $lang = Factory::getLanguage(); $components = []; @@ -73,8 +73,9 @@ protected function getOptions() if (!empty($availableActions)) { // Load language $source = JPATH_ADMINISTRATOR . '/components/' . $item->value; - $lang->load($item->value . 'sys', JPATH_ADMINISTRATOR) - || $lang->load($item->value . 'sys', $source); + if (!$lang->load($item->value . 'sys', JPATH_ADMINISTRATOR)) { + $lang->load($item->value . 'sys', $source); + } // Translate component name $item->text = Text::_($item->text); @@ -83,7 +84,7 @@ protected function getOptions() } } - if (empty($components)) { + if ($components === []) { return []; } diff --git a/administrator/components/com_fields/src/Field/FieldLayoutField.php b/administrator/components/com_fields/src/Field/FieldLayoutField.php index 3eeb1c16b8798..95210395daf6b 100644 --- a/administrator/components/com_fields/src/Field/FieldLayoutField.php +++ b/administrator/components/com_fields/src/Field/FieldLayoutField.php @@ -48,7 +48,7 @@ protected function getInput() $extension = explode('.', (string) $this->form->getValue('context')); $extension = $extension[0]; - if ($extension) { + if ($extension !== '' && $extension !== '0') { // Get the database object and a new query object. $db = $this->getDatabase(); $query = $db->getQuery(true); @@ -123,7 +123,7 @@ protected function getInput() } } - if (\count($files)) { + if ($files !== []) { // Create the group for the template $groups[$template->name] = []; $groups[$template->name]['id'] = $this->id . '_' . $template->element; diff --git a/administrator/components/com_fields/src/Helper/FieldsHelper.php b/administrator/components/com_fields/src/Helper/FieldsHelper.php index 4bb515e879b0f..ca90f2d07edcc 100644 --- a/administrator/components/com_fields/src/Helper/FieldsHelper.php +++ b/administrator/components/com_fields/src/Helper/FieldsHelper.php @@ -225,7 +225,7 @@ public static function getFields( if (\is_array($value)) { $value = array_filter($value, fn($v) => $v !== '' && $v !== null); - $value = $value ? implode(' ', $value) : ''; + $value = $value !== [] ? implode(' ', $value) : ''; } /* @@ -582,7 +582,7 @@ public static function getAssignedCategoriesIds($fieldId) { $fieldId = (int) $fieldId; - if (!$fieldId) { + if ($fieldId === 0) { return []; } @@ -611,7 +611,7 @@ public static function getAssignedCategoriesTitles($fieldId) { $fieldId = (int) $fieldId; - if (!$fieldId) { + if ($fieldId === 0) { return []; } diff --git a/administrator/components/com_fields/src/Model/FieldModel.php b/administrator/components/com_fields/src/Model/FieldModel.php index 4c5107ba57eae..3a66ad7ea0882 100644 --- a/administrator/components/com_fields/src/Model/FieldModel.php +++ b/administrator/components/com_fields/src/Model/FieldModel.php @@ -148,10 +148,8 @@ public function save($data) $data['title'] = $title; $data['label'] = $title; $data['name'] = $name; - } else { - if ($data['name'] == $origTable->name) { - $data['name'] = ''; - } + } elseif ($data['name'] == $origTable->name) { + $data['name'] = ''; } $data['state'] = 0; @@ -245,7 +243,7 @@ public function save($data) ->bind(':fieldid', $fieldId, ParameterType::INTEGER); // If new values are set, delete only old values. Otherwise delete all values. - if ($names) { + if ($names !== []) { $query->whereNotIn($db->quoteName('value'), $names, ParameterType::STRING); } @@ -295,7 +293,7 @@ private function checkDefaultValue($data) // Create the fields object $obj = (object) $data; $obj->params = new Registry($obj->params); - $obj->fieldparams = new Registry(!empty($obj->fieldparams) ? $obj->fieldparams : []); + $obj->fieldparams = new Registry(empty($obj->fieldparams) ? [] : $obj->fieldparams); // Prepare the dom $dom = new \DOMDocument(); @@ -330,7 +328,7 @@ private function checkDefaultValue($data) try { $rule->setDatabase($this->getDatabase()); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $rule->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } } @@ -489,7 +487,7 @@ public function delete(&$pks) $pks = ArrayHelper::toInteger($pks); $pks = array_filter($pks); - if (!empty($pks)) { + if ($pks !== []) { // Delete Values $query = $db->getQuery(true); @@ -627,7 +625,7 @@ public function setFieldValue($fieldId, $itemId, $value) if ($oldValue === null) { // No records available, doing normal insert $needsInsert = true; - } elseif (\count($value) == 1 && \count((array) $oldValue) == 1) { + } elseif (\count($value) === 1 && \count((array) $oldValue) === 1) { // Only a single row value update can be done when not empty $needsUpdate = \is_array($value[0]) ? \count($value[0]) : \strlen($value[0]); $needsDelete = !$needsUpdate; @@ -716,7 +714,7 @@ public function getFieldValue($fieldId, $itemId) */ public function getFieldValues(array $fieldIds, $itemId) { - if (!$fieldIds) { + if ($fieldIds === []) { return []; } @@ -939,19 +937,19 @@ protected function loadFormData() $filters = (array) $app->getUserState('com_fields.fields.filter'); $data->set('state', $input->getInt('state', ((isset($filters['state']) && $filters['state'] !== '') ? $filters['state'] : null))); - $data->set('language', $input->getString('language', (!empty($filters['language']) ? $filters['language'] : null))); - $data->set('group_id', $input->getString('group_id', (!empty($filters['group_id']) ? $filters['group_id'] : null))); + $data->set('language', $input->getString('language', (empty($filters['language']) ? null : $filters['language']))); + $data->set('group_id', $input->getString('group_id', (empty($filters['group_id']) ? null : $filters['group_id']))); $data->set( 'assigned_cat_ids', $input->get( 'assigned_cat_ids', - (!empty($filters['assigned_cat_ids']) ? (array)$filters['assigned_cat_ids'] : [0]), + (empty($filters['assigned_cat_ids']) ? [0] : (array)$filters['assigned_cat_ids']), 'array' ) ); $data->set( 'access', - $input->getInt('access', (!empty($filters['access']) ? $filters['access'] : $app->get('access'))) + $input->getInt('access', (empty($filters['access']) ? $app->get('access') : $filters['access'])) ); // Set the type if available from the request @@ -983,10 +981,8 @@ protected function loadFormData() */ public function validate($form, $data, $group = null) { - if (!$this->getCurrentUser()->authorise('core.admin', 'com_fields')) { - if (isset($data['rules'])) { - unset($data['rules']); - } + if (!$this->getCurrentUser()->authorise('core.admin', 'com_fields') && isset($data['rules'])) { + unset($data['rules']); } return parent::validate($form, $data, $group); diff --git a/administrator/components/com_fields/src/Model/FieldsModel.php b/administrator/components/com_fields/src/Model/FieldsModel.php index b270b75313b27..c1ac48c1e2fab 100644 --- a/administrator/components/com_fields/src/Model/FieldsModel.php +++ b/administrator/components/com_fields/src/Model/FieldsModel.php @@ -228,7 +228,7 @@ function () use ($parts) { } )(); - if ($cat) { + if ($cat instanceof \Joomla\CMS\Categories\CategoryInterface) { foreach ($categories as $assignedCatIds) { // Check if we have the actual category $parent = $cat->get($assignedCatIds); diff --git a/administrator/components/com_fields/src/Model/GroupModel.php b/administrator/components/com_fields/src/Model/GroupModel.php index 90f40cc6d8971..97ae141b6c165 100644 --- a/administrator/components/com_fields/src/Model/GroupModel.php +++ b/administrator/components/com_fields/src/Model/GroupModel.php @@ -283,10 +283,8 @@ protected function preprocessForm(Form $form, $data, $group = 'content') */ public function validate($form, $data, $group = null) { - if (!$this->getCurrentUser()->authorise('core.admin', 'com_fields')) { - if (isset($data['rules'])) { - unset($data['rules']); - } + if (!$this->getCurrentUser()->authorise('core.admin', 'com_fields') && isset($data['rules'])) { + unset($data['rules']); } return parent::validate($form, $data, $group); @@ -317,15 +315,15 @@ protected function loadFormData() $data->set( 'state', - $input->getInt('state', (!empty($filters['state']) ? $filters['state'] : null)) + $input->getInt('state', (empty($filters['state']) ? null : $filters['state'])) ); $data->set( 'language', - $input->getString('language', (!empty($filters['language']) ? $filters['language'] : null)) + $input->getString('language', (empty($filters['language']) ? null : $filters['language'])) ); $data->set( 'access', - $input->getInt('access', (!empty($filters['access']) ? $filters['access'] : $app->get('access'))) + $input->getInt('access', (empty($filters['access']) ? $app->get('access') : $filters['access'])) ); } } diff --git a/administrator/components/com_fields/src/Plugin/FieldsPlugin.php b/administrator/components/com_fields/src/Plugin/FieldsPlugin.php index d5cbbdcd2fa33..bbdca7841e94e 100644 --- a/administrator/components/com_fields/src/Plugin/FieldsPlugin.php +++ b/administrator/components/com_fields/src/Plugin/FieldsPlugin.php @@ -153,7 +153,7 @@ public function onCustomFieldsGetTypes() // The language key $key = strtoupper($layout); - if ($key != strtoupper($this->_name)) { + if ($key !== strtoupper($this->_name)) { $key = strtoupper($this->_name) . '_' . $layout; } @@ -288,7 +288,7 @@ public function onCustomFieldsPrepareDom($field, \DOMElement $parent, Form $form foreach ($params->toArray() as $key => $param) { if (\is_array($param)) { // Multidimensional arrays (eg. list options) can't be transformed properly - $param = \count($param) == \count($param, COUNT_RECURSIVE) ? implode(',', $param) : ''; + $param = \count($param) === \count($param, COUNT_RECURSIVE) ? implode(',', $param) : ''; } if ($param === '' || (!\is_string($param) && !is_numeric($param))) { diff --git a/administrator/components/com_fields/src/Table/FieldTable.php b/administrator/components/com_fields/src/Table/FieldTable.php index ad8b124da1a49..7696e078c87c8 100644 --- a/administrator/components/com_fields/src/Table/FieldTable.php +++ b/administrator/components/com_fields/src/Table/FieldTable.php @@ -133,7 +133,7 @@ public function bind($src, $ignore = '') public function check() { // Check for valid name - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('COM_FIELDS_MUSTCONTAIN_A_TITLE_FIELD')); return false; @@ -145,7 +145,7 @@ public function check() $this->name = ApplicationHelper::stringURLSafe($this->name, $this->language); - if (trim(str_replace('-', '', $this->name)) == '') { + if (trim(str_replace('-', '', $this->name)) === '') { $this->name = StringHelper::increment($this->name, 'dash'); } @@ -174,7 +174,7 @@ public function check() $user = $this->getCurrentUser(); // Set created date if not set. - if (!(int) $this->created_time) { + if ((int) $this->created_time === 0) { $this->created_time = $date; } @@ -183,7 +183,7 @@ public function check() $this->modified_time = $date; $this->modified_by = $user->id; } else { - if (!(int) $this->modified_time) { + if ((int) $this->modified_time === 0) { $this->modified_time = $this->created_time; } @@ -313,7 +313,7 @@ private function getAssetId($name) if ($result = $db->loadResult()) { $assetId = (int) $result; - if ($assetId) { + if ($assetId !== 0) { return $assetId; } } diff --git a/administrator/components/com_fields/src/Table/GroupTable.php b/administrator/components/com_fields/src/Table/GroupTable.php index b72a7145c44da..89e2e062fc049 100644 --- a/administrator/components/com_fields/src/Table/GroupTable.php +++ b/administrator/components/com_fields/src/Table/GroupTable.php @@ -100,7 +100,7 @@ public function bind($src, $ignore = '') public function check() { // Check for a title. - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('COM_FIELDS_MUSTCONTAIN_A_TITLE_GROUP')); return false; @@ -110,7 +110,7 @@ public function check() $user = $this->getCurrentUser(); // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -118,7 +118,7 @@ public function check() $this->modified = $date; $this->modified_by = $user->id; } else { - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $this->created; } @@ -211,7 +211,7 @@ protected function _getAssetParentId(?Table $table = null, $id = null) ->bind(':name', $component[0]); $db->setQuery($query); - if ($assetId = (int) $db->loadResult()) { + if ($assetId = (int) $db->loadResult() !== 0) { return $assetId; } diff --git a/administrator/components/com_fields/src/View/Field/HtmlView.php b/administrator/components/com_fields/src/View/Field/HtmlView.php index f6c82c1d68d2b..0bc76be5c889a 100644 --- a/administrator/components/com_fields/src/View/Field/HtmlView.php +++ b/administrator/components/com_fields/src/View/Field/HtmlView.php @@ -31,6 +31,7 @@ */ class HtmlView extends BaseHtmlView { + public $canDo; /** * @var \Joomla\CMS\Form\Form * @@ -102,7 +103,7 @@ protected function addToolbar() $toolbar = $this->getDocument()->getToolbar(); $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; // Avoid nonsense situation. if ($component == 'com_fields') { @@ -111,8 +112,9 @@ protected function addToolbar() // Load component language file $lang = $this->getLanguage(); - $lang->load($component, JPATH_ADMINISTRATOR) - || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + if (!$lang->load($component, JPATH_ADMINISTRATOR)) { + $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + } $title = Text::sprintf('COM_FIELDS_VIEW_FIELD_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper((string) $component))); diff --git a/administrator/components/com_fields/src/View/Fields/HtmlView.php b/administrator/components/com_fields/src/View/Fields/HtmlView.php index c6a53217be412..45cfbdddd9ed9 100644 --- a/administrator/components/com_fields/src/View/Fields/HtmlView.php +++ b/administrator/components/com_fields/src/View/Fields/HtmlView.php @@ -139,8 +139,9 @@ protected function addToolbar() // Load extension language file $lang = $this->getLanguage(); - $lang->load($component, JPATH_ADMINISTRATOR) - || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + if (!$lang->load($component, JPATH_ADMINISTRATOR)) { + $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + } $title = Text::sprintf('COM_FIELDS_VIEW_FIELDS_TITLE', Text::_(strtoupper((string) $component))); diff --git a/administrator/components/com_fields/src/View/Group/HtmlView.php b/administrator/components/com_fields/src/View/Group/HtmlView.php index fe79b3298bd94..1c06ce22a32ca 100644 --- a/administrator/components/com_fields/src/View/Group/HtmlView.php +++ b/administrator/components/com_fields/src/View/Group/HtmlView.php @@ -122,7 +122,7 @@ protected function addToolbar() $canDo = $this->canDo; $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; // Avoid nonsense situation. if ($component == 'com_fields') { @@ -131,8 +131,9 @@ protected function addToolbar() // Load component language file $lang = $this->getLanguage(); - $lang->load($component, JPATH_ADMINISTRATOR) - || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + if (!$lang->load($component, JPATH_ADMINISTRATOR)) { + $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + } $title = Text::sprintf('COM_FIELDS_VIEW_GROUP_' . ($isNew ? 'ADD' : 'EDIT') . '_TITLE', Text::_(strtoupper((string) $component))); diff --git a/administrator/components/com_fields/src/View/Groups/HtmlView.php b/administrator/components/com_fields/src/View/Groups/HtmlView.php index 3130cb02905af..1b720bfeaaabe 100644 --- a/administrator/components/com_fields/src/View/Groups/HtmlView.php +++ b/administrator/components/com_fields/src/View/Groups/HtmlView.php @@ -141,8 +141,9 @@ protected function addToolbar() // Load component language file $lang = $this->getLanguage(); - $lang->load($component, JPATH_ADMINISTRATOR) - || $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + if (!$lang->load($component, JPATH_ADMINISTRATOR)) { + $lang->load($component, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $component)); + } $title = Text::sprintf('COM_FIELDS_VIEW_GROUPS_TITLE', Text::_(strtoupper((string) $component))); diff --git a/administrator/components/com_fields/tmpl/fields/default.php b/administrator/components/com_fields/tmpl/fields/default.php index 6336da4cb3ef1..490c31c7f1ad1 100644 --- a/administrator/components/com_fields/tmpl/fields/default.php +++ b/administrator/components/com_fields/tmpl/fields/default.php @@ -36,7 +36,7 @@ $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $ordering = ($listOrder == 'a.ordering'); -$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) == 'asc'); +$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) === 'asc'); // The category object of the component $category = Categories::getInstance(str_replace('com_', '', $component) . '.' . $section); diff --git a/administrator/components/com_fields/tmpl/groups/default.php b/administrator/components/com_fields/tmpl/groups/default.php index 9b668be8151d6..126b76ff3e776 100644 --- a/administrator/components/com_fields/tmpl/groups/default.php +++ b/administrator/components/com_fields/tmpl/groups/default.php @@ -40,7 +40,7 @@ $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $ordering = ($listOrder == 'a.ordering'); -$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) == 'asc'); +$saveOrder = ($listOrder == 'a.ordering' && strtolower((string) $listDirn) === 'asc'); if ($saveOrder && !empty($this->items)) { $saveOrderingUrl = 'index.php?option=com_fields&task=groups.saveOrderAjax&tmpl=component&' . Session::getFormToken() . '=1'; diff --git a/administrator/components/com_finder/src/Controller/IndexerController.php b/administrator/components/com_finder/src/Controller/IndexerController.php index 3adbf1b9b832e..c9858cbd2b456 100644 --- a/administrator/components/com_finder/src/Controller/IndexerController.php +++ b/administrator/components/com_finder/src/Controller/IndexerController.php @@ -97,7 +97,7 @@ public function start() $output = ob_get_contents(); // Finder plugins should not create output of any kind. If there is output, that very likely is the result of a PHP error. - if (trim($output)) { + if (trim($output) !== '' && trim($output) !== '0') { throw new \Exception(Text::_('COM_FINDER_AN_ERROR_HAS_OCCURRED')); } @@ -203,7 +203,7 @@ public function batch() $output = ob_get_contents(); // Finder plugins should not create output of any kind. If there is output, that very likely is the result of a PHP error. - if (trim($output)) { + if (trim($output) !== '' && trim($output) !== '0') { throw new \Exception(Text::_('COM_FINDER_INDEXER_ERROR_PLUGIN_FAILURE')); } @@ -254,7 +254,7 @@ public function optimize() $output = ob_get_contents(); // Finder plugins should not create output of any kind. If there is output, that very likely is the result of a PHP error. - if (trim($output)) { + if (trim($output) !== '' && trim($output) !== '0') { throw new \Exception(Text::_('COM_FINDER_AN_ERROR_HAS_OCCURRED')); } diff --git a/administrator/components/com_finder/src/Helper/FinderHelper.php b/administrator/components/com_finder/src/Helper/FinderHelper.php index 3bdff6d9604c9..50f87acff4792 100644 --- a/administrator/components/com_finder/src/Helper/FinderHelper.php +++ b/administrator/components/com_finder/src/Helper/FinderHelper.php @@ -42,6 +42,6 @@ public static function getFinderPluginId() { $pluginRecord = ExtensionHelper::getExtensionRecord('finder', 'plugin', null, 'content'); - return $pluginRecord !== null ? $pluginRecord->extension_id : 0; + return $pluginRecord instanceof \stdClass ? $pluginRecord->extension_id : 0; } } diff --git a/administrator/components/com_finder/src/Helper/LanguageHelper.php b/administrator/components/com_finder/src/Helper/LanguageHelper.php index 34380b58f57ef..01e0f53bcdb0e 100644 --- a/administrator/components/com_finder/src/Helper/LanguageHelper.php +++ b/administrator/components/com_finder/src/Helper/LanguageHelper.php @@ -144,8 +144,9 @@ public static function loadPluginLanguage() // Load language file for each plugin. foreach ($plugins as $plugin) { - $lang->load($plugin->name, JPATH_ADMINISTRATOR) - || $lang->load($plugin->name, JPATH_PLUGINS . '/finder/' . $plugin->element); + if (!$lang->load($plugin->name, JPATH_ADMINISTRATOR)) { + $lang->load($plugin->name, JPATH_PLUGINS . '/finder/' . $plugin->element); + } } } } diff --git a/administrator/components/com_finder/src/Indexer/Helper.php b/administrator/components/com_finder/src/Indexer/Helper.php index b57cdbdb83de8..e1a661e5a6691 100644 --- a/administrator/components/com_finder/src/Indexer/Helper.php +++ b/administrator/components/com_finder/src/Indexer/Helper.php @@ -475,7 +475,7 @@ public static function prepareContent($text, $params = null, ?Result $item = nul $content = Table::getInstance('Content'); $content->text = $text; - if ($item) { + if ($item instanceof \Joomla\Component\Finder\Administrator\Indexer\Result) { $content->bind((array) $item); $content->bind($item->getElements()); } diff --git a/administrator/components/com_finder/src/Indexer/Indexer.php b/administrator/components/com_finder/src/Indexer/Indexer.php index 6aec4b6572342..246b5853f0824 100644 --- a/administrator/components/com_finder/src/Indexer/Indexer.php +++ b/administrator/components/com_finder/src/Indexer/Indexer.php @@ -121,8 +121,8 @@ class Indexer */ public function __construct(?DatabaseInterface $db = null) { - if ($db === null) { - @trigger_error(\sprintf('Database will be mandatory in 5.0.'), E_USER_DEPRECATED); + if (!$db instanceof \Joomla\Database\DatabaseInterface) { + @trigger_error('Database will be mandatory in 5.0.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseInterface::class); } @@ -279,8 +279,9 @@ public static function resetState() */ public function index($item, $format = 'html') { - // Mark beforeIndexing in the profiler. - static::$profiler ? static::$profiler->mark('beforeIndexing') : null; + if (static::$profiler) { + static::$profiler->mark('beforeIndexing'); + } $db = $this->db; $serverType = strtolower($db->getServerType()); @@ -327,8 +328,9 @@ public function index($item, $format = 'html') Taxonomy::removeMaps($linkId); } - // Mark afterUnmapping in the profiler. - static::$profiler ? static::$profiler->mark('afterUnmapping') : null; + if (static::$profiler) { + static::$profiler->mark('afterUnmapping'); + } // Perform cleanup on the item data. $item->publish_start_date = (int) $item->publish_start_date != 0 ? $item->publish_start_date : null; @@ -377,8 +379,9 @@ public function index($item, $format = 'html') // Set up the variables we will need during processing. $count = 0; - // Mark afterLinking in the profiler. - static::$profiler ? static::$profiler->mark('afterLinking') : null; + if (static::$profiler) { + static::$profiler->mark('afterLinking'); + } // Truncate the tokens tables. $db->truncateTable('#__finder_tokens'); @@ -468,8 +471,9 @@ public function index($item, $format = 'html') } } - // Mark afterProcessing in the profiler. - static::$profiler ? static::$profiler->mark('afterProcessing') : null; + if (static::$profiler) { + static::$profiler->mark('afterProcessing'); + } /* * At this point, all of the item's content has been parsed, tokenized @@ -510,8 +514,9 @@ public function index($item, $format = 'html') $db->execute(); } - // Mark afterAggregating in the profiler. - static::$profiler ? static::$profiler->mark('afterAggregating') : null; + if (static::$profiler) { + static::$profiler->mark('afterAggregating'); + } /* * When we pulled down all of the aggregate data, we did a LEFT JOIN @@ -546,7 +551,7 @@ public function index($item, $format = 'html') ->innerJoin($db->quoteName('#__finder_terms', 't'), 't.term = ta.term AND t.language = ta.language') ->where('ta.term_id = 0'); - if ($serverType == 'mysql') { + if ($serverType === 'mysql') { $query->set($db->quoteName('ta.term_id') . ' = ' . $db->quoteName('t.term_id')); } else { $query->set($db->quoteName('term_id') . ' = ' . $db->quoteName('t.term_id')); @@ -555,8 +560,9 @@ public function index($item, $format = 'html') $db->setQuery($query); $db->execute(); - // Mark afterTerms in the profiler. - static::$profiler ? static::$profiler->mark('afterTerms') : null; + if (static::$profiler) { + static::$profiler->mark('afterTerms'); + } /* * After we've made sure that all of the terms are in the terms table @@ -567,7 +573,7 @@ public function index($item, $format = 'html') ->update($db->quoteName('#__finder_terms', 't')) ->innerJoin($db->quoteName('#__finder_tokens_aggregate', 'ta'), 'ta.term_id = t.term_id'); - if ($serverType == 'mysql') { + if ($serverType === 'mysql') { $query->set($db->quoteName('t.links') . ' = t.links + 1'); } else { $query->set($db->quoteName('links') . ' = t.links + 1'); @@ -576,8 +582,9 @@ public function index($item, $format = 'html') $db->setQuery($query); $db->execute(); - // Mark afterTerms in the profiler. - static::$profiler ? static::$profiler->mark('afterTerms') : null; + if (static::$profiler) { + static::$profiler->mark('afterTerms'); + } /* * At this point, the aggregate table contains a record for each @@ -599,8 +606,9 @@ public function index($item, $format = 'html') ); $db->execute(); - // Mark afterMapping in the profiler. - static::$profiler ? static::$profiler->mark('afterMapping') : null; + if (static::$profiler) { + static::$profiler->mark('afterMapping'); + } // Update the signature. $object = serialize($item); @@ -615,8 +623,9 @@ public function index($item, $format = 'html') $db->setQuery($query); $db->execute(); - // Mark afterSigning in the profiler. - static::$profiler ? static::$profiler->mark('afterSigning') : null; + if (static::$profiler) { + static::$profiler->mark('afterSigning'); + } // Truncate the tokens tables. $db->truncateTable('#__finder_tokens'); @@ -627,8 +636,9 @@ public function index($item, $format = 'html') // Toggle the token tables back to memory tables. $this->toggleTables(true); - // Mark afterTruncating in the profiler. - static::$profiler ? static::$profiler->mark('afterTruncating') : null; + if (static::$profiler) { + static::$profiler->mark('afterTruncating'); + } // Trigger a plugin event after indexing PluginHelper::importPlugin('finder'); @@ -774,7 +784,7 @@ public function optimize() ]; foreach ($tables as $table) { - if ($serverType == 'mysql') { + if ($serverType === 'mysql') { $db->setQuery('OPTIMIZE TABLE ' . $db->quoteName($table)); $db->execute(); } else { @@ -987,7 +997,7 @@ protected function toggleTables($memory) return true; } - if (strtolower($this->db->getServerType()) != 'mysql') { + if (strtolower($this->db->getServerType()) !== 'mysql') { $supported = false; return true; diff --git a/administrator/components/com_finder/src/Indexer/Language/El.php b/administrator/components/com_finder/src/Indexer/Language/El.php index a99a38178993c..31d55f710c7e3 100644 --- a/administrator/components/com_finder/src/Indexer/Language/El.php +++ b/administrator/components/com_finder/src/Indexer/Language/El.php @@ -669,7 +669,7 @@ public function stem($token) if ( (preg_match($exept18, $token) || preg_match($exept19, $token)) - && !(preg_match($exept17, $token) || preg_match($exept20, $token)) + && (!preg_match($exept17, $token) && !preg_match($exept20, $token)) ) { $token .= "ΑΓ"; } diff --git a/administrator/components/com_finder/src/Indexer/Query.php b/administrator/components/com_finder/src/Indexer/Query.php index 807ad2d550c09..c5ee6256a6194 100644 --- a/administrator/components/com_finder/src/Indexer/Query.php +++ b/administrator/components/com_finder/src/Indexer/Query.php @@ -207,8 +207,8 @@ class Query */ public function __construct($options, ?DatabaseInterface $db = null) { - if ($db === null) { - @trigger_error(\sprintf('Database will be mandatory in 5.0.'), E_USER_DEPRECATED); + if (!$db instanceof \Joomla\Database\DatabaseInterface) { + @trigger_error('Database will be mandatory in 5.0.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseInterface::class); } @@ -221,13 +221,13 @@ public function __construct($options, ?DatabaseInterface $db = null) $this->empty = !empty($options['empty']); // Get the input language. - $this->language = !empty($options['language']) ? $options['language'] : Helper::getDefaultLanguage(); + $this->language = empty($options['language']) ? Helper::getDefaultLanguage() : $options['language']; // Get the matching mode. $this->mode = 'AND'; // Set the word matching mode - $this->wordmode = !empty($options['word_match']) ? $options['word_match'] : 'exact'; + $this->wordmode = empty($options['word_match']) ? 'exact' : $options['word_match']; // Initialize the temporary date storage. $this->dates = new Registry(); @@ -286,7 +286,7 @@ public function __construct($options, ?DatabaseInterface $db = null) // Check if we have a query string. if (!empty($this->input)) { $this->search = true; - } elseif ($this->empty && (!empty($this->filter) || !empty($this->filters) || !empty($this->date1) || !empty($this->date2))) { + } elseif ($this->empty && (!empty($this->filter) || $this->filters !== [] || !empty($this->date1) || !empty($this->date2))) { // Check if we can search without a query string. $this->search = true; } else { @@ -418,7 +418,7 @@ public function getIncludedTermIds() // Iterate through the included tokens and compile the matching terms. foreach ($this->included as $item) { // Check if we have any terms. - if (empty($item->matches)) { + if ($item->matches === []) { continue; } @@ -537,12 +537,12 @@ protected function processStaticTaxonomy($filterId) $filters = ArrayHelper::toInteger($filters); // Remove any values of zero. - if (\in_array(0, $filters, true) !== false) { + if (\in_array(0, $filters, true)) { unset($filters[array_search(0, $filters, true)]); } // Check if we have any real input. - if (empty($filters)) { + if ($filters === []) { return true; } @@ -597,12 +597,12 @@ protected function processDynamicTaxonomy($filters) $filters = ArrayHelper::toInteger($filters); // Remove any values of zero. - if (\in_array(0, $filters, true) !== false) { + if (\in_array(0, $filters, true)) { unset($filters[array_search(0, $filters, true)]); } // Check if we have any real input. - if (empty($filters)) { + if ($filters === []) { return true; } @@ -871,7 +871,7 @@ protected function processString($input, $lang, $mode) $len = StringHelper::strlen($matches[0][$key]); // Add any terms that are before this phrase to the stack. - if (trim(StringHelper::substr($input, 0, $pos))) { + if (trim(StringHelper::substr($input, 0, $pos)) !== '' && trim(StringHelper::substr($input, 0, $pos)) !== '0') { $terms = array_merge($terms, explode(' ', trim(StringHelper::substr($input, 0, $pos)))); } @@ -892,7 +892,7 @@ protected function processString($input, $lang, $mode) $parts = \array_slice($parts, $tuplecount); // If the chunk is not empty, add it as a phrase. - if (\count($chunk)) { + if ($chunk !== []) { $phrases[] = implode(' ', $chunk); $terms[] = implode(' ', $chunk); } @@ -910,7 +910,7 @@ protected function processString($input, $lang, $mode) $chunk[] = array_shift($parts); // If the chunk is not empty, add it as a phrase. - if (\count($chunk)) { + if ($chunk !== []) { $phrases[] = implode(' ', $chunk); $terms[] = implode(' ', $chunk); } @@ -1292,7 +1292,7 @@ protected function getTokenData($token) } // If no matches were found, try to find a similar but better token. - if (empty($token->matches)) { + if ($token->matches === []) { // Create a database query to get the similar terms. $query->clear() ->select('DISTINCT t.term_id AS id, t.term AS term') diff --git a/administrator/components/com_finder/src/Indexer/Result.php b/administrator/components/com_finder/src/Indexer/Result.php index 6b8911227c968..b3b4f64de7182 100644 --- a/administrator/components/com_finder/src/Indexer/Result.php +++ b/administrator/components/com_finder/src/Indexer/Result.php @@ -395,7 +395,7 @@ public function getTaxonomy($branch = null) public function addTaxonomy($branch, $title, $state = 1, $access = 1, $language = '*') { // We can't add taxonomies with empty titles - if (!trim($title)) { + if (trim($title) === '' || trim($title) === '0') { return; } @@ -430,7 +430,7 @@ public function addTaxonomy($branch, $title, $state = 1, $access = 1, $language public function addNestedTaxonomy($branch, ImmutableNodeInterface $contentNode, $state = 1, $access = 1, $language = '*') { // We can't add taxonomies with empty titles - if (!trim($contentNode->title)) { + if (trim($contentNode->title) === '' || trim($contentNode->title) === '0') { return; } diff --git a/administrator/components/com_finder/src/Indexer/Taxonomy.php b/administrator/components/com_finder/src/Indexer/Taxonomy.php index e6e175c1dffde..929efcf413cae 100644 --- a/administrator/components/com_finder/src/Indexer/Taxonomy.php +++ b/administrator/components/com_finder/src/Indexer/Taxonomy.php @@ -286,7 +286,7 @@ public static function addMap($linkId, $nodeId) $db->execute(); $id = (int) $db->loadResult(); - if (!$id) { + if ($id === 0) { $map = new \stdClass(); $map->link_id = (int) $linkId; $map->node_id = (int) $nodeId; @@ -439,7 +439,7 @@ public static function removeOrphanNodes() $db->setQuery($query); $nodes = $db->loadColumn(); - if (!\count($nodes)) { + if (\count($nodes) === 0) { break; } diff --git a/administrator/components/com_finder/src/Indexer/Token.php b/administrator/components/com_finder/src/Indexer/Token.php index 73b64f2ef9a85..0ba2ffc688614 100644 --- a/administrator/components/com_finder/src/Indexer/Token.php +++ b/administrator/components/com_finder/src/Indexer/Token.php @@ -135,11 +135,7 @@ class Token */ public function __construct($term, $lang, $spacer = ' ') { - if (!$lang) { - $this->language = '*'; - } else { - $this->language = $lang; - } + $this->language = $lang ?: '*'; // Tokens can be a single word or an array of words representing a phrase. if (\is_array($term)) { @@ -179,7 +175,7 @@ public function __construct($term, $lang, $spacer = ' ') */ $this->weight = min($this->length, 15) / 15; $this->weight = $this->common === true ? $this->weight / 8 : $this->weight; - $this->weight = $this->numeric === true ? $this->weight * 1.5 : $this->weight; + $this->weight = $this->numeric ? $this->weight * 1.5 : $this->weight; $this->weight = round($this->weight, 4); } } diff --git a/administrator/components/com_finder/src/Model/SearchesModel.php b/administrator/components/com_finder/src/Model/SearchesModel.php index 9c7f02998cb63..a6f3c86ef0c59 100644 --- a/administrator/components/com_finder/src/Model/SearchesModel.php +++ b/administrator/components/com_finder/src/Model/SearchesModel.php @@ -140,11 +140,7 @@ public function getItems() $items = parent::getItems(); foreach ($items as $item) { - if (\is_resource($item->query)) { - $item->query = unserialize(stream_get_contents($item->query)); - } else { - $item->query = unserialize($item->query); - } + $item->query = \is_resource($item->query) ? unserialize(stream_get_contents($item->query)) : unserialize($item->query); } return $items; diff --git a/administrator/components/com_finder/src/Model/StatisticsModel.php b/administrator/components/com_finder/src/Model/StatisticsModel.php index 8845712b15b58..629044562271d 100644 --- a/administrator/components/com_finder/src/Model/StatisticsModel.php +++ b/administrator/components/com_finder/src/Model/StatisticsModel.php @@ -78,8 +78,9 @@ public function getData() $plugins = PluginHelper::getPlugin('finder'); foreach ($plugins as $plugin) { - $lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_ADMINISTRATOR) - || $lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_PLUGINS . '/finder/' . $plugin->name); + if (!$lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_PLUGINS . '/finder/' . $plugin->name); + } } return $data; diff --git a/administrator/components/com_finder/src/Response/Response.php b/administrator/components/com_finder/src/Response/Response.php index 39691a8520f84..e2bfa375c9483 100644 --- a/administrator/components/com_finder/src/Response/Response.php +++ b/administrator/components/com_finder/src/Response/Response.php @@ -170,8 +170,8 @@ public function __construct($state) $this->startTime = $state->startTime; $this->endTime = Factory::getDate()->toSql(); - $this->start = !empty($state->start) ? (int) $state->start : 0; - $this->complete = !empty($state->complete) ? (int) $state->complete : 0; + $this->start = empty($state->start) ? 0 : (int) $state->start; + $this->complete = empty($state->complete) ? 0 : (int) $state->complete; // Set the appropriate messages. if ($this->totalItems <= 0 && $this->complete) { diff --git a/administrator/components/com_finder/src/Service/HTML/Query.php b/administrator/components/com_finder/src/Service/HTML/Query.php index 2f2a6ffaafa50..4164d4c99586a 100644 --- a/administrator/components/com_finder/src/Service/HTML/Query.php +++ b/administrator/components/com_finder/src/Service/HTML/Query.php @@ -41,21 +41,21 @@ public static function explained(IndexerQuery $query) // Process the required tokens. foreach ($query->included as $token) { - if ($token->required && (!isset($token->derived) || $token->derived == false)) { + if ($token->required && ($token->derived === null || $token->derived == false)) { $parts[] = '' . Text::sprintf('COM_FINDER_QUERY_TOKEN_REQUIRED', $token->term) . ''; } } // Process the optional tokens. foreach ($query->included as $token) { - if (!$token->required && (!isset($token->derived) || $token->derived == false)) { + if (!$token->required && ($token->derived === null || $token->derived == false)) { $parts[] = '' . Text::sprintf('COM_FINDER_QUERY_TOKEN_OPTIONAL', $token->term) . ''; } } // Process the excluded tokens. foreach ($query->excluded as $token) { - if (!isset($token->derived) || $token->derived === false) { + if ($token->derived === null || $token->derived === false) { $parts[] = '' . Text::sprintf('COM_FINDER_QUERY_TOKEN_EXCLUDED', $token->term) . ''; } } @@ -75,7 +75,7 @@ public static function explained(IndexerQuery $query) } // Process the taxonomy filters. - if (!empty($query->filters)) { + if ($query->filters !== []) { // Get the filters in the request. $t = Factory::getApplication()->getInput()->request->get('t', [], 'array'); @@ -133,14 +133,14 @@ public static function suggested(IndexerQuery $query) // Replace the ignored keyword suggestions. foreach (array_reverse($query->ignored) as $token) { - if (isset($token->suggestion)) { + if ($token->suggestion !== null) { $suggested = str_ireplace($token->term, $token->suggestion, $suggested); } } // Replace the included keyword suggestions. foreach (array_reverse($query->included) as $token) { - if (isset($token->suggestion)) { + if ($token->suggestion !== null) { $suggested = str_ireplace($token->term, $token->suggestion, $suggested); } } diff --git a/administrator/components/com_finder/src/Table/FilterTable.php b/administrator/components/com_finder/src/Table/FilterTable.php index 6c352635379ab..3928dd93382a4 100644 --- a/administrator/components/com_finder/src/Table/FilterTable.php +++ b/administrator/components/com_finder/src/Table/FilterTable.php @@ -129,7 +129,7 @@ public function store($updateNulls = true) $userId = $this->getCurrentUser()->id; // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -142,7 +142,7 @@ public function store($updateNulls = true) $this->created_by = $userId; } - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $this->created; } diff --git a/administrator/components/com_finder/src/Table/MapTable.php b/administrator/components/com_finder/src/Table/MapTable.php index 9f3dada7cdcda..e87d0e59b97d6 100644 --- a/administrator/components/com_finder/src/Table/MapTable.php +++ b/administrator/components/com_finder/src/Table/MapTable.php @@ -63,7 +63,7 @@ public function check() } // Check for a title. - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_CATEGORY')); return false; @@ -71,7 +71,7 @@ public function check() $this->alias = ApplicationHelper::stringURLSafe($this->title, $this->language); - if (trim($this->alias) == '') { + if (trim($this->alias) === '') { $this->alias = md5(serialize($this->getProperties())); } diff --git a/administrator/components/com_finder/src/View/Filter/HtmlView.php b/administrator/components/com_finder/src/View/Filter/HtmlView.php index dc0cbebf16502..1d522b61544ba 100644 --- a/administrator/components/com_finder/src/View/Filter/HtmlView.php +++ b/administrator/components/com_finder/src/View/Filter/HtmlView.php @@ -128,7 +128,7 @@ protected function addToolbar() Factory::getApplication()->getInput()->set('hidemainmenu', true); $isNew = ($this->item->filter_id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $this->getCurrentUser()->id); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $this->getCurrentUser()->id; $canDo = ContentHelper::getActions('com_finder'); $toolbar = $this->getDocument()->getToolbar(); diff --git a/administrator/components/com_guidedtours/src/Controller/ToursController.php b/administrator/components/com_guidedtours/src/Controller/ToursController.php index 87d53b20806a0..7a1ab38c3d9f0 100644 --- a/administrator/components/com_guidedtours/src/Controller/ToursController.php +++ b/administrator/components/com_guidedtours/src/Controller/ToursController.php @@ -48,7 +48,7 @@ public function duplicate() $pks = (array) $this->input->post->get('cid', [], 'int'); $pks = array_filter($pks); try { - if (empty($pks)) { + if ($pks === []) { throw new \Exception(Text::_('COM_GUIDEDTOURS_ERROR_NO_GUIDEDTOURS_SELECTED')); } $model = $this->getModel(); diff --git a/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php b/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php index 004b94dac33fa..35837488ee349 100644 --- a/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php +++ b/administrator/components/com_guidedtours/src/Helper/GuidedtoursHelper.php @@ -84,11 +84,11 @@ public static function loadTranslationFiles($uid, bool $steps = false) break; } - $lang->load($extension . '.' . str_replace('-', '_', $tourid), JPATH_ADMINISTRATOR) - || $lang->load($extension . '.' . str_replace('-', '_', $tourid), $source); - if ($steps) { - $lang->load($extension . '.' . str_replace('-', '_', $tourid) . '_steps', JPATH_ADMINISTRATOR) - || $lang->load($extension . '.' . str_replace('-', '_', $tourid) . '_steps', $source); + if (!$lang->load($extension . '.' . str_replace('-', '_', $tourid), JPATH_ADMINISTRATOR)) { + $lang->load($extension . '.' . str_replace('-', '_', $tourid), $source); + } + if ($steps && !$lang->load($extension . '.' . str_replace('-', '_', $tourid) . '_steps', JPATH_ADMINISTRATOR)) { + $lang->load($extension . '.' . str_replace('-', '_', $tourid) . '_steps', $source); } } else { $lang->load('guidedtours.' . str_replace('-', '_', $uid), JPATH_ADMINISTRATOR); diff --git a/administrator/components/com_guidedtours/src/Model/StepModel.php b/administrator/components/com_guidedtours/src/Model/StepModel.php index 437abb1042a00..ba217b5a9406f 100644 --- a/administrator/components/com_guidedtours/src/Model/StepModel.php +++ b/administrator/components/com_guidedtours/src/Model/StepModel.php @@ -92,7 +92,7 @@ public function save($data) if ($pk > 0) { $table->load($pk); - if ((int) $table->tour_id) { + if ((int) $table->tour_id !== 0) { $data['tour_id'] = (int) $table->tour_id; } } @@ -258,7 +258,7 @@ public function getItem($pk = null) $tour = $tourModel->getItem($tourId); // Sets step language to parent tour language - $result->language = !empty($tour->language) ? $tour->language : '*'; + $result->language = empty($tour->language) ? '*' : $tour->language; // Set the step's tour id $result->tour_id = $tourId; diff --git a/administrator/components/com_guidedtours/src/Model/TourModel.php b/administrator/components/com_guidedtours/src/Model/TourModel.php index 0ab944a5dc228..361304ae6fb3f 100644 --- a/administrator/components/com_guidedtours/src/Model/TourModel.php +++ b/administrator/components/com_guidedtours/src/Model/TourModel.php @@ -198,16 +198,11 @@ protected function loadFormData() */ public function getItem($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id'); + $pk = (empty($pk)) ? (int) $this->getState($this->getName() . '.id') : $pk; $table = $this->getTable(); - if (\is_int($pk)) { - $result = $table->load((int) $pk); - } else { - // Attempt to load the row by uid. - $result = $table->load([ 'uid' => $pk ]); - } + $result = \is_int($pk) ? $table->load((int) $pk) : $table->load([ 'uid' => $pk ]); // Check for a table object error. if ($result === false) { @@ -547,7 +542,7 @@ public function isAutostart($pk): bool ->from($db->quoteName('#__guidedtours')) ->where($db->quoteName('published') . ' = 1'); - if (\is_integer($pk)) { + if (is_int($pk)) { $query->where($db->quoteName('id') . ' = :id') ->bind(':id', $pk, ParameterType::INTEGER); } else { diff --git a/administrator/components/com_guidedtours/src/Table/StepTable.php b/administrator/components/com_guidedtours/src/Table/StepTable.php index 777bacd8183b4..4b9296eebe505 100644 --- a/administrator/components/com_guidedtours/src/Table/StepTable.php +++ b/administrator/components/com_guidedtours/src/Table/StepTable.php @@ -89,7 +89,7 @@ public function store($updateNulls = true) $userId = $this->getCurrentUser()->id; // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -103,7 +103,7 @@ public function store($updateNulls = true) $this->created_by = $userId; } - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $date; } diff --git a/administrator/components/com_guidedtours/src/Table/TourTable.php b/administrator/components/com_guidedtours/src/Table/TourTable.php index 65c516e9efafa..044331b831e98 100644 --- a/administrator/components/com_guidedtours/src/Table/TourTable.php +++ b/administrator/components/com_guidedtours/src/Table/TourTable.php @@ -77,7 +77,7 @@ public function store($updateNulls = true) $userId = $this->getCurrentUser()->id; // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -91,7 +91,7 @@ public function store($updateNulls = true) $this->created_by = $userId; } - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $date; } diff --git a/administrator/components/com_guidedtours/src/View/Steps/HtmlView.php b/administrator/components/com_guidedtours/src/View/Steps/HtmlView.php index 101f7df659d47..661a1e9a1e160 100644 --- a/administrator/components/com_guidedtours/src/View/Steps/HtmlView.php +++ b/administrator/components/com_guidedtours/src/View/Steps/HtmlView.php @@ -139,7 +139,7 @@ protected function addToolbar() ->getMVCFactory()->createModel('Tour', 'Administrator', ['ignore_request' => true]); $tour = $tourModel->getItem($this->state->get('filter.tour_id', -1)); - $title = !empty($tour->title) ? $tour->title : ''; + $title = empty($tour->title) ? '' : $tour->title; ToolbarHelper::title(Text::sprintf('COM_GUIDEDTOURS_STEPS_LIST', Text::_($title)), 'map-signs'); $arrow = $this->getLanguage()->isRtl() ? 'arrow-right' : 'arrow-left'; diff --git a/administrator/components/com_installer/src/Controller/DatabaseController.php b/administrator/components/com_installer/src/Controller/DatabaseController.php index eb155cd60938a..91048ba1b25b6 100644 --- a/administrator/components/com_installer/src/Controller/DatabaseController.php +++ b/administrator/components/com_installer/src/Controller/DatabaseController.php @@ -48,7 +48,7 @@ public function fix() // Remove zero values resulting from input filter $cid = array_filter($cid); - if (empty($cid)) { + if ($cid === []) { $this->app->getLogger()->warning( Text::_( 'COM_INSTALLER_ERROR_NO_EXTENSIONS_SELECTED' diff --git a/administrator/components/com_installer/src/Controller/ManageController.php b/administrator/components/com_installer/src/Controller/ManageController.php index 27cb7b9cd4656..68f482ed39efd 100644 --- a/administrator/components/com_installer/src/Controller/ManageController.php +++ b/administrator/components/com_installer/src/Controller/ManageController.php @@ -71,7 +71,7 @@ public function publish() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->setMessage(Text::_('COM_INSTALLER_ERROR_NO_EXTENSIONS_SELECTED'), 'warning'); } else { /** @var ManageModel $model */ @@ -81,12 +81,7 @@ public function publish() if (!$model->publish($ids, $value)) { $this->setMessage(implode('
    ', $model->getErrors()), 'warning'); } else { - if ($value == 1) { - $ntext = 'COM_INSTALLER_N_EXTENSIONS_PUBLISHED'; - } else { - $ntext = 'COM_INSTALLER_N_EXTENSIONS_UNPUBLISHED'; - } - + $ntext = $value == 1 ? 'COM_INSTALLER_N_EXTENSIONS_PUBLISHED' : 'COM_INSTALLER_N_EXTENSIONS_UNPUBLISHED'; $this->setMessage(Text::plural($ntext, \count($ids))); } } @@ -113,7 +108,7 @@ public function remove() // Remove zero values resulting from input filter $eid = array_filter($eid); - if (!empty($eid)) { + if ($eid !== []) { /** @var ManageModel $model */ $model = $this->getModel('manage'); @@ -142,7 +137,7 @@ public function refresh() // Remove zero values resulting from input filter $uid = array_filter($uid); - if (!empty($uid)) { + if ($uid !== []) { /** @var ManageModel $model */ $model = $this->getModel('manage'); diff --git a/administrator/components/com_installer/src/Controller/UpdatesitesController.php b/administrator/components/com_installer/src/Controller/UpdatesitesController.php index 07f0271187b38..0e59661cf2bed 100644 --- a/administrator/components/com_installer/src/Controller/UpdatesitesController.php +++ b/administrator/components/com_installer/src/Controller/UpdatesitesController.php @@ -97,7 +97,7 @@ public function publish() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { throw new \Exception(Text::_('COM_INSTALLER_ERROR_NO_UPDATESITES_SELECTED'), 500); } @@ -136,7 +136,7 @@ public function delete() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { throw new \Exception(Text::_('COM_INSTALLER_ERROR_NO_UPDATESITES_SELECTED'), 500); } diff --git a/administrator/components/com_installer/src/Helper/InstallerHelper.php b/administrator/components/com_installer/src/Helper/InstallerHelper.php index 80be7c5fe4fa6..617db298b4b7e 100644 --- a/administrator/components/com_installer/src/Helper/InstallerHelper.php +++ b/administrator/components/com_installer/src/Helper/InstallerHelper.php @@ -91,13 +91,7 @@ public static function getExtensionGroups() */ public static function getClientOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '0', Text::_('JSITE')); - $options[] = HTMLHelper::_('select.option', '1', Text::_('JADMINISTRATOR')); - $options[] = HTMLHelper::_('select.option', '3', Text::_('JAPI')); - - return $options; + return [HTMLHelper::_('select.option', '0', Text::_('JSITE')), HTMLHelper::_('select.option', '1', Text::_('JADMINISTRATOR')), HTMLHelper::_('select.option', '3', Text::_('JAPI'))]; } /** @@ -109,14 +103,7 @@ public static function getClientOptions() */ public static function getStateOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '0', Text::_('JDISABLED')); - $options[] = HTMLHelper::_('select.option', '1', Text::_('JENABLED')); - $options[] = HTMLHelper::_('select.option', '2', Text::_('JPROTECTED')); - $options[] = HTMLHelper::_('select.option', '3', Text::_('JUNPROTECTED')); - - return $options; + return [HTMLHelper::_('select.option', '0', Text::_('JDISABLED')), HTMLHelper::_('select.option', '1', Text::_('JENABLED')), HTMLHelper::_('select.option', '2', Text::_('JPROTECTED')), HTMLHelper::_('select.option', '3', Text::_('JUNPROTECTED'))]; } /** @@ -246,14 +233,14 @@ public static function getDownloadKey(CMSObject $extension): array $extension->get('folder') ); - if (!$installXmlFile) { + if (!$installXmlFile instanceof \SimpleXMLElement) { return [ 'supported' => false, 'valid' => false, ]; } - if (!isset($installXmlFile->dlid)) { + if (!property_exists($installXmlFile, 'dlid') || $installXmlFile->dlid === null) { return [ 'supported' => false, 'valid' => false, @@ -264,7 +251,7 @@ public static function getDownloadKey(CMSObject $extension): array $suffix = (string) $installXmlFile->dlid['suffix']; $value = substr((string) $extension->get('extra_query'), \strlen($prefix)); - if ($suffix) { + if ($suffix !== '' && $suffix !== '0') { $value = substr($value, 0, -\strlen($suffix)); } diff --git a/administrator/components/com_installer/src/Model/DatabaseModel.php b/administrator/components/com_installer/src/Model/DatabaseModel.php index bc1ad0d3b719e..8f56f21b75401 100644 --- a/administrator/components/com_installer/src/Model/DatabaseModel.php +++ b/administrator/components/com_installer/src/Model/DatabaseModel.php @@ -176,7 +176,7 @@ private function fetchSchemaCache($cid = 0) $result->type === 'plugin' ? $result->folder : null ); - if ($installationXML !== null) { + if ($installationXML instanceof \SimpleXMLElement) { $folderTmp = (string) $installationXML->update->schemas->schemapath[0]; $a = explode('/', $folderTmp); array_pop($a); @@ -530,11 +530,7 @@ public function compareUpdateVersion($extension) */ private function getOtherInformationMessage($status) { - $problemsMessage = []; - $problemsMessage[] = Text::sprintf('COM_INSTALLER_MSG_DATABASE_CHECKED_OK', \count($status['ok'])); - $problemsMessage[] = Text::sprintf('COM_INSTALLER_MSG_DATABASE_SKIPPED', \count($status['skipped'])); - - return $problemsMessage; + return [Text::sprintf('COM_INSTALLER_MSG_DATABASE_CHECKED_OK', \count($status['ok'])), Text::sprintf('COM_INSTALLER_MSG_DATABASE_SKIPPED', \count($status['skipped']))]; } /** diff --git a/administrator/components/com_installer/src/Model/DiscoverModel.php b/administrator/components/com_installer/src/Model/DiscoverModel.php index 85f07f10172d1..281b9a752e189 100644 --- a/administrator/components/com_installer/src/Model/DiscoverModel.php +++ b/administrator/components/com_installer/src/Model/DiscoverModel.php @@ -120,12 +120,10 @@ protected function getListQuery() // Process search filter. $search = $this->getState('filter.search'); - if (!empty($search)) { - if (stripos((string) $search, 'id:') === 0) { - $ids = (int) substr((string) $search, 3); - $query->where($db->quoteName('extension_id') . ' = :eid') - ->bind(':eid', $ids, ParameterType::INTEGER); - } + if (!empty($search) && stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); + $query->where($db->quoteName('extension_id') . ' = :eid') + ->bind(':eid', $ids, ParameterType::INTEGER); } // Note: The search for name, ordering and pagination are processed by the parent InstallerModel class (in extension.php). diff --git a/administrator/components/com_installer/src/Model/InstallModel.php b/administrator/components/com_installer/src/Model/InstallModel.php index e302ff3c8262e..35e36cccd1219 100644 --- a/administrator/components/com_installer/src/Model/InstallModel.php +++ b/administrator/components/com_installer/src/Model/InstallModel.php @@ -182,21 +182,17 @@ public function install() if (isset($package['dir']) && is_dir($package['dir'])) { $installer->setPath('source', $package['dir']); - if (!$installer->findManifest()) { - // If a manifest isn't found at the source, this may be a Joomla package; check the package directory for the Joomla manifest - if (file_exists($package['dir'] . '/administrator/manifests/files/joomla.xml')) { - // We have a Joomla package - if (\in_array($installType, ['upload', 'url'])) { - InstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); - } - - $app->enqueueMessage( - Text::sprintf('COM_INSTALLER_UNABLE_TO_INSTALL_JOOMLA_PACKAGE', Route::_('index.php?option=com_joomlaupdate')), - 'warning' - ); - - return false; + // If a manifest isn't found at the source, this may be a Joomla package; check the package directory for the Joomla manifest + if (!$installer->findManifest() && file_exists($package['dir'] . '/administrator/manifests/files/joomla.xml')) { + // We have a Joomla package + if (\in_array($installType, ['upload', 'url'])) { + InstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); } + $app->enqueueMessage( + Text::sprintf('COM_INSTALLER_UNABLE_TO_INSTALL_JOOMLA_PACKAGE', Route::_('index.php?option=com_joomlaupdate')), + 'warning' + ); + return false; } } @@ -416,7 +412,7 @@ protected function _getPackageFromUrl() $update->loadFromXml($url); $package_url = trim($update->get('downloadurl', false)->_data); - if ($package_url) { + if ($package_url !== '' && $package_url !== '0') { $url = $package_url; } diff --git a/administrator/components/com_installer/src/Model/InstallerModel.php b/administrator/components/com_installer/src/Model/InstallerModel.php index 183eb62c4dd11..728113a120b08 100644 --- a/administrator/components/com_installer/src/Model/InstallerModel.php +++ b/administrator/components/com_installer/src/Model/InstallerModel.php @@ -107,7 +107,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) } // If search string was not found in any of the fields searched remove it from results array. - if (!$found) { + if ($found === 0) { unset($result[$i]); } } @@ -115,7 +115,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) // Process ordering. // Sort array object by selected ordering and selected direction. Sort is case insensitive and using locale sorting. - $result = ArrayHelper::sortObjects($result, $listOrder, strtolower((string) $listDirn) == 'desc' ? -1 : 1, false, true); + $result = ArrayHelper::sortObjects($result, $listOrder, strtolower((string) $listDirn) === 'desc' ? -1 : 1, false, true); // Process pagination. $total = \count($result); @@ -172,7 +172,9 @@ protected function translate(&$items) case 'component': $extension = $item->element; $source = JPATH_ADMINISTRATOR . '/components/' . $extension; - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", $source); + } break; case 'file': $extension = 'files_' . $item->element; @@ -191,17 +193,23 @@ protected function translate(&$items) case 'module': $extension = $item->element; $source = $path . '/modules/' . $extension; - $lang->load("$extension.sys", $path) || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", $path)) { + $lang->load("$extension.sys", $source); + } break; case 'plugin': $extension = 'plg_' . $item->folder . '_' . $item->element; $source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element; - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", $source); + } break; case 'template': $extension = 'tpl_' . $item->element; $source = $path . '/templates/' . $item->element; - $lang->load("$extension.sys", $path) || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", $path)) { + $lang->load("$extension.sys", $source); + } break; case 'package': default: @@ -213,9 +221,9 @@ protected function translate(&$items) // Translate the extension name if possible $item->name = Text::_($item->name); - settype($item->description, 'string'); + $item->description = (string) $item->description; - if (!\in_array($item->type, ['language'])) { + if ($item->type != 'language') { $item->description = Text::_($item->description); } } diff --git a/administrator/components/com_installer/src/Model/LanguagesModel.php b/administrator/components/com_installer/src/Model/LanguagesModel.php index 103741a67a6e6..83f750f5a7cd8 100644 --- a/administrator/components/com_installer/src/Model/LanguagesModel.php +++ b/administrator/components/com_installer/src/Model/LanguagesModel.php @@ -131,7 +131,7 @@ protected function getLanguages() if (empty($updateSite)) { Factory::getApplication()->enqueueMessage(Text::_('COM_INSTALLER_MSG_WARNING_NO_LANGUAGES_UPDATESERVER'), 'warning'); - return; + return null; } try { @@ -143,7 +143,7 @@ protected function getLanguages() if ($response === null || $response->code !== 200) { Factory::getApplication()->enqueueMessage(Text::sprintf('COM_INSTALLER_MSG_ERROR_CANT_CONNECT_TO_UPDATESERVER', $updateSite), 'error'); - return; + return null; } $updateSiteXML = simplexml_load_string($response->body); @@ -151,7 +151,7 @@ protected function getLanguages() if (!$updateSiteXML) { Factory::getApplication()->enqueueMessage(Text::sprintf('COM_INSTALLER_MSG_ERROR_CANT_RETRIEVE_XML', $updateSite), 'error'); - return; + return null; } $languages = []; @@ -164,13 +164,8 @@ protected function getLanguages() $language->$key = (string) $value; } - if ($search) { - if ( - !str_contains(strtolower($language->name), $search) - && !str_contains(strtolower($language->element), $search) - ) { - continue; - } + if ($search !== '' && $search !== '0' && (!str_contains(strtolower($language->name), $search) && !str_contains(strtolower($language->element), $search))) { + continue; } $languages[$language->name] = $language; diff --git a/administrator/components/com_installer/src/Model/UpdateModel.php b/administrator/components/com_installer/src/Model/UpdateModel.php index dd61954f0f809..0f4e451b81525 100644 --- a/administrator/components/com_installer/src/Model/UpdateModel.php +++ b/administrator/components/com_installer/src/Model/UpdateModel.php @@ -149,20 +149,18 @@ protected function getListQuery() $sid = (int) substr((string) $search, 4); $query->where($db->quoteName('u.extension_id') . ' = :sid') ->bind(':sid', $sid, ParameterType::INTEGER); + } elseif (stripos((string) $search, 'uid:') !== false) { + $suid = (int) substr((string) $search, 4); + $query->where($db->quoteName('u.update_site_id') . ' = :suid') + ->bind(':suid', $suid, ParameterType::INTEGER); + } elseif (stripos((string) $search, 'id:') !== false) { + $uid = (int) substr((string) $search, 3); + $query->where($db->quoteName('u.update_id') . ' = :uid') + ->bind(':uid', $uid, ParameterType::INTEGER); } else { - if (stripos((string) $search, 'uid:') !== false) { - $suid = (int) substr((string) $search, 4); - $query->where($db->quoteName('u.update_site_id') . ' = :suid') - ->bind(':suid', $suid, ParameterType::INTEGER); - } elseif (stripos((string) $search, 'id:') !== false) { - $uid = (int) substr((string) $search, 3); - $query->where($db->quoteName('u.update_id') . ' = :uid') - ->bind(':uid', $uid, ParameterType::INTEGER); - } else { - $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; - $query->where($db->quoteName('u.name') . ' LIKE :search') - ->bind(':search', $search); - } + $search = '%' . str_replace(' ', '%', trim((string) $search)) . '%'; + $query->where($db->quoteName('u.name') . ' LIKE :search') + ->bind(':search', $search); } } @@ -421,7 +419,7 @@ private function install($update) $sources = $update->get('downloadSources', []); if ($extra_query = $update->get('extra_query')) { - $url .= (!str_contains($url, '?')) ? '?' : '&'; + $url .= (str_contains($url, '?')) ? '&' : '?'; $url .= $extra_query; } @@ -432,7 +430,7 @@ private function install($update) $url = trim($name->url); if ($extra_query) { - $url .= (!str_contains($url, '?')) ? '?' : '&'; + $url .= (str_contains($url, '?')) ? '&' : '?'; $url .= $extra_query; } diff --git a/administrator/components/com_installer/src/Model/UpdatesitesModel.php b/administrator/components/com_installer/src/Model/UpdatesitesModel.php index 6dc50e798afc1..9d9ad44478183 100644 --- a/administrator/components/com_installer/src/Model/UpdatesitesModel.php +++ b/administrator/components/com_installer/src/Model/UpdatesitesModel.php @@ -351,7 +351,7 @@ public function rebuild(): void // Create a unique array of files ordered by priority $xmlfiles = array_unique(array_merge($parentXmlfiles, $allXmlFiles)); - if (!empty($xmlfiles)) { + if ($xmlfiles !== []) { foreach ($xmlfiles as $file) { // Is it a valid Joomla installation manifest file? $manifest = $tmpInstaller->isManifest($file); @@ -609,7 +609,7 @@ protected function getListQuery() break; } - if (!empty($supportedIDs)) { + if ($supportedIDs !== []) { // Don't remove array_values(). whereIn expect a zero-based array. $query->whereIn($db->quoteName('s.update_site_id'), array_values($supportedIDs)); } else { diff --git a/administrator/components/com_installer/src/View/Install/HtmlView.php b/administrator/components/com_installer/src/View/Install/HtmlView.php index 7d08d7a8dd57a..4c58dbbcbf867 100644 --- a/administrator/components/com_installer/src/View/Install/HtmlView.php +++ b/administrator/components/com_installer/src/View/Install/HtmlView.php @@ -27,6 +27,7 @@ */ class HtmlView extends InstallerViewDefault { + public $paths; /** * Display the view * diff --git a/administrator/components/com_installer/src/View/Languages/HtmlView.php b/administrator/components/com_installer/src/View/Languages/HtmlView.php index a0e6c4bf50257..4d72d5431d835 100644 --- a/administrator/components/com_installer/src/View/Languages/HtmlView.php +++ b/administrator/components/com_installer/src/View/Languages/HtmlView.php @@ -29,6 +29,10 @@ */ class HtmlView extends InstallerViewDefault { + /** + * @var mixed[] + */ + public $installedLang; /** * @var object item list */ diff --git a/administrator/components/com_installer/src/View/Update/HtmlView.php b/administrator/components/com_installer/src/View/Update/HtmlView.php index 8c061935d747a..7386420441352 100644 --- a/administrator/components/com_installer/src/View/Update/HtmlView.php +++ b/administrator/components/com_installer/src/View/Update/HtmlView.php @@ -29,6 +29,10 @@ */ class HtmlView extends InstallerViewDefault { + /** + * @var \stdClass + */ + public $paths; /** * List of update items. * diff --git a/administrator/components/com_installer/src/View/Updatesite/HtmlView.php b/administrator/components/com_installer/src/View/Updatesite/HtmlView.php index f0d61c526ce92..35038a5138a8f 100644 --- a/administrator/components/com_installer/src/View/Updatesite/HtmlView.php +++ b/administrator/components/com_installer/src/View/Updatesite/HtmlView.php @@ -101,7 +101,7 @@ protected function addToolbar(): void $user = $app->getIdentity(); $userId = $user->id; - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out === $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out !== $userId; // Since we don't track these assets at the item level, use the category id. $canDo = ContentHelper::getActions('com_installer', 'updatesite'); diff --git a/administrator/components/com_installer/src/View/Warnings/HtmlView.php b/administrator/components/com_installer/src/View/Warnings/HtmlView.php index f480472187ab0..6fb2bd95d4436 100644 --- a/administrator/components/com_installer/src/View/Warnings/HtmlView.php +++ b/administrator/components/com_installer/src/View/Warnings/HtmlView.php @@ -24,6 +24,7 @@ */ class HtmlView extends InstallerViewDefault { + public $messages; /** * Display the view * diff --git a/administrator/components/com_installer/tmpl/database/default.php b/administrator/components/com_installer/tmpl/database/default.php index dcbd008ce8c64..6ecf74284e399 100644 --- a/administrator/components/com_installer/tmpl/database/default.php +++ b/administrator/components/com_installer/tmpl/database/default.php @@ -97,7 +97,7 @@ type_translated; ?>
    - + - version) ? $item->version : ' '; ?> + version) ? ' ' : $item->version; ?> - creationDate) ? $item->creationDate : ' '; ?> + creationDate) ? ' ' : $item->creationDate; ?> - author) ? $item->author : ' '; ?> + author) ? ' ' : $item->author; ?> folder_translated; ?> diff --git a/administrator/components/com_installer/tmpl/manage/default.php b/administrator/components/com_installer/tmpl/manage/default.php index 4cc7f0640fa6b..7b3d240f1acad 100644 --- a/administrator/components/com_installer/tmpl/manage/default.php +++ b/administrator/components/com_installer/tmpl/manage/default.php @@ -151,7 +151,7 @@ - author) ? $item->author : ' '; ?> + author) ? ' ' : $item->author; ?> folder_translated; ?> diff --git a/administrator/components/com_installer/tmpl/warnings/default.php b/administrator/components/com_installer/tmpl/warnings/default.php index 95c6ab8123892..a0456b199b619 100644 --- a/administrator/components/com_installer/tmpl/warnings/default.php +++ b/administrator/components/com_installer/tmpl/warnings/default.php @@ -21,7 +21,7 @@
    - messages)) : ?> + messages) > 0) : ?> messages as $message) : ?>

    diff --git a/administrator/components/com_joomlaupdate/extract.php b/administrator/components/com_joomlaupdate/extract.php index 460bd36738bfe..0683ce62f90c5 100644 --- a/administrator/components/com_joomlaupdate/extract.php +++ b/administrator/components/com_joomlaupdate/extract.php @@ -567,7 +567,7 @@ public function enforceMinimumExecutionTime() public function setFilename(string $value) { // Security check: disallow remote filenames - if (!empty($value) && str_contains($value, '://')) { + if ($value !== '' && $value !== '0' && str_contains($value, '://')) { $this->setError('Invalid archive location'); return; @@ -591,7 +591,7 @@ public function setAddPath(string $addPath): void $this->addPath = str_replace('\\', '/', $this->addPath); $this->addPath = rtrim($this->addPath, '/'); - if (!empty($this->addPath)) { + if ($this->addPath !== '' && $this->addPath !== '0') { $this->addPath .= '/'; } } @@ -638,7 +638,7 @@ public function initialize(): void $this->readArchiveHeader(); - if (!empty($this->getError())) { + if (!in_array($this->getError(), [null, '', '0'], true)) { $this->debugMsg(\sprintf('Error: %s', $this->getError()), self::LOG_ERROR); return; @@ -727,12 +727,12 @@ public function step(): bool $error = $this->getError(); - if (!empty($error)) { + if ($error !== null && $error !== '' && $error !== '0') { $this->debugMsg(\sprintf('Step failed with error: %s', $error), self::LOG_ERROR); } // Did we just finish or run into an error? - if (!empty($error) || $this->runState === self::AK_STATE_FINISHED) { + if ($error !== null && $error !== '' && $error !== '0' || $this->runState === self::AK_STATE_FINISHED) { $this->debugMsg('Returning true (must stop running) from step()', self::LOG_DEBUG); // Reset internal state, prevents __wakeup from trying to open a non-existent file @@ -1002,7 +1002,7 @@ private function readFileHeader(): bool $headerData = unpack($format, $headerBinary); // Check signature - if (!($headerData['sig'] == 0x04034b50)) { + if ($headerData['sig'] != 0x04034b50) { // The signature is not the one used for files. Is this a central directory record (i.e. we're done)? if ($headerData['sig'] == 0x02014b50) { $this->debugMsg('Found Central Directory header; the extraction is complete', self::LOG_DEBUG); @@ -1083,7 +1083,7 @@ private function readFileHeader(): bool } // Find hard-coded banned files - if ((basename($this->fileHeader->file) == ".") || (basename($this->fileHeader->file) == "..")) { + if ((basename($this->fileHeader->file) === ".") || (basename($this->fileHeader->file) === "..")) { $isBannedFile = true; } @@ -1128,10 +1128,10 @@ private function readFileHeader(): bool } // Get the translated path name - if ($this->fileHeader->type == 'file') { + if ($this->fileHeader->type === 'file') { $this->fileHeader->realFile = $this->fileHeader->file; $this->setLastExtractedFilename($this->fileHeader->file); - } elseif ($this->fileHeader->type == 'dir') { + } elseif ($this->fileHeader->type === 'dir') { $this->fileHeader->timestamp = 0; $dir = $this->fileHeader->file; @@ -1354,14 +1354,11 @@ private function processTypeLink(): bool $data .= $mydata; $leftBytes -= $reallyReadBytes; - if ($reallyReadBytes < $toReadBytes) { - // We read less than requested! - if ($this->isEOF()) { - $this->debugMsg('EOF when reading symlink data', self::LOG_WARNING); - $this->setError('The archive file is corrupt or truncated'); - - return false; - } + // We read less than requested! + if ($reallyReadBytes < $toReadBytes && $this->isEOF()) { + $this->debugMsg('EOF when reading symlink data', self::LOG_WARNING); + $this->setError('The archive file is corrupt or truncated'); + return false; } } @@ -1443,22 +1440,19 @@ private function processTypeFileUncompressed(): bool $leftBytes -= $reallyReadBytes; $this->dataReadLength += $reallyReadBytes; - if ($reallyReadBytes < $toReadBytes) { - // We read less than requested! Why? Did we hit local EOF? - if ($this->isEOF()) { - // Nope. The archive is corrupt - $this->debugMsg('EOF when reading stored file data', self::LOG_WARNING); - $this->setError('The archive file is corrupt or truncated'); - - return false; - } + // We read less than requested! Why? Did we hit local EOF? + if ($reallyReadBytes < $toReadBytes && $this->isEOF()) { + // Nope. The archive is corrupt + $this->debugMsg('EOF when reading stored file data', self::LOG_WARNING); + $this->setError('The archive file is corrupt or truncated'); + return false; } if (\is_resource($outfp)) { @fwrite($outfp, $data); } - if ($this->getTimeLeft()) { + if ($this->getTimeLeft() !== 0.0) { $this->debugMsg('Out of time; will resume extraction in the next step', self::LOG_DEBUG); } } @@ -1610,7 +1604,7 @@ private function getPhpMaxExecTime(): int } $phpMaxTime = @\ini_get("maximum_execution_time"); - $phpMaxTime = (!is_numeric($phpMaxTime) ? 10 : @\intval($phpMaxTime)) ?: 10; + $phpMaxTime = (is_numeric($phpMaxTime) ? @\intval($phpMaxTime) : 10) ?: 10; return max(1, $phpMaxTime); } @@ -1737,7 +1731,7 @@ function timingSafeEquals($known, $user) $safeLen = \strlen($known); $userLen = \strlen($user); - if ($userLen != $safeLen) { + if ($userLen !== $safeLen) { return false; } @@ -1814,9 +1808,9 @@ function getConfiguration(): ?array */ $password = $extractionSetup['security.password'] ?? null; $userPassword = $_REQUEST['password'] ?? ''; - $userPassword = !\is_string($userPassword) ? '' : trim($userPassword); + $userPassword = \is_string($userPassword) ? trim($userPassword) : ''; - if (empty($password) || !\is_string($password) || (trim($password) == '') || (\strlen(trim($password)) < 32)) { + if (empty($password) || !\is_string($password) || (trim($password) === '') || (\strlen(trim($password)) < 32)) { return null; } @@ -1828,7 +1822,7 @@ function getConfiguration(): ?array // An "instance" variable will resume the engine from the serialised instance $serialized = $_REQUEST['instance'] ?? null; - if (!\is_null($serialized) && empty(ZIPExtraction::unserialiseInstance($serialized))) { + if (!\is_null($serialized) && !ZIPExtraction::unserialiseInstance($serialized) instanceof \ZIPExtraction) { // The serialised instance is corrupt or someone tries to trick us. YOU SHALL NOT PASS! return null; } @@ -1843,7 +1837,7 @@ function getConfiguration(): ?array ]; $configuration = getConfiguration(); -$enabled = !empty($configuration); +$enabled = $configuration !== null && $configuration !== []; /** * Sets the PHP timeout to 3600 seconds @@ -1884,7 +1878,7 @@ function setHugeMemoryLimit() $sourceFile = $configuration['setup.sourcefile'] ?? ''; $destDir = ($configuration['setup.destdir'] ?? null) ?: __DIR__; $basePath = rtrim(str_replace('\\', '/', __DIR__), '/'); - $basePath = empty($basePath) ? $basePath : ($basePath . '/'); + $basePath = $basePath === '' || $basePath === '0' ? $basePath : ($basePath . '/'); $sourceFile = (empty($sourcePath) ? '' : (rtrim((string) $sourcePath, '/\\') . '/')) . $sourceFile; $engine = ZIPExtraction::getInstance(); diff --git a/administrator/components/com_joomlaupdate/src/Controller/UpdateController.php b/administrator/components/com_joomlaupdate/src/Controller/UpdateController.php index ca3fb0c7cf65c..4a4a620115498 100644 --- a/administrator/components/com_joomlaupdate/src/Controller/UpdateController.php +++ b/administrator/components/com_joomlaupdate/src/Controller/UpdateController.php @@ -511,19 +511,13 @@ public function fetchExtensionCompatibility() array_intersect($upgradeCompatibilityStatus->compatibleVersions, $currentCompatibilityStatus->compatibleVersions) ); - if (!empty($bothCompatibleVersions)) { + if ($bothCompatibleVersions !== []) { $upgradeOldestVersion = $bothCompatibleVersions[0]; $upgradeUpdateVersion = end($bothCompatibleVersions); } } - if (version_compare($upgradeOldestVersion, $extensionVersion, '>')) { - // Installed version is empty or older than the oldest compatible update: Update required - $resultGroup = 2; - } else { - // Current version is compatible - $resultGroup = 3; - } + $resultGroup = version_compare($upgradeOldestVersion, $extensionVersion, '>') ? 2 : 3; if ($currentUpdateVersion !== false && version_compare($upgradeUpdateVersion, $currentUpdateVersion, '<')) { // Special case warning when version compatible with target is lower than current @@ -624,19 +618,13 @@ public function batchextensioncompatibility() array_intersect($upgradeCompatibilityStatus->compatibleVersions, $currentCompatibilityStatus->compatibleVersions) ); - if (!empty($bothCompatibleVersions)) { + if ($bothCompatibleVersions !== []) { $upgradeOldestVersion = $bothCompatibleVersions[0]; $upgradeUpdateVersion = end($bothCompatibleVersions); } } - if (version_compare($upgradeOldestVersion, $extensionVersion, '>')) { - // Installed version is empty or older than the oldest compatible update: Update required - $resultGroup = 2; - } else { - // Current version is compatible - $resultGroup = 3; - } + $resultGroup = version_compare($upgradeOldestVersion, $extensionVersion, '>') ? 2 : 3; if ($currentUpdateVersion !== false && version_compare($upgradeUpdateVersion, $currentUpdateVersion, '<')) { // Special case warning when version compatible with target is lower than current diff --git a/administrator/components/com_joomlaupdate/src/Model/UpdateModel.php b/administrator/components/com_joomlaupdate/src/Model/UpdateModel.php index abd5e966757f0..35f5f4f581cde 100644 --- a/administrator/components/com_joomlaupdate/src/Model/UpdateModel.php +++ b/administrator/components/com_joomlaupdate/src/Model/UpdateModel.php @@ -94,7 +94,7 @@ public function applyUpdateSite() case 'custom': // "Custom" // @todo: check if the customurl is valid and not just "not empty". - if (trim((string) $params->get('customurl', '')) != '') { + if (trim((string) $params->get('customurl', '')) !== '') { $updateURL = trim((string) $params->get('customurl', '')); } else { Factory::getApplication()->enqueueMessage(Text::_('COM_JOOMLAUPDATE_CONFIG_UPDATESOURCE_CUSTOM_ERROR'), 'error'); @@ -436,7 +436,7 @@ public function download() // Is it a 0-byte file? If so, re-download please. $filesize = @filesize($target); - if (empty($filesize)) { + if ($filesize === 0 || $filesize === false) { $mirror = 0; while (!($download = $this->downloadPackage($packageURL, $target)) && isset($sources[$mirror])) { @@ -859,7 +859,7 @@ public function finaliseUpgrade() return false; } - if ($msg) { + if ($msg !== '' && $msg !== '0') { $installer->set('extension_message', $msg); } @@ -1023,7 +1023,7 @@ public function captiveLogin($credentials) $username = $credentials['username'] ?? null; $user = $this->getCurrentUser(); - if (strtolower($user->username) != strtolower((string) $username)) { + if (strtolower($user->username) !== strtolower((string) $username)) { return false; } @@ -1035,12 +1035,7 @@ public function captiveLogin($credentials) // Get the global Authentication object. $authenticate = Authentication::getInstance(); $response = $authenticate->authenticate($credentials); - - if ($response->status !== Authentication::STATUS_SUCCESS) { - return false; - } - - return true; + return $response->status === Authentication::STATUS_SUCCESS; } /** @@ -1053,12 +1048,7 @@ public function captiveLogin($credentials) public function captiveFileExists() { $file = Factory::getApplication()->getUserState('com_joomlaupdate.temp_file', null); - - if (empty($file) || !is_file($file)) { - return false; - } - - return true; + return !empty($file) && is_file($file); } /** @@ -1317,7 +1307,7 @@ public function getIniParserAvailability() { $disabledFunctions = \ini_get('disable_functions'); - if (!empty($disabledFunctions)) { + if (!($disabledFunctions === '' || $disabledFunctions === '0' || $disabledFunctions === false)) { // Attempt to detect them in the PHP INI disable_functions variable. $disabledFunctions = explode(',', trim($disabledFunctions)); @@ -1375,14 +1365,9 @@ private function getDatabaseSchemaCheck(): bool if ($changeInformation['errorsCount'] !== 0) { return false; } - // Check if database schema version does not match CMS version - if ($model->getSchemaVersion($coreExtensionInfo->extension_id) != $changeInformation['schema']) { - return false; - } - // No database problems found - return true; + return $model->getSchemaVersion($coreExtensionInfo->extension_id) == $changeInformation['schema']; } /** @@ -1710,10 +1695,12 @@ protected function translateExtensionName(&$item) $source = $path . '/templates/' . $item->element; } - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) - || $lang->load("$extension.sys", $source); - $lang->load($extension, JPATH_ADMINISTRATOR) - || $lang->load($extension, $source); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", $source); + } + if (!$lang->load($extension, JPATH_ADMINISTRATOR)) { + $lang->load($extension, $source); + } // Translate the extension name if possible $item->name = strip_tags(Text::_($item->name)); @@ -1913,7 +1900,7 @@ private function checkPackageFileNoZip(string $filePath, $packageName) // Look for installation/index.php while (($pos = strpos($fileChunk, 'installation/index.php', $offset)) !== false) { // Check if entry is a central directory file header and the file name is exactly 22 bytes long - if (substr($fileChunk, $pos - 46, 4) == $headerSignature && substr($fileChunk, $pos - 18, 2) == $sizeSignatureIndexPhp) { + if (substr($fileChunk, $pos - 46, 4) === $headerSignature && substr($fileChunk, $pos - 18, 2) === $sizeSignatureIndexPhp) { @fclose($fp); throw new \RuntimeException(Text::sprintf('COM_JOOMLAUPDATE_VIEW_UPLOAD_ERROR_INSTALL_PACKAGE', $packageName), 500); @@ -1927,7 +1914,7 @@ private function checkPackageFileNoZip(string $filePath, $packageName) // Look for administrator/manifests/files/joomla.xml if not found yet while ($headerInfo === false && ($pos = strpos($fileChunk, 'administrator/manifests/files/joomla.xml', $offset)) !== false) { // Check if entry is inside a ZIP central directory header and the file name is exactly 40 bytes long - if (substr($fileChunk, $pos - 46, 4) == $headerSignature && substr($fileChunk, $pos - 18, 2) == $sizeSignatureJoomlaXml) { + if (substr($fileChunk, $pos - 46, 4) === $headerSignature && substr($fileChunk, $pos - 18, 2) === $sizeSignatureJoomlaXml) { $headerInfo = unpack('VOffset', substr($fileChunk, $pos - 4, 4)); break; @@ -2028,7 +2015,7 @@ private function checkManifestXML(string $manifest, $packageName) $versionPackage = (string) $manifestXml->version ?: ''; - if (!$versionPackage) { + if ($versionPackage === '' || $versionPackage === '0') { throw new \RuntimeException(Text::sprintf('COM_JOOMLAUPDATE_VIEW_UPLOAD_ERROR_NO_VERSION_FOUND', $packageName), 500); } diff --git a/administrator/components/com_joomlaupdate/src/View/Joomlaupdate/HtmlView.php b/administrator/components/com_joomlaupdate/src/View/Joomlaupdate/HtmlView.php index 72db5813aa7f0..f65625d4b474d 100644 --- a/administrator/components/com_joomlaupdate/src/View/Joomlaupdate/HtmlView.php +++ b/administrator/components/com_joomlaupdate/src/View/Joomlaupdate/HtmlView.php @@ -29,6 +29,14 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var string + */ + public $langKey; + /** + * @var string + */ + public $updateSourceKey; /** * An array with the Joomla! update information. * diff --git a/administrator/components/com_joomlaupdate/tmpl/joomlaupdate/preupdatecheck.php b/administrator/components/com_joomlaupdate/tmpl/joomlaupdate/preupdatecheck.php index 8abd7a5efa2e7..3aeb09ce2a300 100644 --- a/administrator/components/com_joomlaupdate/tmpl/joomlaupdate/preupdatecheck.php +++ b/administrator/components/com_joomlaupdate/tmpl/joomlaupdate/preupdatecheck.php @@ -120,7 +120,7 @@ - +

    id, false, 'cid', 'cb', $item->title); ?> items as $i => $item) : ?> language && $multilang) { - if ($item->language !== '*') { - $language = $item->language; - } + if ($item->language && $multilang && $item->language !== '*') { + $language = $item->language; } $link = 'index.php?Itemid=' . $item->id; diff --git a/administrator/components/com_menus/tmpl/menus/default.php b/administrator/components/com_menus/tmpl/menus/default.php index 997c551a7fec2..394a7369c8c20 100644 --- a/administrator/components/com_menus/tmpl/menus/default.php +++ b/administrator/components/com_menus/tmpl/menus/default.php @@ -237,7 +237,7 @@ - + menutype, false); ?>
    diff --git a/administrator/components/com_plugins/src/Helper/PluginsHelper.php b/administrator/components/com_plugins/src/Helper/PluginsHelper.php index a32bea364ed84..7efd26ff37694 100644 --- a/administrator/components/com_plugins/src/Helper/PluginsHelper.php +++ b/administrator/components/com_plugins/src/Helper/PluginsHelper.php @@ -36,12 +36,7 @@ class PluginsHelper */ public static function publishedOptions() { - // Build the active state filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '1', 'JENABLED'); - $options[] = HTMLHelper::_('select.option', '0', 'JDISABLED'); - - return $options; + return [HTMLHelper::_('select.option', '1', 'JENABLED'), HTMLHelper::_('select.option', '0', 'JDISABLED')]; } /** diff --git a/administrator/components/com_plugins/src/Model/PluginModel.php b/administrator/components/com_plugins/src/Model/PluginModel.php index c12192d5dbd91..aaa7dc9955da7 100644 --- a/administrator/components/com_plugins/src/Model/PluginModel.php +++ b/administrator/components/com_plugins/src/Model/PluginModel.php @@ -157,7 +157,7 @@ protected function loadFormData() */ public function getItem($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('plugin.id'); + $pk = (empty($pk)) ? (int) $this->getState('plugin.id') : $pk; $cacheId = $pk; @@ -188,11 +188,7 @@ public function getItem($pk = null) // Get the plugin XML. $path = Path::clean(JPATH_PLUGINS . '/' . $table->folder . '/' . $table->element . '/' . $table->element . '.xml'); - if (file_exists($path)) { - $this->_cache[$cacheId]->xml = simplexml_load_file($path); - } else { - $this->_cache[$cacheId]->xml = null; - } + $this->_cache[$cacheId]->xml = file_exists($path) ? simplexml_load_file($path) : null; } return $this->_cache[$cacheId]; @@ -264,8 +260,9 @@ protected function preprocessForm(Form $form, $data, $group = 'content') $elements = $db->loadColumn(); foreach ($elements as $elementa) { - $lang->load('plg_' . $folder . '_' . $elementa . '.sys', JPATH_ADMINISTRATOR) - || $lang->load('plg_' . $folder . '_' . $elementa . '.sys', JPATH_PLUGINS . '/' . $folder . '/' . $elementa); + if (!$lang->load('plg_' . $folder . '_' . $elementa . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load('plg_' . $folder . '_' . $elementa . '.sys', JPATH_PLUGINS . '/' . $folder . '/' . $elementa); + } } if (empty($folder) || empty($element)) { @@ -280,14 +277,13 @@ protected function preprocessForm(Form $form, $data, $group = 'content') } // Load the core and/or local language file(s). - $lang->load('plg_' . $folder . '_' . $element, JPATH_ADMINISTRATOR) - || $lang->load('plg_' . $folder . '_' . $element, JPATH_PLUGINS . '/' . $folder . '/' . $element); + if (!$lang->load('plg_' . $folder . '_' . $element, JPATH_ADMINISTRATOR)) { + $lang->load('plg_' . $folder . '_' . $element, JPATH_PLUGINS . '/' . $folder . '/' . $element); + } - if (file_exists($formFile)) { - // Get the plugin form. - if (!$form->loadFile($formFile, false, '//config')) { - throw new \Exception(Text::_('JERROR_LOADFILE_FAILED')); - } + // Get the plugin form. + if (file_exists($formFile) && !$form->loadFile($formFile, false, '//config')) { + throw new \Exception(Text::_('JERROR_LOADFILE_FAILED')); } // Attempt to load the xml file. diff --git a/administrator/components/com_plugins/src/Model/PluginsModel.php b/administrator/components/com_plugins/src/Model/PluginsModel.php index 8fad3b41970b0..fd7878df2cbda 100644 --- a/administrator/components/com_plugins/src/Model/PluginsModel.php +++ b/administrator/components/com_plugins/src/Model/PluginsModel.php @@ -142,7 +142,7 @@ protected function _getList($query, $limitstart = 0, $limit = 0) } $orderingDirection = strtolower((string) $this->getState('list.direction')); - $direction = ($orderingDirection == 'desc') ? -1 : 1; + $direction = ($orderingDirection === 'desc') ? -1 : 1; $result = ArrayHelper::sortObjects($result, $ordering, $direction, true, true); $total = \count($result); @@ -188,8 +188,9 @@ protected function translate(&$items) foreach ($items as &$item) { $source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element; $extension = 'plg_' . $item->folder . '_' . $item->element; - $lang->load($extension . '.sys', JPATH_ADMINISTRATOR) - || $lang->load($extension . '.sys', $source); + if (!$lang->load($extension . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load($extension . '.sys', $source); + } $item->name = Text::_($item->name); } } @@ -260,12 +261,10 @@ protected function getListQuery() // Filter by search in name or id. $search = $this->getState('filter.search'); - if (!empty($search)) { - if (stripos((string) $search, 'id:') === 0) { - $ids = (int) substr((string) $search, 3); - $query->where($db->quoteName('a.extension_id') . ' = :id'); - $query->bind(':id', $ids, ParameterType::INTEGER); - } + if (!empty($search) && stripos((string) $search, 'id:') === 0) { + $ids = (int) substr((string) $search, 3); + $query->where($db->quoteName('a.extension_id') . ' = :id'); + $query->bind(':id', $ids, ParameterType::INTEGER); } return $query; diff --git a/administrator/components/com_plugins/tmpl/plugin/edit.php b/administrator/components/com_plugins/tmpl/plugin/edit.php index f86981d307194..e0057e39e35e7 100644 --- a/administrator/components/com_plugins/tmpl/plugin/edit.php +++ b/administrator/components/com_plugins/tmpl/plugin/edit.php @@ -48,7 +48,7 @@

    item->xml) { - echo ($text = (string) $this->item->xml->name) ? Text::_($text) : $this->item->name; + echo ($text = (string) $this->item->xml->name !== '' && $text = (string) $this->item->xml->name !== '0') ? Text::_($text) : $this->item->name; } else { echo Text::_('COM_PLUGINS_XML_ERR'); } diff --git a/administrator/components/com_postinstall/src/Controller/MessageController.php b/administrator/components/com_postinstall/src/Controller/MessageController.php index eea4f229c6573..3320147ba93a3 100644 --- a/administrator/components/com_postinstall/src/Controller/MessageController.php +++ b/administrator/components/com_postinstall/src/Controller/MessageController.php @@ -66,7 +66,7 @@ public function unpublish() $eid = (int) $model->getState('eid', $model->getJoomlaFilesExtensionId()); - if (empty($eid)) { + if ($eid === 0) { $eid = $model->getJoomlaFilesExtensionId(); } @@ -93,7 +93,7 @@ public function republish() $eid = (int) $model->getState('eid', $model->getJoomlaFilesExtensionId()); - if (empty($eid)) { + if ($eid === 0) { $eid = $model->getJoomlaFilesExtensionId(); } @@ -120,7 +120,7 @@ public function archive() $eid = (int) $model->getState('eid', $model->getJoomlaFilesExtensionId()); - if (empty($eid)) { + if ($eid === 0) { $eid = $model->getJoomlaFilesExtensionId(); } diff --git a/administrator/components/com_postinstall/src/Model/MessagesModel.php b/administrator/components/com_postinstall/src/Model/MessagesModel.php index ccf4b1b0e4542..42331ec392b85 100644 --- a/administrator/components/com_postinstall/src/Model/MessagesModel.php +++ b/administrator/components/com_postinstall/src/Model/MessagesModel.php @@ -49,7 +49,7 @@ protected function populateState() $eid = (int) Factory::getApplication()->getInput()->getInt('eid'); - if ($eid) { + if ($eid !== 0) { $this->setState('eid', $eid); } } @@ -435,7 +435,7 @@ protected function onProcessList(&$resultArray) } } - if (!empty($unset_keys)) { + if ($unset_keys !== []) { foreach ($unset_keys as $key) { unset($resultArray[$key]); } @@ -571,7 +571,7 @@ public function addPostInstallationMessage(array $options) $allKeys = array_keys($options); $extraKeys = array_diff($allKeys, $defaultKeys); - if (!empty($extraKeys)) { + if ($extraKeys !== []) { foreach ($extraKeys as $key) { unset($options[$key]); } @@ -588,7 +588,7 @@ public function addPostInstallationMessage(array $options) } // Make sure there's an extension_id - if (!(int) $options['extension_id']) { + if ((int) $options['extension_id'] === 0) { throw new \Exception('Post-installation message definitions need an extension_id', 500); } @@ -635,10 +635,8 @@ public function addPostInstallationMessage(array $options) } } - if ($options['type'] == 'link') { - if (empty($options['link'])) { - throw new \Exception('Post-installation message definitions need an action (URL) when they are of type "link"', 500); - } + if ($options['type'] == 'link' && empty($options['link'])) { + throw new \Exception('Post-installation message definitions need an action (URL) when they are of type "link"', 500); } // The condition file and method are only required when the type is not "message" diff --git a/administrator/components/com_postinstall/src/View/Messages/HtmlView.php b/administrator/components/com_postinstall/src/View/Messages/HtmlView.php index a9c596c63c491..28d7d33bb5e94 100644 --- a/administrator/components/com_postinstall/src/View/Messages/HtmlView.php +++ b/administrator/components/com_postinstall/src/View/Messages/HtmlView.php @@ -27,6 +27,19 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var int + */ + public $joomlaFilesExtensionId; + public $eid; + /** + * @var string + */ + public $token; + /** + * @var mixed[] + */ + public $extension_options; /** * An array of items * @@ -59,7 +72,7 @@ public function display($tpl = null) $this->joomlaFilesExtensionId = $model->getJoomlaFilesExtensionId(); $this->eid = (int) $model->getState('eid', $this->joomlaFilesExtensionId); - if (empty($this->eid)) { + if ($this->eid === 0) { $this->eid = $this->joomlaFilesExtensionId; } diff --git a/administrator/components/com_privacy/src/Controller/ConsentsController.php b/administrator/components/com_privacy/src/Controller/ConsentsController.php index 2987fa43ce9c3..dac552082a041 100644 --- a/administrator/components/com_privacy/src/Controller/ConsentsController.php +++ b/administrator/components/com_privacy/src/Controller/ConsentsController.php @@ -44,7 +44,7 @@ public function invalidate() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('JERROR_NO_ITEMS_SELECTED'), CMSApplication::MSG_ERROR); } else { /** @var ConsentsModel $model */ diff --git a/administrator/components/com_privacy/src/Controller/RequestController.php b/administrator/components/com_privacy/src/Controller/RequestController.php index ab792bead43ce..089d4cd08d596 100644 --- a/administrator/components/com_privacy/src/Controller/RequestController.php +++ b/administrator/components/com_privacy/src/Controller/RequestController.php @@ -357,10 +357,8 @@ protected function postSaveHook(BaseDatabaseModel $model, $validData = []) return; } - if (!$model->logRequestCreated($model->getState($model->getName() . '.id'))) { - if ($error = $model->getError()) { - $this->app->enqueueMessage($error, 'warning'); - } + if (!$model->logRequestCreated($model->getState($model->getName() . '.id')) && $error = $model->getError()) { + $this->app->enqueueMessage($error, 'warning'); } if (!$model->notifyUserAdminCreatedRequest($model->getState($model->getName() . '.id'))) { diff --git a/administrator/components/com_privacy/src/Model/ExportModel.php b/administrator/components/com_privacy/src/Model/ExportModel.php index 8ae502d1d713b..f58fb96c5eb1f 100644 --- a/administrator/components/com_privacy/src/Model/ExportModel.php +++ b/administrator/components/com_privacy/src/Model/ExportModel.php @@ -52,7 +52,7 @@ class ExportModel extends BaseDatabaseModel implements UserFactoryAwareInterface */ public function collectDataForExportRequest($id = null) { - $id = !empty($id) ? $id : (int) $this->getState($this->getName() . '.request_id'); + $id = empty($id) ? (int) $this->getState($this->getName() . '.request_id') : $id; if (!$id) { $this->setError(Text::_('COM_PRIVACY_ERROR_REQUEST_ID_REQUIRED_FOR_EXPORT')); @@ -93,7 +93,7 @@ public function collectDataForExportRequest($id = null) ->setLimit(1) )->loadResult(); - $user = $userId ? $this->getUserFactory()->loadUserById($userId) : null; + $user = $userId !== 0 ? $this->getUserFactory()->loadUserById($userId) : null; // Log the export $this->logExport($table); @@ -127,7 +127,7 @@ public function collectDataForExportRequest($id = null) */ public function emailDataExport($id = null) { - $id = !empty($id) ? $id : (int) $this->getState($this->getName() . '.request_id'); + $id = empty($id) ? (int) $this->getState($this->getName() . '.request_id') : $id; if (!$id) { $this->setError(Text::_('COM_PRIVACY_ERROR_REQUEST_ID_REQUIRED_FOR_EXPORT')); @@ -188,7 +188,7 @@ public function emailDataExport($id = null) 1 )->loadResult(); - if ($userId) { + if ($userId !== 0) { $receiver = $this->getUserFactory()->loadUserById($userId); /* @@ -206,8 +206,9 @@ public function emailDataExport($id = null) } // Ensure the right language files have been loaded - $lang->load('com_privacy', JPATH_ADMINISTRATOR) - || $lang->load('com_privacy', JPATH_ADMINISTRATOR . '/components/com_privacy'); + if (!$lang->load('com_privacy', JPATH_ADMINISTRATOR)) { + $lang->load('com_privacy', JPATH_ADMINISTRATOR . '/components/com_privacy'); + } // The mailer can be set to either throw Exceptions or return boolean false, account for both try { diff --git a/administrator/components/com_privacy/src/Model/RemoveModel.php b/administrator/components/com_privacy/src/Model/RemoveModel.php index 864e79a840455..903e565cf5186 100644 --- a/administrator/components/com_privacy/src/Model/RemoveModel.php +++ b/administrator/components/com_privacy/src/Model/RemoveModel.php @@ -48,7 +48,7 @@ class RemoveModel extends BaseDatabaseModel implements UserFactoryAwareInterface */ public function removeDataForRequest($id = null) { - $id = !empty($id) ? $id : (int) $this->getState($this->getName() . '.request_id'); + $id = empty($id) ? (int) $this->getState($this->getName() . '.request_id') : $id; if (!$id) { $this->setError(Text::_('COM_PRIVACY_ERROR_REQUEST_ID_REQUIRED_FOR_REMOVE')); @@ -89,7 +89,7 @@ public function removeDataForRequest($id = null) ->setLimit(1) )->loadResult(); - $user = $userId ? $this->getUserFactory()->loadUserById($userId) : null; + $user = $userId !== 0 ? $this->getUserFactory()->loadUserById($userId) : null; $canRemove = true; $dispatcher = $this->getDispatcher(); diff --git a/administrator/components/com_privacy/src/Model/RequestModel.php b/administrator/components/com_privacy/src/Model/RequestModel.php index b49d95b9a7eaa..71813b8ac86e6 100644 --- a/administrator/components/com_privacy/src/Model/RequestModel.php +++ b/administrator/components/com_privacy/src/Model/RequestModel.php @@ -272,7 +272,7 @@ public function notifyUserAdminCreatedRequest($id) ->setLimit(1) )->loadResult(); - if ($userId) { + if ($userId !== 0) { $receiver = $this->getUserFactory()->loadUserById($userId); /* @@ -290,8 +290,9 @@ public function notifyUserAdminCreatedRequest($id) } // Ensure the right language files have been loaded - $lang->load('com_privacy', JPATH_ADMINISTRATOR) - || $lang->load('com_privacy', JPATH_ADMINISTRATOR . '/components/com_privacy'); + if (!$lang->load('com_privacy', JPATH_ADMINISTRATOR)) { + $lang->load('com_privacy', JPATH_ADMINISTRATOR . '/components/com_privacy'); + } // Regenerate the confirmation token $token = ApplicationHelper::getHash(UserHelper::genRandomPassword()); @@ -365,7 +366,7 @@ public function save($data) { $table = $this->getTable(); $key = $table->getKeyName(); - $pk = !empty($data[$key]) ? $data[$key] : (int) $this->getState($this->getName() . '.id'); + $pk = empty($data[$key]) ? (int) $this->getState($this->getName() . '.id') : $data[$key]; if (!$pk && !Factory::getApplication()->get('mailonline', 1)) { $this->setError(Text::_('COM_PRIVACY_ERROR_CANNOT_CREATE_REQUEST_WHEN_SENDMAIL_DISABLED')); diff --git a/administrator/components/com_privacy/src/Service/HTML/Privacy.php b/administrator/components/com_privacy/src/Service/HTML/Privacy.php index 4a088b2315e3f..c199cab73698a 100644 --- a/administrator/components/com_privacy/src/Service/HTML/Privacy.php +++ b/administrator/components/com_privacy/src/Service/HTML/Privacy.php @@ -34,19 +34,12 @@ class Privacy */ public function statusLabel($status) { - switch ($status) { - case 2: - return '' . Text::_('COM_PRIVACY_STATUS_COMPLETED') . ''; - - case 1: - return '' . Text::_('COM_PRIVACY_STATUS_CONFIRMED') . ''; - - case -1: - return '' . Text::_('COM_PRIVACY_STATUS_INVALID') . ''; - - default: - case 0: - return '' . Text::_('COM_PRIVACY_STATUS_PENDING') . ''; - } + return match ($status) { + 2 => '' . Text::_('COM_PRIVACY_STATUS_COMPLETED') . '', + 1 => '' . Text::_('COM_PRIVACY_STATUS_CONFIRMED') . '', + -1 => '' . Text::_('COM_PRIVACY_STATUS_INVALID') . '', + 0 => '' . Text::_('COM_PRIVACY_STATUS_PENDING') . '', + default => null, + }; } } diff --git a/administrator/components/com_privacy/src/View/Request/HtmlView.php b/administrator/components/com_privacy/src/View/Request/HtmlView.php index 58cb2eea48c7b..76c0380af2380 100644 --- a/administrator/components/com_privacy/src/View/Request/HtmlView.php +++ b/administrator/components/com_privacy/src/View/Request/HtmlView.php @@ -90,8 +90,9 @@ public function display($tpl = null) // Load the com_actionlogs language strings for use in the layout $lang = $this->getLanguage(); - $lang->load('com_actionlogs', JPATH_ADMINISTRATOR) - || $lang->load('com_actionlogs', JPATH_ADMINISTRATOR . '/components/com_actionlogs'); + if (!$lang->load('com_actionlogs', JPATH_ADMINISTRATOR)) { + $lang->load('com_actionlogs', JPATH_ADMINISTRATOR . '/components/com_actionlogs'); + } } // Variables only required for the edit layout diff --git a/administrator/components/com_redirect/src/Controller/LinksController.php b/administrator/components/com_redirect/src/Controller/LinksController.php index 4f13f9538a6c8..d0f1ff43835b7 100644 --- a/administrator/components/com_redirect/src/Controller/LinksController.php +++ b/administrator/components/com_redirect/src/Controller/LinksController.php @@ -42,7 +42,7 @@ public function activate() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('COM_REDIRECT_NO_ITEM_SELECTED'), 'warning'); } else { $newUrl = $this->input->getString('new_url'); @@ -79,7 +79,7 @@ public function duplicateUrls() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->app->enqueueMessage(Text::_('COM_REDIRECT_NO_ITEM_SELECTED'), 'warning'); } else { $newUrl = $this->input->getString('new_url'); @@ -150,7 +150,7 @@ public function batch() // Set default message on error - overwrite if successful $this->setMessage(Text::_('COM_REDIRECT_NO_ITEM_ADDED'), 'error'); - if (!empty($batch_urls)) { + if ($batch_urls !== []) { $model = $this->getModel('Links'); // Execute the batch process diff --git a/administrator/components/com_redirect/src/Helper/RedirectHelper.php b/administrator/components/com_redirect/src/Helper/RedirectHelper.php index 8cf148fd8ab85..eda5f1521f508 100644 --- a/administrator/components/com_redirect/src/Helper/RedirectHelper.php +++ b/administrator/components/com_redirect/src/Helper/RedirectHelper.php @@ -42,15 +42,7 @@ class RedirectHelper */ public static function publishedOptions() { - // Build the active state filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '*', 'JALL'); - $options[] = HTMLHelper::_('select.option', '1', 'JENABLED'); - $options[] = HTMLHelper::_('select.option', '0', 'JDISABLED'); - $options[] = HTMLHelper::_('select.option', '2', 'JARCHIVED'); - $options[] = HTMLHelper::_('select.option', '-2', 'JTRASHED'); - - return $options; + return [HTMLHelper::_('select.option', '*', 'JALL'), HTMLHelper::_('select.option', '1', 'JENABLED'), HTMLHelper::_('select.option', '0', 'JDISABLED'), HTMLHelper::_('select.option', '2', 'JARCHIVED'), HTMLHelper::_('select.option', '-2', 'JTRASHED')]; } /** diff --git a/administrator/components/com_redirect/src/Model/LinkModel.php b/administrator/components/com_redirect/src/Model/LinkModel.php index c982c0bf1c462..a76fd023395de 100644 --- a/administrator/components/com_redirect/src/Model/LinkModel.php +++ b/administrator/components/com_redirect/src/Model/LinkModel.php @@ -133,7 +133,7 @@ public function activate(&$pks, $url, $comment = null) $pks = ArrayHelper::toInteger($pks); // Populate default comment if necessary. - $comment = (!empty($comment)) ? $comment : Text::sprintf('COM_REDIRECT_REDIRECTED_ON', HTMLHelper::_('date', time())); + $comment = (empty($comment)) ? Text::sprintf('COM_REDIRECT_REDIRECTED_ON', HTMLHelper::_('date', time())) : $comment; // Access checks. if (!$user->authorise('core.edit', 'com_redirect')) { diff --git a/administrator/components/com_redirect/src/Model/LinksModel.php b/administrator/components/com_redirect/src/Model/LinksModel.php index b088659d2870d..a9cc0c80fc3a4 100644 --- a/administrator/components/com_redirect/src/Model/LinksModel.php +++ b/administrator/components/com_redirect/src/Model/LinksModel.php @@ -248,11 +248,7 @@ public function batchProcess($batchUrls) $old_url = $batch_url[0]; // Destination URL can also be an external URL - if (!empty($batch_url[1])) { - $new_url = $batch_url[1]; - } else { - $new_url = ''; - } + $new_url = empty($batch_url[1]) ? '' : $batch_url[1]; $db->execute(); } diff --git a/administrator/components/com_redirect/src/Table/LinkTable.php b/administrator/components/com_redirect/src/Table/LinkTable.php index 926d352fea1a2..a4e594dcf3706 100644 --- a/administrator/components/com_redirect/src/Table/LinkTable.php +++ b/administrator/components/com_redirect/src/Table/LinkTable.php @@ -62,7 +62,7 @@ public function check() $this->new_url = trim(rawurldecode($this->new_url)); // Check for valid name. - if (empty($this->old_url)) { + if ($this->old_url === '' || $this->old_url === '0') { $this->setError(Text::_('COM_REDIRECT_ERROR_SOURCE_URL_REQUIRED')); return false; @@ -74,23 +74,20 @@ public function check() } // Check for valid name if not in advanced mode. - if (empty($this->new_url) && ComponentHelper::getParams('com_redirect')->get('mode', 0) == false) { + if (($this->new_url === '' || $this->new_url === '0') && ComponentHelper::getParams('com_redirect')->get('mode', 0) == false) { $this->setError(Text::_('COM_REDIRECT_ERROR_DESTINATION_URL_REQUIRED')); return false; } - if (empty($this->new_url) && ComponentHelper::getParams('com_redirect')->get('mode', 0) == true) { - // Else if an empty URL and in redirect mode only throw the same error if the code is a 3xx status code - if ($this->header < 400 && $this->header >= 300) { - $this->setError(Text::_('COM_REDIRECT_ERROR_DESTINATION_URL_REQUIRED')); - - return false; - } + // Else if an empty URL and in redirect mode only throw the same error if the code is a 3xx status code + if (($this->new_url === '' || $this->new_url === '0') && ComponentHelper::getParams('com_redirect')->get('mode', 0) == true && ($this->header < 400 && $this->header >= 300)) { + $this->setError(Text::_('COM_REDIRECT_ERROR_DESTINATION_URL_REQUIRED')); + return false; } // Check for duplicates - if ($this->old_url == $this->new_url) { + if ($this->old_url === $this->new_url) { $this->setError(Text::_('COM_REDIRECT_ERROR_DUPLICATE_URLS')); return false; @@ -109,7 +106,7 @@ public function check() $urls = $db->loadAssocList(); foreach ($urls as $url) { - if ($url['old_url'] === $this->old_url && (int) $url['id'] != (int) $this->id) { + if ($url['old_url'] === $this->old_url && (int) $url['id'] !== (int) $this->id) { $this->setError(Text::_('COM_REDIRECT_ERROR_DUPLICATE_OLD_URL')); return false; diff --git a/administrator/components/com_scheduler/src/Controller/DisplayController.php b/administrator/components/com_scheduler/src/Controller/DisplayController.php index 568c2fc18bb27..f7410ba64dfac 100644 --- a/administrator/components/com_scheduler/src/Controller/DisplayController.php +++ b/administrator/components/com_scheduler/src/Controller/DisplayController.php @@ -46,13 +46,10 @@ public function display($cachable = false, $urlparams = []) $layout = $this->input->get('layout', 'default'); // Check for edit form. - if ($layout === 'edit') { - if (!$this->validateEntry()) { - $tasksViewUrl = Route::_('index.php?option=com_scheduler&view=tasks', false); - $this->setRedirect($tasksViewUrl); - - return false; - } + if ($layout === 'edit' && !$this->validateEntry()) { + $tasksViewUrl = Route::_('index.php?option=com_scheduler&view=tasks', false); + $this->setRedirect($tasksViewUrl); + return false; } // Let the parent method take over diff --git a/administrator/components/com_scheduler/src/Controller/TaskController.php b/administrator/components/com_scheduler/src/Controller/TaskController.php index 6783c31512f40..4dedf9af43029 100644 --- a/administrator/components/com_scheduler/src/Controller/TaskController.php +++ b/administrator/components/com_scheduler/src/Controller/TaskController.php @@ -50,7 +50,7 @@ public function add(): bool $taskType = $input->get('type'); $taskOption = $validTaskOptions->findOption($taskType) ?: null; - if (!$taskOption) { + if (!$taskOption instanceof \Joomla\Component\Scheduler\Administrator\Task\TaskOption) { // ? : Is this the right redirect [review] $redirectUrl = 'index.php?option=' . $this->option . '&view=select&layout=edit'; $this->setRedirect(Route::_($redirectUrl, false)); diff --git a/administrator/components/com_scheduler/src/Controller/TasksController.php b/administrator/components/com_scheduler/src/Controller/TasksController.php index 2121ecf71eea3..b634162b88b7e 100644 --- a/administrator/components/com_scheduler/src/Controller/TasksController.php +++ b/administrator/components/com_scheduler/src/Controller/TasksController.php @@ -63,7 +63,7 @@ public function unlock(): void // Remove zero values resulting from input filter $cid = array_filter($cid); - if (empty($cid)) { + if ($cid === []) { $this->app->getLogger() ->warning(Text::_($this->text_prefix . '_NO_ITEM_SELECTED'), ['category' => 'jerror']); } else { @@ -85,7 +85,7 @@ public function unlock(): void $noticeText = $this->text_prefix . '_N_ITEMS_UNLOCKED'; } - if (\count($cid)) { + if ($cid !== []) { $this->setMessage(Text::plural($noticeText, \count($cid))); } } catch (\Exception $e) { diff --git a/administrator/components/com_scheduler/src/Event/ExecuteTaskEvent.php b/administrator/components/com_scheduler/src/Event/ExecuteTaskEvent.php index c517f68eaf58b..e5d3cd79e05ee 100644 --- a/administrator/components/com_scheduler/src/Event/ExecuteTaskEvent.php +++ b/administrator/components/com_scheduler/src/Event/ExecuteTaskEvent.php @@ -57,7 +57,7 @@ public function setResult(array $snapshot = []): void { $this->arguments['resultSnapshot'] = $snapshot; - if (!empty($snapshot)) { + if ($snapshot !== []) { $this->stopPropagation(); } } diff --git a/administrator/components/com_scheduler/src/Field/IntervalField.php b/administrator/components/com_scheduler/src/Field/IntervalField.php index eaf5e87aa6e8b..7942aeae8ec51 100644 --- a/administrator/components/com_scheduler/src/Field/IntervalField.php +++ b/administrator/components/com_scheduler/src/Field/IntervalField.php @@ -88,7 +88,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null): bool $parentResult = FormField::setup($element, $value, $group); $subtype = ((string) $element['subtype'] ?? '') ?: null; - if (empty($subtype) || !\array_key_exists($subtype, self::SUBTYPES)) { + if ($subtype === null || $subtype === '' || $subtype === '0' || !\array_key_exists($subtype, self::SUBTYPES)) { return false; } diff --git a/administrator/components/com_scheduler/src/Model/TaskModel.php b/administrator/components/com_scheduler/src/Model/TaskModel.php index aaa0e279640e0..9539cc6fa8792 100644 --- a/administrator/components/com_scheduler/src/Model/TaskModel.php +++ b/administrator/components/com_scheduler/src/Model/TaskModel.php @@ -760,7 +760,7 @@ public function unlock(array &$pks): bool } // Check if there are items to change. - if (!\count($pks)) { + if ($pks === []) { return true; } diff --git a/administrator/components/com_scheduler/src/Model/TasksModel.php b/administrator/components/com_scheduler/src/Model/TasksModel.php index a0e23c4e92d8d..f201561c5585d 100644 --- a/administrator/components/com_scheduler/src/Model/TasksModel.php +++ b/administrator/components/com_scheduler/src/Model/TasksModel.php @@ -170,7 +170,7 @@ protected function getListQuery(): QueryInterface $query, &$filterCount ) { - if ($filterCount++) { + if ($filterCount++ !== 0) { $query->extendWhere($outerGlue, $conditions, $innerGlue); } else { $query->where($conditions, $innerGlue); diff --git a/administrator/components/com_scheduler/src/Scheduler/Scheduler.php b/administrator/components/com_scheduler/src/Scheduler/Scheduler.php index 6d96c1526eed7..4274efc04778d 100644 --- a/administrator/components/com_scheduler/src/Scheduler/Scheduler.php +++ b/administrator/components/com_scheduler/src/Scheduler/Scheduler.php @@ -116,7 +116,7 @@ public function runTask(array $options): ?Task ); // ? Should this be logged? (probably, if an ID is passed?) - if (empty($task)) { + if (!$task instanceof \Joomla\Component\Scheduler\Administrator\Task\Task) { return null; } diff --git a/administrator/components/com_scheduler/src/Table/TaskTable.php b/administrator/components/com_scheduler/src/Table/TaskTable.php index d34479f817f41..4c79e853c2516 100644 --- a/administrator/components/com_scheduler/src/Table/TaskTable.php +++ b/administrator/components/com_scheduler/src/Table/TaskTable.php @@ -112,7 +112,7 @@ public function check(): bool // Set created date if not set. // ? Might not need since the constructor already sets this - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = Factory::getDate()->toSql(); } @@ -258,7 +258,7 @@ public function unlock(array $pks = [], ?int $userId = null): bool $this->getDispatcher()->dispatch('onTaskBeforeUnlock', $event); // Some pre-processing before we can work with the keys. - if (!empty($pks)) { + if ($pks !== []) { foreach ($pks as $key => $pk) { if (!\is_array($pk)) { $pks[$key] = [$this->_tbl_key => $pk]; @@ -267,7 +267,7 @@ public function unlock(array $pks = [], ?int $userId = null): bool } // If there are no primary keys set check to see if the instance key is set and use that. - if (empty($pks)) { + if ($pks === []) { $pk = []; foreach ($this->_tbl_keys as $key) { diff --git a/administrator/components/com_scheduler/src/Task/Task.php b/administrator/components/com_scheduler/src/Task/Task.php index d02a5654bec7a..137c14b232ac1 100644 --- a/administrator/components/com_scheduler/src/Task/Task.php +++ b/administrator/components/com_scheduler/src/Task/Task.php @@ -198,7 +198,7 @@ public function run(): bool } // Exit early if task routine is not available - if (!SchedulerHelper::getTaskOptions()->findOption($this->get('type'))) { + if (!SchedulerHelper::getTaskOptions()->findOption($this->get('type')) instanceof \Joomla\Component\Scheduler\Administrator\Task\TaskOption) { $this->snapshot['status'] = Status::NO_ROUTINE; $this->skipExecution(); $this->dispatchExitEvent(); @@ -552,11 +552,6 @@ public static function isValidState(string $state): bool public static function isValidId(string $id): bool { $id = is_numeric($id) ? ($id + 0) : $id; - - if (!\is_int($id) || $id <= 0) { - return false; - } - - return true; + return \is_int($id) && $id > 0; } } diff --git a/administrator/components/com_scheduler/src/Traits/TaskPluginTrait.php b/administrator/components/com_scheduler/src/Traits/TaskPluginTrait.php index bac962a5677bb..8cfadedcad005 100644 --- a/administrator/components/com_scheduler/src/Traits/TaskPluginTrait.php +++ b/administrator/components/com_scheduler/src/Traits/TaskPluginTrait.php @@ -133,7 +133,7 @@ public function enhanceTaskItemForm($context, $data = null): bool $enhancementFormName = self::TASKS_MAP[$routineId]['form'] ?? ''; // Return if routine is not supported by the plugin or the routine does not have a form linked in TASKS_MAP. - if (!$isSupported || \strlen((string) $enhancementFormName) === 0) { + if (!$isSupported || (string) $enhancementFormName === '') { return true; } @@ -272,12 +272,12 @@ public function standardRoutineHandler(ExecuteTaskEvent $event): void $exitCode = Status::NO_EXIT; // We call the mapped method if it exists and confirms to the ($event) -> int signature. - if (!empty($methodName) && ($staticReflection = new \ReflectionClass($this))->hasMethod($methodName)) { + if ($methodName !== '' && $methodName !== '0' && ($staticReflection = new \ReflectionClass($this))->hasMethod($methodName)) { $method = $staticReflection->getMethod($methodName); // Might need adjustments here for PHP8 named parameters. if ( - !($method->getNumberOfRequiredParameters() === 1) + $method->getNumberOfRequiredParameters() !== 1 || !$method->getParameters()[0]->hasType() || $method->getParameters()[0]->getType()->getName() !== ExecuteTaskEvent::class || !$method->hasReturnType() diff --git a/administrator/components/com_scheduler/src/View/Logs/HtmlView.php b/administrator/components/com_scheduler/src/View/Logs/HtmlView.php index 083d4382c180b..ec7f12204db6a 100644 --- a/administrator/components/com_scheduler/src/View/Logs/HtmlView.php +++ b/administrator/components/com_scheduler/src/View/Logs/HtmlView.php @@ -93,7 +93,7 @@ public function display($tpl = null): void $this->activeFilters = $model->getActiveFilters(); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } diff --git a/administrator/components/com_scheduler/src/View/Tasks/HtmlView.php b/administrator/components/com_scheduler/src/View/Tasks/HtmlView.php index d58d60c9f9552..c7901db21fdab 100644 --- a/administrator/components/com_scheduler/src/View/Tasks/HtmlView.php +++ b/administrator/components/com_scheduler/src/View/Tasks/HtmlView.php @@ -31,6 +31,10 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var bool + */ + public $hasDueTasks; /** * Array of task items. * diff --git a/administrator/components/com_tags/src/Model/TagModel.php b/administrator/components/com_tags/src/Model/TagModel.php index 4424fd1d12b1f..1813fc5b1a997 100644 --- a/administrator/components/com_tags/src/Model/TagModel.php +++ b/administrator/components/com_tags/src/Model/TagModel.php @@ -130,7 +130,7 @@ public function getItem($pk = null) // Convert the modified date to local user time for display in the form. $tz = new \DateTimeZone(Factory::getApplication()->get('offset')); - if ((int) $result->modified_time) { + if ((int) $result->modified_time !== 0) { $date = new Date($result->modified_time); $date->setTimezone($tz); $result->modified_time = $date->toSql(true); @@ -214,7 +214,7 @@ public function save($data) /** @var \Joomla\Component\Tags\Administrator\Table\TagTable $table */ $table = $this->getTable(); $input = Factory::getApplication()->getInput(); - $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState($this->getName() . '.id'); + $pk = (empty($data['id'])) ? (int) $this->getState($this->getName() . '.id') : $data['id']; $isNew = true; $context = $this->option . '.' . $this->name; diff --git a/administrator/components/com_tags/src/Model/TagsModel.php b/administrator/components/com_tags/src/Model/TagsModel.php index 5842b6a74943d..b9298d36abb7b 100644 --- a/administrator/components/com_tags/src/Model/TagsModel.php +++ b/administrator/components/com_tags/src/Model/TagsModel.php @@ -191,13 +191,13 @@ protected function getListQuery() $query->select('(' . (string) $subQueryCountTaggedItems . ') AS ' . $db->quoteName('countTaggedItems')); // Filter on the level. - if ($level = (int) $this->getState('filter.level')) { + if ($level = (int) $this->getState('filter.level') !== 0) { $query->where($db->quoteName('a.level') . ' <= :level') ->bind(':level', $level, ParameterType::INTEGER); } // Filter by access level. - if ($access = (int) $this->getState('filter.access')) { + if ($access = (int) $this->getState('filter.access') !== 0) { $query->where($db->quoteName('a.access') . ' = :access') ->bind(':access', $access, ParameterType::INTEGER); } diff --git a/administrator/components/com_tags/src/Table/TagTable.php b/administrator/components/com_tags/src/Table/TagTable.php index d472cf7bbc15e..3d864d02cc1ee 100644 --- a/administrator/components/com_tags/src/Table/TagTable.php +++ b/administrator/components/com_tags/src/Table/TagTable.php @@ -85,7 +85,7 @@ public function check() } // Check for valid name. - if (trim($this->title) == '') { + if (trim($this->title) === '') { throw new \UnexpectedValueException('The title is empty'); } @@ -95,7 +95,7 @@ public function check() $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); - if (trim(str_replace('-', '', $this->alias)) == '') { + if (trim(str_replace('-', '', $this->alias)) === '') { $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } @@ -143,15 +143,15 @@ public function check() $this->images = '{}'; } - if (!(int) $this->checked_out_time) { + if ((int) $this->checked_out_time === 0) { $this->checked_out_time = null; } - if (!(int) $this->publish_up) { + if ((int) $this->publish_up === 0) { $this->publish_up = null; } - if (!(int) $this->publish_down) { + if ((int) $this->publish_down === 0) { $this->publish_down = null; } @@ -179,7 +179,7 @@ public function store($updateNulls = true) } else { // New tag. A tag created and created_by field can be set by the user, // so we don't touch either of these if they are set. - if (!(int) $this->created_time) { + if ((int) $this->created_time === 0) { $this->created_time = $date->toSql(); } @@ -187,7 +187,7 @@ public function store($updateNulls = true) $this->created_user_id = $user->id; } - if (!(int) $this->modified_time) { + if ((int) $this->modified_time === 0) { $this->modified_time = $this->created_time; } diff --git a/administrator/components/com_tags/src/View/Tag/HtmlView.php b/administrator/components/com_tags/src/View/Tag/HtmlView.php index 1bceced1de023..7553d4f7cef64 100644 --- a/administrator/components/com_tags/src/View/Tag/HtmlView.php +++ b/administrator/components/com_tags/src/View/Tag/HtmlView.php @@ -117,7 +117,7 @@ protected function addToolbar() $user = $this->getCurrentUser(); $userId = $user->id; $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $userId); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $userId; $toolbar = $this->getDocument()->getToolbar(); $canDo = ContentHelper::getActions('com_tags'); diff --git a/administrator/components/com_tags/tmpl/tags/default.php b/administrator/components/com_tags/tmpl/tags/default.php index f946c49b882a5..77df7506e94e2 100644 --- a/administrator/components/com_tags/tmpl/tags/default.php +++ b/administrator/components/com_tags/tmpl/tags/default.php @@ -31,7 +31,7 @@ $userId = $user->id; $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); -$saveOrder = ($listOrder == 'a.lft' && strtolower((string) $listDirn) == 'asc'); +$saveOrder = ($listOrder == 'a.lft' && strtolower((string) $listDirn) === 'asc'); $extension = $this->escape($this->state->get('filter.extension')); $parts = explode('.', (string) $extension); $component = $parts[0]; diff --git a/administrator/components/com_templates/src/Controller/StylesController.php b/administrator/components/com_templates/src/Controller/StylesController.php index c6af2f430fa3a..02e7979586042 100644 --- a/administrator/components/com_templates/src/Controller/StylesController.php +++ b/administrator/components/com_templates/src/Controller/StylesController.php @@ -41,7 +41,7 @@ public function duplicate() $pks = array_filter($pks); try { - if (empty($pks)) { + if ($pks === []) { throw new \Exception(Text::_('COM_TEMPLATES_NO_TEMPLATE_SELECTED')); } @@ -89,7 +89,7 @@ public function setDefault() $pks = array_filter($pks); try { - if (empty($pks)) { + if ($pks === []) { throw new \Exception(Text::_('COM_TEMPLATES_NO_TEMPLATE_SELECTED')); } @@ -125,7 +125,7 @@ public function unsetDefault() $pks = array_filter($pks); try { - if (empty($pks)) { + if ($pks === []) { throw new \Exception(Text::_('COM_TEMPLATES_NO_TEMPLATE_SELECTED')); } diff --git a/administrator/components/com_templates/src/Controller/TemplateController.php b/administrator/components/com_templates/src/Controller/TemplateController.php index 87ecc2bb6550e..22a6c69109c20 100644 --- a/administrator/components/com_templates/src/Controller/TemplateController.php +++ b/administrator/components/com_templates/src/Controller/TemplateController.php @@ -103,7 +103,7 @@ public function publish() $task = $this->getTask(); $value = ArrayHelper::getValue($values, $task, 0, 'int'); - if (empty($ids)) { + if ($ids === []) { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_NO_FILE_SELECTED'), 'warning'); } else { /* @var \Joomla\Component\Templates\Administrator\Model\TemplateModel $model */ @@ -427,11 +427,11 @@ public function delete() return; } - if (base64_decode(urldecode($file)) == '/index.php') { + if (base64_decode(urldecode($file)) === '/index.php') { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_INDEX_DELETE'), 'warning'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $this->input->getInt('isMedia', 0); $this->setRedirect(Route::_($url, false)); - } elseif (base64_decode(urldecode($file)) == '/joomla.asset.json') { + } elseif (base64_decode(urldecode($file)) === '/joomla.asset.json') { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_ASSET_FILE_DELETE'), 'warning'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $this->input->getInt('isMedia', 0); $this->setRedirect(Route::_($url, false)); @@ -480,7 +480,7 @@ public function createFile() return; } - if ($type == 'null') { + if ($type === 'null') { $this->setMessage(Text::_('COM_TEMPLATES_INVALID_FILE_TYPE'), 'error'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $this->input->getInt('isMedia', 0); $this->setRedirect(Route::_($url, false)); @@ -623,7 +623,7 @@ public function deleteFolder() return; } - if (empty($location)) { + if ($location === '' || $location === '0') { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_ROOT_DELETE'), 'warning'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $isMedia; $this->setRedirect(Route::_($url, false)); @@ -669,11 +669,11 @@ public function renameFile() return; } - if (base64_decode(urldecode($file)) == '/index.php') { + if (base64_decode(urldecode($file)) === '/index.php') { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_RENAME_INDEX'), 'warning'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $isMedia; $this->setRedirect(Route::_($url, false)); - } elseif (base64_decode(urldecode($file)) == '/joomla.asset.json') { + } elseif (base64_decode(urldecode($file)) === '/joomla.asset.json') { $this->setMessage(Text::_('COM_TEMPLATES_ERROR_RENAME_ASSET_FILE'), 'warning'); $url = 'index.php?option=com_templates&view=template&id=' . $id . '&file=' . $file . '&isMedia=' . $isMedia; $this->setRedirect(Route::_($url, false)); @@ -932,7 +932,7 @@ public function child() $model->setState('to_path', $this->app->get('tmp_path') . '/' . $model->getState('tmp_prefix')); // Process only if we have a new name entered - if (!\strlen((string) $newName)) { + if ((string) (string) $newName === '') { $this->setMessage(Text::sprintf('COM_TEMPLATES_ERROR_INVALID_TEMPLATE_NAME'), 'error'); return false; @@ -992,7 +992,7 @@ public function child() $this->setMessage(Text::sprintf('COM_TEMPLATES_CHILD_SUCCESS', $newName)); $model->cleanup(); - if (\count($extraStyles) > 0) { + if ($extraStyles !== []) { $model->setState('stylesToCopy', $extraStyles); $model->copyStyles(); } diff --git a/administrator/components/com_templates/src/Helper/TemplateHelper.php b/administrator/components/com_templates/src/Helper/TemplateHelper.php index 7f4d1d509ae62..d72860e4773bf 100644 --- a/administrator/components/com_templates/src/Helper/TemplateHelper.php +++ b/administrator/components/com_templates/src/Helper/TemplateHelper.php @@ -98,7 +98,7 @@ public static function canUpload($file, $err = '') $allowable = array_merge($imageTypes, $sourceTypes, $fontTypes, $archiveTypes); - if ($format == '' || $format == false || (!\in_array($format, $allowable))) { + if ($format === '' || $format == false || (!\in_array($format, $allowable))) { $app = Factory::getApplication(); $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_WARNFILETYPE'), 'error'); @@ -113,7 +113,7 @@ public static function canUpload($file, $err = '') $entry = $zip->getNameIndex($i); $endString = substr($entry, -1); - if ($endString != DIRECTORY_SEPARATOR) { + if ($endString !== DIRECTORY_SEPARATOR) { $explodeArray = explode('.', $entry); $ext = end($explodeArray); diff --git a/administrator/components/com_templates/src/Helper/TemplatesHelper.php b/administrator/components/com_templates/src/Helper/TemplatesHelper.php index 615354706b65b..be2bcb26fec52 100644 --- a/administrator/components/com_templates/src/Helper/TemplatesHelper.php +++ b/administrator/components/com_templates/src/Helper/TemplatesHelper.php @@ -36,12 +36,7 @@ class TemplatesHelper */ public static function getClientOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '0', Text::_('JSITE')); - $options[] = HTMLHelper::_('select.option', '1', Text::_('JADMINISTRATOR')); - - return $options; + return [HTMLHelper::_('select.option', '0', Text::_('JSITE')), HTMLHelper::_('select.option', '1', Text::_('JADMINISTRATOR'))]; } /** @@ -133,7 +128,7 @@ public static function getPositions($clientId, $templateDir) // Extensions use 'extension' as the root tag. Languages use 'metafile' instead - if ($xml->getName() != 'extension' && $xml->getName() != 'metafile') { + if ($xml->getName() !== 'extension' && $xml->getName() !== 'metafile') { unset($xml); return false; @@ -141,11 +136,7 @@ public static function getPositions($clientId, $templateDir) $positions = (array) $xml->positions; - if (isset($positions['position'])) { - $positions = (array) $positions['position']; - } else { - $positions = []; - } + $positions = isset($positions['position']) ? (array) $positions['position'] : []; } return $positions; diff --git a/administrator/components/com_templates/src/Model/StyleModel.php b/administrator/components/com_templates/src/Model/StyleModel.php index bb381388aea5e..dc1dc0b5878d0 100644 --- a/administrator/components/com_templates/src/Model/StyleModel.php +++ b/administrator/components/com_templates/src/Model/StyleModel.php @@ -331,7 +331,7 @@ protected function loadFormData() */ public function getItem($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('style.id'); + $pk = (empty($pk)) ? (int) $this->getState('style.id') : $pk; if (!isset($this->_cache[$pk])) { // Get a row instance. @@ -359,11 +359,7 @@ public function getItem($pk = null) $client = ApplicationHelper::getClientInfo($table->client_id); $path = Path::clean($client->path . '/templates/' . $table->template . '/templateDetails.xml'); - if (file_exists($path)) { - $this->_cache[$pk]->xml = simplexml_load_file($path); - } else { - $this->_cache[$pk]->xml = null; - } + $this->_cache[$pk]->xml = file_exists($path) ? simplexml_load_file($path) : null; } return $this->_cache[$pk]; @@ -396,18 +392,18 @@ protected function preprocessForm(Form $form, $data, $group = 'content') // Load the core and/or local language file(s). // Default to using parent template language constants - $lang->load('tpl_' . $data->parent, $client->path) - || $lang->load('tpl_' . $data->parent, $client->path . '/templates/' . $data->parent); + if (!$lang->load('tpl_' . $data->parent, $client->path)) { + $lang->load('tpl_' . $data->parent, $client->path . '/templates/' . $data->parent); + } // Apply any, optional, overrides for child template language constants - $lang->load('tpl_' . $template, $client->path) - || $lang->load('tpl_' . $template, $client->path . '/templates/' . $template); + if (!$lang->load('tpl_' . $template, $client->path)) { + $lang->load('tpl_' . $template, $client->path . '/templates/' . $template); + } - if (file_exists($formFile)) { - // Get the template form. - if (!$form->loadFile($formFile, false, '//config')) { - throw new \Exception(Text::_('JERROR_LOADFILE_FAILED')); - } + // Get the template form. + if (file_exists($formFile) && !$form->loadFile($formFile, false, '//config')) { + throw new \Exception(Text::_('JERROR_LOADFILE_FAILED')); } // Disable home field if it is default style @@ -464,7 +460,7 @@ public function save($data) $app = Factory::getApplication(); $table = $this->getTable(); - $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('style.id'); + $pk = (empty($data['id'])) ? (int) $this->getState('style.id') : $data['id']; $isNew = true; // Include the extension plugins for the save events. @@ -725,7 +721,7 @@ public function getAdminTemplate(int $styleId): \stdClass ] ); - if ($styleId) { + if ($styleId !== 0) { $query->extendWhere( 'OR', [ diff --git a/administrator/components/com_templates/src/Model/StylesModel.php b/administrator/components/com_templates/src/Model/StylesModel.php index b8e075438c1d0..6e4ec26350ed9 100644 --- a/administrator/components/com_templates/src/Model/StylesModel.php +++ b/administrator/components/com_templates/src/Model/StylesModel.php @@ -72,7 +72,7 @@ protected function populateState($ordering = 'a.template', $direction = 'asc') if (!$app->isClient('api')) { // Special case for the client id. $clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int'); - $clientId = !\in_array($clientId, [0, 1]) ? 0 : $clientId; + $clientId = \in_array($clientId, [0, 1]) ? $clientId : 0; $this->setState('client_id', $clientId); } diff --git a/administrator/components/com_templates/src/Model/TemplateModel.php b/administrator/components/com_templates/src/Model/TemplateModel.php index 178b72b201937..890a61d022131 100644 --- a/administrator/components/com_templates/src/Model/TemplateModel.php +++ b/administrator/components/com_templates/src/Model/TemplateModel.php @@ -107,11 +107,7 @@ protected function storeFileInfo($path, $name, $template) $temp->template = $template->element; $temp->extension_id = $template->extension_id; - if ($coreFile = $this->getCoreFile($path . $name, $template->client_id)) { - $temp->coreFile = md5_file($coreFile); - } else { - $temp->coreFile = null; - } + $temp->coreFile = $coreFile = $this->getCoreFile($path . $name, $template->client_id) ? md5_file($coreFile) : null; return $temp; } @@ -371,10 +367,11 @@ public function getFiles() $lang = Factory::getLanguage(); // Load the core and/or local language file(s). - $lang->load('tpl_' . $template->element, $client->path) + if (!($lang->load('tpl_' . $template->element, $client->path) || (!empty($template->xmldata->parent) && $lang->load('tpl_' . $template->xmldata->parent, $client->path)) - || $lang->load('tpl_' . $template->element, $client->path . '/templates/' . $template->element) - || (!empty($template->xmldata->parent) && $lang->load('tpl_' . $template->xmldata->parent, $client->path . '/templates/' . $template->xmldata->parent)); + || $lang->load('tpl_' . $template->element, $client->path . '/templates/' . $template->element)) && !empty($template->xmldata->parent)) { + $lang->load('tpl_' . $template->xmldata->parent, $client->path . '/templates/' . $template->xmldata->parent); + } $this->element = $path; if (!is_writable($path)) { @@ -456,7 +453,7 @@ public function getDirectoryTree($dir) return strnatcmp($result[$a]->name, $result[$b]->name); }); - return !empty($result) ? $result : ['.']; + return $result === [] ? ['.'] : $result; } /** @@ -572,7 +569,7 @@ public function getCoreFile($file, $client_id) */ private function getSafeName($name) { - if (str_contains($name, '-') && preg_match('/[0-9]/', $name)) { + if (str_contains($name, '-') && preg_match('/\d/', $name)) { // Get the extension $extension = File::getExt($name); @@ -732,12 +729,9 @@ public function copy() // Delete new folder if it exists $toPath = $this->getState('to_path'); - if (is_dir(Path::clean($toPath))) { - if (!Folder::delete($toPath)) { - $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE'), 'error'); - - return false; - } + if (is_dir(Path::clean($toPath)) && !Folder::delete($toPath)) { + $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE'), 'error'); + return false; } // Copy all files from $fromName template to $newName folder @@ -775,13 +769,8 @@ public function copy() Folder::copy(JPATH_SITE . '/media/' . $destination, $toPath . '/' . $folder); } - // Adjust to new template name - if (!$this->fixTemplateName()) { - return false; - } - - return true; + return $this->fixTemplateName(); } $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_INVALID_FROM_NAME'), 'error'); @@ -946,7 +935,7 @@ public function &getSource() } catch (\Exception) { $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_FOUND'), 'error'); - return; + return null; } if (file_exists($filePath)) { @@ -1086,7 +1075,7 @@ public function getOverridesList() $folders = Folder::folders($componentPath . '/' . $component, '^view[s]?$', false, true); $folders = array_merge($folders, Folder::folders($componentPath . '/' . $component, '^tmpl?$', false, true)); - if (!$folders) { + if ($folders === []) { continue; } @@ -1182,7 +1171,7 @@ public function createOverride($override) $url = Path::clean($explodeArray[$size - 3] . '/' . $explodeArray[$size - 1]); - if ($explodeArray[$size - 2] == 'layouts') { + if ($explodeArray[$size - 2] === 'layouts') { $htmlPath = Path::clean($client->path . '/templates/' . $template->element . '/html/layouts/' . $url); } else { $htmlPath = Path::clean($client->path . '/templates/' . $template->element . '/html/' . $url); @@ -1690,11 +1679,7 @@ public function getFont() $fileName = end($explodeArray); $path = $this->getBasePath() . base64_decode((string) $app->getInput()->get('file')); - if (stristr($client->path, 'administrator') == false) { - $folder = '/templates/'; - } else { - $folder = '/administrator/templates/'; - } + $folder = stristr($client->path, 'administrator') == false ? '/templates/' : '/administrator/templates/'; $uri = Uri::root(true) . $folder . $template->element; @@ -1712,6 +1697,7 @@ public function getFont() return $font; } + return null; } /** @@ -1851,7 +1837,7 @@ public function extractArchive($file) */ protected function checkFormat($ext) { - if (!isset($this->allowedFormats)) { + if (!property_exists($this, 'allowedFormats') || $this->allowedFormats === null) { $params = ComponentHelper::getParams('com_templates'); $imageTypes = explode(',', (string) $params->get('image_formats', 'gif,bmp,jpg,jpeg,png,webp')); $sourceTypes = explode(',', (string) $params->get('source_formats', 'txt,less,ini,xml,js,php,css,scss,sass,json')); @@ -1946,12 +1932,9 @@ public function child() return false; } - } else { - if (!Folder::create($toPath)) { - $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE'), 'error'); - - return false; - } + } elseif (!Folder::create($toPath)) { + $app->enqueueMessage(Text::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE'), 'error'); + return false; } // Create the html folder @@ -2048,19 +2031,8 @@ public function child() return false; } - // Create an empty media folder structure - if ( - !Folder::create($toPath . '/media') - || !Folder::create($toPath . '/media/css') - || !Folder::create($toPath . '/media/js') - || !Folder::create($toPath . '/media/images') - || !Folder::create($toPath . '/media/scss') - ) { - return false; - } - - return true; + return !(!Folder::create($toPath . '/media') || !Folder::create($toPath . '/media/css') || !Folder::create($toPath . '/media/js') || !Folder::create($toPath . '/media/images') || !Folder::create($toPath . '/media/scss')); } /** diff --git a/administrator/components/com_templates/src/Model/TemplatesModel.php b/administrator/components/com_templates/src/Model/TemplatesModel.php index 846adf452fb5c..eeeda85fb9a75 100644 --- a/administrator/components/com_templates/src/Model/TemplatesModel.php +++ b/administrator/components/com_templates/src/Model/TemplatesModel.php @@ -208,7 +208,7 @@ protected function populateState($ordering = 'a.element', $direction = 'asc') { // Special case for the client id. $clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int'); - $clientId = (!\in_array($clientId, [0, 1])) ? 0 : $clientId; + $clientId = (\in_array($clientId, [0, 1])) ? $clientId : 0; $this->setState('client_id', $clientId); // Load the parameters. diff --git a/administrator/components/com_templates/src/View/Styles/HtmlView.php b/administrator/components/com_templates/src/View/Styles/HtmlView.php index 8833a8a174410..ed03d0dc73fac 100644 --- a/administrator/components/com_templates/src/View/Styles/HtmlView.php +++ b/administrator/components/com_templates/src/View/Styles/HtmlView.php @@ -29,6 +29,10 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var int + */ + public $total; /** * An array of items * diff --git a/administrator/components/com_templates/src/View/Template/HtmlView.php b/administrator/components/com_templates/src/View/Template/HtmlView.php index 98bd482ac993d..69db97169dd31 100644 --- a/administrator/components/com_templates/src/View/Template/HtmlView.php +++ b/administrator/components/com_templates/src/View/Template/HtmlView.php @@ -33,6 +33,15 @@ */ class HtmlView extends BaseHtmlView { + public $updatedList; + /** + * @var mixed[] + */ + public $styles; + /** + * @var string + */ + public $stylesHTML; /** * The Model state * @@ -154,7 +163,7 @@ class HtmlView extends BaseHtmlView * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null */ public function display($tpl = null) { @@ -222,6 +231,7 @@ public function display($tpl = null) } parent::display($tpl); + return null; } /** diff --git a/administrator/components/com_templates/src/View/Templates/HtmlView.php b/administrator/components/com_templates/src/View/Templates/HtmlView.php index ffe907ba60176..2e70db3b92aed 100644 --- a/administrator/components/com_templates/src/View/Templates/HtmlView.php +++ b/administrator/components/com_templates/src/View/Templates/HtmlView.php @@ -30,6 +30,10 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var int + */ + public $total; /** * The list of templates * diff --git a/administrator/components/com_templates/tmpl/template/default.php b/administrator/components/com_templates/tmpl/template/default.php index 82bd69830bbdf..01a1eaf8f537c 100644 --- a/administrator/components/com_templates/tmpl/template/default.php +++ b/administrator/components/com_templates/tmpl/template/default.php @@ -178,7 +178,7 @@   - +   diff --git a/administrator/components/com_templates/tmpl/template/default_tree.php b/administrator/components/com_templates/tmpl/template/default_tree.php index 17a923b4fcc72..5138c46d99319 100644 --- a/administrator/components/com_templates/tmpl/template/default_tree.php +++ b/administrator/components/com_templates/tmpl/template/default_tree.php @@ -32,11 +32,7 @@ } } - if ($count === $keyArrayCount) { - $class = 'folder show'; - } else { - $class = 'folder'; - } + $class = $count === $keyArrayCount ? 'folder show' : 'folder'; } else { $class = 'folder'; } diff --git a/administrator/components/com_templates/tmpl/template/default_tree_media.php b/administrator/components/com_templates/tmpl/template/default_tree_media.php index 66b5d0d9890a6..ec0c937c00e2a 100644 --- a/administrator/components/com_templates/tmpl/template/default_tree_media.php +++ b/administrator/components/com_templates/tmpl/template/default_tree_media.php @@ -38,11 +38,7 @@ } } - if ($count === $keyArrayCount) { - $class = 'folder show'; - } else { - $class = 'folder'; - } + $class = $count === $keyArrayCount ? 'folder show' : 'folder'; } else { $class = 'folder'; } diff --git a/administrator/components/com_users/src/Controller/GroupController.php b/administrator/components/com_users/src/Controller/GroupController.php index f3e0d4cb0e5b2..192ca8ec408e3 100644 --- a/administrator/components/com_users/src/Controller/GroupController.php +++ b/administrator/components/com_users/src/Controller/GroupController.php @@ -62,11 +62,9 @@ protected function allowSave($data, $key = 'id') protected function allowEdit($data = [], $key = 'id') { // Check if this group is a Super Admin - if (Access::checkGroup($data[$key], 'core.admin')) { - // If I'm not a Super Admin, then disallow the edit. - if (!$this->app->getIdentity()->authorise('core.admin')) { - return false; - } + // If I'm not a Super Admin, then disallow the edit. + if (Access::checkGroup($data[$key], 'core.admin') && !$this->app->getIdentity()->authorise('core.admin')) { + return false; } return parent::allowEdit($data, $key); diff --git a/administrator/components/com_users/src/Controller/LevelController.php b/administrator/components/com_users/src/Controller/LevelController.php index f4d36c7a69fa7..293a988e3ccd1 100644 --- a/administrator/components/com_users/src/Controller/LevelController.php +++ b/administrator/components/com_users/src/Controller/LevelController.php @@ -108,7 +108,7 @@ public function delete() throw new NotAllowed(Text::_('JERROR_ALERTNOAUTHOR'), 403); } - if (empty($ids)) { + if ($ids === []) { $this->setMessage(Text::_('COM_USERS_NO_LEVELS_SELECTED'), 'warning'); } else { // Get the model. diff --git a/administrator/components/com_users/src/Controller/MailController.php b/administrator/components/com_users/src/Controller/MailController.php index 0d94f6a25b0c0..36f655435c582 100644 --- a/administrator/components/com_users/src/Controller/MailController.php +++ b/administrator/components/com_users/src/Controller/MailController.php @@ -43,11 +43,7 @@ public function send() $model = $this->getModel('Mail'); - if ($model->send()) { - $type = 'message'; - } else { - $type = 'error'; - } + $type = $model->send() ? 'message' : 'error'; $msg = $model->getError(); $this->setRedirect('index.php?option=com_users&view=mail', $msg, $type); diff --git a/administrator/components/com_users/src/Controller/MethodController.php b/administrator/components/com_users/src/Controller/MethodController.php index 2816d28535fab..a20ea03f871f0 100644 --- a/administrator/components/com_users/src/Controller/MethodController.php +++ b/administrator/components/com_users/src/Controller/MethodController.php @@ -352,7 +352,7 @@ public function save($cachable = false, $urlparams = []): void $title = $this->input->getString('title', null); $title = trim($title); - if (empty($title)) { + if ($title === '' || $title === '0') { $method = $model->getMethod($record->method); $title = $method['display']; } @@ -468,7 +468,7 @@ private function assertMethodExists(?string $method): void /** @var MethodModel $model */ $model = $this->getModel('Method'); - if (empty($method) || !$model->methodExists($method)) { + if ($method === null || $method === '' || $method === '0' || !$model->methodExists($method)) { throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); } } diff --git a/administrator/components/com_users/src/Controller/UserController.php b/administrator/components/com_users/src/Controller/UserController.php index 0f130f410db1d..1beb11dc5e481 100644 --- a/administrator/components/com_users/src/Controller/UserController.php +++ b/administrator/components/com_users/src/Controller/UserController.php @@ -48,11 +48,9 @@ class UserController extends FormController protected function allowEdit($data = [], $key = 'id') { // Check if this person is a Super Admin - if (Access::check($data[$key], 'core.admin')) { - // If I'm not a Super Admin, then disallow the edit. - if (!$this->app->getIdentity()->authorise('core.admin')) { - return false; - } + // If I'm not a Super Admin, then disallow the edit. + if (Access::check($data[$key], 'core.admin') && !$this->app->getIdentity()->authorise('core.admin')) { + return false; } // Allow users to edit their own account diff --git a/administrator/components/com_users/src/Controller/UsersController.php b/administrator/components/com_users/src/Controller/UsersController.php index 9840b5708dd2e..9083d86745994 100644 --- a/administrator/components/com_users/src/Controller/UsersController.php +++ b/administrator/components/com_users/src/Controller/UsersController.php @@ -92,7 +92,7 @@ public function changeBlock() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->setMessage(Text::_('COM_USERS_USERS_NO_ITEM_SELECTED'), 'warning'); } else { // Get the model. @@ -101,12 +101,10 @@ public function changeBlock() // Change the state of the records. if (!$model->block($ids, $value)) { $this->setMessage($model->getError(), 'error'); - } else { - if ($value == 1) { - $this->setMessage(Text::plural('COM_USERS_N_USERS_BLOCKED', \count($ids))); - } elseif ($value == 0) { - $this->setMessage(Text::plural('COM_USERS_N_USERS_UNBLOCKED', \count($ids))); - } + } elseif ($value == 1) { + $this->setMessage(Text::plural('COM_USERS_N_USERS_BLOCKED', \count($ids))); + } elseif ($value == 0) { + $this->setMessage(Text::plural('COM_USERS_N_USERS_UNBLOCKED', \count($ids))); } } @@ -130,7 +128,7 @@ public function activate() // Remove zero values resulting from input filter $ids = array_filter($ids); - if (empty($ids)) { + if ($ids === []) { $this->setMessage(Text::_('COM_USERS_USERS_NO_ITEM_SELECTED'), 'error'); } else { // Get the model. diff --git a/administrator/components/com_users/src/Field/GroupparentField.php b/administrator/components/com_users/src/Field/GroupparentField.php index 905f1a2971204..4f7a832e575cb 100644 --- a/administrator/components/com_users/src/Field/GroupparentField.php +++ b/administrator/components/com_users/src/Field/GroupparentField.php @@ -70,7 +70,7 @@ protected function getOptions() $currentGroupId = (int) Factory::getApplication()->getInput()->get('id', 0, 'int'); // Prevent to set yourself as parent - if ($currentGroupId) { + if ($currentGroupId !== 0) { unset($options[$currentGroupId]); } diff --git a/administrator/components/com_users/src/Helper/DebugHelper.php b/administrator/components/com_users/src/Helper/DebugHelper.php index 2635774858057..7c7260eb167c9 100644 --- a/administrator/components/com_users/src/Helper/DebugHelper.php +++ b/administrator/components/com_users/src/Helper/DebugHelper.php @@ -46,15 +46,16 @@ public static function getComponents() $items = $db->setQuery($query)->loadObjectList(); - if (\count($items)) { + if (\count($items) > 0) { $lang = Factory::getLanguage(); foreach ($items as &$item) { // Load language $extension = $item->value; $source = JPATH_ADMINISTRATOR . '/components/' . $extension; - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) - || $lang->load("$extension.sys", $source); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", $source); + } // Translate component name $item->text = Text::_($item->text); @@ -98,16 +99,16 @@ public static function getDebugActions($component = null) } // Use default actions from configuration if no component selected or component doesn't have actions - if (empty($actions)) { + if ($actions === []) { $filename = JPATH_ADMINISTRATOR . '/components/com_config/forms/application.xml'; if (is_file($filename)) { $xml = simplexml_load_file($filename); foreach ($xml->children()->fieldset as $fieldset) { - if ('permissions' == (string) $fieldset['name']) { + if ('permissions' === (string) $fieldset['name']) { foreach ($fieldset->children() as $field) { - if ('rules' == (string) $field['name']) { + if ('rules' === (string) $field['name']) { foreach ($field->children() as $action) { $descr = (string) $action['title']; @@ -132,10 +133,11 @@ public static function getDebugActions($component = null) $extension = 'com_config'; $source = JPATH_ADMINISTRATOR . '/components/' . $extension; - $lang->load($extension, JPATH_ADMINISTRATOR, null, false, false) + if (!($lang->load($extension, JPATH_ADMINISTRATOR, null, false, false) || $lang->load($extension, $source, null, false, false) - || $lang->load($extension, JPATH_ADMINISTRATOR, $lang->getDefault(), false, false) - || $lang->load($extension, $source, $lang->getDefault(), false, false); + || $lang->load($extension, JPATH_ADMINISTRATOR, $lang->getDefault(), false, false))) { + $lang->load($extension, $source, $lang->getDefault(), false, false); + } } } @@ -149,15 +151,6 @@ public static function getDebugActions($component = null) */ public static function getLevelsOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '1', Text::sprintf('COM_USERS_OPTION_LEVEL_COMPONENT', 1)); - $options[] = HTMLHelper::_('select.option', '2', Text::sprintf('COM_USERS_OPTION_LEVEL_CATEGORY', 2)); - $options[] = HTMLHelper::_('select.option', '3', Text::sprintf('COM_USERS_OPTION_LEVEL_DEEPER', 3)); - $options[] = HTMLHelper::_('select.option', '4', '4'); - $options[] = HTMLHelper::_('select.option', '5', '5'); - $options[] = HTMLHelper::_('select.option', '6', '6'); - - return $options; + return [HTMLHelper::_('select.option', '1', Text::sprintf('COM_USERS_OPTION_LEVEL_COMPONENT', 1)), HTMLHelper::_('select.option', '2', Text::sprintf('COM_USERS_OPTION_LEVEL_CATEGORY', 2)), HTMLHelper::_('select.option', '3', Text::sprintf('COM_USERS_OPTION_LEVEL_DEEPER', 3)), HTMLHelper::_('select.option', '4', '4'), HTMLHelper::_('select.option', '5', '5'), HTMLHelper::_('select.option', '6', '6')]; } } diff --git a/administrator/components/com_users/src/Helper/Mfa.php b/administrator/components/com_users/src/Helper/Mfa.php index f102a580c206d..1f5619d11fe04 100644 --- a/administrator/components/com_users/src/Helper/Mfa.php +++ b/administrator/components/com_users/src/Helper/Mfa.php @@ -203,7 +203,7 @@ public static function canAddEditMethod(?User $user = null): bool $neverMFAGroups = ComponentHelper::getParams('com_users')->get('neverMFAUserGroups', []); $neverMFAGroups = \is_array($neverMFAGroups) ? $neverMFAGroups : []; - if (\count(array_intersect($user->getAuthorisedGroups(), $neverMFAGroups))) { + if (array_intersect($user->getAuthorisedGroups(), $neverMFAGroups) !== []) { return false; } @@ -257,7 +257,7 @@ public static function canDeleteMethod(?User $user = null): bool */ public static function getUserMfaRecords(?int $userId): array { - if (empty($userId)) { + if ($userId === null || $userId === 0) { $user = Factory::getApplication()->getIdentity() ?: Factory::getUser(); $userId = $user->id ?: 0; } @@ -331,7 +331,7 @@ function ($record) use (&$hasBackupCodes) { public static function canShowConfigurationInterface(?User $user = null): bool { // If I have no user to check against that's all the checking I can do. - if (empty($user)) { + if (!$user instanceof \Joomla\CMS\User\User) { return false; } diff --git a/administrator/components/com_users/src/Helper/UsersHelper.php b/administrator/components/com_users/src/Helper/UsersHelper.php index 171c3f99e4908..c1a4d34d5676e 100644 --- a/administrator/components/com_users/src/Helper/UsersHelper.php +++ b/administrator/components/com_users/src/Helper/UsersHelper.php @@ -43,12 +43,7 @@ class UsersHelper extends ContentHelper */ public static function getStateOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '0', Text::_('JENABLED')); - $options[] = HTMLHelper::_('select.option', '1', Text::_('JDISABLED')); - - return $options; + return [HTMLHelper::_('select.option', '0', Text::_('JENABLED')), HTMLHelper::_('select.option', '1', Text::_('JDISABLED'))]; } /** @@ -60,12 +55,7 @@ public static function getStateOptions() */ public static function getActiveOptions() { - // Build the filter options. - $options = []; - $options[] = HTMLHelper::_('select.option', '0', Text::_('COM_USERS_ACTIVATED')); - $options[] = HTMLHelper::_('select.option', '1', Text::_('COM_USERS_UNACTIVATED')); - - return $options; + return [HTMLHelper::_('select.option', '0', Text::_('COM_USERS_ACTIVATED')), HTMLHelper::_('select.option', '1', Text::_('COM_USERS_UNACTIVATED'))]; } /** diff --git a/administrator/components/com_users/src/Model/BackupcodesModel.php b/administrator/components/com_users/src/Model/BackupcodesModel.php index cae3ab133197b..db225c9d523a0 100644 --- a/administrator/components/com_users/src/Model/BackupcodesModel.php +++ b/administrator/components/com_users/src/Model/BackupcodesModel.php @@ -48,7 +48,7 @@ class BackupcodesModel extends BaseDatabaseModel public function getBackupCodesRecord(?User $user = null): ?MfaTable { // Make sure I have a user - if (empty($user)) { + if (!$user instanceof \Joomla\CMS\User\User) { $user = $this->getCurrentUser(); } @@ -81,7 +81,7 @@ public function getBackupCodesRecord(?User $user = null): ?MfaTable public function regenerateBackupCodes(?User $user = null): void { // Make sure I have a user - if (empty($user)) { + if (!$user instanceof \Joomla\CMS\User\User) { $user = $this->getCurrentUser(); } @@ -110,7 +110,7 @@ public function regenerateBackupCodes(?User $user = null): void public function saveBackupCodes(array $codes, ?User $user = null): bool { // Make sure I have a user - if (empty($user)) { + if (!$user instanceof \Joomla\CMS\User\User) { $user = $this->getCurrentUser(); } @@ -170,7 +170,7 @@ public function saveBackupCodes(array $codes, ?User $user = null): bool public function getBackupCodes(?User $user = null): ?array { // Make sure I have a user - if (empty($user)) { + if (!$user instanceof \Joomla\CMS\User\User) { $user = $this->getCurrentUser(); } diff --git a/administrator/components/com_users/src/Model/CaptiveModel.php b/administrator/components/com_users/src/Model/CaptiveModel.php index f67da8cbb59a6..6cf930a3d8847 100644 --- a/administrator/components/com_users/src/Model/CaptiveModel.php +++ b/administrator/components/com_users/src/Model/CaptiveModel.php @@ -90,7 +90,7 @@ public function getRecords(?User $user = null, bool $includeBackupCodes = false) $records = MfaHelper::getUserMfaRecords($user->id); // No MFA Methods? Then we obviously don't need to display a Captive login page. - if (empty($records)) { + if ($records === []) { return []; } @@ -136,7 +136,7 @@ private function getActiveMethodNames(): ?array $mfaMethods = MfaHelper::getMfaMethods(); // If no MFA Method is active we can't really display a Captive login page. - if (empty($mfaMethods)) { + if ($mfaMethods === []) { $this->activeMFAMethodNames = []; return $this->activeMFAMethodNames; @@ -209,7 +209,7 @@ public function loadCaptiveRenderOptions(?MfaTable $record): CaptiveRenderOption { $renderOptions = new CaptiveRenderOptions(); - if (empty($record)) { + if (!$record instanceof \Joomla\Component\Users\Administrator\Table\MfaTable) { return $renderOptions; } @@ -279,14 +279,14 @@ public function translateMethodName(string $name): string $map = []; $mfaMethods = MfaHelper::getMfaMethods(); - if (!empty($mfaMethods)) { + if ($mfaMethods !== []) { foreach ($mfaMethods as $mfaMethod) { $map[$mfaMethod['name']] = $mfaMethod['display']; } } } - if ($name == 'backupcodes') { + if ($name === 'backupcodes') { return Text::_('COM_USERS_USER_BACKUPCODES'); } @@ -309,14 +309,14 @@ public function getMethodImage(string $name): string $map = []; $mfaMethods = MfaHelper::getMfaMethods(); - if (!empty($mfaMethods)) { + if ($mfaMethods !== []) { foreach ($mfaMethods as $mfaMethod) { $map[$mfaMethod['name']] = $mfaMethod['image']; } } } - if ($name == 'backupcodes') { + if ($name === 'backupcodes') { return 'media/com_users/images/emergency.svg'; } @@ -343,7 +343,7 @@ public function onAfterModuleList(Module\AfterModuleListEvent $event): void { $modules = $event->getModules(); - if (empty($modules)) { + if ($modules === []) { return; } @@ -365,7 +365,7 @@ private function filterModules(array &$modules): void { $allowedPositions = $this->getAllowedModulePositions(); - if (empty($allowedPositions)) { + if ($allowedPositions === []) { $modules = []; return; diff --git a/administrator/components/com_users/src/Model/GroupModel.php b/administrator/components/com_users/src/Model/GroupModel.php index bcb16170e0977..0245b841a00df 100644 --- a/administrator/components/com_users/src/Model/GroupModel.php +++ b/administrator/components/com_users/src/Model/GroupModel.php @@ -179,7 +179,7 @@ public function save($data) $groupSuperAdmin = false; } elseif ($parentSuperAdmin === true) { // If parent is true (allowed), group is true unless explicitly set to false - $groupSuperAdmin = ($groupSuperAdmin === false) ? false : true; + $groupSuperAdmin = $groupSuperAdmin !== false; } // Check for non-super admin trying to save with super admin group diff --git a/administrator/components/com_users/src/Model/LevelModel.php b/administrator/components/com_users/src/Model/LevelModel.php index 634404dcda3b7..cd53282e59b3a 100644 --- a/administrator/components/com_users/src/Model/LevelModel.php +++ b/administrator/components/com_users/src/Model/LevelModel.php @@ -95,7 +95,7 @@ public function delete(&$pks) } } - if (!empty($levelsInUse)) { + if ($levelsInUse !== []) { $app = Factory::getApplication(); $app->enqueueMessage(Text::_('COM_USERS_ERROR_VIEW_LEVEL_IN_USE'), 'error'); @@ -105,7 +105,7 @@ public function delete(&$pks) } } - if (empty($pks)) { + if ($pks === []) { // Nothing left to delete return true; } diff --git a/administrator/components/com_users/src/Model/LevelsModel.php b/administrator/components/com_users/src/Model/LevelsModel.php index ba6f4033ebbef..dfe55d89ab0ad 100644 --- a/administrator/components/com_users/src/Model/LevelsModel.php +++ b/administrator/components/com_users/src/Model/LevelsModel.php @@ -150,7 +150,7 @@ protected function getListQuery() public function reorder($pk, $direction = 0) { // Sanitize the id and adjustment. - $pk = (!empty($pk)) ? $pk : (int) $this->getState('level.id'); + $pk = (empty($pk)) ? (int) $this->getState('level.id') : $pk; $user = $this->getCurrentUser(); // Get an instance of the record's table. diff --git a/administrator/components/com_users/src/Model/MailModel.php b/administrator/components/com_users/src/Model/MailModel.php index 143fb6d3f647f..6a8eba2626710 100644 --- a/administrator/components/com_users/src/Model/MailModel.php +++ b/administrator/components/com_users/src/Model/MailModel.php @@ -115,7 +115,7 @@ public function send() $message_body = \array_key_exists('message', $data) ? $data['message'] : ''; // Automatically removes html formatting - if (!$mode) { + if ($mode === 0) { $message_body = InputFilter::getInstance()->clean($message_body, 'string'); } @@ -186,14 +186,14 @@ public function send() ]; $mailer->addTemplateData($data); - $recipientType = $bcc ? 'bcc' : 'to'; + $recipientType = $bcc !== 0 ? 'bcc' : 'to'; // Add recipients foreach ($rows as $row) { $mailer->addRecipient($row->email, $row->name, $recipientType); } - if ($bcc) { + if ($bcc !== 0) { $mailer->addRecipient($app->get('mailfrom'), $app->get('fromname')); } @@ -219,7 +219,7 @@ public function send() return false; } - if (empty($rs)) { + if ($rs === false) { $app->setUserState('com_users.display.mail.data', $data); $this->setError(Text::_('COM_USERS_MAIL_THE_MAIL_COULD_NOT_BE_SENT')); diff --git a/administrator/components/com_users/src/Model/MethodModel.php b/administrator/components/com_users/src/Model/MethodModel.php index df3a3f6a8f681..77cf5dd5a44f9 100644 --- a/administrator/components/com_users/src/Model/MethodModel.php +++ b/administrator/components/com_users/src/Model/MethodModel.php @@ -231,7 +231,7 @@ private function populateMfaMethods(): void $this->mfaMethods = []; $mfaMethods = MfaHelper::getMfaMethods(); - if (empty($mfaMethods)) { + if ($mfaMethods === []) { return; } diff --git a/administrator/components/com_users/src/Model/MethodsModel.php b/administrator/components/com_users/src/Model/MethodsModel.php index 0efe426b28c1c..3c35b3c6dc1a6 100644 --- a/administrator/components/com_users/src/Model/MethodsModel.php +++ b/administrator/components/com_users/src/Model/MethodsModel.php @@ -61,7 +61,7 @@ public function getMethods(?User $user = null): array // Put the user MFA records into the Methods array $userMfaRecords = MfaHelper::getUserMfaRecords($user->id); - if (!empty($userMfaRecords)) { + if ($userMfaRecords !== []) { foreach ($userMfaRecords as $record) { if (!isset($methods[$record->method])) { continue; @@ -119,7 +119,7 @@ public function deleteAll(?User $user = null): void */ public function formatRelative(?string $dateTimeText): string { - if (empty($dateTimeText)) { + if ($dateTimeText === null || $dateTimeText === '' || $dateTimeText === '0') { return Text::_('JNEVER'); } @@ -152,7 +152,7 @@ public function formatRelative(?string $dateTimeText): string $checkNow = $jNow->format('Ymd', true); $checkDate = $jDate->format('Ymd', true); - if ($checkDate == $checkNow) { + if ($checkDate === $checkNow) { $formatString = Text::_('COM_USERS_MFA_LBL_DATE_FORMAT_TODAY'); $containerString = Text::_('COM_USERS_MFA_LBL_TODAY'); } else { @@ -163,7 +163,7 @@ public function formatRelative(?string $dateTimeText): string $jYesterday->sub($oneSecond); $checkYesterday = $jYesterday->format('Ymd', true); - if ($checkDate == $checkYesterday) { + if ($checkDate === $checkYesterday) { $formatString = Text::_('COM_USERS_MFA_LBL_DATE_FORMAT_YESTERDAY'); $containerString = Text::_('COM_USERS_MFA_LBL_YESTERDAY'); } diff --git a/administrator/components/com_users/src/Model/NotesModel.php b/administrator/components/com_users/src/Model/NotesModel.php index 6e847e511aa18..1e935635b4d49 100644 --- a/administrator/components/com_users/src/Model/NotesModel.php +++ b/administrator/components/com_users/src/Model/NotesModel.php @@ -132,7 +132,7 @@ protected function getListQuery() // Filter by a single category. $categoryId = (int) $this->getState('filter.category_id'); - if ($categoryId) { + if ($categoryId !== 0) { $query->where($db->quoteName('a.catid') . ' = :catid') ->bind(':catid', $categoryId, ParameterType::INTEGER); } @@ -140,7 +140,7 @@ protected function getListQuery() // Filter by a single user. $userId = (int) $this->getState('filter.user_id'); - if ($userId) { + if ($userId !== 0) { // Add the body and where filter. $query->select('a.body') ->where($db->quoteName('a.user_id') . ' = :user_id') diff --git a/administrator/components/com_users/src/Model/UserModel.php b/administrator/components/com_users/src/Model/UserModel.php index 889add8c3d370..f75a91393c6d0 100644 --- a/administrator/components/com_users/src/Model/UserModel.php +++ b/administrator/components/com_users/src/Model/UserModel.php @@ -100,7 +100,7 @@ public function getTable($type = 'User', $prefix = 'Joomla\\CMS\\Table\\', $conf */ public function getItem($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('user.id'); + $pk = (empty($pk)) ? (int) $this->getState('user.id') : $pk; if ($this->_item === null) { $this->_item = []; @@ -224,14 +224,14 @@ protected function preprocessForm(Form $form, $data, $group = 'user') */ public function save($data) { - $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('user.id'); + $pk = (empty($data['id'])) ? (int) $this->getState('user.id') : $data['id']; $user = $this->getUserFactory()->loadUserById($pk); $my = $this->getCurrentUser(); $iAmSuperAdmin = $my->authorise('core.admin'); // User cannot modify own user groups - if ((int) $user->id == (int) $my->id && !$iAmSuperAdmin && isset($data['groups'])) { + if ((int) $user->id === (int) $my->id && !$iAmSuperAdmin && isset($data['groups'])) { // Form was probably tampered with Factory::getApplication()->enqueueMessage(Text::_('COM_USERS_USERS_ERROR_CANNOT_EDIT_OWN_GROUP'), 'warning'); @@ -245,7 +245,7 @@ public function save($data) } // Make sure user groups is selected when add/edit an account - if (empty($data['groups']) && ((int) $user->id != (int) $my->id || $iAmSuperAdmin)) { + if (empty($data['groups']) && ((int) $user->id !== (int) $my->id || $iAmSuperAdmin)) { $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_SAVE_ACCOUNT_WITHOUT_GROUPS')); return false; @@ -445,7 +445,7 @@ public function block(&$pks, $value = 1) return false; } - if ($table->block) { + if ($table->block !== 0) { UserHelper::destroyUserSessions($table->id); } @@ -635,16 +635,12 @@ public function batchReset($userIds, $action) } // Set the action to perform - if ($action === 'yes') { - $value = 1; - } else { - $value = 0; - } + $value = $action === 'yes' ? 1 : 0; // Prune out the current user if they are in the supplied user ID array $userIds = array_diff($userIds, [$this->getCurrentUser()->id]); - if (empty($userIds)) { + if ($userIds === []) { $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_REQUIRERESET_SELF')); return false; @@ -874,7 +870,7 @@ public function getGroups() */ public function getAssignedGroups($userId = null) { - $userId = (!empty($userId)) ? $userId : (int) $this->getState('user.id'); + $userId = (empty($userId)) ? (int) $this->getState('user.id') : $userId; if (empty($userId)) { $result = []; diff --git a/administrator/components/com_users/src/Model/UsersModel.php b/administrator/components/com_users/src/Model/UsersModel.php index a534c1de0c8fb..7c1b7f683f3a9 100644 --- a/administrator/components/com_users/src/Model/UsersModel.php +++ b/administrator/components/com_users/src/Model/UsersModel.php @@ -167,11 +167,7 @@ public function getItems() $groups = $this->getState('filter.groups'); $groupId = $this->getState('filter.group_id'); - if (isset($groups) && (empty($groups) || $groupId && !\in_array($groupId, $groups))) { - $items = []; - } else { - $items = parent::getItems(); - } + $items = isset($groups) && (empty($groups) || $groupId && !\in_array($groupId, $groups)) ? [] : parent::getItems(); // Bail out on an error or empty list. if (empty($items)) { @@ -437,15 +433,10 @@ protected function getListQuery() // Apply the range filter. if ($range || ($registrationStart && $registrationEnd)) { - if ($range) { - $dates = $this->buildDateRange($range); - } else { - $dates = [ - 'dNow' => $registrationEnd, - 'dStart' => $registrationStart, - ]; - } - + $dates = $range ? $this->buildDateRange($range) : [ + 'dNow' => $registrationEnd, + 'dStart' => $registrationStart, + ]; if ($dates['dStart'] !== false) { $dStart = $dates['dStart']->format('Y-m-d H:i:s'); diff --git a/administrator/components/com_users/src/Service/HTML/Users.php b/administrator/components/com_users/src/Service/HTML/Users.php index 23b33abba7961..4e48970c31b5e 100644 --- a/administrator/components/com_users/src/Service/HTML/Users.php +++ b/administrator/components/com_users/src/Service/HTML/Users.php @@ -267,6 +267,7 @@ public function value($value) if (!\is_array($value)) { return htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8'); } + return null; } /** @@ -413,10 +414,10 @@ public function editor($value) $title = $db->loadResult(); if ($title) { - $lang->load("plg_editors_$value.sys", JPATH_ADMINISTRATOR) - || $lang->load("plg_editors_$value.sys", JPATH_PLUGINS . '/editors/' . $value); + if (!$lang->load("plg_editors_$value.sys", JPATH_ADMINISTRATOR)) { + $lang->load("plg_editors_$value.sys", JPATH_PLUGINS . '/editors/' . $value); + } $lang->load($title . '.sys'); - return Text::_($title); } diff --git a/administrator/components/com_users/src/Table/MfaTable.php b/administrator/components/com_users/src/Table/MfaTable.php index a7ff6ac6b280c..1fea968b1e188 100644 --- a/administrator/components/com_users/src/Table/MfaTable.php +++ b/administrator/components/com_users/src/Table/MfaTable.php @@ -109,7 +109,7 @@ public function store($updateNulls = true) $this->options = $this->encryptService->encrypt(json_encode($this->options ?: [])); // Set last_used date to null if empty or zero date - if (!((int) $this->last_used)) { + if ((int) $this->last_used === 0) { $this->last_used = null; } diff --git a/administrator/components/com_users/src/Table/NoteTable.php b/administrator/components/com_users/src/Table/NoteTable.php index 816011df83798..e64fcf413b830 100644 --- a/administrator/components/com_users/src/Table/NoteTable.php +++ b/administrator/components/com_users/src/Table/NoteTable.php @@ -69,7 +69,7 @@ public function store($updateNulls = true) $date = Factory::getDate()->toSql(); $userId = $this->getCurrentUser()->id; - if (!((int) $this->review_time)) { + if ((int) $this->review_time === 0) { $this->review_time = null; } diff --git a/administrator/components/com_users/src/View/Methods/HtmlView.php b/administrator/components/com_users/src/View/Methods/HtmlView.php index 19ddba506c657..c59db767e7c54 100644 --- a/administrator/components/com_users/src/View/Methods/HtmlView.php +++ b/administrator/components/com_users/src/View/Methods/HtmlView.php @@ -125,7 +125,7 @@ public function display($tpl = null): void foreach ($this->methods as $methodName => $method) { $methodActiveRecords = \count($method['active']); - if (!$methodActiveRecords) { + if ($methodActiveRecords === 0) { continue; } diff --git a/administrator/components/com_users/src/View/Note/HtmlView.php b/administrator/components/com_users/src/View/Note/HtmlView.php index 6d6f5d4bf3275..abeba0d4e1c5f 100644 --- a/administrator/components/com_users/src/View/Note/HtmlView.php +++ b/administrator/components/com_users/src/View/Note/HtmlView.php @@ -100,7 +100,7 @@ protected function addToolbar() $user = $this->getCurrentUser(); $isNew = ($this->item->id == 0); - $checkedOut = !(\is_null($this->item->checked_out) || $this->item->checked_out == $user->id); + $checkedOut = !\is_null($this->item->checked_out) && $this->item->checked_out != $user->id; $toolbar = $this->getDocument()->getToolbar(); // Since we don't track these assets at the item level, use the category id. diff --git a/administrator/components/com_users/src/View/SiteTemplateTrait.php b/administrator/components/com_users/src/View/SiteTemplateTrait.php index 9e064b67b9775..43839687b6461 100644 --- a/administrator/components/com_users/src/View/SiteTemplateTrait.php +++ b/administrator/components/com_users/src/View/SiteTemplateTrait.php @@ -36,7 +36,7 @@ private function setSiteTemplateStyle(): void $app = Factory::getApplication(); $templateStyle = (int) ComponentHelper::getParams('com_users')->get('captive_template', ''); - if (empty($templateStyle) || !$app->isClient('site')) { + if ($templateStyle === 0 || !$app->isClient('site')) { return; } diff --git a/administrator/components/com_users/src/View/User/HtmlView.php b/administrator/components/com_users/src/View/User/HtmlView.php index b361d18ae1ccc..664b59af6e86d 100644 --- a/administrator/components/com_users/src/View/User/HtmlView.php +++ b/administrator/components/com_users/src/View/User/HtmlView.php @@ -120,7 +120,7 @@ public function display($tpl = null) // Prevent user from modifying own group(s) $user = $this->getCurrentUser(); - if ((int) $user->id != (int) $this->item->id || $user->authorise('core.admin')) { + if ((int) $user->id !== (int) $this->item->id || $user->authorise('core.admin')) { $this->grouplist = $model->getGroups(); $this->groups = $model->getAssignedGroups(); } @@ -130,7 +130,7 @@ public function display($tpl = null) $userBeingEdited = $this->getUserFactory()->loadUserById($this->item->id); - if ($this->item->id > 0 && (int) $userBeingEdited->id == (int) $this->item->id) { + if ($this->item->id > 0 && (int) $userBeingEdited->id === (int) $this->item->id) { try { $this->mfaConfigurationUI = Mfa::canShowConfigurationInterface($userBeingEdited) ? Mfa::getConfigurationInterface($userBeingEdited) diff --git a/administrator/components/com_users/tmpl/methods/default.php b/administrator/components/com_users/tmpl/methods/default.php index f9a325a3436a2..a1d48b8600674 100644 --- a/administrator/components/com_users/tmpl/methods/default.php +++ b/administrator/components/com_users/tmpl/methods/default.php @@ -33,7 +33,7 @@ class="btn btn-danger btn-sm"> - methods)) : ?> + methods) === 0) : ?>
    diff --git a/administrator/components/com_users/tmpl/methods/list.php b/administrator/components/com_users/tmpl/methods/list.php index 74ddbb3f9c30b..f971315d704e4 100644 --- a/administrator/components/com_users/tmpl/methods/list.php +++ b/administrator/components/com_users/tmpl/methods/list.php @@ -37,7 +37,7 @@ $methodClass = 'com-users-methods-list-method-name-' . htmlentities((string) $method['name']) . ($this->defaultMethod == $methodName ? ' com-users-methods-list-method-default' : ''); ?> -
    +
    - + 0) : ?>
    diff --git a/administrator/components/com_users/tmpl/users/modal.php b/administrator/components/com_users/tmpl/users/modal.php index ee6773a60ebd1..7800a598333b5 100644 --- a/administrator/components/com_users/tmpl/users/modal.php +++ b/administrator/components/com_users/tmpl/users/modal.php @@ -33,7 +33,7 @@ ?>
    - +

    diff --git a/administrator/modules/mod_latestactions/tmpl/default.php b/administrator/modules/mod_latestactions/tmpl/default.php index a36b6fc510125..ead0adcb3701c 100644 --- a/administrator/modules/mod_latestactions/tmpl/default.php +++ b/administrator/modules/mod_latestactions/tmpl/default.php @@ -23,7 +23,7 @@
    diff --git a/administrator/modules/mod_menu/src/Menu/CssMenu.php b/administrator/modules/mod_menu/src/Menu/CssMenu.php index 589c00eccef3c..08e8cec8efe73 100644 --- a/administrator/modules/mod_menu/src/Menu/CssMenu.php +++ b/administrator/modules/mod_menu/src/Menu/CssMenu.php @@ -311,7 +311,7 @@ protected function preprocess($parent) * processing. It is needed for links from menu items of third party extensions link to Joomla! core * components like com_categories, com_fields... */ - $item->element = !empty($uri->getVar('option')) ? $uri->getVar('option') : ''; + $item->element = empty($uri->getVar('option')) ? '' : $uri->getVar('option'); // Exclude item if is not enabled if ($item->element !== '' && !ComponentHelper::isEnabled($item->element)) { @@ -458,8 +458,7 @@ protected function preprocess($parent) } // Ok we passed everything, load language at last only - if (!empty($item->element)) { - $language->load($item->element . '.sys', JPATH_ADMINISTRATOR) || + if (!empty($item->element) && !$language->load($item->element . '.sys', JPATH_ADMINISTRATOR)) { $language->load($item->element . '.sys', JPATH_ADMINISTRATOR . '/components/' . $item->element); } @@ -490,10 +489,10 @@ protected function preprocess($parent) */ public function getIconClass($node) { - $identifier = !empty($node->class) ? $node->class : ''; + $identifier = empty($node->class) ? '' : $node->class; // Top level is special - if (trim($identifier) == '') { + if (trim($identifier) === '') { return null; } diff --git a/administrator/modules/mod_menu/tmpl/default_submenu.php b/administrator/modules/mod_menu/tmpl/default_submenu.php index 88f7beb0be511..76d66f6109056 100644 --- a/administrator/modules/mod_menu/tmpl/default_submenu.php +++ b/administrator/modules/mod_menu/tmpl/default_submenu.php @@ -81,7 +81,7 @@ // Get the menu icon $icon = $this->getIconClass($current); $iconClass = ($icon != '' && $current->level == 1) ? '' : ''; -$ajax = !empty($current->ajaxbadge) ? '' : ''; +$ajax = empty($current->ajaxbadge) ? '' : ''; $iconImage = $current->icon; $homeImage = ''; @@ -90,7 +90,7 @@ } if ($iconImage) { - if (str_starts_with($iconImage, 'class:') && substr($iconImage, 6) == 'icon-home') { + if (str_starts_with($iconImage, 'class:') && substr($iconImage, 6) === 'icon-home') { $iconImage = ''; $iconImage .= '' . Text::_('JDEFAULT') . ''; } elseif (str_starts_with($iconImage, 'image:')) { @@ -103,7 +103,7 @@ $itemImage = (empty($itemIconClass) && $itemImage) ? '  ' : ''; // If the item image is not set, the item title would not have margin. Here we add it. -if ($icon == '' && $iconClass == '' && $current->level == 1 && $current->target == '') { +if ($icon == '' && $iconClass === '' && $current->level == 1 && $current->target == '') { $iconClass = ''; } diff --git a/administrator/modules/mod_popular/mod_popular.php b/administrator/modules/mod_popular/mod_popular.php index 1896c3d58aff5..cf299933a706d 100644 --- a/administrator/modules/mod_popular/mod_popular.php +++ b/administrator/modules/mod_popular/mod_popular.php @@ -34,7 +34,7 @@ } // If there are some articles to display. -if (\count($list)) { +if (\count($list) > 0) { require ModuleHelper::getLayoutPath('mod_popular', $params->get('layout', 'default')); return; diff --git a/administrator/modules/mod_popular/src/Helper/PopularHelper.php b/administrator/modules/mod_popular/src/Helper/PopularHelper.php index 926196117773e..60dab03c2031b 100644 --- a/administrator/modules/mod_popular/src/Helper/PopularHelper.php +++ b/administrator/modules/mod_popular/src/Helper/PopularHelper.php @@ -109,7 +109,7 @@ public static function getTitle($params) $catid = (int) $params->get('catid', null); $title = ''; - if ($catid) { + if ($catid !== 0) { $category = Categories::getInstance('Content')->get($catid); $title = Text::_('MOD_POPULAR_UNEXISTING'); @@ -119,7 +119,7 @@ public static function getTitle($params) } return Text::plural( - 'MOD_POPULAR_TITLE' . ($catid ? '_CATEGORY' : '') . ($who != '0' ? "_$who" : ''), + 'MOD_POPULAR_TITLE' . ($catid !== 0 ? '_CATEGORY' : '') . ($who != '0' ? "_$who" : ''), (int) $params->get('count', 5), $title ); diff --git a/administrator/modules/mod_popular/tmpl/default.php b/administrator/modules/mod_popular/tmpl/default.php index 4949093a8177e..a07f8f490ce96 100644 --- a/administrator/modules/mod_popular/tmpl/default.php +++ b/administrator/modules/mod_popular/tmpl/default.php @@ -26,7 +26,7 @@
    - + 0) : ?>
    diff --git a/administrator/modules/mod_privacy_status/src/Helper/PrivacyStatusHelper.php b/administrator/modules/mod_privacy_status/src/Helper/PrivacyStatusHelper.php index f290d7a2146e7..f8944a38a9eea 100644 --- a/administrator/modules/mod_privacy_status/src/Helper/PrivacyStatusHelper.php +++ b/administrator/modules/mod_privacy_status/src/Helper/PrivacyStatusHelper.php @@ -135,7 +135,7 @@ public static function getRequestFormPublished() $db->setQuery($query); $homeId = (int) $db->loadResult(); - $itemId = $homeId ? '&Itemid=' . $homeId : ''; + $itemId = $homeId !== 0 ? '&Itemid=' . $homeId : ''; } else { $itemId = ''; } diff --git a/administrator/modules/mod_submenu/src/Menu/Menu.php b/administrator/modules/mod_submenu/src/Menu/Menu.php index 62ae7602f09b8..946a8dbee514d 100644 --- a/administrator/modules/mod_submenu/src/Menu/Menu.php +++ b/administrator/modules/mod_submenu/src/Menu/Menu.php @@ -224,8 +224,7 @@ public static function preprocess($parent) } // Ok we passed everything, load language at last only - if ($item->element) { - $language->load($item->element . '.sys', JPATH_ADMINISTRATOR) || + if ($item->element && !$language->load($item->element . '.sys', JPATH_ADMINISTRATOR)) { $language->load($item->element . '.sys', JPATH_ADMINISTRATOR . '/components/' . $item->element); } diff --git a/administrator/modules/mod_title/src/Dispatcher/Dispatcher.php b/administrator/modules/mod_title/src/Dispatcher/Dispatcher.php index 9beaf2a43295d..c82e4e329a98c 100644 --- a/administrator/modules/mod_title/src/Dispatcher/Dispatcher.php +++ b/administrator/modules/mod_title/src/Dispatcher/Dispatcher.php @@ -36,7 +36,7 @@ protected function getLayoutData() // Get the component title div // @deprecated 5.2.0 will be removed in 7.0 as this property is not used anymore see WebApplication - if (isset($this->getApplication()->JComponentTitle)) { + if (property_exists($this->getApplication(), 'JComponentTitle') && $this->getApplication()->JComponentTitle !== null) { $data['title'] = $this->getApplication()->JComponentTitle; } diff --git a/administrator/modules/mod_user/tmpl/default.php b/administrator/modules/mod_user/tmpl/default.php index e855c4b2f2d92..33dc79b80f171 100644 --- a/administrator/modules/mod_user/tmpl/default.php +++ b/administrator/modules/mod_user/tmpl/default.php @@ -24,7 +24,7 @@ $tParams = $app->getTemplate(true)->params; // Not all templates support a colorScheme -$colorSchemeSwitch = !!$tParams->get('colorScheme'); +$colorSchemeSwitch = (bool) $tParams->get('colorScheme'); // Load the Bootstrap Dropdown HTMLHelper::_('bootstrap.dropdown', '.dropdown-toggle'); diff --git a/administrator/templates/atum/component.php b/administrator/templates/atum/component.php index 22554425a0a27..ba7fbebf42002 100644 --- a/administrator/templates/atum/component.php +++ b/administrator/templates/atum/component.php @@ -76,7 +76,7 @@ $themeModes = ['os' => ' data-color-scheme-os', 'light' => ' data-bs-theme="light" data-color-scheme="light"', 'dark' => ' data-bs-theme="dark" data-color-scheme="dark"']; // Check for User choose, for now this have a priority over the parameters $userColorScheme = $app->getInput()->cookie->get('userColorScheme', ''); - if ($userColorScheme && !empty($themeModes[$userColorScheme])) { + if ($userColorScheme && (isset($themeModes[$userColorScheme]) && ($themeModes[$userColorScheme] !== '' && $themeModes[$userColorScheme] !== '0'))) { $themeModeAttr = $themeModes[$userColorScheme]; } else { // Check parameters first (User and Template), then look if we have detected the OS color scheme (if it set to 'os') diff --git a/administrator/templates/atum/error_full.php b/administrator/templates/atum/error_full.php index 88655b6ca8781..e0a8508c76f1d 100644 --- a/administrator/templates/atum/error_full.php +++ b/administrator/templates/atum/error_full.php @@ -85,7 +85,7 @@ $themeModes = ['os' => ' data-color-scheme-os', 'light' => ' data-bs-theme="light" data-color-scheme="light"', 'dark' => ' data-bs-theme="dark" data-color-scheme="dark"']; // Check for User choose, for now this have a priority over the parameters $userColorScheme = $app->getInput()->cookie->get('userColorScheme', ''); - if ($userColorScheme && !empty($themeModes[$userColorScheme])) { + if ($userColorScheme && (isset($themeModes[$userColorScheme]) && ($themeModes[$userColorScheme] !== '' && $themeModes[$userColorScheme] !== '0'))) { $themeModeAttr = $themeModes[$userColorScheme]; } else { // Check parameters first (User and Template), then look if we have detected the OS color scheme (if it set to 'os') @@ -156,7 +156,7 @@
    renderBacktrace(); ?> - error->getPrevious()) : ?> + error->getPrevious() instanceof \Throwable) : ?> _error here and in the loop as setError() assigns errors to this property and we need this for the backtrace to work correctly ?> diff --git a/administrator/templates/atum/error_login.php b/administrator/templates/atum/error_login.php index 92c7bd900f6f6..fbd83c2342f00 100644 --- a/administrator/templates/atum/error_login.php +++ b/administrator/templates/atum/error_login.php @@ -89,7 +89,7 @@ $themeModes = ['os' => ' data-color-scheme-os', 'light' => ' data-bs-theme="light" data-color-scheme="light"', 'dark' => ' data-bs-theme="dark" data-color-scheme="dark"']; // Check for User choose, for now this have a priority over the parameters $userLastMode = $app->getInput()->cookie->get('userColorScheme', ''); - if ($userLastMode && !empty($themeModes[$userLastMode])) { + if ($userLastMode && (isset($themeModes[$userLastMode]) && ($themeModes[$userLastMode] !== '' && $themeModes[$userLastMode] !== '0'))) { $themeModeAttr = $themeModes[$userLastMode]; } else { // Check parameters first (User and Template), then look if we have detected the OS color scheme (if it set to 'os') @@ -150,7 +150,7 @@
    renderBacktrace(); ?> - error->getPrevious()) : ?> + error->getPrevious() instanceof \Throwable) : ?> _error here and in the loop as setError() assigns errors to this property and we need this for the backtrace to work correctly ?> diff --git a/administrator/templates/atum/html/layouts/chromes/body.php b/administrator/templates/atum/html/layouts/chromes/body.php index 453fab6a8d8c6..8b4ce336894a2 100644 --- a/administrator/templates/atum/html/layouts/chromes/body.php +++ b/administrator/templates/atum/html/layouts/chromes/body.php @@ -31,7 +31,7 @@ $moduleTag = $params->get('module_tag', 'div'); $bootstrapSize = (int) $params->get('bootstrap_size', 6); -$moduleClass = $bootstrapSize ? 'col-md-' . $bootstrapSize : 'col-md-12'; +$moduleClass = $bootstrapSize !== 0 ? 'col-md-' . $bootstrapSize : 'col-md-12'; $headerTag = htmlspecialchars((string) $params->get('header_tag', 'h2'), ENT_QUOTES, 'UTF-8'); $moduleClassSfx = $params->get('moduleclass_sfx', ''); diff --git a/administrator/templates/atum/html/layouts/chromes/well.php b/administrator/templates/atum/html/layouts/chromes/well.php index 743a7face8821..1c7f3809c03a3 100644 --- a/administrator/templates/atum/html/layouts/chromes/well.php +++ b/administrator/templates/atum/html/layouts/chromes/well.php @@ -32,7 +32,7 @@ $moduleTag = $params->get('module_tag', 'div'); $bootstrapSize = (int) $params->get('bootstrap_size', 12); -$moduleClass = $bootstrapSize ? 'col-md-' . $bootstrapSize : 'col-md-12'; +$moduleClass = $bootstrapSize !== 0 ? 'col-md-' . $bootstrapSize : 'col-md-12'; $headerTag = htmlspecialchars((string) $params->get('header_tag', 'h2'), ENT_QUOTES, 'UTF-8'); $moduleClassSfx = $params->get('moduleclass_sfx', ''); diff --git a/administrator/templates/atum/html/layouts/status.php b/administrator/templates/atum/html/layouts/status.php index d21a3c4cb94e5..89f533da17ef6 100644 --- a/administrator/templates/atum/html/layouts/status.php +++ b/administrator/templates/atum/html/layouts/status.php @@ -32,11 +32,7 @@ $dom->loadHTML('' . $out); $els = $dom->getElementsByTagName('a'); - if ($els[0]) { - $moduleCollapsedHtml[] = $dom->saveHTML($els[0]); - } else { - $moduleCollapsedHtml[] = $out; - } + $moduleCollapsedHtml[] = $els[0] ? $dom->saveHTML($els[0]) : $out; } else { $moduleCollapsedHtml[] = $out; } diff --git a/administrator/templates/atum/index.php b/administrator/templates/atum/index.php index 33e346bcb211d..2640b984d4ea7 100644 --- a/administrator/templates/atum/index.php +++ b/administrator/templates/atum/index.php @@ -113,7 +113,7 @@ function adjustColorLightness($r, $g, $b, $percent) $themeModes = ['os' => ' data-color-scheme-os', 'light' => ' data-bs-theme="light" data-color-scheme="light"', 'dark' => ' data-bs-theme="dark" data-color-scheme="dark"']; // Check for User choose, for now this have a priority over the parameters $userColorScheme = $app->getInput()->cookie->get('userColorScheme', ''); - if ($userColorScheme && !empty($themeModes[$userColorScheme])) { + if ($userColorScheme && (isset($themeModes[$userColorScheme]) && ($themeModes[$userColorScheme] !== '' && $themeModes[$userColorScheme] !== '0'))) { $themeModeAttr = $themeModes[$userColorScheme]; } else { // Check parameters first (User and Template), then look if we have detected the OS color scheme (if it set to 'os') diff --git a/administrator/templates/atum/login.php b/administrator/templates/atum/login.php index afc8e6c08955c..f9a8ae808e562 100644 --- a/administrator/templates/atum/login.php +++ b/administrator/templates/atum/login.php @@ -83,7 +83,7 @@ $themeModes = ['os' => ' data-color-scheme-os', 'light' => ' data-bs-theme="light" data-color-scheme="light"', 'dark' => ' data-bs-theme="dark" data-color-scheme="dark"']; // Check for User choose, for now this have a priority over the parameters $userColorScheme = $app->getInput()->cookie->get('userColorScheme', ''); - if ($userColorScheme && !empty($themeModes[$userColorScheme])) { + if ($userColorScheme && (isset($themeModes[$userColorScheme]) && ($themeModes[$userColorScheme] !== '' && $themeModes[$userColorScheme] !== '0'))) { $themeModeAttr = $themeModes[$userColorScheme]; } else { // Check parameters first (User and Template), then look if we have detected the OS color scheme (if it set to 'os') diff --git a/administrator/templates/system/error.php b/administrator/templates/system/error.php index d469a07a1b1c9..7f6ec0bd5c4d8 100644 --- a/administrator/templates/system/error.php +++ b/administrator/templates/system/error.php @@ -48,7 +48,7 @@
    renderBacktrace(); ?> - error->getPrevious()) : ?> + error->getPrevious() instanceof \Throwable) : ?> _error here and in the loop as setError() assigns errors to this property and we need this for the backtrace to work correctly?> diff --git a/api/components/com_config/src/Controller/ApplicationController.php b/api/components/com_config/src/Controller/ApplicationController.php index a9c3215ca9b8d..e2abccaf46e6b 100644 --- a/api/components/com_config/src/Controller/ApplicationController.php +++ b/api/components/com_config/src/Controller/ApplicationController.php @@ -66,7 +66,7 @@ public function displayList() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } /** @var ApplicationModel $model */ @@ -127,11 +127,7 @@ public function edit() $messages = []; for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) { - if ($errors[$i] instanceof \Exception) { - $messages[] = "{$errors[$i]->getMessage()}"; - } else { - $messages[] = "{$errors[$i]}"; - } + $messages[] = $errors[$i] instanceof \Exception ? "{$errors[$i]->getMessage()}" : "{$errors[$i]}"; } throw new InvalidParameterException(implode("\n", $messages)); diff --git a/api/components/com_config/src/Controller/ComponentController.php b/api/components/com_config/src/Controller/ComponentController.php index 092466d50cf28..b225f6a659554 100644 --- a/api/components/com_config/src/Controller/ComponentController.php +++ b/api/components/com_config/src/Controller/ComponentController.php @@ -68,7 +68,7 @@ public function displayList() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } /** @var ComponentModel $model */ @@ -131,11 +131,7 @@ public function edit() $messages = []; for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) { - if ($errors[$i] instanceof \Exception) { - $messages[] = "{$errors[$i]->getMessage()}"; - } else { - $messages[] = "{$errors[$i]}"; - } + $messages[] = $errors[$i] instanceof \Exception ? "{$errors[$i]->getMessage()}" : "{$errors[$i]}"; } throw new InvalidParameterException(implode("\n", $messages)); diff --git a/api/components/com_contact/src/Controller/ContactController.php b/api/components/com_contact/src/Controller/ContactController.php index 625946cbc7ea7..92f2885e3cebb 100644 --- a/api/components/com_contact/src/Controller/ContactController.php +++ b/api/components/com_contact/src/Controller/ContactController.php @@ -75,8 +75,9 @@ protected function preprocessSaveData(array $data): array { foreach (FieldsHelper::getFields('com_contact.contact') as $field) { if (isset($data[$field->name])) { - !isset($data['com_fields']) && $data['com_fields'] = []; - + if (!isset($data['com_fields'])) { + $data['com_fields'] = []; + } $data['com_fields'][$field->name] = $data[$field->name]; unset($data[$field->name]); } @@ -140,11 +141,7 @@ public function submitForm($id = null) $messages = []; for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) { - if ($errors[$i] instanceof \Exception) { - $messages[] = "{$errors[$i]->getMessage()}"; - } else { - $messages[] = "{$errors[$i]}"; - } + $messages[] = $errors[$i] instanceof \Exception ? "{$errors[$i]->getMessage()}" : "{$errors[$i]}"; } throw new InvalidParameterException(implode("\n", $messages)); diff --git a/api/components/com_content/src/Controller/ArticlesController.php b/api/components/com_content/src/Controller/ArticlesController.php index e8df153e3d98e..8b983946ea91b 100644 --- a/api/components/com_content/src/Controller/ArticlesController.php +++ b/api/components/com_content/src/Controller/ArticlesController.php @@ -108,8 +108,9 @@ protected function preprocessSaveData(array $data): array { foreach (FieldsHelper::getFields('com_content.article') as $field) { if (isset($data[$field->name])) { - !isset($data['com_fields']) && $data['com_fields'] = []; - + if (!isset($data['com_fields'])) { + $data['com_fields'] = []; + } $data['com_fields'][$field->name] = $data[$field->name]; unset($data[$field->name]); } diff --git a/api/components/com_languages/src/Controller/OverridesController.php b/api/components/com_languages/src/Controller/OverridesController.php index c006b6979c70c..bf0ba37c88f72 100644 --- a/api/components/com_languages/src/Controller/OverridesController.php +++ b/api/components/com_languages/src/Controller/OverridesController.php @@ -118,11 +118,7 @@ protected function save($recordKey = null) $messages = []; for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) { - if ($errors[$i] instanceof \Exception) { - $messages[] = "{$errors[$i]->getMessage()}"; - } else { - $messages[] = "{$errors[$i]}"; - } + $messages[] = $errors[$i] instanceof \Exception ? "{$errors[$i]->getMessage()}" : "{$errors[$i]}"; } throw new InvalidParameterException(implode("\n", $messages)); diff --git a/api/components/com_languages/src/Controller/StringsController.php b/api/components/com_languages/src/Controller/StringsController.php index f6c24f3617687..67572669f3b50 100644 --- a/api/components/com_languages/src/Controller/StringsController.php +++ b/api/components/com_languages/src/Controller/StringsController.php @@ -78,7 +78,7 @@ public function search() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } /** @var \Joomla\Component\Languages\Administrator\Model\StringsModel $model */ diff --git a/api/components/com_media/src/Controller/MediaController.php b/api/components/com_media/src/Controller/MediaController.php index 129d49050f26f..979d2a0815fd0 100644 --- a/api/components/com_media/src/Controller/MediaController.php +++ b/api/components/com_media/src/Controller/MediaController.php @@ -216,7 +216,7 @@ public function add(): void $missingParameters[] = 'content'; } - if (\count($missingParameters)) { + if ($missingParameters !== []) { throw new InvalidParameterException( Text::sprintf('WEBSERVICE_COM_MEDIA_MISSING_REQUIRED_PARAMETERS', implode(' & ', $missingParameters)) ); @@ -320,9 +320,11 @@ protected function save($recordKey = null) $model = $this->getModel($modelName, '', ['ignore_request' => true, 'state' => $this->modelState]); $json = $this->input->json; + // Decode content, if any + $content = base64_decode((string) $json->get('content', '', 'raw')); // Decode content, if any - if ($content = base64_decode((string) $json->get('content', '', 'raw'))) { + if ($content !== '' && $content !== '0') { $this->checkContent(); } diff --git a/api/components/com_menus/src/Controller/ItemsController.php b/api/components/com_menus/src/Controller/ItemsController.php index 14b2a818d5607..32fb7aa00e175 100644 --- a/api/components/com_menus/src/Controller/ItemsController.php +++ b/api/components/com_menus/src/Controller/ItemsController.php @@ -99,9 +99,15 @@ public function add() $this->input->set('com_menus.items.menutype', $data['menutype']); } - isset($data['type']) && $this->input->set('type', $data['type']); - isset($data['parent_id']) && $this->input->set('parent_id', $data['parent_id']); - isset($data['link']) && $this->input->set('link', $data['link']); + if (isset($data['type'])) { + $this->input->set('type', $data['type']); + } + if (isset($data['parent_id'])) { + $this->input->set('parent_id', $data['parent_id']); + } + if (isset($data['link'])) { + $this->input->set('link', $data['link']); + } $this->input->set('id', '0'); @@ -124,9 +130,15 @@ public function edit() $this->input->set('com_menus.items.menutype', $data['menutype']); } - isset($data['type']) && $this->input->set('type', $data['type']); - isset($data['parent_id']) && $this->input->set('parent_id', $data['parent_id']); - isset($data['link']) && $this->input->set('link', $data['link']); + if (isset($data['type'])) { + $this->input->set('type', $data['type']); + } + if (isset($data['parent_id'])) { + $this->input->set('parent_id', $data['parent_id']); + } + if (isset($data['link'])) { + $this->input->set('link', $data['link']); + } return parent::edit(); } @@ -153,7 +165,7 @@ public function getTypes() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } /** @var ListModel $model */ diff --git a/api/components/com_modules/src/Controller/ModulesController.php b/api/components/com_modules/src/Controller/ModulesController.php index 31066a3ac2c30..d0642c50238c4 100644 --- a/api/components/com_modules/src/Controller/ModulesController.php +++ b/api/components/com_modules/src/Controller/ModulesController.php @@ -94,7 +94,7 @@ public function getTypes() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } /** @var SelectModel $model */ diff --git a/api/components/com_privacy/src/Controller/RequestsController.php b/api/components/com_privacy/src/Controller/RequestsController.php index e58e12d227907..26ad6d794932d 100644 --- a/api/components/com_privacy/src/Controller/RequestsController.php +++ b/api/components/com_privacy/src/Controller/RequestsController.php @@ -68,7 +68,7 @@ public function export($id = null) ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $model = $this->getModel('export'); @@ -76,7 +76,7 @@ public function export($id = null) try { $modelName = $model->getName(); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $model->setState($modelName . '.request_id', $id); diff --git a/api/components/com_users/src/Controller/UsersController.php b/api/components/com_users/src/Controller/UsersController.php index 21b75eb2e0ac2..50c7b5a5b28e4 100644 --- a/api/components/com_users/src/Controller/UsersController.php +++ b/api/components/com_users/src/Controller/UsersController.php @@ -57,8 +57,9 @@ protected function preprocessSaveData(array $data): array { foreach (FieldsHelper::getFields('com_users.user') as $field) { if (isset($data[$field->name])) { - !isset($data['com_fields']) && $data['com_fields'] = []; - + if (!isset($data['com_fields'])) { + $data['com_fields'] = []; + } $data['com_fields'][$field->name] = $data[$field->name]; unset($data[$field->name]); } @@ -72,10 +73,8 @@ protected function preprocessSaveData(array $data): array } } - if ($this->input->getMethod() === 'POST') { - if (isset($data['password'])) { - $data['password2'] = $data['password']; - } + if ($this->input->getMethod() === 'POST' && isset($data['password'])) { + $data['password2'] = $data['password']; } return $data; diff --git a/build/build.php b/build/build.php index 15ecfc5c4e1e1..31355f1df7df8 100644 --- a/build/build.php +++ b/build/build.php @@ -738,11 +738,7 @@ function clean_composer(string $dir) if (str_contains($packageName, 'Full_Package')) { $type = 'FULL'; } elseif (str_contains($packageName, 'Patch_Package')) { - if (str_contains($packageName, '.x_to')) { - $type = 'MINOR'; - } else { - $type = 'POINT'; - } + $type = str_contains($packageName, '.x_to') ? 'MINOR' : 'POINT'; } elseif (str_contains($packageName, 'Update_Package')) { $type = 'UPGRADE'; } diff --git a/build/bump.php b/build/bump.php index e1d3f01cbbd45..7fcaf33958e7c 100644 --- a/build/bump.php +++ b/build/bump.php @@ -98,12 +98,12 @@ function usage($command) // Check version string (exit if not correct). $versionParts = explode('-', $opts['v']); -if (!preg_match('#^[0-9]+\.[0-9]+\.[0-9]+$#', $versionParts[0])) { +if (!preg_match('#^\d+\.\d+\.\d+$#', $versionParts[0])) { usage($argv[0]); die(); } -if (isset($versionParts[1]) && !preg_match('#(dev|alpha|beta|rc)[0-9]*#', $versionParts[1])) { +if (isset($versionParts[1]) && !preg_match('#(dev|alpha|beta|rc)\d*#', $versionParts[1])) { usage($argv[0]); die(); } @@ -125,16 +125,14 @@ function usage($command) if (!isset($versionParts[1])) { $versionParts[1] = ''; -} else { - if (preg_match('#^dev#', $versionParts[1])) { - $dev_status = 'Development'; - } elseif (preg_match('#^alpha#', $versionParts[1])) { - $dev_status = 'Alpha'; - } elseif (preg_match('#^beta#', $versionParts[1])) { - $dev_status = 'Beta'; - } elseif (preg_match('#^rc#', $versionParts[1])) { - $dev_status = 'Release Candidate'; - } +} elseif (preg_match('#^dev#', $versionParts[1])) { + $dev_status = 'Development'; +} elseif (preg_match('#^alpha#', $versionParts[1])) { + $dev_status = 'Alpha'; +} elseif (preg_match('#^beta#', $versionParts[1])) { + $dev_status = 'Beta'; +} elseif (preg_match('#^rc#', $versionParts[1])) { + $dev_status = 'Release Candidate'; } if (!isset($versionParts[2])) { @@ -155,9 +153,9 @@ function usage($command) 'major' => $versionSubParts[0], 'minor' => $versionSubParts[1], 'patch' => $versionSubParts[2], - 'extra' => (!empty($versionParts[1]) ? $versionParts[1] : '') . (!empty($versionParts[2]) ? (!empty($versionParts[1]) ? '-' : '') . $versionParts[2] : ''), + 'extra' => (empty($versionParts[1]) ? '' : $versionParts[1]) . (empty($versionParts[2]) ? '' : (empty($versionParts[1]) ? '' : '-') . $versionParts[2]), 'release' => $versionSubParts[0] . '.' . $versionSubParts[1] . '.' . $versionSubParts[2], - 'dev_devel' => $versionSubParts[2] . (!empty($versionParts[1]) ? '-' . $versionParts[1] : '') . (!empty($versionParts[2]) ? '-' . $versionParts[2] : ''), + 'dev_devel' => $versionSubParts[2] . (empty($versionParts[1]) ? '' : '-' . $versionParts[1]) . (empty($versionParts[2]) ? '' : '-' . $versionParts[2]), 'dev_status' => $dev_status, 'build' => '', 'reldate' => $date->format('j-F-Y'), @@ -185,7 +183,7 @@ function usage($command) echo '- Release timezone:' . PHP_TAB . $version['reltz'] . PHP_EOL; echo '- Creation date:' . PHP_TAB . $version['credate'] . PHP_EOL; -if (!empty($version['codename'])) { +if (isset($version['codename']) && ($version['codename'] !== '' && $version['codename'] !== '0')) { echo '- Codename:' . PHP_TAB . PHP_TAB . $version['codename'] . PHP_EOL; } @@ -208,7 +206,7 @@ function usage($command) $fileContents = preg_replace("#RELTIME\s*=\s*'[^\']*'#", "RELTIME = '" . $version['reltime'] . "'", (string) $fileContents); $fileContents = preg_replace("#RELTZ\s*=\s*'[^\']*'#", "RELTZ = '" . $version['reltz'] . "'", (string) $fileContents); - if (!empty($version['codename'])) { + if (isset($version['codename']) && ($version['codename'] !== '' && $version['codename'] !== '0')) { $fileContents = preg_replace("#CODENAME\s*=\s*'[^\']*'#", "CODENAME = '" . $version['codename'] . "'", (string) $fileContents); } @@ -265,8 +263,8 @@ function usage($command) foreach ($readMeFiles as $readMeFile) { if (file_exists($rootPath . $readMeFile)) { $fileContents = file_get_contents($rootPath . $readMeFile); - $fileContents = preg_replace('#Joomla! [0-9]+\.[0-9]+ (|\[)version#', 'Joomla! ' . $version['main'] . ' $1version', $fileContents); - $fileContents = preg_replace('#Joomla_[0-9]+\.[0-9]+_version#', 'Joomla_' . $version['main'] . '_version', (string) $fileContents); + $fileContents = preg_replace('#Joomla! \d+\.\d+ (|\[)version#', 'Joomla! ' . $version['main'] . ' $1version', $fileContents); + $fileContents = preg_replace('#Joomla_\d+\.\d+_version#', 'Joomla_' . $version['main'] . '_version', (string) $fileContents); file_put_contents($rootPath . $readMeFile, $fileContents); } } diff --git a/build/check_ruleset_xml.php b/build/check_ruleset_xml.php index 92c7a85eb9499..f3850c85a8c7a 100644 --- a/build/check_ruleset_xml.php +++ b/build/check_ruleset_xml.php @@ -85,7 +85,7 @@ function usage($command) echo "... done." . PHP_EOL; -if (!\count($obsoleteLineIdxs)) { +if ($obsoleteLineIdxs === []) { echo "No obsolete lines found." . PHP_EOL; exit(0); diff --git a/build/convert_or_die.php b/build/convert_or_die.php index 0514b7c8ba268..0306a04598fd3 100644 --- a/build/convert_or_die.php +++ b/build/convert_or_die.php @@ -8,10 +8,8 @@ function insertDefineOrDie($file, $keyword) $realfile = \dirname(__DIR__) . '/' . $file; - if (!file_exists($realfile)) { - if ($file === 'plugins/task/checkfiles/checkfiles.php') { - return; - } + if (!file_exists($realfile) && $file === 'plugins/task/checkfiles/checkfiles.php') { + return; } $currentcontent = file($realfile); @@ -44,9 +42,9 @@ function insertDefineOrDie($file, $keyword) $insert = max($lastUse, $lastComment, $lastNamespace); $distance = 0; - if (empty(trim($currentcontent[$insert + 2]))) { + if (in_array(trim($currentcontent[$insert + 2]), ['', '0'], true)) { $distance++; - if (empty(trim($currentcontent[$insert + 3]))) { + if (in_array(trim($currentcontent[$insert + 3]), ['', '0'], true)) { $distance++; } } diff --git a/build/deleted_file_check.php b/build/deleted_file_check.php index 1599753e3ef3c..e72bd2180eac5 100644 --- a/build/deleted_file_check.php +++ b/build/deleted_file_check.php @@ -220,7 +220,7 @@ function usage($command) foreach ($filesDifference as $file) { // Don't remove any specific files (e.g. language files) that we want to keep on upgrade - if (array_search($file, $filesToKeep) !== false) { + if (in_array($file, $filesToKeep)) { continue; } diff --git a/build/github_rebase.php b/build/github_rebase.php index e13b82706e61d..0608ea2861cd8 100644 --- a/build/github_rebase.php +++ b/build/github_rebase.php @@ -24,7 +24,7 @@ $script = array_shift($argv); -if (empty($argv)) { +if ($argv === []) { echo << $hashes) { if (str_ends_with((string) $packageName, '.zip')) { $table[$type] .= "| [ZIP Archive (.zip)]"; - } else if (str_ends_with((string) $packageName, '.tar.gz')) { + } elseif (str_ends_with((string) $packageName, '.tar.gz')) { $table[$type] .= "| [GNU Zip Archive (.tar.gz)]"; - } else if (str_ends_with((string) $packageName, '.tar.bz2')) { + } elseif (str_ends_with((string) $packageName, '.tar.bz2')) { $table[$type] .= "| [Bzip2 Archive (.tar.zst)]"; - } else if (str_ends_with((string) $packageName, '.tar.zst')) { + } elseif (str_ends_with((string) $packageName, '.tar.zst')) { $table[$type] .= "| [Zstandard Archive (.tar.zst)]"; } else { // Unknown file types @@ -68,7 +68,7 @@ MD; // Installation Packages -if (!empty($table['FULL'])): +if (isset($table['FULL']) && ($table['FULL'] !== '' && $table['FULL'] !== '0')): $output .= <<getArgs()) === 0) { + if ($methodCall->getArgs() === []) { $name = str_replace('Controller', '', $scope->getClassReflection()->getNativeReflection()->getShortName()); } @@ -42,7 +42,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method $prefix = strpos((string) $scope->getNamespace(), 'Site') ? 'Site' : 'Administrator'; } - if (\count($methodCall->getArgs()) > 0) { + if ($methodCall->getArgs() !== []) { $name = str_replace("'", '', $methodCall->getArgs()[0]->value->getAttribute('rawValue')); } @@ -55,7 +55,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method } // Search in namespaces which belong to the defined prefix - foreach ($this->findNamespaces($prefix) as $ns => $path) { + foreach (array_keys($this->findNamespaces($prefix)) as $ns) { foreach (['Model', 'View'] as $type) { if (($methodReflection->getName() !== 'create' . $type && $methodReflection->getName() !== 'get' . $type) || !class_exists($ns . $type . '\\' . $name . $type)) { @@ -67,7 +67,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method } // Search in all namespaces, eg. when an admin model is loaded on site - foreach ($this->getNamespaces() as $ns => $path) { + foreach (array_keys($this->getNamespaces()) as $ns) { foreach (['Model', 'View'] as $type) { if (($methodReflection->getName() !== 'create' . $type && $methodReflection->getName() !== 'get' . $type) || !class_exists($ns . $type . '\\' . $name . $type)) { diff --git a/build/phpstan/src/DynamicReturnType/DIContainer.php b/build/phpstan/src/DynamicReturnType/DIContainer.php index dcbce4618e60a..ff488073b2543 100644 --- a/build/phpstan/src/DynamicReturnType/DIContainer.php +++ b/build/phpstan/src/DynamicReturnType/DIContainer.php @@ -32,7 +32,7 @@ public function isMethodSupported(MethodReflection $methodReflection): bool public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type { - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { return null; } diff --git a/build/phpstan/src/DynamicReturnType/ExtensionManagerInterface.php b/build/phpstan/src/DynamicReturnType/ExtensionManagerInterface.php index f5cd72dffe72e..6cf80557eff2b 100644 --- a/build/phpstan/src/DynamicReturnType/ExtensionManagerInterface.php +++ b/build/phpstan/src/DynamicReturnType/ExtensionManagerInterface.php @@ -33,7 +33,7 @@ public function isMethodSupported(MethodReflection $methodReflection): bool public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type { - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { return null; } diff --git a/build/phpstan/src/DynamicReturnType/MVCFactoryInterfaceInterface.php b/build/phpstan/src/DynamicReturnType/MVCFactoryInterfaceInterface.php index 6bda93e549274..b533697a96963 100644 --- a/build/phpstan/src/DynamicReturnType/MVCFactoryInterfaceInterface.php +++ b/build/phpstan/src/DynamicReturnType/MVCFactoryInterfaceInterface.php @@ -31,14 +31,14 @@ public function isMethodSupported(MethodReflection $methodReflection): bool public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type { - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { return null; } $name = str_replace("'", '', $methodCall->getArgs()[0]->value->getAttribute('rawValue')); $prefix = str_replace("'", '', $methodCall->getArgs()[1]->value->getAttribute('rawValue')); - foreach ($this->findNamespaces($prefix) as $ns => $path) { + foreach (array_keys($this->findNamespaces($prefix)) as $ns) { foreach (['Controller', 'Model', 'View', 'Table'] as $type) { if ($methodReflection->getName() !== 'create' . $type || !class_exists($ns . $type . '\\' . $name . $type)) { continue; diff --git a/build/phpstan/src/DynamicReturnType/ModelBootComponent.php b/build/phpstan/src/DynamicReturnType/ModelBootComponent.php index a3fc1b6c9e55b..856dae4844c74 100644 --- a/build/phpstan/src/DynamicReturnType/ModelBootComponent.php +++ b/build/phpstan/src/DynamicReturnType/ModelBootComponent.php @@ -31,13 +31,14 @@ public function isMethodSupported(MethodReflection $methodReflection): bool public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type { - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { return null; } $name = str_replace("'", '', $methodCall->getArgs()[0]->value->getAttribute('rawValue')); + $namespace = $this->findNamespace('\\Component\\' . $name . '\\Administrator'); - if ($namespace = $this->findNamespace('\\Component\\' . $name . '\\Administrator')) { + if ($namespace !== '' && $namespace !== '0') { return new ObjectType($namespace . 'Extension\\' . $name . 'Component'); } diff --git a/build/phpstan/src/DynamicReturnType/ModelTableLoader.php b/build/phpstan/src/DynamicReturnType/ModelTableLoader.php index 8ef9e11d3a1c4..710653bcebd22 100644 --- a/build/phpstan/src/DynamicReturnType/ModelTableLoader.php +++ b/build/phpstan/src/DynamicReturnType/ModelTableLoader.php @@ -34,7 +34,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method $name = ''; $prefix = ''; - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { $name = end(explode('\\', $scope->getClassReflection()->getNativeReflection()->getShortName())); // Some models have form as part of their name @@ -45,7 +45,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method $prefix = 'Administrator'; } - if (\count($methodCall->getArgs()) > 0) { + if ($methodCall->getArgs() !== []) { $name = str_replace("'", '', $methodCall->getArgs()[0]->value->getAttribute('rawValue')); } @@ -57,7 +57,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method return null; } - foreach ($this->findNamespaces($prefix) as $ns => $path) { + foreach (array_keys($this->findNamespaces($prefix)) as $ns) { if (!class_exists($ns . 'Table\\' . $name . 'Table')) { continue; } diff --git a/build/phpstan/src/DynamicReturnType/NamespaceBased.php b/build/phpstan/src/DynamicReturnType/NamespaceBased.php index da4ea4a5eb6fc..7825677c6d1c9 100644 --- a/build/phpstan/src/DynamicReturnType/NamespaceBased.php +++ b/build/phpstan/src/DynamicReturnType/NamespaceBased.php @@ -51,7 +51,7 @@ protected function findNamespaces(string $name): array */ protected function findNamespace(string $name): string { - foreach ($this->getNamespaces() as $ns => $path) { + foreach (array_keys($this->getNamespaces()) as $ns) { if (!stripos($ns, $name)) { continue; } diff --git a/build/phpstan/src/DynamicReturnType/ViewModelLoader.php b/build/phpstan/src/DynamicReturnType/ViewModelLoader.php index a3956f5c70d51..07fb37e5961d9 100644 --- a/build/phpstan/src/DynamicReturnType/ViewModelLoader.php +++ b/build/phpstan/src/DynamicReturnType/ViewModelLoader.php @@ -34,7 +34,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method $name = ''; $prefix = ''; - if (\count($methodCall->getArgs()) === 0) { + if ($methodCall->getArgs() === []) { $name = end(explode('\\', (string) $scope->getNamespace())); } @@ -42,7 +42,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method $prefix = strpos((string) $scope->getNamespace(), 'Site') ? 'Site' : 'Administrator'; } - if (\count($methodCall->getArgs()) > 0) { + if ($methodCall->getArgs() !== []) { $name = str_replace("'", '', $methodCall->getArgs()[0]->value->getAttribute('rawValue')); } @@ -55,7 +55,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method } // Search in namespaces which belong to the defined prefix - foreach ($this->findNamespaces($prefix) as $ns => $path) { + foreach (array_keys($this->findNamespaces($prefix)) as $ns) { if (!class_exists($ns . 'Model\\' . $name . 'Model')) { continue; } @@ -64,7 +64,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method } // Search in all namespaces, eg. when an admin model is loaded on site - foreach ($this->getNamespaces() as $ns => $path) { + foreach (array_keys($this->getNamespaces()) as $ns) { if (!class_exists($ns . 'Model\\' . $name . 'Model')) { continue; } diff --git a/build/psr12/clean_errors.php b/build/psr12/clean_errors.php index 5a4d999d92bc8..edbf5a00a7460 100644 --- a/build/psr12/clean_errors.php +++ b/build/psr12/clean_errors.php @@ -105,11 +105,11 @@ // We skip blank lines do { $nextLine = ltrim($fileContent[$lineNo]); - if (empty($nextLine)) { - $lineNo = $lineNo + 1; + if ($nextLine === '' || $nextLine === '0') { + $lineNo += 1; $nextLine = ltrim($fileContent[$lineNo]); } - } while (empty($nextLine)); + } while ($nextLine === '' || $nextLine === '0'); $sourceLineStartNo = $lineNo; $sourceLineEndNo = $lineNo; @@ -120,14 +120,12 @@ $found = true; } - if ($sourceLineStartNo === $sourceLineEndNo) { - if (str_starts_with(ltrim($fileContent[$sourceLineStartNo]), '/*')) { - while (!str_starts_with(ltrim($fileContent[$sourceLineEndNo]), '*/')) { - $sourceLineEndNo++; - } + if ($sourceLineStartNo === $sourceLineEndNo && str_starts_with(ltrim($fileContent[$sourceLineStartNo]), '/*')) { + while (!str_starts_with(ltrim($fileContent[$sourceLineEndNo]), '*/')) { $sourceLineEndNo++; - $found = true; } + $sourceLineEndNo++; + $found = true; } if (!$found) { diff --git a/build/psr12/convert_pull_requests.php b/build/psr12/convert_pull_requests.php index ce7f8dd2d2791..d84c2f5963ed9 100644 --- a/build/psr12/convert_pull_requests.php +++ b/build/psr12/convert_pull_requests.php @@ -22,7 +22,7 @@ $script = array_shift($argv); -if (empty($argv)) { +if ($argv === []) { echo << $value) { + foreach (array_keys($tasks) as $task) { if (stripos($argi[1], $task) !== false) { $tasks[$task] = true; } @@ -120,7 +120,7 @@ } $checkPath = implode(',', $output); - if (empty($checkPath)) { + if ($checkPath === '' || $checkPath === '0') { die(0); } } @@ -158,10 +158,8 @@ if (($entry === ".") || ($entry === "..")) { continue; } - if (!is_dir($dir->path . '/' . $entry)) { - if (!str_ends_with($entry, '.php')) { - continue; - } + if (!is_dir($dir->path . '/' . $entry) && !str_ends_with($entry, '.php')) { + continue; } if ( $folder === 'libraries' @@ -200,7 +198,7 @@ // Recreate temp dir $cleanItems = glob($tmpDir . '/{,.}*', GLOB_MARK | GLOB_BRACE); foreach ($cleanItems as $item) { - if (basename($item) == '.' || basename($item) == '..') { + if (basename($item) === '.' || basename($item) === '..') { continue; } unlink($item); diff --git a/build/rector.php b/build/rector.php index a672e6a8b1ae3..5852a774c938e 100644 --- a/build/rector.php +++ b/build/rector.php @@ -35,7 +35,7 @@ // Complete sets with rules $rectorConfig->sets([ LevelSetList::UP_TO_PHP_81, - //SetList::CODE_QUALITY, + SetList::CODE_QUALITY, //SetList::CODING_STYLE, //SetList::DEAD_CODE, //SetList::EARLY_RETURN, diff --git a/components/com_ajax/ajax.php b/components/com_ajax/ajax.php index 7b8dce4e30758..224a44ac3fe4b 100644 --- a/components/com_ajax/ajax.php +++ b/components/com_ajax/ajax.php @@ -46,7 +46,7 @@ $parts = null; // Check for valid format -if (!$format) { +if ($format === '' || $format === '0') { $results = new InvalidArgumentException(Text::_('COM_AJAX_SPECIFY_FORMAT'), 404); } elseif ($input->get('module')) { /** @@ -97,8 +97,9 @@ // Load language file for module $basePath = JPATH_BASE; $lang = Factory::getLanguage(); - $lang->load('mod_' . $module, $basePath) - || $lang->load('mod_' . $module, $basePath . '/modules/mod_' . $module); + if (!$lang->load('mod_' . $module, $basePath)) { + $lang->load('mod_' . $module, $basePath . '/modules/mod_' . $module); + } try { $results = \call_user_func($class . '::' . $method . 'Ajax'); @@ -181,8 +182,9 @@ if (method_exists($class, $method . 'Ajax')) { // Load language file for template $lang = Factory::getLanguage(); - $lang->load('tpl_' . $template, $basePath) - || $lang->load('tpl_' . $template, $basePath . '/templates/' . $template); + if (!$lang->load('tpl_' . $template, $basePath)) { + $lang->load('tpl_' . $template, $basePath . '/templates/' . $template); + } try { $results = \call_user_func($class . '::' . $method . 'Ajax'); diff --git a/components/com_banners/src/Helper/BannerHelper.php b/components/com_banners/src/Helper/BannerHelper.php index 4da7af3fb1e51..395e7fe20e09d 100644 --- a/components/com_banners/src/Helper/BannerHelper.php +++ b/components/com_banners/src/Helper/BannerHelper.php @@ -40,11 +40,6 @@ abstract class BannerHelper public static function isImage($url) { $urlCheck = explode('?', $url); - - if (preg_match('#\.(?:bmp|gif|jpe?g|png|webp)$#i', $urlCheck[0])) { - return true; - } - - return false; + return (bool) preg_match('#\.(?:bmp|gif|jpe?g|png|webp)$#i', $urlCheck[0]); } } diff --git a/components/com_banners/src/Model/BannerModel.php b/components/com_banners/src/Model/BannerModel.php index d1f9e469d5755..0cd3fe150dbf3 100644 --- a/components/com_banners/src/Model/BannerModel.php +++ b/components/com_banners/src/Model/BannerModel.php @@ -68,7 +68,7 @@ public function click() try { $db->execute(); } catch (\RuntimeException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } // Track clicks @@ -106,7 +106,7 @@ public function click() try { $db->execute(); } catch (\RuntimeException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } $count = $db->loadResult(); @@ -147,7 +147,7 @@ public function click() try { $db->execute(); } catch (\RuntimeException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } } } @@ -161,7 +161,7 @@ public function click() */ public function &getItem() { - if (!isset($this->_item)) { + if ($this->_item === null) { /** @var \Joomla\CMS\Cache\Controller\CallbackController $cache */ $cache = Factory::getCache('com_banners', 'callback'); diff --git a/components/com_banners/src/Model/BannersModel.php b/components/com_banners/src/Model/BannersModel.php index 0f4db650302eb..5d9923e8fc2cb 100644 --- a/components/com_banners/src/Model/BannersModel.php +++ b/components/com_banners/src/Model/BannersModel.php @@ -118,7 +118,7 @@ protected function getListQuery() ) ->bind([':nowDate1', ':nowDate2'], $nowDate); - if ($cid) { + if ($cid !== 0) { $query->where( [ $db->quoteName('a.cid') . ' = :clientId', @@ -169,7 +169,7 @@ protected function getListQuery() $query->where($db->quoteName('a.catid') . $type . ':categoryId') ->bind(':categoryId', $categoryId, ParameterType::INTEGER); } - } elseif (\is_array($categoryId) && (\count($categoryId) > 0)) { + } elseif (\is_array($categoryId) && ($categoryId !== [])) { $categoryId = ArrayHelper::toInteger($categoryId); if ($this->getState('filter.category_id.include', true)) { @@ -262,7 +262,7 @@ public function getItems() $this->setState('filter.keywords', $keywords); // If no keywords are provided, avoid running the query. - if (!$keywords) { + if ($keywords === []) { $this->cache['items'] = []; return $this->cache['items']; @@ -314,7 +314,7 @@ public function impress() try { $db->execute(); } catch (ExecutionFailureException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } foreach ($items as $item) { @@ -351,7 +351,7 @@ public function impress() try { $db->execute(); } catch (ExecutionFailureException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } if ($db->getAffectedRows() === 0) { @@ -375,7 +375,7 @@ public function impress() try { $db->execute(); } catch (ExecutionFailureException $e) { - throw new \Exception($e->getMessage(), 500); + throw new \Exception($e->getMessage(), 500, $e); } } } diff --git a/components/com_banners/src/Service/Router.php b/components/com_banners/src/Service/Router.php index 3dfc73258f9d7..16bf78594db17 100644 --- a/components/com_banners/src/Service/Router.php +++ b/components/com_banners/src/Service/Router.php @@ -74,7 +74,7 @@ public function parse(&$segments) // View is always the first element of the array $count = \count($segments); - if ($count) { + if ($count !== 0) { $count--; $segment = array_shift($segments); @@ -85,7 +85,7 @@ public function parse(&$segments) } } - if ($count) { + if ($count !== 0) { $segment = array_shift($segments); if (is_numeric($segment)) { diff --git a/components/com_config/src/Model/FormModel.php b/components/com_config/src/Model/FormModel.php index cf96ceeb35614..dee42b1e91fad 100644 --- a/components/com_config/src/Model/FormModel.php +++ b/components/com_config/src/Model/FormModel.php @@ -147,12 +147,7 @@ protected function loadForm($name, $source = null, $options = [], $clear = false // Get the form. $form = Form::getInstance($name, $source, $options, false, $xpath); - if (isset($options['load_data']) && $options['load_data']) { - // Get the data for the form. - $data = $this->loadFormData(); - } else { - $data = []; - } + $data = isset($options['load_data']) && $options['load_data'] ? $this->loadFormData() : []; // Allow for additional modification of the form, and events to be triggered. // We pass the data because plugins may require it. diff --git a/components/com_config/src/Model/ModulesModel.php b/components/com_config/src/Model/ModulesModel.php index 6c95df40b7720..9bdc9842abdcc 100644 --- a/components/com_config/src/Model/ModulesModel.php +++ b/components/com_config/src/Model/ModulesModel.php @@ -89,8 +89,9 @@ protected function preprocessForm(Form $form, $data, $group = 'content') $formFile = Path::clean($basePath . '/modules/' . $module . '/' . $module . '.xml'); // Load the core and/or local language file(s). - $lang->load($module, $basePath) - || $lang->load($module, $basePath . '/modules/' . $module); + if (!$lang->load($module, $basePath)) { + $lang->load($module, $basePath . '/modules/' . $module); + } if (file_exists($formFile)) { // Get the module form. @@ -133,15 +134,15 @@ public function getPositions() if (isset($xml->positions[0])) { // Load language files - $lang->load('tpl_' . $templateName . '.sys', JPATH_BASE) - || $lang->load('tpl_' . $templateName . '.sys', JPATH_BASE . '/templates/' . $templateName); - + if (!$lang->load('tpl_' . $templateName . '.sys', JPATH_BASE)) { + $lang->load('tpl_' . $templateName . '.sys', JPATH_BASE . '/templates/' . $templateName); + } foreach ($xml->positions[0] as $position) { $value = (string) $position; $text = preg_replace('/[^a-zA-Z0-9_\-]/', '_', 'TPL_' . strtoupper((string) $templateName) . '_POSITION_' . strtoupper($value)); // Construct list of positions - $currentTemplatePositions[] = self::createOption($value, Text::_($text) . ' [' . $value . ']'); + $currentTemplatePositions[] = $this->createOption($value, Text::_($text) . ' [' . $value . ']'); } } } @@ -149,17 +150,17 @@ public function getPositions() $templateGroups = []; // Add an empty value to be able to deselect a module position - $option = self::createOption(); - $templateGroups[''] = self::createOptionGroup('', [$option]); + $option = $this->createOption(); + $templateGroups[''] = $this->createOptionGroup('', [$option]); - $templateGroups[$templateName] = self::createOptionGroup($templateName, $currentTemplatePositions); + $templateGroups[$templateName] = $this->createOptionGroup($templateName, $currentTemplatePositions); // Add custom position to options $customGroupText = Text::_('COM_MODULES_CUSTOM_POSITION'); $editPositions = true; $customPositions = self::getActivePositions(0, $editPositions); - $templateGroups[$customGroupText] = self::createOptionGroup($customGroupText, $customPositions); + $templateGroups[$customGroupText] = $this->createOptionGroup($customGroupText, $customPositions); return $templateGroups; } @@ -191,7 +192,7 @@ public static function getActivePositions($clientId, $editPositions = false) } catch (\RuntimeException $e) { Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); - return; + return null; } // Build the list @@ -218,7 +219,7 @@ public static function getActivePositions($clientId, $editPositions = false) * * @since 3.6.3 */ - private static function createOption($value = '', $text = '') + private function createOption($value = '', $text = '') { if (empty($text)) { $text = $value; @@ -241,13 +242,8 @@ private static function createOption($value = '', $text = '') * * @since 3.6.3 */ - private static function createOptionGroup($label = '', $options = []) + private function createOptionGroup($label = '', $options = []) { - $group = []; - $group['value'] = $label; - $group['text'] = $label; - $group['items'] = $options; - - return $group; + return ['value' => $label, 'text' => $label, 'items' => $options]; } } diff --git a/components/com_config/src/Model/TemplatesModel.php b/components/com_config/src/Model/TemplatesModel.php index 04fa54ff037c2..b72fb7e7111f2 100644 --- a/components/com_config/src/Model/TemplatesModel.php +++ b/components/com_config/src/Model/TemplatesModel.php @@ -96,8 +96,9 @@ protected function preprocessForm(Form $form, $data, $group = 'content') $template = Factory::getApplication()->getTemplate(); // Load the core and/or local language file(s). - $lang->load('tpl_' . $template, JPATH_BASE) - || $lang->load('tpl_' . $template, JPATH_BASE . '/templates/' . $template); + if (!$lang->load('tpl_' . $template, JPATH_BASE)) { + $lang->load('tpl_' . $template, JPATH_BASE . '/templates/' . $template); + } // Look for com_config.xml, which contains fields to display $formFile = Path::clean(JPATH_BASE . '/templates/' . $template . '/com_config.xml'); diff --git a/components/com_config/src/View/Modules/HtmlView.php b/components/com_config/src/View/Modules/HtmlView.php index 832c8298aa28b..25f77e82c86e5 100644 --- a/components/com_config/src/View/Modules/HtmlView.php +++ b/components/com_config/src/View/Modules/HtmlView.php @@ -27,6 +27,10 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var mixed[] + */ + public $positions; /** * The module to be rendered * diff --git a/components/com_config/src/View/Templates/HtmlView.php b/components/com_config/src/View/Templates/HtmlView.php index 02acda31cf761..335560f99e4e8 100644 --- a/components/com_config/src/View/Templates/HtmlView.php +++ b/components/com_config/src/View/Templates/HtmlView.php @@ -28,6 +28,10 @@ */ class HtmlView extends BaseHtmlView { + /** + * @var mixed + */ + public $data; /** * The data to be displayed in the form * diff --git a/components/com_config/tmpl/modules/default_options.php b/components/com_config/tmpl/modules/default_options.php index 184fd90e12aed..173e48cd632c6 100644 --- a/components/com_config/tmpl/modules/default_options.php +++ b/components/com_config/tmpl/modules/default_options.php @@ -21,7 +21,7 @@ $i = 0; foreach ($fieldSets as $name => $fieldSet) : - $label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_MODULES_' . strtoupper($name) . '_FIELDSET_LABEL'; + $label = empty($fieldSet->label) ? 'COM_MODULES_' . strtoupper($name) . '_FIELDSET_LABEL' : $fieldSet->label; $class = isset($fieldSet->class) && !empty($fieldSet->class) ? $fieldSet->class : ''; diff --git a/components/com_config/tmpl/templates/default_options.php b/components/com_config/tmpl/templates/default_options.php index febcf7937e4bf..97c1637aed546 100644 --- a/components/com_config/tmpl/templates/default_options.php +++ b/components/com_config/tmpl/templates/default_options.php @@ -26,7 +26,7 @@ } else { // Fall-back to display all in params foreach ($fieldSets as $name => $fieldSet) { - $label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_CONFIG_' . $name . '_FIELDSET_LABEL'; + $label = empty($fieldSet->label) ? 'COM_CONFIG_' . $name . '_FIELDSET_LABEL' : $fieldSet->label; if (isset($fieldSet->description) && trim($fieldSet->description)) { echo '

    ' . $this->escape(Text::_($fieldSet->description)) . '

    '; diff --git a/components/com_contact/layouts/fields/render.php b/components/com_contact/layouts/fields/render.php index be06eaf2af3a7..62fdc490b6946 100644 --- a/components/com_contact/layouts/fields/render.php +++ b/components/com_contact/layouts/fields/render.php @@ -48,7 +48,7 @@ // Loop through the fields and print them foreach ($fields as $field) { // If the value is empty do nothing - if (!strlen($field->value)) { + if ((string) $field->value === '') { continue; } diff --git a/components/com_contact/src/Controller/ContactController.php b/components/com_contact/src/Controller/ContactController.php index bcb9861f207a6..0a6c6d185b088 100644 --- a/components/com_contact/src/Controller/ContactController.php +++ b/components/com_contact/src/Controller/ContactController.php @@ -128,18 +128,13 @@ public function submit() } // Check for a valid session cookie - if ($contact->params->get('validate_session', 0)) { - if (Factory::getSession()->getState() !== 'active') { - $this->app->enqueueMessage(Text::_('JLIB_ENVIRONMENT_SESSION_INVALID'), 'warning'); - - // Save the data in the session. - $this->app->setUserState('com_contact.contact.data', $data); - - // Redirect back to the contact form. - $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false)); - - return false; - } + if ($contact->params->get('validate_session', 0) && Factory::getSession()->getState() !== 'active') { + $this->app->enqueueMessage(Text::_('JLIB_ENVIRONMENT_SESSION_INVALID'), 'warning'); + // Save the data in the session. + $this->app->setUserState('com_contact.contact.data', $data); + // Redirect back to the contact form. + $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false)); + return false; } // Contact plugins @@ -344,7 +339,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; if (!$recordId) { return false; @@ -354,7 +349,7 @@ protected function allowEdit($data = [], $key = 'id') $record = $this->getModel()->getItem($recordId); $categoryId = (int) $record->catid; - if ($categoryId) { + if ($categoryId !== 0) { $user = $this->app->getIdentity(); // The category has been set. Check the category permissions. diff --git a/components/com_contact/src/Helper/AssociationHelper.php b/components/com_contact/src/Helper/AssociationHelper.php index 95e712aa40263..a4e7e417d8537 100644 --- a/components/com_contact/src/Helper/AssociationHelper.php +++ b/components/com_contact/src/Helper/AssociationHelper.php @@ -41,18 +41,13 @@ public static function getAssociations($id = 0, $view = null) $view ??= $jinput->get('view'); $id = empty($id) ? $jinput->getInt('id') : $id; - if ($view === 'contact') { - if ($id) { - $associations = Associations::getAssociations('com_contact', '#__contact_details', 'com_contact.item', $id); - - $return = []; - - foreach ($associations as $tag => $item) { - $return[$tag] = RouteHelper::getContactRoute($item->id, (int) $item->catid, $item->language); - } - - return $return; + if ($view === 'contact' && $id) { + $associations = Associations::getAssociations('com_contact', '#__contact_details', 'com_contact.item', $id); + $return = []; + foreach ($associations as $tag => $item) { + $return[$tag] = RouteHelper::getContactRoute($item->id, (int) $item->catid, $item->language); } + return $return; } if ($view === 'category' || $view === 'categories') { diff --git a/components/com_contact/src/Helper/RouteHelper.php b/components/com_contact/src/Helper/RouteHelper.php index 073dc4d42ad25..a0bdafb4ef73e 100644 --- a/components/com_contact/src/Helper/RouteHelper.php +++ b/components/com_contact/src/Helper/RouteHelper.php @@ -66,11 +66,7 @@ public static function getContactRoute($id, $catid, $language = 0) */ public static function getCategoryRoute($catid, $language = 0) { - if ($catid instanceof CategoryNode) { - $id = $catid->id; - } else { - $id = (int) $catid; - } + $id = $catid instanceof CategoryNode ? $catid->id : (int) $catid; if ($id < 1) { $link = ''; diff --git a/components/com_contact/src/Model/CategoriesModel.php b/components/com_contact/src/Model/CategoriesModel.php index e1801d8e5a017..79df1101d47cf 100644 --- a/components/com_contact/src/Model/CategoriesModel.php +++ b/components/com_contact/src/Model/CategoriesModel.php @@ -117,22 +117,14 @@ public function getItems() $menu = $app->getMenu(); $active = $menu->getActive(); - if ($active) { - $params = $active->getParams(); - } else { - $params = new Registry(); - } + $params = $active ? $active->getParams() : new Registry(); $options = []; $options['countItems'] = $params->get('show_cat_items_cat', 1) || !$params->get('show_empty_categories_cat', 0); $categories = Categories::getInstance('Contact', $options); $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); - if (\is_object($this->_parent)) { - $this->_items = $this->_parent->getChildren(); - } else { - $this->_items = false; - } + $this->_items = \is_object($this->_parent) ? $this->_parent->getChildren() : false; } return $this->_items; diff --git a/components/com_contact/src/Model/CategoryModel.php b/components/com_contact/src/Model/CategoryModel.php index 75320d0222173..b7f03fec3a89c 100644 --- a/components/com_contact/src/Model/CategoryModel.php +++ b/components/com_contact/src/Model/CategoryModel.php @@ -125,7 +125,7 @@ public function getItems() // Convert the params field into an object, saving original in _params foreach ($items as $item) { - if (!isset($this->_params)) { + if (!property_exists($this, '_params') || $this->_params === null) { $item->params = new Registry($item->params); } @@ -137,7 +137,7 @@ public function getItems() } // Load tags of all items. - if ($taggedItems) { + if ($taggedItems !== []) { $tagsHelper = new TagsHelper(); $itemIds = array_keys($taggedItems); @@ -364,11 +364,7 @@ public function getCategory() $menu = $app->getMenu(); $active = $menu->getActive(); - if ($active) { - $params = $active->getParams(); - } else { - $params = new Registry(); - } + $params = $active ? $active->getParams() : new Registry(); $options = []; $options['countItems'] = $params->get('show_cat_items', 1) || $params->get('show_empty_categories', 0); @@ -486,7 +482,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('category.id'); + $pk = (empty($pk)) ? (int) $this->getState('category.id') : $pk; $table = Table::getInstance('Category'); $table->hit($pk); diff --git a/components/com_contact/src/Model/FeaturedModel.php b/components/com_contact/src/Model/FeaturedModel.php index 4f964afd8efad..84288ea72be2a 100644 --- a/components/com_contact/src/Model/FeaturedModel.php +++ b/components/com_contact/src/Model/FeaturedModel.php @@ -67,7 +67,7 @@ public function getItems() // Convert the params field into an object, saving original in _params foreach ($items as $item) { - if (!isset($this->_params)) { + if (!property_exists($this, '_params') || $this->_params === null) { $item->params = new Registry($item->params); } } diff --git a/components/com_contact/src/Model/FormModel.php b/components/com_contact/src/Model/FormModel.php index 7490fb331115a..f2ef7f51c1c39 100644 --- a/components/com_contact/src/Model/FormModel.php +++ b/components/com_contact/src/Model/FormModel.php @@ -89,7 +89,7 @@ public function getForm($data = [], $loadData = true) */ public function getItem($itemId = null) { - $itemId = (int) (!empty($itemId)) ? $itemId : $this->getState('contact.id'); + $itemId = (int) (!empty($itemId)) !== 0 ? $itemId : $this->getState('contact.id'); // Get a row instance. $table = $this->getTable(); diff --git a/components/com_contact/src/Rule/ContactEmailMessageRule.php b/components/com_contact/src/Rule/ContactEmailMessageRule.php index 67863f9c9db91..288d121fb4a09 100644 --- a/components/com_contact/src/Rule/ContactEmailMessageRule.php +++ b/components/com_contact/src/Rule/ContactEmailMessageRule.php @@ -48,7 +48,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr if ($banned) { foreach (explode(';', (string) $banned) as $item) { $item = trim($item); - if ($item != '' && StringHelper::stristr($value, $item) !== false) { + if ($item !== '' && StringHelper::stristr($value, $item) !== false) { return false; } } diff --git a/components/com_contact/src/Rule/ContactEmailRule.php b/components/com_contact/src/Rule/ContactEmailRule.php index 32a0be057418e..29b0a1946d09f 100644 --- a/components/com_contact/src/Rule/ContactEmailRule.php +++ b/components/com_contact/src/Rule/ContactEmailRule.php @@ -52,7 +52,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr if ($banned) { foreach (explode(';', (string) $banned) as $item) { $item = trim($item); - if ($item != '' && StringHelper::stristr($value, $item) !== false) { + if ($item !== '' && StringHelper::stristr($value, $item) !== false) { return false; } } diff --git a/components/com_contact/src/Rule/ContactEmailSubjectRule.php b/components/com_contact/src/Rule/ContactEmailSubjectRule.php index efa17cca1543a..40ccc365b91f7 100644 --- a/components/com_contact/src/Rule/ContactEmailSubjectRule.php +++ b/components/com_contact/src/Rule/ContactEmailSubjectRule.php @@ -48,7 +48,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr if ($banned) { foreach (explode(';', (string) $banned) as $item) { $item = trim($item); - if ($item != '' && StringHelper::stristr($value, $item) !== false) { + if ($item !== '' && StringHelper::stristr($value, $item) !== false) { return false; } } diff --git a/components/com_contact/src/Service/Router.php b/components/com_contact/src/Service/Router.php index 4d19ee32e8ac7..6f7c34f6295ea 100644 --- a/components/com_contact/src/Service/Router.php +++ b/components/com_contact/src/Service/Router.php @@ -260,7 +260,7 @@ public function getContactId($segment, $query) $id = (int) $this->db->loadResult(); // Do we have a URL with ID? - if ($id) { + if ($id !== 0) { return $id; } @@ -269,7 +269,7 @@ public function getContactId($segment, $query) $id = (int) $segment; - if ($id) { + if ($id !== 0) { $dbquery = $this->db->getQuery(true); $dbquery->select($this->db->quoteName('alias')) ->from($this->db->quoteName('#__contact_details')) diff --git a/components/com_contact/src/View/Category/HtmlView.php b/components/com_contact/src/View/Category/HtmlView.php index 2ab162e8fcc1e..cb5dad49d7e26 100644 --- a/components/com_contact/src/View/Category/HtmlView.php +++ b/components/com_contact/src/View/Category/HtmlView.php @@ -26,6 +26,8 @@ */ class HtmlView extends CategoryView { + public $menu; + public $pathway; /** * @var string The name of the extension for the category * @since 3.2 @@ -77,7 +79,7 @@ public function display($tpl = null) if ($item->params->get('show_email_headings', 0) == 1) { $item->email_to = trim($item->email_to); - if (!empty($item->email_to) && MailHelper::isEmailAddress($item->email_to)) { + if ($item->email_to !== '' && $item->email_to !== '0' && MailHelper::isEmailAddress($item->email_to)) { $item->email_to = HTMLHelper::_('email.cloak', $item->email_to); } else { $item->email_to = ''; diff --git a/components/com_contact/src/View/Contact/HtmlView.php b/components/com_contact/src/View/Contact/HtmlView.php index 4e6c55a4463bf..73306affc6d67 100644 --- a/components/com_contact/src/View/Contact/HtmlView.php +++ b/components/com_contact/src/View/Contact/HtmlView.php @@ -34,6 +34,10 @@ */ class HtmlView extends BaseHtmlView implements UserFactoryAwareInterface { + /** + * @var \Joomla\CMS\User\User|null + */ + public $contactUser; use UserFactoryAwareTrait; /** @@ -133,7 +137,7 @@ class HtmlView extends BaseHtmlView implements UserFactoryAwareInterface * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null */ public function display($tpl = null) { @@ -345,7 +349,7 @@ public function display($tpl = null) $contactUser->text = ''; $app->triggerEvent('onContentPrepare', ['com_users.user', &$contactUser, &$item->params, 0]); - if (!isset($contactUser->jcfields)) { + if (!property_exists($contactUser, 'jcfields') || $contactUser->jcfields === null) { $contactUser->jcfields = []; } } @@ -377,6 +381,7 @@ public function display($tpl = null) $this->_prepareDocument(); parent::display($tpl); + return null; } /** diff --git a/components/com_contact/src/View/Contact/VcfView.php b/components/com_contact/src/View/Contact/VcfView.php index 7145c262b9016..fe539d0a9594e 100644 --- a/components/com_contact/src/View/Contact/VcfView.php +++ b/components/com_contact/src/View/Contact/VcfView.php @@ -69,12 +69,12 @@ public function display($tpl = null) $firstname = ''; - if (!empty($name_and_midname)) { + if ($name_and_midname !== '' && $name_and_midname !== '0') { $namearray = explode(' ', $name_and_midname); $firstname = $namearray[0]; $middlename = (\count($namearray) > 1) ? $namearray[1] : ''; - $card_name = $firstname . ' ' . ($middlename ? $middlename . ' ' : '') . $card_name; + $card_name = $firstname . ' ' . ($middlename !== '' && $middlename !== '0' ? $middlename . ' ' : '') . $card_name; } } else { // "Firstname Middlename Lastname" format support @@ -83,7 +83,7 @@ public function display($tpl = null) $middlename = (\count($namearray) > 2) ? $namearray[1] : ''; $firstname = array_shift($namearray); $lastname = \count($namearray) ? end($namearray) : ''; - $card_name = $firstname . ($middlename ? ' ' . $middlename : '') . ($lastname ? ' ' . $lastname : ''); + $card_name = $firstname . ($middlename !== '' && $middlename !== '0' ? ' ' . $middlename : '') . ($lastname ? ' ' . $lastname : ''); } $rev = date('c', strtotime($item->modified)); diff --git a/components/com_contact/src/View/Featured/HtmlView.php b/components/com_contact/src/View/Featured/HtmlView.php index f9a23d4d5a108..aab1ba2c82970 100644 --- a/components/com_contact/src/View/Featured/HtmlView.php +++ b/components/com_contact/src/View/Featured/HtmlView.php @@ -29,6 +29,10 @@ */ class HtmlView extends BaseHtmlView { + public $maxLevel; + public $category; + public $children; + public $parent; /** * The item model state * @@ -116,7 +120,7 @@ public function display($tpl = null) if ($item->params->get('show_email', 0) == 1) { $item->email_to = trim($item->email_to); - if (!empty($item->email_to) && MailHelper::isEmailAddress($item->email_to)) { + if ($item->email_to !== '' && $item->email_to !== '0' && MailHelper::isEmailAddress($item->email_to)) { $item->email_to = HTMLHelper::_('email.cloak', $item->email_to); } else { $item->email_to = ''; diff --git a/components/com_contact/src/View/Form/HtmlView.php b/components/com_contact/src/View/Form/HtmlView.php index 5f9137c9fb8b3..323b5edd9f57a 100644 --- a/components/com_contact/src/View/Form/HtmlView.php +++ b/components/com_contact/src/View/Form/HtmlView.php @@ -70,7 +70,7 @@ class HtmlView extends BaseHtmlView * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null * * @throws \Exception * @since 4.0.0 @@ -95,7 +95,7 @@ public function display($tpl = null) $authorised = $canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by === $user->id); } - if ($authorised !== true) { + if (!$authorised) { $app->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'error'); $app->setHeader('status', 403, true); @@ -133,6 +133,7 @@ public function display($tpl = null) $this->_prepareDocument(); parent::display($tpl); + return null; } /** diff --git a/components/com_content/src/Controller/ArticleController.php b/components/com_content/src/Controller/ArticleController.php index 4680d527034fd..79058e7185771 100644 --- a/components/com_content/src/Controller/ArticleController.php +++ b/components/com_content/src/Controller/ArticleController.php @@ -69,7 +69,7 @@ public function add() // Redirect to the return page. $this->setRedirect($this->getReturnPage()); - return; + return null; } // Redirect to the edit screen. @@ -124,7 +124,7 @@ protected function allowAdd($data = []) */ protected function allowEdit($data = [], $key = 'id') { - $recordId = (int) isset($data[$key]) ? $data[$key] : 0; + $recordId = (int) isset($data[$key]) !== 0 ? $data[$key] : 0; $user = $this->app->getIdentity(); // Zero record (id:0), return component edit permission by calling parent controller method @@ -368,11 +368,9 @@ public function save($key = null, $urlVar = 'a_id') } } elseif ($this->getTask() === 'save2copy') { // Redirect to the article page, use the redirect url set from parent controller - } else { + } elseif ($result) { // If ok, redirect to the return page. - if ($result) { - $this->setRedirect(Route::_($this->getReturnPage(), false)); - } + $this->setRedirect(Route::_($this->getReturnPage(), false)); } return $result; diff --git a/components/com_content/src/Controller/DisplayController.php b/components/com_content/src/Controller/DisplayController.php index 8f9bb4c3bd190..8d438070ac79a 100644 --- a/components/com_content/src/Controller/DisplayController.php +++ b/components/com_content/src/Controller/DisplayController.php @@ -110,13 +110,9 @@ public function display($cachable = false, $urlparams = false) throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id), 403); } - if ($vName === 'article' && \in_array($this->input->getMethod(), ['GET', 'POST'])) { - // Get/Create the model - if ($model = $this->getModel($vName)) { - if (ComponentHelper::getParams('com_content')->get('record_hits', 1) == 1) { - $model->hit(); - } - } + // Get/Create the model + if ($vName === 'article' && \in_array($this->input->getMethod(), ['GET', 'POST']) && ($model = $this->getModel($vName)) && ComponentHelper::getParams('com_content')->get('record_hits', 1) == 1) { + $model->hit(); } parent::display($cachable, $safeurlparams); diff --git a/components/com_content/src/Helper/AssociationHelper.php b/components/com_content/src/Helper/AssociationHelper.php index 83ff4387395f3..d100af7a87ed6 100644 --- a/components/com_content/src/Helper/AssociationHelper.php +++ b/components/com_content/src/Helper/AssociationHelper.php @@ -49,51 +49,42 @@ public static function getAssociations($id = 0, $view = null, $layout = null) $layout = $jinput->get('layout', '', 'string'); } - if ($view === 'article') { - if ($id) { - $user = Factory::getUser(); - $groups = implode(',', $user->getAuthorisedViewLevels()); - $db = Factory::getDbo(); - $advClause = []; - - // Filter by user groups - $advClause[] = 'c2.access IN (' . $groups . ')'; - - // Filter by current language - $advClause[] = 'c2.language != ' . $db->quote(Factory::getLanguage()->getTag()); - - if (!$user->authorise('core.edit.state', 'com_content') && !$user->authorise('core.edit', 'com_content')) { - // Filter by start and end dates. - $date = Factory::getDate(); - - $nowDate = $db->quote($date->toSql()); - - $advClause[] = '(c2.publish_up IS NULL OR c2.publish_up <= ' . $nowDate . ')'; - $advClause[] = '(c2.publish_down IS NULL OR c2.publish_down >= ' . $nowDate . ')'; - - // Filter by published - $advClause[] = 'c2.state = 1'; - } - - $associations = Associations::getAssociations( - 'com_content', - '#__content', - 'com_content.item', - $id, - 'id', - 'alias', - 'catid', - $advClause - ); - - $return = []; - - foreach ($associations as $tag => $item) { - $return[$tag] = RouteHelper::getArticleRoute($item->id, (int) $item->catid, $item->language, $layout); - } - - return $return; + if ($view === 'article' && $id) { + $user = Factory::getUser(); + $groups = implode(',', $user->getAuthorisedViewLevels()); + $db = Factory::getDbo(); + $advClause = []; + // Filter by user groups + $advClause[] = 'c2.access IN (' . $groups . ')'; + // Filter by current language + $advClause[] = 'c2.language != ' . $db->quote(Factory::getLanguage()->getTag()); + if (!$user->authorise('core.edit.state', 'com_content') && !$user->authorise('core.edit', 'com_content')) { + // Filter by start and end dates. + $date = Factory::getDate(); + + $nowDate = $db->quote($date->toSql()); + + $advClause[] = '(c2.publish_up IS NULL OR c2.publish_up <= ' . $nowDate . ')'; + $advClause[] = '(c2.publish_down IS NULL OR c2.publish_down >= ' . $nowDate . ')'; + + // Filter by published + $advClause[] = 'c2.state = 1'; + } + $associations = Associations::getAssociations( + 'com_content', + '#__content', + 'com_content.item', + $id, + 'id', + 'alias', + 'catid', + $advClause + ); + $return = []; + foreach ($associations as $tag => $item) { + $return[$tag] = RouteHelper::getArticleRoute($item->id, (int) $item->catid, $item->language, $layout); } + return $return; } if ($view === 'category' || $view === 'categories') { diff --git a/components/com_content/src/Helper/RouteHelper.php b/components/com_content/src/Helper/RouteHelper.php index fc86fcf69b4e4..6bb60ccc9a9d0 100644 --- a/components/com_content/src/Helper/RouteHelper.php +++ b/components/com_content/src/Helper/RouteHelper.php @@ -69,11 +69,7 @@ public static function getArticleRoute($id, $catid = 0, $language = null, $layou */ public static function getCategoryRoute($catid, $language = 0, $layout = null) { - if ($catid instanceof CategoryNode) { - $id = $catid->id; - } else { - $id = (int) $catid; - } + $id = $catid instanceof CategoryNode ? $catid->id : (int) $catid; if ($id < 1) { return ''; diff --git a/components/com_content/src/Model/ArchiveModel.php b/components/com_content/src/Model/ArchiveModel.php index 957083f3cc958..35ff2863c989a 100644 --- a/components/com_content/src/Model/ArchiveModel.php +++ b/components/com_content/src/Model/ArchiveModel.php @@ -114,17 +114,17 @@ protected function getListQuery() // First, get the date field $queryDate = QueryHelper::getQueryDate($articleOrderDate, $this->getDatabase()); - if ($month = (int) $this->getState('filter.month')) { + if ($month = (int) $this->getState('filter.month') !== 0) { $query->where($query->month($queryDate) . ' = :month') ->bind(':month', $month, ParameterType::INTEGER); } - if ($year = (int) $this->getState('filter.year')) { + if ($year = (int) $this->getState('filter.year') !== 0) { $query->where($query->year($queryDate) . ' = :year') ->bind(':year', $year, ParameterType::INTEGER); } - if (\count($catids) > 0) { + if ($catids !== []) { $query->whereIn($db->quoteName('c.id'), $catids); } diff --git a/components/com_content/src/Model/ArticleModel.php b/components/com_content/src/Model/ArticleModel.php index dd64c43756e0b..6eca8db62f558 100644 --- a/components/com_content/src/Model/ArticleModel.php +++ b/components/com_content/src/Model/ArticleModel.php @@ -292,7 +292,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('article.id'); + $pk = (empty($pk)) ? (int) $this->getState('article.id') : $pk; $table = Table::getInstance('Content', '\\Joomla\\CMS\\Table\\'); $table->hit($pk); @@ -342,7 +342,6 @@ public function storeVote($pk = 0, $rate = 0) // There are no ratings yet, so lets insert our rating if (!$rating) { $query = $db->getQuery(true); - // Create the base insert statement. $query->insert($db->quoteName('#__content_rating')) ->columns( @@ -357,10 +356,8 @@ public function storeVote($pk = 0, $rate = 0) ->bind(':pk', $pk, ParameterType::INTEGER) ->bind(':ip', $userIP) ->bind(':rate', $rate, ParameterType::INTEGER); - // Set the query and execute the insert. $db->setQuery($query); - try { $db->execute(); } catch (\RuntimeException $e) { @@ -368,37 +365,32 @@ public function storeVote($pk = 0, $rate = 0) return false; } - } else { - if ($userIP != $rating->lastip) { - $query = $db->getQuery(true); - - // Create the base update statement. - $query->update($db->quoteName('#__content_rating')) - ->set( - [ - $db->quoteName('rating_count') . ' = ' . $db->quoteName('rating_count') . ' + 1', - $db->quoteName('rating_sum') . ' = ' . $db->quoteName('rating_sum') . ' + :rate', - $db->quoteName('lastip') . ' = :ip', - ] - ) - ->where($db->quoteName('content_id') . ' = :pk') - ->bind(':rate', $rate, ParameterType::INTEGER) - ->bind(':ip', $userIP) - ->bind(':pk', $pk, ParameterType::INTEGER); - - // Set the query and execute the update. - $db->setQuery($query); - - try { - $db->execute(); - } catch (\RuntimeException $e) { - Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); + } elseif ($userIP != $rating->lastip) { + $query = $db->getQuery(true); + // Create the base update statement. + $query->update($db->quoteName('#__content_rating')) + ->set( + [ + $db->quoteName('rating_count') . ' = ' . $db->quoteName('rating_count') . ' + 1', + $db->quoteName('rating_sum') . ' = ' . $db->quoteName('rating_sum') . ' + :rate', + $db->quoteName('lastip') . ' = :ip', + ] + ) + ->where($db->quoteName('content_id') . ' = :pk') + ->bind(':rate', $rate, ParameterType::INTEGER) + ->bind(':ip', $userIP) + ->bind(':pk', $pk, ParameterType::INTEGER); + // Set the query and execute the update. + $db->setQuery($query); + try { + $db->execute(); + } catch (\RuntimeException $e) { + Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); - return false; - } - } else { return false; } + } else { + return false; } $this->cleanCache(); diff --git a/components/com_content/src/Model/ArticlesModel.php b/components/com_content/src/Model/ArticlesModel.php index f60a0413b6aa1..05120c8bd1434 100644 --- a/components/com_content/src/Model/ArticlesModel.php +++ b/components/com_content/src/Model/ArticlesModel.php @@ -440,7 +440,7 @@ protected function getListQuery() $query->where($db->quoteName('a.catid') . $type . ':categoryId'); $query->bind(':categoryId', $categoryId, ParameterType::INTEGER); } - } elseif (\is_array($categoryId) && (\count($categoryId) > 0)) { + } elseif (\is_array($categoryId) && ($categoryId !== [])) { $categoryId = ArrayHelper::toInteger($categoryId); if (!empty($categoryId)) { @@ -464,7 +464,7 @@ protected function getListQuery() } elseif (\is_array($authorId)) { $authorId = array_values(array_filter($authorId, 'is_numeric')); - if ($authorId) { + if ($authorId !== []) { $type = $this->getState('filter.author_id.include', true) ? ' IN' : ' NOT IN'; $authorWhere = $db->quoteName('a.created_by') . $type . ' (' . implode(',', $query->bindArray($authorId)) . ')'; } @@ -478,15 +478,15 @@ protected function getListQuery() $type = $this->getState('filter.author_alias.include', true) ? ' = ' : ' <> '; $authorAliasWhere = $db->quoteName('a.created_by_alias') . $type . ':authorAlias'; $query->bind(':authorAlias', $authorAlias); - } elseif (\is_array($authorAlias) && !empty($authorAlias)) { + } elseif (\is_array($authorAlias) && $authorAlias !== []) { $type = $this->getState('filter.author_alias.include', true) ? ' IN' : ' NOT IN'; $authorAliasWhere = $db->quoteName('a.created_by_alias') . $type . ' (' . implode(',', $query->bindArray($authorAlias, ParameterType::STRING)) . ')'; } - if (!empty($authorWhere) && !empty($authorAliasWhere)) { + if ($authorWhere !== '' && $authorWhere !== '0' && ($authorAliasWhere !== '' && $authorAliasWhere !== '0')) { $query->where('(' . $authorWhere . ' OR ' . $authorAliasWhere . ')'); - } elseif (!empty($authorWhere) || !empty($authorAliasWhere)) { + } elseif ($authorWhere !== '' && $authorWhere !== '0' || $authorAliasWhere !== '' && $authorAliasWhere !== '0') { // One of these is empty, the other is not so we just add both $query->where($authorWhere . $authorAliasWhere); } @@ -623,7 +623,7 @@ protected function getListQuery() $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id') ); } - } elseif ($tagId = (int) $tagId) { + } elseif ($tagId = (int) $tagId !== 0) { $query->join( 'INNER', $db->quoteName('#__contentitem_tag_map', 'tagmap'), @@ -692,18 +692,12 @@ public function getItems() foreach ($menuParamsArray as $key => $value) { if ($value === 'use_article') { // If the article has a value, use it - if ($articleParams->get($key) != '') { - // Get the value from the article - $articleArray[$key] = $articleParams->get($key); - } else { - // Otherwise, use the global value - $articleArray[$key] = $globalParams->get($key); - } + $articleArray[$key] = $articleParams->get($key) != '' ? $articleParams->get($key) : $globalParams->get($key); } } // Merge the selected article params - if (\count($articleArray) > 0) { + if ($articleArray !== []) { $articleParams = new Registry($articleArray); $item->params->merge($articleParams); } @@ -752,13 +746,11 @@ public function getItems() if ($access) { // If the access filter has been set, we already have only the articles this user can view. $item->params->set('access-view', true); - } else { + } elseif ($item->catid == 0 || $item->category_access === null) { // If no access filter is set, the layout takes some responsibility for display of limited information. - if ($item->catid == 0 || $item->category_access === null) { - $item->params->set('access-view', \in_array($item->access, $groups)); - } else { - $item->params->set('access-view', \in_array($item->access, $groups) && \in_array($item->category_access, $groups)); - } + $item->params->set('access-view', \in_array($item->access, $groups)); + } else { + $item->params->set('access-view', \in_array($item->access, $groups) && \in_array($item->category_access, $groups)); } // Some contexts may not use tags data at all, so we allow callers to disable loading tag data @@ -773,7 +765,7 @@ public function getItems() } // Load tags of all items. - if ($taggedItems) { + if ($taggedItems !== []) { $tagsHelper = new TagsHelper(); $itemIds = array_keys($taggedItems); diff --git a/components/com_content/src/Model/CategoriesModel.php b/components/com_content/src/Model/CategoriesModel.php index 5c25dc5f4227e..a263993204bf2 100644 --- a/components/com_content/src/Model/CategoriesModel.php +++ b/components/com_content/src/Model/CategoriesModel.php @@ -116,22 +116,14 @@ public function getItems($recursive = false) $menu = $app->getMenu(); $active = $menu->getActive(); - if ($active) { - $params = $active->getParams(); - } else { - $params = new Registry(); - } + $params = $active ? $active->getParams() : new Registry(); $options = []; $options['countItems'] = $params->get('show_cat_num_articles_cat', 1) || !$params->get('show_empty_categories_cat', 0); $categories = Categories::getInstance('Content', $options); $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); - if (\is_object($this->_parent)) { - $this->cache[$store] = $this->_parent->getChildren($recursive); - } else { - $this->cache[$store] = false; - } + $this->cache[$store] = \is_object($this->_parent) ? $this->_parent->getChildren($recursive) : false; } return $this->cache[$store]; diff --git a/components/com_content/src/Model/CategoryModel.php b/components/com_content/src/Model/CategoryModel.php index 3ee9e4dd4e451..d11c56c855e3f 100644 --- a/components/com_content/src/Model/CategoryModel.php +++ b/components/com_content/src/Model/CategoryModel.php @@ -335,7 +335,7 @@ public function getPagination() public function getCategory() { if (!\is_object($this->_item)) { - if (isset($this->state->params)) { + if (property_exists($this->state, 'params') && $this->state->params !== null) { $params = $this->state->params; $options = []; $options['countItems'] = $params->get('show_cat_num_articles', 1) || !$params->get('show_empty_categories_cat', 0); @@ -464,7 +464,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('category.id'); + $pk = (empty($pk)) ? (int) $this->getState('category.id') : $pk; $table = Table::getInstance('Category', '\\Joomla\\CMS\\Table\\'); $table->hit($pk); diff --git a/components/com_content/src/Model/FeaturedModel.php b/components/com_content/src/Model/FeaturedModel.php index 82771831000d1..1cdfdeda9a9ea 100644 --- a/components/com_content/src/Model/FeaturedModel.php +++ b/components/com_content/src/Model/FeaturedModel.php @@ -61,11 +61,7 @@ protected function populateState($ordering = null, $direction = null) $params = $this->state->params; - if ($menu = $app->getMenu()->getActive()) { - $menuParams = $menu->getParams(); - } else { - $menuParams = new Registry(); - } + $menuParams = $menu = $app->getMenu()->getActive() ? $menu->getParams() : new Registry(); $mergedParams = clone $menuParams; $mergedParams->merge($params); diff --git a/components/com_content/src/Model/FormModel.php b/components/com_content/src/Model/FormModel.php index 2fbbe4476af3c..27a499b1257ec 100644 --- a/components/com_content/src/Model/FormModel.php +++ b/components/com_content/src/Model/FormModel.php @@ -57,11 +57,7 @@ protected function populateState() $params = $app->getParams(); $this->setState('params', $params); - if ($params && $params->get('enable_category') == 1 && $params->get('catid')) { - $catId = $params->get('catid'); - } else { - $catId = 0; - } + $catId = $params && $params->get('enable_category') == 1 && $params->get('catid') ? $params->get('catid') : 0; // Load state from the request. $pk = $input->getInt('a_id'); @@ -84,7 +80,7 @@ protected function populateState() */ public function getItem($itemId = null) { - $itemId = (int) (!empty($itemId)) ? $itemId : $this->getState('article.id'); + $itemId = (int) (!empty($itemId)) !== 0 ? $itemId : $this->getState('article.id'); // Get a row instance. $table = $this->getTable(); @@ -129,7 +125,7 @@ public function getItem($itemId = null) // New item. $catId = (int) $this->getState('article.catid'); - if ($catId) { + if ($catId !== 0) { $value->params->set('access-change', $user->authorise('core.edit.state', 'com_content.category.' . $catId)); $value->catid = $catId; } else { diff --git a/components/com_content/src/Service/Router.php b/components/com_content/src/Service/Router.php index 18357e86d8cdb..7b6168480709b 100644 --- a/components/com_content/src/Service/Router.php +++ b/components/com_content/src/Service/Router.php @@ -261,7 +261,7 @@ public function getArticleId($segment, $query) $id = (int) $this->db->loadResult(); // Do we have a URL with ID? - if ($id) { + if ($id !== 0) { return $id; } @@ -270,7 +270,7 @@ public function getArticleId($segment, $query) $id = (int) $segment; - if ($id) { + if ($id !== 0) { $dbquery = $this->db->getQuery(true); $dbquery->select($this->db->quoteName('alias')) ->from($this->db->quoteName('#__content')) diff --git a/components/com_content/src/View/Category/HtmlView.php b/components/com_content/src/View/Category/HtmlView.php index 52bbecd7acfba..efbcacc766e57 100644 --- a/components/com_content/src/View/Category/HtmlView.php +++ b/components/com_content/src/View/Category/HtmlView.php @@ -27,6 +27,12 @@ */ class HtmlView extends CategoryView { + /** + * @var bool + */ + public $vote; + public $menu; + public $pathway; /** * @var array Array of leading items for blog display * @since 3.2 diff --git a/components/com_content/src/View/Form/HtmlView.php b/components/com_content/src/View/Form/HtmlView.php index 4fcf4ac399e37..443a048ed28da 100644 --- a/components/com_content/src/View/Form/HtmlView.php +++ b/components/com_content/src/View/Form/HtmlView.php @@ -107,7 +107,7 @@ class HtmlView extends BaseHtmlView * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null */ public function display($tpl = null) { @@ -202,6 +202,7 @@ public function display($tpl = null) $this->_prepareDocument(); parent::display($tpl); + return null; } /** diff --git a/components/com_content/tmpl/featured/default.php b/components/com_content/tmpl/featured/default.php index 374974ab737bf..c885025e0365d 100644 --- a/components/com_content/tmpl/featured/default.php +++ b/components/com_content/tmpl/featured/default.php @@ -21,7 +21,7 @@
    - lead_items)) : ?> + lead_items !== []) : ?>
    lead_items as &$item) : ?>
    @@ -34,7 +34,7 @@
    - intro_items)) : ?> + intro_items !== []) : ?> params->get('blog_class', ''); ?> params->get('num_columns') > 1) : ?> params->get('multi_column_order', 0) === 0 ? ' masonry-' : ' columns-'; ?> @@ -52,7 +52,7 @@
    - link_items)) : ?> + link_items !== []) : ?>
    loadTemplate('links'); ?>
    diff --git a/components/com_contenthistory/src/Dispatcher/Dispatcher.php b/components/com_contenthistory/src/Dispatcher/Dispatcher.php index 9534de6e17e16..43694786fe906 100644 --- a/components/com_contenthistory/src/Dispatcher/Dispatcher.php +++ b/components/com_contenthistory/src/Dispatcher/Dispatcher.php @@ -35,8 +35,9 @@ class Dispatcher extends ComponentDispatcher protected function loadLanguage() { // Load common and local language files. - $this->app->getLanguage()->load($this->option, JPATH_ADMINISTRATOR) || - $this->app->getLanguage()->load($this->option, JPATH_SITE); + if (!$this->app->getLanguage()->load($this->option, JPATH_ADMINISTRATOR)) { + $this->app->getLanguage()->load($this->option, JPATH_SITE); + } } /** diff --git a/components/com_fields/layouts/fields/render.php b/components/com_fields/layouts/fields/render.php index a62326e57e04a..aaa1c7fb74d01 100644 --- a/components/com_fields/layouts/fields/render.php +++ b/components/com_fields/layouts/fields/render.php @@ -64,7 +64,7 @@ $output[] = '
  • ' . $content . '
  • '; } -if (empty($output)) { +if ($output === []) { return; } ?> diff --git a/components/com_finder/src/Helper/FinderHelper.php b/components/com_finder/src/Helper/FinderHelper.php index c7ce9e84b1571..f1a95e1a12cc2 100644 --- a/components/com_finder/src/Helper/FinderHelper.php +++ b/components/com_finder/src/Helper/FinderHelper.php @@ -42,7 +42,7 @@ public static function logSearch(Query $searchquery, $resultCount = 0) return; } - if (trim($searchquery->input) == '' && !$searchquery->empty) { + if (trim($searchquery->input) === '' && !$searchquery->empty) { return; } @@ -71,7 +71,7 @@ public static function logSearch(Query $searchquery, $resultCount = 0) $query->clear(); // Update the table based on the results - if ($hits) { + if ($hits !== 0) { $query->update($db->quoteName('#__finder_logging')) ->set('hits = (hits + 1)') ->where($db->quoteName('md5sum') . ' = ' . $db->quote($entry->md5sum)); diff --git a/components/com_finder/src/Model/SearchModel.php b/components/com_finder/src/Model/SearchModel.php index 506c2ca666eff..ae2e9316e4dd0 100644 --- a/components/com_finder/src/Model/SearchModel.php +++ b/components/com_finder/src/Model/SearchModel.php @@ -115,11 +115,7 @@ public function getItems() // Convert the rows to result objects. foreach ($items as $rk => $row) { // Build the result object. - if (\is_resource($row->object)) { - $result = unserialize(stream_get_contents($row->object)); - } else { - $result = unserialize($row->object); - } + $result = \is_resource($row->object) ? unserialize(stream_get_contents($row->object)) : unserialize($row->object); $result->cleanURL = $result->route; @@ -189,7 +185,7 @@ protected function getListQuery() * groups. Within each group there can be an array of values that will * use OR clauses. */ - if (!empty($this->searchquery->filters)) { + if ($this->searchquery->filters !== []) { // Convert the associative array to a numerically indexed array. $groups = array_values($this->searchquery->filters); $taxonomies = \call_user_func_array('array_merge', array_values($this->searchquery->filters)); @@ -314,7 +310,7 @@ protected function getListQuery() */ if (\count($this->requiredTerms)) { foreach ($this->requiredTerms as $terms) { - if (\count($terms)) { + if (\count($terms) > 0) { $query->having('SUM(CASE WHEN m.term_id IN (' . implode(',', $terms) . ') THEN 1 ELSE 0 END) > 0'); } else { $query->where('false'); diff --git a/components/com_finder/src/Model/SuggestionsModel.php b/components/com_finder/src/Model/SuggestionsModel.php index d3a9e5d65e1ed..e3619998d6bd1 100644 --- a/components/com_finder/src/Model/SuggestionsModel.php +++ b/components/com_finder/src/Model/SuggestionsModel.php @@ -89,7 +89,7 @@ protected function getListQuery() $termIds = $db->setQuery($termIdQuery, 0, 100)->loadColumn(); // Early return on term mismatch - if (!\count($termIds)) { + if (\count($termIds) === 0) { return $termIdQuery; } diff --git a/components/com_finder/src/View/Search/FeedView.php b/components/com_finder/src/View/Search/FeedView.php index a6c608e94872e..25d6845028007 100644 --- a/components/com_finder/src/View/Search/FeedView.php +++ b/components/com_finder/src/View/Search/FeedView.php @@ -86,7 +86,7 @@ public function display($tpl = null) $item->description = $result->description; // Use Unix date to cope for non-english languages - $item->date = (int) $result->start_date ? HTMLHelper::_('date', $result->start_date, 'U') : $result->indexdate; + $item->date = (int) $result->start_date !== 0 ? HTMLHelper::_('date', $result->start_date, 'U') : $result->indexdate; // Loads item info into RSS array $this->getDocument()->addItem($item); diff --git a/components/com_finder/src/View/Search/HtmlView.php b/components/com_finder/src/View/Search/HtmlView.php index 1bd379a3afc81..cfd46bac9e1c2 100644 --- a/components/com_finder/src/View/Search/HtmlView.php +++ b/components/com_finder/src/View/Search/HtmlView.php @@ -39,6 +39,10 @@ */ class HtmlView extends BaseHtmlView implements SiteRouterAwareInterface { + /** + * @var mixed[] + */ + public $sortOrderFields; use SiteRouterAwareTrait; /** @@ -145,15 +149,25 @@ public function display($tpl = null) // Get view data. $this->state = $model->getState(); $this->query = $model->getQuery(); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderQuery') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderQuery'); + } $this->results = $model->getItems(); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderResults') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderResults'); + } $this->sortOrderFields = $model->getSortOrderFields(); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderSortOrderFields') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderSortOrderFields'); + } $this->total = $model->getTotal(); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderTotal') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderTotal'); + } $this->pagination = $model->getPagination(); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderPagination') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderPagination'); + } // Flag indicates to not add limitstart=0 to URL $this->pagination->hideEmptyLimitstart = true; @@ -240,11 +254,15 @@ public function display($tpl = null) $this->prepareDocument(); - \JDEBUG ? Profiler::getInstance('Application')->mark('beforeFinderLayout') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('beforeFinderLayout'); + } parent::display($tpl); - \JDEBUG ? Profiler::getInstance('Application')->mark('afterFinderLayout') : null; + if (\JDEBUG) { + Profiler::getInstance('Application')->mark('afterFinderLayout'); + } } /** diff --git a/components/com_finder/tmpl/search/default_result.php b/components/com_finder/tmpl/search/default_result.php index 771217e3f772e..0662205ebcb3f 100644 --- a/components/com_finder/tmpl/search/default_result.php +++ b/components/com_finder/tmpl/search/default_result.php @@ -117,7 +117,7 @@ title; ?> - +
  • : diff --git a/components/com_finder/tmpl/search/default_results.php b/components/com_finder/tmpl/search/default_results.php index 8c8b8b5141c4a..e21a85a080cbf 100644 --- a/components/com_finder/tmpl/search/default_results.php +++ b/components/com_finder/tmpl/search/default_results.php @@ -54,7 +54,7 @@
  • -query->highlight) && $this->params->get('highlight_terms', 1)) : ?> +query->highlight !== [] && $this->params->get('highlight_terms', 1)) : ?> getDocument()->getWebAssetManager()->useScript('highlight'); diff --git a/components/com_menus/layouts/joomla/searchtools/default.php b/components/com_menus/layouts/joomla/searchtools/default.php index 6e08fb2e2265f..8818a29e7905b 100644 --- a/components/com_menus/layouts/joomla/searchtools/default.php +++ b/components/com_menus/layouts/joomla/searchtools/default.php @@ -19,7 +19,7 @@ $data = $displayData; // Receive overridable options -$data['options'] = !empty($data['options']) ? $data['options'] : []; +$data['options'] = empty($data['options']) ? [] : $data['options']; $noResultsText = ''; $hideActiveFilters = false; @@ -72,8 +72,8 @@ 'showSelector' => $showSelector, 'orderFieldSelector' => '#list_fullordering', 'showNoResults' => !empty($noResultsText), - 'noResultsText' => !empty($noResultsText) ? $noResultsText : '', - 'formSelector' => !empty($data['options']['formSelector']) ? $data['options']['formSelector'] : '#adminForm', + 'noResultsText' => empty($noResultsText) ? '' : $noResultsText, + 'formSelector' => empty($data['options']['formSelector']) ? '#adminForm' : $data['options']['formSelector'], ]; // Merge custom options in the options array. diff --git a/components/com_newsfeeds/src/Helper/AssociationHelper.php b/components/com_newsfeeds/src/Helper/AssociationHelper.php index 302d290bb0c4c..deec9a9dea41d 100644 --- a/components/com_newsfeeds/src/Helper/AssociationHelper.php +++ b/components/com_newsfeeds/src/Helper/AssociationHelper.php @@ -41,18 +41,13 @@ public static function getAssociations($id = 0, $view = null) $view ??= $jinput->get('view'); $id = empty($id) ? $jinput->getInt('id') : $id; - if ($view === 'newsfeed') { - if ($id) { - $associations = Associations::getAssociations('com_newsfeeds', '#__newsfeeds', 'com_newsfeeds.item', $id); - - $return = []; - - foreach ($associations as $tag => $item) { - $return[$tag] = RouteHelper::getNewsfeedRoute($item->id, (int) $item->catid, $item->language); - } - - return $return; + if ($view === 'newsfeed' && $id) { + $associations = Associations::getAssociations('com_newsfeeds', '#__newsfeeds', 'com_newsfeeds.item', $id); + $return = []; + foreach ($associations as $tag => $item) { + $return[$tag] = RouteHelper::getNewsfeedRoute($item->id, (int) $item->catid, $item->language); } + return $return; } if ($view === 'category' || $view === 'categories') { diff --git a/components/com_newsfeeds/src/Helper/RouteHelper.php b/components/com_newsfeeds/src/Helper/RouteHelper.php index e236310299e68..c1bd0c62ddaa2 100644 --- a/components/com_newsfeeds/src/Helper/RouteHelper.php +++ b/components/com_newsfeeds/src/Helper/RouteHelper.php @@ -59,11 +59,7 @@ public static function getNewsfeedRoute($id, $catid, $language = 0) */ public static function getCategoryRoute($catid, $language = 0) { - if ($catid instanceof CategoryNode) { - $id = $catid->id; - } else { - $id = (int) $catid; - } + $id = $catid instanceof CategoryNode ? $catid->id : (int) $catid; if ($id < 1) { $link = ''; diff --git a/components/com_newsfeeds/src/Model/CategoriesModel.php b/components/com_newsfeeds/src/Model/CategoriesModel.php index 6ad7b106849a2..8249189782964 100644 --- a/components/com_newsfeeds/src/Model/CategoriesModel.php +++ b/components/com_newsfeeds/src/Model/CategoriesModel.php @@ -119,22 +119,14 @@ public function getItems() $menu = $app->getMenu(); $active = $menu->getActive(); - if ($active) { - $params = $active->getParams(); - } else { - $params = new Registry(); - } + $params = $active ? $active->getParams() : new Registry(); $options = []; $options['countItems'] = $params->get('show_cat_items_cat', 1) || !$params->get('show_empty_categories_cat', 0); $categories = Categories::getInstance('Newsfeeds', $options); $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); - if (\is_object($this->_parent)) { - $this->_items = $this->_parent->getChildren(); - } else { - $this->_items = false; - } + $this->_items = \is_object($this->_parent) ? $this->_parent->getChildren() : false; } return $this->_items; diff --git a/components/com_newsfeeds/src/Model/CategoryModel.php b/components/com_newsfeeds/src/Model/CategoryModel.php index 9f848d0135917..db19f1e63d7c6 100644 --- a/components/com_newsfeeds/src/Model/CategoryModel.php +++ b/components/com_newsfeeds/src/Model/CategoryModel.php @@ -120,7 +120,7 @@ public function getItems() // Convert the params field into an object, saving original in _params foreach ($items as $item) { - if (!isset($this->_params)) { + if (!property_exists($this, '_params') || $this->_params === null) { $item->params = new Registry($item->params); } @@ -132,7 +132,7 @@ public function getItems() } // Load tags of all items. - if ($taggedItems) { + if ($taggedItems !== []) { $tagsHelper = new TagsHelper(); $itemIds = array_keys($taggedItems); @@ -167,7 +167,7 @@ protected function getListQuery() ->whereIn($db->quoteName('a.access'), $groups); // Filter by category. - if ($categoryId = (int) $this->getState('category.id')) { + if ($categoryId = (int) $this->getState('category.id') !== 0) { $query->where($db->quoteName('a.catid') . ' = :categoryId') ->join('LEFT', $db->quoteName('#__categories', 'c'), $db->quoteName('c.id') . ' = ' . $db->quoteName('a.catid')) ->whereIn($db->quoteName('c.access'), $groups) @@ -304,11 +304,7 @@ public function getCategory() $menu = $app->getMenu(); $active = $menu->getActive(); - if ($active) { - $params = $active->getParams(); - } else { - $params = new Registry(); - } + $params = $active ? $active->getParams() : new Registry(); $options = []; $options['countItems'] = $params->get('show_cat_items', 1) || $params->get('show_empty_categories', 0); @@ -403,7 +399,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('category.id'); + $pk = (empty($pk)) ? (int) $this->getState('category.id') : $pk; $table = Table::getInstance('Category', '\\Joomla\\CMS\\Table\\'); $table->hit($pk); } diff --git a/components/com_newsfeeds/src/Model/NewsfeedModel.php b/components/com_newsfeeds/src/Model/NewsfeedModel.php index 154e30e1defdd..dea23e138fece 100644 --- a/components/com_newsfeeds/src/Model/NewsfeedModel.php +++ b/components/com_newsfeeds/src/Model/NewsfeedModel.php @@ -214,7 +214,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('newsfeed.id'); + $pk = (empty($pk)) ? (int) $this->getState('newsfeed.id') : $pk; $table = $this->getTable('Newsfeed', 'Administrator'); $table->hit($pk); diff --git a/components/com_newsfeeds/src/Service/Router.php b/components/com_newsfeeds/src/Service/Router.php index b4069b2ee23a6..8bacd133e7351 100644 --- a/components/com_newsfeeds/src/Service/Router.php +++ b/components/com_newsfeeds/src/Service/Router.php @@ -241,7 +241,7 @@ public function getNewsfeedId($segment, $query) $id = (int) $this->db->loadResult(); // Do we have a URL with ID? - if ($id) { + if ($id !== 0) { return $id; } @@ -250,7 +250,7 @@ public function getNewsfeedId($segment, $query) $id = (int) $segment; - if ($id) { + if ($id !== 0) { $dbquery = $this->db->getQuery(true); $dbquery->select($this->db->quoteName('alias')) ->from($this->db->quoteName('#__newsfeeds')) diff --git a/components/com_newsfeeds/src/View/Category/HtmlView.php b/components/com_newsfeeds/src/View/Category/HtmlView.php index f9a7b1f08477e..9edebec3957c9 100644 --- a/components/com_newsfeeds/src/View/Category/HtmlView.php +++ b/components/com_newsfeeds/src/View/Category/HtmlView.php @@ -24,6 +24,8 @@ */ class HtmlView extends CategoryView { + public $menu; + public $pathway; /** * @var string Default title to use for page title * @since 3.2 @@ -88,7 +90,7 @@ protected function prepareDocument() $category = $this->category->getParent(); while ( - isset($category->id) && $category->id > 1 + property_exists($category, 'id') && $category->id !== null && $category->id > 1 && (!isset($menu->query['option']) || $menu->query['option'] !== 'com_newsfeeds' || $menu->query['view'] === 'newsfeed' || $id != $category->id) ) { diff --git a/components/com_newsfeeds/src/View/Newsfeed/HtmlView.php b/components/com_newsfeeds/src/View/Newsfeed/HtmlView.php index aaa1f2afd9bc6..70c0340fbd9ef 100644 --- a/components/com_newsfeeds/src/View/Newsfeed/HtmlView.php +++ b/components/com_newsfeeds/src/View/Newsfeed/HtmlView.php @@ -31,6 +31,11 @@ */ class HtmlView extends BaseHtmlView { + public $rssDoc; + /** + * @var string + */ + public $msg; /** * The model state * @@ -262,7 +267,7 @@ protected function _prepareDocument() $category = Categories::getInstance('Newsfeeds')->get($this->item->catid); while ( - isset($category->id) && $category->id > 1 + property_exists($category, 'id') && $category->id !== null && $category->id > 1 && (!isset($menu->query['option']) || $menu->query['option'] !== 'com_newsfeeds' || $menu->query['view'] === 'newsfeed' || $id != $category->id) ) { diff --git a/components/com_privacy/src/Model/RemindModel.php b/components/com_privacy/src/Model/RemindModel.php index 3672e52de9cdd..57dcd712c003b 100644 --- a/components/com_privacy/src/Model/RemindModel.php +++ b/components/com_privacy/src/Model/RemindModel.php @@ -117,13 +117,8 @@ public function remindRequest($data) 'created' => Factory::getDate()->toSql(), ] ); - - if (!$saved) { - // Error was set by the save method - return false; - } - - return true; + // Error was set by the save method + return $saved; } /** diff --git a/components/com_tags/src/Helper/RouteHelper.php b/components/com_tags/src/Helper/RouteHelper.php index 395f6765f76e8..3c586d1628888 100644 --- a/components/com_tags/src/Helper/RouteHelper.php +++ b/components/com_tags/src/Helper/RouteHelper.php @@ -120,7 +120,7 @@ public static function getComponentTagRoute(string $id, string $language = '*'): $id = array_values(array_filter($id)); - if (!\count($id)) { + if ($id === []) { return ''; } @@ -207,7 +207,7 @@ protected static function _findItem($needles = null) // Only match menu items that list one tag if (isset($item->query['id']) && \is_array($item->query['id'])) { - foreach ($item->query['id'] as $position => $tagId) { + foreach (array_keys($item->query['id']) as $position) { if (!isset(self::$lookup[$lang][$view][$item->query['id'][$position]]) || \count($item->query['id']) == 1) { self::$lookup[$lang][$view][$item->query['id'][$position]] = $item->id; } diff --git a/components/com_tags/src/Model/TagModel.php b/components/com_tags/src/Model/TagModel.php index 427ca37b65e69..0800d3d1ecd78 100644 --- a/components/com_tags/src/Model/TagModel.php +++ b/components/com_tags/src/Model/TagModel.php @@ -224,7 +224,7 @@ protected function populateState($ordering = 'c.core_title', $direction = 'ASC') $itemid = $pkString . ':' . $app->getInput()->get('Itemid', 0, 'int'); $orderCol = $app->getUserStateFromRequest('com_tags.tag.list.' . $itemid . '.filter_order', 'filter_order', '', 'string'); - $orderCol = !$orderCol ? $this->state->params->get('tag_list_orderby', 'c.core_title') : $orderCol; + $orderCol = $orderCol ?: $this->state->params->get('tag_list_orderby', 'c.core_title'); if (!\in_array($orderCol, $this->filter_fields)) { $orderCol = 'c.core_title'; @@ -233,7 +233,7 @@ protected function populateState($ordering = 'c.core_title', $direction = 'ASC') $this->setState('list.ordering', $orderCol); $listOrder = $app->getUserStateFromRequest('com_tags.tag.list.' . $itemid . '.filter_order_direction', 'filter_order_Dir', '', 'string'); - $listOrder = !$listOrder ? $this->state->params->get('tag_list_orderby_direction', 'ASC') : $listOrder; + $listOrder = $listOrder ?: $this->state->params->get('tag_list_orderby_direction', 'ASC'); if (!\in_array(strtoupper((string) $listOrder), ['ASC', 'DESC', ''])) { $listOrder = 'ASC'; @@ -276,10 +276,8 @@ public function getItem($pk = null) $table->load($id); // Check published state. - if ($published = $this->getState('tag.state')) { - if ($table->published != $published) { - continue; - } + if (($published = $this->getState('tag.state')) && $table->published != $published) { + continue; } if (!\in_array($table->access, $this->getCurrentUser()->getAuthorisedViewLevels())) { @@ -315,7 +313,7 @@ public function hit($pk = 0) $hitcount = $input->getInt('hitcount', 1); if ($hitcount) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState('tag.id'); + $pk = (empty($pk)) ? (int) $this->getState('tag.id') : $pk; /** @var \Joomla\Component\Tags\Administrator\Table\TagTable $table */ $table = $this->getTable(); diff --git a/components/com_tags/src/Model/TagsModel.php b/components/com_tags/src/Model/TagsModel.php index 42a05f5ab0fed..335248ee2940a 100644 --- a/components/com_tags/src/Model/TagsModel.php +++ b/components/com_tags/src/Model/TagsModel.php @@ -111,7 +111,7 @@ protected function getListQuery() ->join('LEFT', $db->quoteName('#__users', 'u'), $db->quoteName('a.created_user_id') . ' = ' . $db->quoteName('u.id')) ->whereIn($db->quoteName('a.access'), $groups); - if (!empty($pid)) { + if ($pid !== 0) { $query->where($db->quoteName('a.parent_id') . ' = :pid') ->bind(':pid', $pid, ParameterType::INTEGER); } @@ -137,12 +137,10 @@ protected function getListQuery() if ($format === 'feed') { $limit = $app->get('feed_limit'); + } elseif ($this->state->params->get('show_pagination_limit')) { + $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint'); } else { - if ($this->state->params->get('show_pagination_limit')) { - $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint'); - } else { - $limit = $this->state->params->get('maximum', 20); - } + $limit = $this->state->params->get('maximum', 20); } $this->setState('list.limit', $limit); diff --git a/components/com_tags/src/Service/Router.php b/components/com_tags/src/Service/Router.php index e758b5d1bb083..c72960fb74ca4 100644 --- a/components/com_tags/src/Service/Router.php +++ b/components/com_tags/src/Service/Router.php @@ -73,11 +73,7 @@ public function __construct(SiteApplication $app, AbstractMenu $menu, ?CategoryF $sefPlugin = PluginHelper::getPlugin('system', 'sef'); - if ($sefPlugin) { - $this->sefparams = new Registry($sefPlugin->params); - } else { - $this->sefparams = new Registry(); - } + $this->sefparams = $sefPlugin ? new Registry($sefPlugin->params) : new Registry(); $this->buildLookup(); } @@ -183,14 +179,11 @@ public function preprocess($query) } // TODO: Remove this whole block in 6.0 as it is a bug - if (!$this->sefparams->get('strictrouting', 0)) { - // If not found, return language specific home link - if (!isset($query['Itemid'])) { - $default = $this->menu->getDefault($lang); - - if (!empty($default->id)) { - $query['Itemid'] = $default->id; - } + // If not found, return language specific home link + if (!$this->sefparams->get('strictrouting', 0) && !isset($query['Itemid'])) { + $default = $this->menu->getDefault($lang); + if (!empty($default->id)) { + $query['Itemid'] = $default->id; } } @@ -210,7 +203,7 @@ public function build(&$query) { $segments = []; - $menuItem = !empty($query['Itemid']) ? $this->menu->getItem($query['Itemid']) : false; + $menuItem = empty($query['Itemid']) ? false : $this->menu->getItem($query['Itemid']); if ($menuItem && $menuItem->query['option'] == 'com_tags') { if ($menuItem->query['view'] == 'tags') { @@ -236,7 +229,7 @@ public function build(&$query) * We check if there is a difference between the tags of the menu item and the query. * If they are identical, we exactly match the menu item. Otherwise we append all tags to the URL */ - if (\count(array_diff($int_ids, $mIds)) > 0 || \count(array_diff($mIds, $int_ids)) > 0) { + if (array_diff($int_ids, $mIds) !== [] || array_diff($mIds, $int_ids) !== []) { foreach ($ids as $id) { $segments[] = $id; } @@ -306,7 +299,7 @@ public function parse(&$segments) $ids[] = $this->fixSegment($id); } - if (\count($ids)) { + if (\count($ids) > 0) { $vars['id'] = $ids; $vars['view'] = 'tag'; } diff --git a/components/com_tags/src/View/Tag/HtmlView.php b/components/com_tags/src/View/Tag/HtmlView.php index aa365dbcfe813..25f02f5d02c95 100644 --- a/components/com_tags/src/View/Tag/HtmlView.php +++ b/components/com_tags/src/View/Tag/HtmlView.php @@ -193,7 +193,7 @@ public function display($tpl = null) $itemElement->event = new \stdClass(); // For some plugins. - $itemElement->text = !empty($itemElement->core_body) ? $itemElement->core_body : ''; + $itemElement->text = empty($itemElement->core_body) ? '' : $itemElement->core_body; $itemElement->core_params = new Registry($itemElement->core_params); diff --git a/components/com_tags/src/View/Tags/HtmlView.php b/components/com_tags/src/View/Tags/HtmlView.php index 9e8d077481033..f40f7cdc89787 100644 --- a/components/com_tags/src/View/Tags/HtmlView.php +++ b/components/com_tags/src/View/Tags/HtmlView.php @@ -122,11 +122,9 @@ public function display($tpl = null) if (isset($active->query['layout'])) { $this->setLayout($active->query['layout']); } - } else { + } elseif ($layout = $this->params->get('tags_layout')) { // Load default All Tags layout from component - if ($layout = $this->params->get('tags_layout')) { - $this->setLayout($layout); - } + $this->setLayout($layout); } $this->_prepareDocument(); diff --git a/components/com_users/src/Controller/DisplayController.php b/components/com_users/src/Controller/DisplayController.php index 34571888ab1c6..c95f98c219b64 100644 --- a/components/com_users/src/Controller/DisplayController.php +++ b/components/com_users/src/Controller/DisplayController.php @@ -58,7 +58,7 @@ public function display($cachable = false, $urlparams = false) // Redirect to profile page. $this->setRedirect(Route::_('index.php?option=com_users&view=profile', false)); - return; + return null; } // Check if user registration is enabled @@ -66,7 +66,7 @@ public function display($cachable = false, $urlparams = false) // Registration is disabled - Redirect to login page. $this->setRedirect(Route::_('index.php?option=com_users&view=login', false)); - return; + return null; } // The user is a guest, load the registration model and show the registration page. @@ -82,7 +82,7 @@ public function display($cachable = false, $urlparams = false) // Redirect to login page. $this->setRedirect(Route::_('index.php?option=com_users&view=login', false)); - return; + return null; } $model = $this->getModel($vName); @@ -102,7 +102,7 @@ public function display($cachable = false, $urlparams = false) // Redirect to profile page. $this->setRedirect(Route::_('index.php?option=com_users&view=profile', false)); - return; + return null; } $model = $this->getModel($vName); @@ -135,5 +135,6 @@ public function display($cachable = false, $urlparams = false) $view->display(); } + return null; } } diff --git a/components/com_users/src/Controller/ProfileController.php b/components/com_users/src/Controller/ProfileController.php index 50a6652559ba7..df35a14626fef 100644 --- a/components/com_users/src/Controller/ProfileController.php +++ b/components/com_users/src/Controller/ProfileController.php @@ -53,7 +53,7 @@ public function edit() } // Check if the user logged in with a cookie - if (isset($user->cookieLogin) && !empty($user->cookieLogin)) { + if (property_exists($user, 'cookieLogin') && $user->cookieLogin !== null && !empty($user->cookieLogin)) { // If so, the user must login to edit the password and other data. $app->enqueueMessage(Text::_('JGLOBAL_REMEMBER_MUST_LOGIN'), 'message'); $this->setRedirect(Route::_('index.php?option=com_users&view=login', false)); @@ -73,7 +73,7 @@ public function edit() /** * Method to save a user's profile data. * - * @return void|boolean + * @return bool|null * * @since 1.6 * @throws \Exception @@ -207,6 +207,7 @@ public function save() // Flush the data from the session. $app->setUserState('com_users.edit.profile.data', null); + return null; } /** diff --git a/components/com_users/src/Controller/RegistrationController.php b/components/com_users/src/Controller/RegistrationController.php index 93ec4f2169698..273f754d392e7 100644 --- a/components/com_users/src/Controller/RegistrationController.php +++ b/components/com_users/src/Controller/RegistrationController.php @@ -80,25 +80,19 @@ public function activate() $userToActivate = $this->getUserFactory()->loadUserById($userIdToActivate); // Admin activation is on and admin is activating the account - if (($uParams->get('useractivation') == 2) && $userToActivate->getParam('activate', 0)) { - // If a user admin is not logged in, redirect them to the login page with an error message - if (!$user->authorise('core.create', 'com_users') || !$user->authorise('core.manage', 'com_users')) { - $activationUrl = 'index.php?option=com_users&task=registration.activate&token=' . $token; - $loginUrl = 'index.php?option=com_users&view=login&return=' . base64_encode($activationUrl); - - // In case we still run into this in the second step the user does not have the right permissions - $message = Text::_('COM_USERS_REGISTRATION_ACL_ADMIN_ACTIVATION_PERMISSIONS'); - - // When we are not logged in we should login - if ($user->guest) { - $message = Text::_('COM_USERS_REGISTRATION_ACL_ADMIN_ACTIVATION'); - } - - $this->setMessage($message); - $this->setRedirect(Route::_($loginUrl, false)); - - return false; + // If a user admin is not logged in, redirect them to the login page with an error message + if ($uParams->get('useractivation') == 2 && $userToActivate->getParam('activate', 0) && (!$user->authorise('core.create', 'com_users') || !$user->authorise('core.manage', 'com_users'))) { + $activationUrl = 'index.php?option=com_users&task=registration.activate&token=' . $token; + $loginUrl = 'index.php?option=com_users&view=login&return=' . base64_encode($activationUrl); + // In case we still run into this in the second step the user does not have the right permissions + $message = Text::_('COM_USERS_REGISTRATION_ACL_ADMIN_ACTIVATION_PERMISSIONS'); + // When we are not logged in we should login + if ($user->guest) { + $message = Text::_('COM_USERS_REGISTRATION_ACL_ADMIN_ACTIVATION'); } + $this->setMessage($message); + $this->setRedirect(Route::_($loginUrl, false)); + return false; } // Attempt to activate the user. @@ -199,10 +193,8 @@ public function register() if (isset($filteredData[$field->group][$fieldName])) { $requestData[$field->group][$fieldName] = $filteredData[$field->group][$fieldName]; } - } else { - if (isset($filteredData[$fieldName])) { - $requestData[$fieldName] = $filteredData[$fieldName]; - } + } elseif (isset($filteredData[$fieldName])) { + $requestData[$fieldName] = $filteredData[$fieldName]; } } } diff --git a/components/com_users/src/Model/ProfileModel.php b/components/com_users/src/Model/ProfileModel.php index 6e35814a1d9ea..2808b9c8a2df9 100644 --- a/components/com_users/src/Model/ProfileModel.php +++ b/components/com_users/src/Model/ProfileModel.php @@ -220,7 +220,7 @@ protected function populateState() // Get the user id. $userId = Factory::getApplication()->getUserState('com_users.edit.profile.id'); - $userId = !empty($userId) ? $userId : (int) $this->getCurrentUser()->id; + $userId = empty($userId) ? (int) $this->getCurrentUser()->id : $userId; // Set the user id. $this->setState('user.id', $userId); @@ -241,7 +241,7 @@ protected function populateState() */ public function save($data) { - $userId = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('user.id'); + $userId = (empty($data['id'])) ? (int) $this->getState('user.id') : $data['id']; $user = new User($userId); diff --git a/components/com_users/src/Rule/LoginUniqueFieldRule.php b/components/com_users/src/Rule/LoginUniqueFieldRule.php index 8bdb2b122a07b..65f7d390e6cd0 100644 --- a/components/com_users/src/Rule/LoginUniqueFieldRule.php +++ b/components/com_users/src/Rule/LoginUniqueFieldRule.php @@ -48,11 +48,11 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $loginRedirectUrl = $input['params']->login_redirect_url; $loginRedirectMenuitem = $input['params']->login_redirect_menuitem; - if ($form === null) { + if (!$form instanceof \Joomla\CMS\Form\Form) { throw new \InvalidArgumentException(\sprintf('The value for $form must not be null in %s', static::class)); } - if ($input === null) { + if (!$input instanceof \Joomla\Registry\Registry) { throw new \InvalidArgumentException(\sprintf('The value for $input must not be null in %s', static::class)); } diff --git a/components/com_users/src/Rule/LogoutUniqueFieldRule.php b/components/com_users/src/Rule/LogoutUniqueFieldRule.php index c8c8dabca028c..b3bbdd63ce78b 100644 --- a/components/com_users/src/Rule/LogoutUniqueFieldRule.php +++ b/components/com_users/src/Rule/LogoutUniqueFieldRule.php @@ -48,11 +48,11 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $logoutRedirectUrl = $input['params']->logout_redirect_url; $logoutRedirectMenuitem = $input['params']->logout_redirect_menuitem; - if ($form === null) { + if (!$form instanceof \Joomla\CMS\Form\Form) { throw new \InvalidArgumentException(\sprintf('The value for $form must not be null in %s', static::class)); } - if ($input === null) { + if (!$input instanceof \Joomla\Registry\Registry) { throw new \InvalidArgumentException(\sprintf('The value for $input must not be null in %s', static::class)); } diff --git a/components/com_users/src/View/Profile/HtmlView.php b/components/com_users/src/View/Profile/HtmlView.php index 54f4226116b6b..6b6ebab8cf51e 100644 --- a/components/com_users/src/View/Profile/HtmlView.php +++ b/components/com_users/src/View/Profile/HtmlView.php @@ -93,7 +93,7 @@ class HtmlView extends BaseHtmlView * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null * * @since 1.6 * @throws \Exception @@ -117,7 +117,7 @@ public function display($tpl = null) } // View also takes responsibility for checking if the user logged in with remember me. - if (isset($user->cookieLogin) && !empty($user->cookieLogin)) { + if (property_exists($user, 'cookieLogin') && $user->cookieLogin !== null && !empty($user->cookieLogin)) { // If so, the user must login to edit the password and other data. // What should happen here? Should we force a logout which destroys the cookies? $app = Factory::getApplication(); @@ -154,6 +154,7 @@ public function display($tpl = null) $this->prepareDocument(); parent::display($tpl); + return null; } /** diff --git a/components/com_users/tmpl/login/default.php b/components/com_users/tmpl/login/default.php index 58883dfd46c31..b612a42d3f22f 100644 --- a/components/com_users/tmpl/login/default.php +++ b/components/com_users/tmpl/login/default.php @@ -12,7 +12,7 @@ /** @var \Joomla\Component\Users\Site\View\Login\HtmlView $this */ -if ((isset($this->user->cookieLogin) && !empty($this->user->cookieLogin)) || $this->user->guest) { +if ((property_exists($this->user, 'cookieLogin') && $this->user->cookieLogin !== null && !empty($this->user->cookieLogin)) || $this->user->guest) { // The user is not logged in or needs to provide a password. echo $this->loadTemplate('login'); } else { diff --git a/components/com_users/tmpl/methods/default.php b/components/com_users/tmpl/methods/default.php index ceb3a5064c6b3..46d61150453ca 100644 --- a/components/com_users/tmpl/methods/default.php +++ b/components/com_users/tmpl/methods/default.php @@ -39,7 +39,7 @@ class="btn btn-danger btn-sm">
    - methods)) : ?> + methods) === 0) : ?>
    diff --git a/components/com_users/tmpl/methods/list.php b/components/com_users/tmpl/methods/list.php index 433f38a161915..32b744aa2aac9 100644 --- a/components/com_users/tmpl/methods/list.php +++ b/components/com_users/tmpl/methods/list.php @@ -37,8 +37,8 @@ $methodClass = 'com-users-methods-list-method-name-' . htmlentities((string) $method['name']) . ($this->defaultMethod == $methodName ? ' com-users-methods-list-method-default' : ''); ?> -
    -
    +
    +
    <?php echo $this->escape($method['display']) ?>
    - + 0) : ?>
    diff --git a/components/com_users/tmpl/profile/default_custom.php b/components/com_users/tmpl/profile/default_custom.php index 000903f051683..d25ae8d23da43 100644 --- a/components/com_users/tmpl/profile/default_custom.php +++ b/components/com_users/tmpl/profile/default_custom.php @@ -57,7 +57,7 @@
    fieldname, $customFields)) : ?> - fieldname]->value) ? $customFields[$field->fieldname]->value : Text::_('COM_USERS_PROFILE_VALUE_NOT_FOUND'); ?> + fieldname]->value) !== 0 ? $customFields[$field->fieldname]->value : Text::_('COM_USERS_PROFILE_VALUE_NOT_FOUND'); ?> id)) : ?> id, $field->value); ?> fieldname)) : ?> diff --git a/components/com_wrapper/src/View/Wrapper/HtmlView.php b/components/com_wrapper/src/View/Wrapper/HtmlView.php index c6adf00651d31..a03e5ce3e1b24 100644 --- a/components/com_wrapper/src/View/Wrapper/HtmlView.php +++ b/components/com_wrapper/src/View/Wrapper/HtmlView.php @@ -78,11 +78,7 @@ public function display($tpl = null) $wrapper = new \stdClass(); // Auto height control - if ($params->def('height_auto')) { - $wrapper->load = 'onload="iFrameHeight(this)"'; - } else { - $wrapper->load = ''; - } + $wrapper->load = $params->def('height_auto') ? 'onload="iFrameHeight(this)"' : ''; $url = $params->def('url', ''); diff --git a/installation/src/Application/CliInstallationApplication.php b/installation/src/Application/CliInstallationApplication.php index ad0f6534f92cb..f52ede2bd8093 100644 --- a/installation/src/Application/CliInstallationApplication.php +++ b/installation/src/Application/CliInstallationApplication.php @@ -74,7 +74,7 @@ final class CliInstallationApplication extends Application implements CMSApplica * @var Integer * @since 5.0.2 */ - protected $clientId; + protected $clientId = 2; /** * Class constructor. @@ -108,9 +108,6 @@ public function __construct( $version = new Version(); $this->setVersion($version->getShortVersion()); - // Register the client ID. - $this->clientId = 2; - // Run the parent constructor. parent::__construct($input, $output, $config); @@ -220,7 +217,7 @@ public function getLocaliseAdmin(?DatabaseInterface $db = null) $langfiles = []; // If db connection, fetch them from the database. - if ($db) { + if ($db instanceof \Joomla\Database\DatabaseInterface) { foreach (LanguageHelper::getInstalledLanguages(null, null, null, null, null, null, $db) as $clientId => $language) { $clientName = $clientId === 0 ? 'site' : 'admin'; diff --git a/installation/src/Application/InstallationApplication.php b/installation/src/Application/InstallationApplication.php index a05c073b03502..8d15274531b9b 100644 --- a/installation/src/Application/InstallationApplication.php +++ b/installation/src/Application/InstallationApplication.php @@ -139,7 +139,7 @@ public function debugLanguage() $guesses = []; - foreach ($orphans as $key => $occurrence) { + foreach (array_keys($orphans) as $key) { $guess = str_replace('_', ' ', $key); $parts = explode(' ', $guess); @@ -351,7 +351,7 @@ public function getLocaliseAdmin(?DatabaseInterface $db = null) $langfiles = []; // If db connection, fetch them from the database. - if ($db) { + if ($db instanceof \Joomla\Database\DatabaseInterface) { foreach (LanguageHelper::getInstalledLanguages(null, null, null, null, null, null, $db) as $clientId => $language) { $clientName = $clientId === 0 ? 'site' : 'admin'; @@ -479,7 +479,7 @@ protected function initialiseApp($options = []) */ public function loadDocument(?Document $document = null) { - if ($document === null) { + if (!$document instanceof \Joomla\CMS\Document\Document) { $lang = $this->getLanguage(); $type = $this->input->get('format', 'html', 'word'); $date = new Date('now'); diff --git a/installation/src/Controller/InstallationController.php b/installation/src/Controller/InstallationController.php index 9d7da966393ec..8f6efe001478f 100644 --- a/installation/src/Controller/InstallationController.php +++ b/installation/src/Controller/InstallationController.php @@ -241,7 +241,7 @@ public function languages() // Remove zero values resulting from input filter $lids = array_filter($lids); - if (empty($lids)) { + if ($lids === []) { // No languages have been selected $this->app->enqueueMessage(Text::_('INSTL_LANGUAGES_NO_LANGUAGE_SELECTED'), 'warning'); } else { diff --git a/installation/src/Helper/DatabaseHelper.php b/installation/src/Helper/DatabaseHelper.php index a3047ce73f213..03f9bc10cc4a3 100644 --- a/installation/src/Helper/DatabaseHelper.php +++ b/installation/src/Helper/DatabaseHelper.php @@ -157,11 +157,7 @@ public static function getMinimumServerVersion($db, $options) // Get minimum database version required by the CMS if (\in_array($options->db_type, ['mysql', 'mysqli'])) { - if ($db->isMariaDb()) { - $minDbVersionCms = self::$dbMinimumMariaDb; - } else { - $minDbVersionCms = self::$dbMinimumMySql; - } + $minDbVersionCms = $db->isMariaDb() ? self::$dbMinimumMariaDb : self::$dbMinimumMySql; } else { $minDbVersionCms = self::$dbMinimumPostgreSql; } @@ -207,7 +203,7 @@ public static function validateConnectionParameters($options) } // Validate database table prefix. - if (empty($options->db_prefix) || !preg_match('#^[a-zA-Z]+[a-zA-Z0-9_]*$#', $options->db_prefix)) { + if (empty($options->db_prefix) || !preg_match('#^[a-zA-Z]+\w*$#', $options->db_prefix)) { return Text::_('INSTL_DATABASE_PREFIX_MSG'); } @@ -226,10 +222,8 @@ public static function validateConnectionParameters($options) } // Workaround for UPPERCASE table prefix for postgresql - if (\in_array($options->db_type, ['pgsql', 'postgresql'])) { - if (strtolower($options->db_prefix) != $options->db_prefix) { - return Text::_('INSTL_DATABASE_FIX_LOWERCASE'); - } + if (\in_array($options->db_type, ['pgsql', 'postgresql']) && strtolower($options->db_prefix) != $options->db_prefix) { + return Text::_('INSTL_DATABASE_FIX_LOWERCASE'); } // Validate and clean up database connection encryption options @@ -272,16 +266,13 @@ public static function validateConnectionParameters($options) if (empty($options->db_sslca)) { return Text::sprintf('INSTL_DATABASE_ENCRYPTION_MSG_FILE_FIELD_EMPTY', Text::_('INSTL_DATABASE_ENCRYPTION_CA_LABEL')); } - if (!is_file(Path::clean($options->db_sslca))) { return Text::sprintf('INSTL_DATABASE_ENCRYPTION_MSG_FILE_FIELD_BAD', Text::_('INSTL_DATABASE_ENCRYPTION_CA_LABEL')); } - } else { + } elseif (!empty($options->db_sslca)) { // Reset unused option - if (!empty($options->db_sslca)) { - $options->db_sslca = ''; - $optionsChanged = true; - } + $options->db_sslca = ''; + $optionsChanged = true; } // Check key and certificate if two-way encryption @@ -340,7 +331,7 @@ public static function checkRemoteDbHost($options) && !\defined('_JCLI_INSTALLATION'); // Per default allowed DB hosts: localhost / 127.0.0.1 / ::1 (optionally with port) - $localhost = '/^(((localhost|127\.0\.0\.1|\[\:\:1\])(\:[1-9]{1}[0-9]{0,4})?)|(\:\:1))$/'; + $localhost = '/^(((localhost|127\.0\.0\.1|\[\:\:1\])(\:[1-9]{1}\d{0,4})?)|(\:\:1))$/'; // Check the security file if the db_host is not localhost / 127.0.0.1 / ::1 if ($shouldCheckLocalhost && preg_match($localhost, $options->db_host) !== 1) { diff --git a/installation/src/Model/ChecksModel.php b/installation/src/Model/ChecksModel.php index cc3cd4bf02943..3b5ab2555b890 100644 --- a/installation/src/Model/ChecksModel.php +++ b/installation/src/Model/ChecksModel.php @@ -37,7 +37,7 @@ public function getIniParserAvailability() { $disabled_functions = \ini_get('disable_functions'); - if (!empty($disabled_functions)) { + if (!($disabled_functions === '' || $disabled_functions === '0' || $disabled_functions === false)) { // Attempt to detect them in the PHP INI disable_functions variable. $disabled_functions = explode(',', trim($disabled_functions)); $number_of_disabled_functions = \count($disabled_functions); @@ -87,7 +87,7 @@ public function getPhpOptions() $option->label = Text::_('INSTL_DATABASE_SUPPORT'); $option->label .= '
    (' . implode(', ', $available) . ')'; $option->state = \count($available); - $option->notice = $option->state ? null : Text::_('INSTL_NOTICE_DATABASE_SUPPORT'); + $option->notice = $option->state !== 0 ? null : Text::_('INSTL_NOTICE_DATABASE_SUPPORT'); $options[] = $option; // Check for mbstring options. @@ -95,7 +95,7 @@ public function getPhpOptions() // Check for default MB language. $option = new \stdClass(); $option->label = Text::_('INSTL_MB_LANGUAGE_IS_DEFAULT'); - $option->state = (strtolower(\ini_get('mbstring.language')) == 'neutral'); + $option->state = (strtolower(\ini_get('mbstring.language')) === 'neutral'); $option->notice = $option->state ? null : Text::_('INSTL_NOTICE_MBLANG_NOTDEFAULT'); $options[] = $option; } @@ -247,7 +247,7 @@ public function getForm($view = null) $data = (array) $this->getOptions(); // Bind the form data if present. - if (!empty($data)) { + if ($data !== []) { $form->bind($data); } diff --git a/installation/src/Model/ConfigurationModel.php b/installation/src/Model/ConfigurationModel.php index 23326e72f8bda..7bfc948917b6e 100644 --- a/installation/src/Model/ConfigurationModel.php +++ b/installation/src/Model/ConfigurationModel.php @@ -453,11 +453,7 @@ public function createConfiguration($options) $path = JPATH_CONFIGURATION . '/configuration.php'; // Determine if the configuration file path is writable. - if (file_exists($path)) { - $canWrite = is_writable($path); - } else { - $canWrite = is_writable(JPATH_CONFIGURATION . '/'); - } + $canWrite = file_exists($path) ? is_writable($path) : is_writable(JPATH_CONFIGURATION . '/'); /* * If the file exists but isn't writable OR if the file doesn't exist and the parent directory diff --git a/installation/src/Model/DatabaseModel.php b/installation/src/Model/DatabaseModel.php index a2bb67313ccc3..c71fa0b39cbb2 100644 --- a/installation/src/Model/DatabaseModel.php +++ b/installation/src/Model/DatabaseModel.php @@ -199,7 +199,7 @@ public function createDatabase(array $options) } // @internal Check for spaces in beginning or end of name. - if (\strlen(trim($options->db_name)) <> \strlen($options->db_name)) { + if (\strlen(trim($options->db_name)) !== \strlen($options->db_name)) { throw new \RuntimeException(Text::_('INSTL_DATABASE_NAME_INVALID_SPACES')); } @@ -233,7 +233,7 @@ public function createDatabase(array $options) $options = (array) $options; // Remove *_errors value. - foreach ($options as $i => $option) { + foreach (array_keys($options) as $i) { if (isset($i['1']) && $i['1'] == '*') { unset($options[$i]); @@ -273,13 +273,8 @@ public function handleOldDatabase(array $options) } catch (\RuntimeException) { // Continue Anyhow } - // Backup any old database. - if (!$this->backupDatabase($db, $options['db_prefix'])) { - return false; - } - - return true; + return $this->backupDatabase($db, $options['db_prefix']); } /** @@ -309,13 +304,8 @@ public function createTables(string $schema, array $options) return false; } - // Attempt to import the database schema. - if (!$this->populateDatabase($db, $schemaFile)) { - return false; - } - - return true; + return $this->populateDatabase($db, $schemaFile); } /** @@ -422,7 +412,7 @@ public function populateDatabase($db, $schema) $query = trim((string) $query); // If the query isn't empty and is not a MySQL or PostgreSQL comment, execute it. - if (!empty($query) && ($query[0] != '#') && ($query[0] != '-')) { + if ($query !== '' && $query !== '0' && ($query[0] !== '#') && ($query[0] !== '-')) { // Execute the query. $db->setQuery($query); @@ -471,15 +461,15 @@ protected function splitQueries($query) // Parse the schema file to break up queries. for ($i = 0; $i < \strlen($query) - 1; $i++) { - if ($query[$i] == ';' && !$in_string) { + if ($query[$i] === ';' && !$in_string) { $queries[] = substr($query, 0, $i); $query = substr($query, $i + 1); $i = 0; } - if ($in_string && ($query[$i] == $in_string) && $buffer[1] != "\\") { + if ($in_string && ($query[$i] === $in_string) && $buffer[1] !== "\\") { $in_string = false; - } elseif (!$in_string && ($query[$i] == '"' || $query[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) { + } elseif (!$in_string && ($query[$i] === '"' || $query[$i] === "'") && (!isset($buffer[0]) || $buffer[0] !== "\\")) { $in_string = $query[$i]; } @@ -491,7 +481,7 @@ protected function splitQueries($query) } // If the is anything left over, add it to the queries. - if (!empty($query)) { + if ($query !== '' && $query !== '0') { $queries[] = $query; } diff --git a/installation/src/Model/LanguagesModel.php b/installation/src/Model/LanguagesModel.php index a777d8c79d174..1e009a5e2545f 100644 --- a/installation/src/Model/LanguagesModel.php +++ b/installation/src/Model/LanguagesModel.php @@ -106,7 +106,7 @@ public function getItems() $extId = (int) $db->loadResult(); - if ($extId) { + if ($extId !== 0) { $updater = Updater::getInstance(); /* @@ -351,11 +351,7 @@ protected function getInstalledlangs($clientName = 'administrator') // If current then set published. $params = ComponentHelper::getParams('com_languages'); - if ($params->get($client->name, 'en-GB') == $row->language) { - $row->published = 1; - } else { - $row->published = 0; - } + $row->published = $params->get($client->name, 'en-GB') == $row->language ? 1 : 0; $row->checked_out = null; $data[] = $row; @@ -522,7 +518,7 @@ public function getForm($view = null) $data = (array) $this->getOptions(); // Bind the form data if present. - if (!empty($data)) { + if ($data !== []) { $form->bind($data); } diff --git a/installation/src/Model/SetupModel.php b/installation/src/Model/SetupModel.php index 14cb848722fbc..ca72a701dd465 100644 --- a/installation/src/Model/SetupModel.php +++ b/installation/src/Model/SetupModel.php @@ -104,7 +104,7 @@ public function getForm($view = null) $data = (array) $this->getOptions(); // Bind the form data if present. - if (!empty($data)) { + if ($data !== []) { $form->bind($data); } diff --git a/installation/template/error.php b/installation/template/error.php index edb9dba322c98..dc0ab6b8e2088 100644 --- a/installation/template/error.php +++ b/installation/template/error.php @@ -79,7 +79,7 @@
    renderBacktrace(); ?> - error->getPrevious()) : ?> + error->getPrevious() instanceof \Throwable) : ?> _error here and in the loop as setError() assigns errors to this property and we need this for the backtrace to work correctly?> diff --git a/installation/tmpl/remove/default.php b/installation/tmpl/remove/default.php index 14268f908e7b1..b81994f0bc4c0 100644 --- a/installation/tmpl/remove/default.php +++ b/installation/tmpl/remove/default.php @@ -271,7 +271,7 @@ class="btn btn-primary w-100" - version, 0, 3) != $version::MAJOR_VERSION . '.' . $version::MINOR_VERSION || substr($language->version, 0, 5) != $currentShortVersion) : ?> + version, 0, 3) !== $version::MAJOR_VERSION . '.' . $version::MINOR_VERSION || substr($language->version, 0, 5) != $currentShortVersion) : ?> version; ?> version; ?> diff --git a/layouts/joomla/content/options_default.php b/layouts/joomla/content/options_default.php index 71c903995f58a..4fc686fa0125a 100644 --- a/layouts/joomla/content/options_default.php +++ b/layouts/joomla/content/options_default.php @@ -19,7 +19,7 @@ ?> -
    +
    name; ?> description)) : ?>
    diff --git a/layouts/joomla/content/text_filters.php b/layouts/joomla/content/text_filters.php index 3fc04eaae84db..ef8998b15adda 100644 --- a/layouts/joomla/content/text_filters.php +++ b/layouts/joomla/content/text_filters.php @@ -14,7 +14,7 @@ ?> -
    +
    name; ?>
    diff --git a/layouts/joomla/edit/frontediting_modules.php b/layouts/joomla/edit/frontediting_modules.php index 6462604d6f8b0..a3680216f199a 100644 --- a/layouts/joomla/edit/frontediting_modules.php +++ b/layouts/joomla/edit/frontediting_modules.php @@ -53,7 +53,7 @@ $regex = '/\bitem-(\d+)\b/'; preg_match_all($regex, (string) $moduleHtml, $menuItemids); - if ($menuItemids) { + if ($menuItemids !== []) { foreach ($menuItemids[1] as $menuItemid) { $menuitemEditUrl = Uri::base() . 'administrator/index.php?option=com_menus&view=item&client_id=0&layout=edit&id=' . (int) $menuItemid; $moduleHtml = preg_replace( diff --git a/layouts/joomla/edit/params.php b/layouts/joomla/edit/params.php index d2f222c71eab1..033a728d898fa 100644 --- a/layouts/joomla/edit/params.php +++ b/layouts/joomla/edit/params.php @@ -104,7 +104,7 @@ $isGrandchild = $xml->xpath('//fieldset//fieldset//fieldset[@name="' . $name . '"]'); if (!$isGrandchild && $hasParent) { - echo '
    '; + echo '
    '; echo '' . $label . ''; // Include the description when available @@ -135,7 +135,7 @@ // Directly add a fieldset if we have no children if (!$hasChildren) { - echo '
    '; + echo '
    '; echo '' . $label . ''; // Include the description when available diff --git a/layouts/joomla/edit/title_alias.php b/layouts/joomla/edit/title_alias.php index 1bcb121b11c27..178745ddba39b 100644 --- a/layouts/joomla/edit/title_alias.php +++ b/layouts/joomla/edit/title_alias.php @@ -17,7 +17,7 @@ ?>
    - renderField($title) : ''; ?> + renderField($title) : ''; ?>
    renderField('alias'); ?> diff --git a/layouts/joomla/form/field/calendar.php b/layouts/joomla/form/field/calendar.php index 62e871a976367..96f794fc47a1f 100644 --- a/layouts/joomla/form/field/calendar.php +++ b/layouts/joomla/form/field/calendar.php @@ -77,8 +77,12 @@ empty($size) ? null : $attributes['size'] = $size; empty($maxlength) ? null : $attributes['maxlength'] = $maxLength; empty($class) ? $attributes['class'] = 'form-control' : $attributes['class'] = 'form-control ' . $class; -!$readonly ? null : $attributes['readonly'] = 'readonly'; -!$disabled ? null : $attributes['disabled'] = 'disabled'; +if ($readonly) { + $attributes['readonly'] = 'readonly'; +} +if ($disabled) { + $attributes['disabled'] = 'disabled'; +} empty($onchange) ? null : $attributes['onchange'] = $onchange; if ($required) { @@ -155,10 +159,10 @@ id="" name="" value="" - + - + data-alt-value="" autocomplete="off">
    diff --git a/layouts/joomla/form/field/modal-select/buttons.php b/layouts/joomla/form/field/modal-select/buttons.php index a877514dd3e3a..17cdad7f9afde 100644 --- a/layouts/joomla/form/field/modal-select/buttons.php +++ b/layouts/joomla/form/field/modal-select/buttons.php @@ -73,9 +73,9 @@ ?> diff --git a/layouts/joomla/form/field/number.php b/layouts/joomla/form/field/number.php index d2c4ce80848eb..69cf657629649 100644 --- a/layouts/joomla/form/field/number.php +++ b/layouts/joomla/form/field/number.php @@ -47,17 +47,17 @@ */ $attributes = [ - !empty($class) ? 'class="form-control ' . $class . '"' : 'class="form-control"', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($class) ? 'class="form-control"' : 'class="form-control ' . $class . '"', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', - !empty($onchange) ? 'onchange="' . $onchange . '"' : '', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($onchange) ? '' : 'onchange="' . $onchange . '"', isset($max) ? 'max="' . $max . '"' : '', - !empty($step) ? 'step="' . $step . '"' : '', + empty($step) ? '' : 'step="' . $step . '"', isset($min) ? 'min="' . $min . '"' : '', $required ? 'required' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', $autofocus ? 'autofocus' : '', $dataAttribute, ]; diff --git a/layouts/joomla/form/field/password.php b/layouts/joomla/form/field/password.php index 9a0f64065f434..c02560b73fa58 100644 --- a/layouts/joomla/form/field/password.php +++ b/layouts/joomla/form/field/password.php @@ -84,25 +84,25 @@ } $ariaDescribedBy = $rules ? $name . '-rules ' : ''; -$ariaDescribedBy .= !empty($description) ? (($id ?: $name) . '-desc') : ''; +$ariaDescribedBy .= empty($description) ? ('') : ($id ?: $name) . '-desc'; $attributes = [ - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', - !empty($class) ? 'class="form-control ' . $class . '"' : 'class="form-control"', - !empty($ariaDescribedBy) ? 'aria-describedby="' . trim($ariaDescribedBy) . '"' : '', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', + empty($class) ? 'class="form-control"' : 'class="form-control ' . $class . '"', + $ariaDescribedBy === '' || $ariaDescribedBy === '0' ? '' : 'aria-describedby="' . trim($ariaDescribedBy) . '"', $readonly ? 'readonly' : '', $disabled ? 'disabled' : '', - !empty($size) ? 'size="' . $size . '"' : '', - !empty($maxLength) ? 'maxlength="' . $maxLength . '"' : '', + empty($size) ? '' : 'size="' . $size . '"', + empty($maxLength) ? '' : 'maxlength="' . $maxLength . '"', $required ? 'required' : '', $autofocus ? 'autofocus' : '', - !empty($minLength) ? 'data-min-length="' . $minLength . '"' : '', - !empty($minIntegers) ? 'data-min-integers="' . $minIntegers . '"' : '', - !empty($minSymbols) ? 'data-min-symbols="' . $minSymbols . '"' : '', - !empty($minUppercase) ? 'data-min-uppercase="' . $minUppercase . '"' : '', - !empty($minLowercase) ? 'data-min-lowercase="' . $minLowercase . '"' : '', - !empty($forcePassword) ? 'data-min-force="' . $forcePassword . '"' : '', + empty($minLength) ? '' : 'data-min-length="' . $minLength . '"', + empty($minIntegers) ? '' : 'data-min-integers="' . $minIntegers . '"', + empty($minSymbols) ? '' : 'data-min-symbols="' . $minSymbols . '"', + empty($minUppercase) ? '' : 'data-min-uppercase="' . $minUppercase . '"', + empty($minLowercase) ? '' : 'data-min-lowercase="' . $minLowercase . '"', + empty($forcePassword) ? '' : 'data-min-force="' . $forcePassword . '"', $dataAttribute, ]; diff --git a/layouts/joomla/form/field/radio/buttons.php b/layouts/joomla/form/field/radio/buttons.php index a0e1e3b48ea57..fca32b9242967 100644 --- a/layouts/joomla/form/field/radio/buttons.php +++ b/layouts/joomla/form/field/radio/buttons.php @@ -84,8 +84,8 @@ $option) : ?> disable) ? 'disabled' : ''; - $style = $disabled ? ' style="pointer-events: none"' : ''; + $disabled = empty($option->disable) ? '' : 'disabled'; + $style = $disabled !== '' && $disabled !== '0' ? ' style="pointer-events: none"' : ''; // Initialize some option attributes. if ($isBtnYesNo) { @@ -97,13 +97,13 @@ }; } - $optionClass = !empty($option->class) ? $option->class : $btnClass; + $optionClass = empty($option->class) ? $btnClass : $option->class; $optionClass = trim($optionClass . ' ' . $disabled); $checked = ((string) $option->value === $value) ? 'checked="checked"' : ''; // Initialize some JavaScript option attributes. - $onclick = !empty($option->onclick) ? 'onclick="' . $option->onclick . '"' : ''; - $onchange = !empty($option->onchange) ? 'onchange="' . $option->onchange . '"' : ''; + $onclick = empty($option->onclick) ? '' : 'onclick="' . $option->onclick . '"'; + $onchange = empty($option->onchange) ? '' : 'onchange="' . $option->onchange . '"'; $oid = $id . $i; $ovalue = htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8'); $attributes = array_filter([$checked, $disabled, ltrim($style), $onchange, $onclick]); diff --git a/layouts/joomla/form/field/radiobasic.php b/layouts/joomla/form/field/radiobasic.php index c47d39d0e18ea..5ad5bf522fa3c 100644 --- a/layouts/joomla/form/field/radiobasic.php +++ b/layouts/joomla/form/field/radiobasic.php @@ -69,12 +69,12 @@ value === $value) ? 'checked="checked"' : ''; - $optionClass = !empty($option->class) ? 'class="' . $option->class . '"' : ''; + $optionClass = empty($option->class) ? '' : 'class="' . $option->class . '"'; $disabled = !empty($option->disable) || ($disabled && !$checked) ? 'disabled' : ''; // Initialize some JavaScript option attributes. - $onclick = !empty($option->onclick) ? 'onclick="' . $option->onclick . '"' : ''; - $onchange = !empty($option->onchange) ? 'onchange="' . $option->onchange . '"' : ''; + $onclick = empty($option->onclick) ? '' : 'onclick="' . $option->onclick . '"'; + $onchange = empty($option->onchange) ? '' : 'onchange="' . $option->onchange . '"'; $oid = $id . $i; $ovalue = htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8'); $attributes = array_filter([$checked, $optionClass, $disabled, $onchange, $onclick]); diff --git a/layouts/joomla/form/field/range.php b/layouts/joomla/form/field/range.php index 838ffdd7d43d3..512b9bebbf7e8 100644 --- a/layouts/joomla/form/field/range.php +++ b/layouts/joomla/form/field/range.php @@ -50,13 +50,13 @@ // Initialize some field attributes. $attributes = [ $class ? 'class="form-range ' . $class . '"' : 'class="form-range"', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', - !empty($onchange) ? 'onchange="' . $onchange . '"' : '', - !empty($max) ? 'max="' . $max . '"' : '', - !empty($step) ? 'step="' . $step . '"' : '', - !empty($min) ? 'min="' . $min . '"' : '', + empty($onchange) ? '' : 'onchange="' . $onchange . '"', + empty($max) ? '' : 'max="' . $max . '"', + empty($step) ? '' : 'step="' . $step . '"', + empty($min) ? '' : 'min="' . $min . '"', $autofocus ? 'autofocus' : '', $dataAttribute, ]; diff --git a/layouts/joomla/form/field/rules.php b/layouts/joomla/form/field/rules.php index 0a6a15f286a58..af515faf09fc3 100644 --- a/layouts/joomla/form/field/rules.php +++ b/layouts/joomla/form/field/rules.php @@ -167,8 +167,8 @@ class="form-select novalidate" value, $action->name, $assetId); - $inheritedGroupParentAssetRule = !empty($parentAssetId) ? Access::checkGroup($group->value, $action->name, $parentAssetId) : null; - $inheritedParentGroupRule = !empty($group->parent_id) ? Access::checkGroup($group->parent_id, $action->name, $assetId) : null; + $inheritedGroupParentAssetRule = empty($parentAssetId) ? null : Access::checkGroup($group->value, $action->name, $parentAssetId); + $inheritedParentGroupRule = empty($group->parent_id) ? null : Access::checkGroup($group->parent_id, $action->name, $assetId); // Current group is a Super User group, so calculated setting is "Allowed (Super User)". if ($isSuperUserGroup) { diff --git a/layouts/joomla/form/field/tag.php b/layouts/joomla/form/field/tag.php index 781b874fd9cb9..c493b4df52127 100644 --- a/layouts/joomla/form/field/tag.php +++ b/layouts/joomla/form/field/tag.php @@ -69,7 +69,7 @@ } $attr2 = ''; -$attr2 .= !empty($class) ? ' class="' . $class . '"' : ''; +$attr2 .= empty($class) ? '' : ' class="' . $class . '"'; $attr2 .= ' placeholder="' . $this->escape($hint ?: Text::_('JGLOBAL_TYPE_OR_SELECT_SOME_TAGS')) . '" '; $attr2 .= $dataAttribute; @@ -96,7 +96,7 @@ // E.g. form field type tag sends $this->value as array if ($multiple && is_array($value)) { - if (!count($value)) { + if ($value === []) { $value[] = ''; } diff --git a/layouts/joomla/form/field/tel.php b/layouts/joomla/form/field/tel.php index dc7f06c0aad84..dcd0d4cf9cabc 100644 --- a/layouts/joomla/form/field/tel.php +++ b/layouts/joomla/form/field/tel.php @@ -49,18 +49,18 @@ */ $attributes = [ - !empty($size) ? 'size="' . $size . '"' : '', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($size) ? '' : 'size="' . $size . '"', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', $autofocus ? 'autofocus' : '', $spellcheck ? '' : 'spellcheck="false"', $onchange ? 'onchange="' . $onchange . '"' : '', - !empty($maxLength) ? $maxLength : '', + empty($maxLength) ? '' : $maxLength, $required ? 'required' : '', - !empty($pattern) ? 'pattern="' . $pattern . '"' : '', + empty($pattern) ? '' : 'pattern="' . $pattern . '"', $dataAttribute, ]; ?> @@ -68,7 +68,7 @@ type="tel" inputmode="tel" name="" - + id="" value="" > diff --git a/layouts/joomla/form/field/text.php b/layouts/joomla/form/field/text.php index 4dcaf2c4fce1f..598a1e70a688b 100644 --- a/layouts/joomla/form/field/text.php +++ b/layouts/joomla/form/field/text.php @@ -76,26 +76,26 @@ } $attributes = [ - !empty($class) ? 'class="form-control ' . $class . $charcounterclass . '"' : 'class="form-control' . $charcounterclass . '"', - !empty($size) ? 'size="' . $size . '"' : '', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($class) ? 'class="form-control' . $charcounterclass . '"' : 'class="form-control ' . $class . $charcounterclass . '"', + empty($size) ? '' : 'size="' . $size . '"', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', $dataAttribute, $list, - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', $onchange ? ' onchange="' . $onchange . '"' : '', - !empty($maxLength) ? $maxLength : '', + empty($maxLength) ? '' : $maxLength, $required ? 'required' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', $autofocus ? ' autofocus' : '', $spellcheck ? '' : 'spellcheck="false"', - !empty($inputmode) ? $inputmode : '', - !empty($counterlabel) ? $counterlabel : '', - !empty($pattern) ? 'pattern="' . $pattern . '"' : '', + empty($inputmode) ? '' : $inputmode, + empty($counterlabel) ? '' : $counterlabel, + empty($pattern) ? '' : 'pattern="' . $pattern . '"', // @TODO add a proper string here!!! - !empty($validationtext) ? 'data-validation-text="' . $this->escape(Text::_($validationtext)) . '"' : '', + empty($validationtext) ? '' : 'data-validation-text="' . $this->escape(Text::_($validationtext)) . '"', ]; $addonBeforeHtml = '' . Text::_($addonBefore) . ''; diff --git a/layouts/joomla/form/field/textarea.php b/layouts/joomla/form/field/textarea.php index 0c2132f819ef3..8d9b365613b2d 100644 --- a/layouts/joomla/form/field/textarea.php +++ b/layouts/joomla/form/field/textarea.php @@ -67,19 +67,19 @@ $attributes = [ $columns ?: '', $rows ?: '', - !empty($class) ? 'class="form-control ' . $class . $charcounter . '"' : 'class="form-control' . $charcounter . '"', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($class) ? 'class="form-control' . $charcounter . '"' : 'class="form-control ' . $class . $charcounter . '"', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', $onchange ? 'onchange="' . $onchange . '"' : '', $onclick ? 'onclick="' . $onclick . '"' : '', $required ? 'required' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', $autofocus ? 'autofocus' : '', $spellcheck ? '' : 'spellcheck="false"', $maxlength ?: '', - !empty($counterlabel) ? $counterlabel : '', + empty($counterlabel) ? '' : $counterlabel, $dataAttribute, ]; ?> diff --git a/layouts/joomla/form/field/time.php b/layouts/joomla/form/field/time.php index dd783018f86c1..45a6a9710139e 100644 --- a/layouts/joomla/form/field/time.php +++ b/layouts/joomla/form/field/time.php @@ -49,12 +49,12 @@ */ $attributes = [ - !empty($class) ? 'class="form-control ' . $class . '"' : 'class="form-control"', - !empty($description) ? 'aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($class) ? 'class="form-control"' : 'class="form-control ' . $class . '"', + empty($description) ? '' : 'aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? 'disabled' : '', $readonly ? 'readonly' : '', - strlen($hint) ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', - !empty($onchange) ? 'onchange="' . $onchange . '"' : '', + strlen($hint) !== 0 ? 'placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($onchange) ? '' : 'onchange="' . $onchange . '"', isset($max) ? 'max="' . $max . '"' : '', isset($step) ? 'step="' . $step . '"' : '', isset($min) ? 'min="' . $min . '"' : '', diff --git a/layouts/joomla/form/field/url.php b/layouts/joomla/form/field/url.php index 5c3bdcb765b86..0fad6fc032d18 100644 --- a/layouts/joomla/form/field/url.php +++ b/layouts/joomla/form/field/url.php @@ -50,16 +50,16 @@ */ $attributes = [ - !empty($size) ? ' size="' . $size . '"' : '', - !empty($description) ? ' aria-describedby="' . ($id ?: $name) . '-desc"' : '', + empty($size) ? '' : ' size="' . $size . '"', + empty($description) ? '' : ' aria-describedby="' . ($id ?: $name) . '-desc"', $disabled ? ' disabled' : '', $readonly ? ' readonly' : '', - strlen($hint) ? ' placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', - !empty($autocomplete) ? 'autocomplete="' . $autocomplete . '"' : '', + strlen($hint) !== 0 ? ' placeholder="' . htmlspecialchars($hint, ENT_COMPAT, 'UTF-8') . '"' : '', + empty($autocomplete) ? '' : 'autocomplete="' . $autocomplete . '"', $autofocus ? ' autofocus' : '', $spellcheck ? '' : ' spellcheck="false"', $onchange ? ' onchange="' . $onchange . '"' : '', - !empty($maxLength) ? $maxLength : '', + empty($maxLength) ? '' : $maxLength, $required ? ' required' : '', $dataAttribute, ]; @@ -72,4 +72,4 @@ $value = $this->escape(PunycodeHelper::urlToUTF8($value)); } ?> - inputmode="url" name="" id="" value="" > + inputmode="url" name="" id="" value="" > diff --git a/layouts/joomla/form/renderfield.php b/layouts/joomla/form/renderfield.php index 8bc343fdc027d..c007fc0049683 100644 --- a/layouts/joomla/form/renderfield.php +++ b/layouts/joomla/form/renderfield.php @@ -37,7 +37,7 @@ $id = ($id ?? $name) . '-desc'; $hideLabel = !empty($options['hiddenLabel']); $hideDescription = empty($options['hiddenDescription']) ? false : $options['hiddenDescription']; -$descClass = ($options['descClass'] ?? '') ?: (!empty($options['inlineHelp']) ? 'hide-aware-inline-help d-none' : ''); +$descClass = ($options['descClass'] ?? '') ?: (empty($options['inlineHelp']) ? '' : 'hide-aware-inline-help d-none'); if (!empty($parentclass)) { $class .= ' ' . $parentclass; diff --git a/layouts/joomla/pagination/link.php b/layouts/joomla/pagination/link.php index 5f17aee9c8a30..e7960eb899e9c 100644 --- a/layouts/joomla/pagination/link.php +++ b/layouts/joomla/pagination/link.php @@ -53,14 +53,8 @@ } if ($displayData['active']) { - if ($item->base > 0) { - $limit = 'limitstart.value=' . $item->base; - } else { - $limit = 'limitstart.value=0'; - } - + $limit = $item->base > 0 ? 'limitstart.value=' . $item->base : 'limitstart.value=0'; $class = 'active'; - if ($app->isClient('administrator')) { $link = 'href="#" onclick="document.adminForm.' . $item->prefix . $limit . '; Joomla.submitform();return false;"'; } elseif ($app->isClient('site')) { diff --git a/layouts/joomla/pagination/links.php b/layouts/joomla/pagination/links.php index e103fb3c10c4b..06d000724d39a 100644 --- a/layouts/joomla/pagination/links.php +++ b/layouts/joomla/pagination/links.php @@ -39,11 +39,7 @@ } if ($currentPage >= $step) { - if ($currentPage % $step === 0) { - $range = ceil($currentPage / $step) + 1; - } else { - $range = ceil($currentPage / $step); - } + $range = $currentPage % $step === 0 ? ceil($currentPage / $step) + 1 : ceil($currentPage / $step); } $first = ($currentPage - 1) * $list['limit'] + 1; $last = $first + $list['limit'] - 1; diff --git a/layouts/joomla/quickicons/icon.php b/layouts/joomla/quickicons/icon.php index 2016c1eef0fa8..60abbc02135af 100644 --- a/layouts/joomla/quickicons/icon.php +++ b/layouts/joomla/quickicons/icon.php @@ -16,11 +16,7 @@ $target = empty($displayData['target']) ? '' : (' target="' . $displayData['target'] . '"'); $onclick = empty($displayData['onclick']) ? '' : (' onclick="' . $displayData['onclick'] . '"'); -if (isset($displayData['ajaxurl'])) { - $dataUrl = 'data-url="' . $displayData['ajaxurl'] . '"'; -} else { - $dataUrl = ''; -} +$dataUrl = isset($displayData['ajaxurl']) ? 'data-url="' . $displayData['ajaxurl'] . '"' : ''; // The title for the link (a11y) $title = empty($displayData['title']) ? '' : (' title="' . $this->escape($displayData['title']) . '"'); diff --git a/layouts/joomla/searchtools/default.php b/layouts/joomla/searchtools/default.php index 6688a0280364d..e739fadebac20 100644 --- a/layouts/joomla/searchtools/default.php +++ b/layouts/joomla/searchtools/default.php @@ -17,7 +17,7 @@ $data = $displayData; // Receive overridable options -$data['options'] = !empty($data['options']) ? $data['options'] : []; +$data['options'] = empty($data['options']) ? [] : $data['options']; $noResultsText = ''; $hideActiveFilters = false; @@ -66,8 +66,8 @@ 'showSelector' => $showSelector, 'orderFieldSelector' => '#list_fullordering', 'showNoResults' => !empty($noResultsText), - 'noResultsText' => !empty($noResultsText) ? $noResultsText : '', - 'formSelector' => !empty($data['options']['formSelector']) ? $data['options']['formSelector'] : '#adminForm', + 'noResultsText' => empty($noResultsText) ? '' : $noResultsText, + 'formSelector' => empty($data['options']['formSelector']) ? '#adminForm' : $data['options']['formSelector'], ]; // Merge custom options in the options array. diff --git a/layouts/joomla/searchtools/default/bar.php b/layouts/joomla/searchtools/default/bar.php index e10e576862816..6401c316bafc9 100644 --- a/layouts/joomla/searchtools/default/bar.php +++ b/layouts/joomla/searchtools/default/bar.php @@ -16,7 +16,7 @@ $data = $displayData; // Receive overridable options -$data['options'] = !empty($data['options']) ? $data['options'] : []; +$data['options'] = empty($data['options']) ? [] : $data['options']; if (is_array($data['options'])) { $data['options'] = new Registry($data['options']); diff --git a/layouts/joomla/searchtools/grid/sort.php b/layouts/joomla/searchtools/grid/sort.php index 8c968bcded826..eec3b263a282a 100644 --- a/layouts/joomla/searchtools/grid/sort.php +++ b/layouts/joomla/searchtools/grid/sort.php @@ -23,7 +23,7 @@ if ($data->order === $data->selected) : $icon = $data->orderIcon; $sort = $data->direction === 'asc' ? 'descending' : 'ascending'; - $heading = !empty($data->title) ? Text::_($data->title) : Text::_('JGRID_HEADING_ORDERING'); + $heading = empty($data->title) ? Text::_('JGRID_HEADING_ORDERING') : Text::_($data->title); $caption = Text::sprintf('JGRID_HEADING_CAPTION_' . ($data->direction === 'asc' ? 'desc' : 'asc'), $heading); $selected = ' selected'; $id = 'id="sorted"'; @@ -37,7 +37,7 @@ data-order="order; ?>" data-direction="direction); ?>" data-caption="" - + data-sort="" > @@ -49,6 +49,6 @@ class="ms-1 " aria-hidden="true"> - title)) ? Text::_($data->title) : Text::_('JGRID_HEADING_ORDERING'); ?> + title)) ? Text::_('JGRID_HEADING_ORDERING') : Text::_($data->title); ?> diff --git a/layouts/joomla/sidebars/submenu.php b/layouts/joomla/sidebars/submenu.php index 5605da1626f42..0885781959bec 100644 --- a/layouts/joomla/sidebars/submenu.php +++ b/layouts/joomla/sidebars/submenu.php @@ -34,15 +34,23 @@
  • hide) : ?> - - - - + if ($displayData->hide) { + ?> + + + + - + ?>
  • diff --git a/layouts/joomla/system/message.php b/layouts/joomla/system/message.php index 4ed0dd3164c05..151a82f406369 100644 --- a/layouts/joomla/system/message.php +++ b/layouts/joomla/system/message.php @@ -46,7 +46,7 @@ ->useStyle('webcomponent.joomla-alert') ->useScript('messages'); -if (is_array($msgList) && !empty($msgList)) { +if (is_array($msgList) && $msgList !== []) { $messages = []; foreach ($msgList as $type => $msgs) { diff --git a/layouts/joomla/toolbar/basic.php b/layouts/joomla/toolbar/basic.php index 313c5b6125890..464a769217e0c 100644 --- a/layouts/joomla/toolbar/basic.php +++ b/layouts/joomla/toolbar/basic.php @@ -43,13 +43,13 @@ $taskAttr = ''; $title = ''; -$idAttr = !empty($id) ? ' id="' . $id . '"' : ''; -$listAttr = !empty($listCheck) ? ' list-selection' : ''; -$formAttr = !empty($form) ? ' form="' . $this->escape($form) . '"' : ''; -$validate = !empty($formValidation) ? ' form-validation' : ''; -$msgAttr = !empty($message) ? ' confirm-message="' . $this->escape($message) . '"' : ''; +$idAttr = empty($id) ? '' : ' id="' . $id . '"'; +$listAttr = empty($listCheck) ? '' : ' list-selection'; +$formAttr = empty($form) ? '' : ' form="' . $this->escape($form) . '"'; +$validate = empty($formValidation) ? '' : ' form-validation'; +$msgAttr = empty($message) ? '' : ' confirm-message="' . $this->escape($message) . '"'; -if ($msgAttr) { +if ($msgAttr !== '' && $msgAttr !== '0') { Text::script('WARNING'); Text::script('JYES'); Text::script('JNO'); diff --git a/layouts/joomla/toolbar/link.php b/layouts/joomla/toolbar/link.php index 06c8ae63aa6dc..a07bb6a56ae00 100644 --- a/layouts/joomla/toolbar/link.php +++ b/layouts/joomla/toolbar/link.php @@ -24,7 +24,7 @@ * @var string $htmlAttributes */ -$margin = (!str_contains($url ?? '', 'index.php?option=com_config')) ? '' : 'ms-auto'; +$margin = (str_contains($url ?? '', 'index.php?option=com_config')) ? 'ms-auto' : ''; $target = empty($target) ? '' : 'target="' . $target . '"'; ?> diff --git a/layouts/joomla/toolbar/popup.php b/layouts/joomla/toolbar/popup.php index c8dd0f4dd60c2..7889155636956 100644 --- a/layouts/joomla/toolbar/popup.php +++ b/layouts/joomla/toolbar/popup.php @@ -60,8 +60,8 @@ $modalAttrs['data-bs-target'] = '#' . $selector; } -$idAttr = !empty($id) ? ' id="' . $id . '"' : ''; -$listAttr = !empty($listCheck) ? ' list-selection' : ''; +$idAttr = empty($id) ? '' : ' id="' . $id . '"'; +$listAttr = empty($listCheck) ? '' : ' list-selection'; ?> > diff --git a/layouts/joomla/toolbar/standard.php b/layouts/joomla/toolbar/standard.php index 6e7b61360fd7e..bfd7527af5d64 100644 --- a/layouts/joomla/toolbar/standard.php +++ b/layouts/joomla/toolbar/standard.php @@ -39,13 +39,13 @@ $tagName ??= 'button'; $taskAttr = ''; -$idAttr = !empty($id) ? ' id="' . $id . '"' : ''; -$listAttr = !empty($listCheck) ? ' list-selection' : ''; -$formAttr = !empty($form) ? ' form="' . $this->escape($form) . '"' : ''; -$validate = !empty($formValidation) ? ' form-validation' : ''; -$msgAttr = !empty($message) ? ' confirm-message="' . $this->escape($message) . '"' : ''; +$idAttr = empty($id) ? '' : ' id="' . $id . '"'; +$listAttr = empty($listCheck) ? '' : ' list-selection'; +$formAttr = empty($form) ? '' : ' form="' . $this->escape($form) . '"'; +$validate = empty($formValidation) ? '' : ' form-validation'; +$msgAttr = empty($message) ? '' : ' confirm-message="' . $this->escape($message) . '"'; -if ($msgAttr) { +if ($msgAttr !== '' && $msgAttr !== '0') { Text::script('WARNING'); Text::script('JYES'); Text::script('JNO'); diff --git a/layouts/plugins/system/privacyconsent/label.php b/layouts/plugins/system/privacyconsent/label.php index 394f10f738b3d..b3b1729b31cb9 100644 --- a/layouts/plugins/system/privacyconsent/label.php +++ b/layouts/plugins/system/privacyconsent/label.php @@ -59,7 +59,7 @@ // Build the class for the label. $class = 'required'; -$class = !empty($labelclass) ? $class . ' ' . $labelclass : $class; +$class = empty($labelclass) ? $class : $class . ' ' . $labelclass; if ($privacyLink) { $attribs = [ diff --git a/layouts/plugins/system/webauthn/manage.php b/layouts/plugins/system/webauthn/manage.php index 6cc0ba3650c22..cc588d68eb481 100644 --- a/layouts/plugins/system/webauthn/manage.php +++ b/layouts/plugins/system/webauthn/manage.php @@ -73,7 +73,7 @@ ?>
    + if (is_string($error) && ($error !== '' && $error !== '0')) : ?>
    diff --git a/layouts/plugins/user/terms/label.php b/layouts/plugins/user/terms/label.php index 61223ffe99097..d5970994e5014 100644 --- a/layouts/plugins/user/terms/label.php +++ b/layouts/plugins/user/terms/label.php @@ -58,7 +58,7 @@ // Build the class for the label. $class = 'required'; -$class = !empty($labelclass) ? $class . ' ' . $labelclass : $class; +$class = empty($labelclass) ? $class : $class . ' ' . $labelclass; if ($article) { $attribs = [ diff --git a/libraries/bootstrap.php b/libraries/bootstrap.php index 734af206db314..b83b425623c18 100644 --- a/libraries/bootstrap.php +++ b/libraries/bootstrap.php @@ -58,7 +58,7 @@ class_exists(\Joomla\CMS\Autoload\ClassLoader::class); \Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer::setTemplate(__DIR__ . '/../templates/system/fatal.php'); // Register the error handler which processes E_USER_DEPRECATED errors -if (error_reporting() & E_USER_DEPRECATED) { +if ((error_reporting() & E_USER_DEPRECATED) !== 0) { set_error_handler(\Joomla\CMS\Exception\ExceptionHandler::handleUserDeprecatedErrors(...), E_USER_DEPRECATED); } diff --git a/libraries/loader.php b/libraries/loader.php index c7efc1be55c6d..bec781c25bbd8 100644 --- a/libraries/loader.php +++ b/libraries/loader.php @@ -188,36 +188,28 @@ public static function import($key, $base = null) $success = false; $parts = explode('.', $key); $class = array_pop($parts); - $base = (!empty($base)) ? $base : __DIR__; + $base = (empty($base)) ? __DIR__ : $base; $path = str_replace('.', DIRECTORY_SEPARATOR, $key); // Handle special case for helper classes. - if ($class === 'helper') { - $class = ucfirst((string) array_pop($parts)) . ucfirst($class); - } else { - // Standard class. - $class = ucfirst($class); - } + $class = $class === 'helper' ? ucfirst((string) array_pop($parts)) . ucfirst($class) : ucfirst($class); // If we are importing a library from the Joomla namespace set the class to autoload. if (str_starts_with($path, 'joomla')) { // Since we are in the Joomla namespace prepend the classname with J. $class = 'J' . $class; - // Only register the class for autoloading if the file exists. if (is_file($base . '/' . $path . '.php')) { self::$classes[strtolower($class)] = $base . '/' . $path . '.php'; $success = true; } - } else { + } elseif (is_file($base . '/' . $path . '.php')) { /** * If we are not importing a library from the Joomla namespace directly include the * file since we cannot assert the file/folder naming conventions. */ // If the file exists attempt to include it. - if (is_file($base . '/' . $path . '.php')) { - $success = (bool) include_once $base . '/' . $path . '.php'; - } + $success = (bool) include_once $base . '/' . $path . '.php'; } // Add the import key to the memory cache container. @@ -297,11 +289,9 @@ public static function register($class, $path, $force = true) $class = strtolower($class); // Only attempt to register the class if the name and file exist. - if (!empty($class) && is_file($path)) { - // Register the class with the autoloader if not already registered or the force flag is set. - if ($force || empty(self::$classes[$class])) { - self::$classes[$class] = $path; - } + // Register the class with the autoloader if not already registered or the force flag is set. + if ($class !== '' && $class !== '0' && is_file($path) && ($force || empty(self::$classes[$class]))) { + self::$classes[$class] = $path; } } @@ -335,13 +325,11 @@ public static function registerPrefix($prefix, $path, $reset = false, $prepend = // If the prefix is not yet registered or we have an explicit reset flag then set set the path. if ($reset || !isset(self::$prefixes[$prefix])) { self::$prefixes[$prefix] = [$path]; - } else { + } elseif ($prepend) { // Otherwise we want to simply add the path to the prefix. - if ($prepend) { - array_unshift(self::$prefixes[$prefix], $path); - } else { - self::$prefixes[$prefix][] = $path; - } + array_unshift(self::$prefixes[$prefix], $path); + } else { + self::$prefixes[$prefix][] = $path; } } @@ -413,13 +401,11 @@ public static function registerNamespace($namespace, $path, $reset = false, $pre // If the namespace is not yet registered or we have an explicit reset flag then set the path. if ($reset || !isset(self::$namespaces[$namespace])) { self::$namespaces[$namespace] = [$path]; - } else { + } elseif ($prepend) { // Otherwise we want to simply add the path to the namespace. - if ($prepend) { - array_unshift(self::$namespaces[$namespace], $path); - } else { - self::$namespaces[$namespace][] = $path; - } + array_unshift(self::$namespaces[$namespace], $path); + } else { + self::$namespaces[$namespace][] = $path; } } diff --git a/libraries/namespacemap.php b/libraries/namespacemap.php index 17dc25979274c..8938404ae8825 100644 --- a/libraries/namespacemap.php +++ b/libraries/namespacemap.php @@ -197,7 +197,7 @@ private function getNamespaces(string $type): array $namespace = (string) $namespaceNode; // Ignore when the string is empty - if (!$namespace) { + if ($namespace === '' || $namespace === '0') { continue; } diff --git a/libraries/php-encryption/Crypto.php b/libraries/php-encryption/Crypto.php index 1dbbf5c6af8b4..c9b0b81a7be66 100644 --- a/libraries/php-encryption/Crypto.php +++ b/libraries/php-encryption/Crypto.php @@ -248,7 +248,7 @@ public static function RuntimeTest() throw new CryptoTestFailedException(); } - if (self::ENCRYPTION_INFO == self::AUTHENTICATION_INFO) { + if (self::ENCRYPTION_INFO === self::AUTHENTICATION_INFO) { throw new CryptoTestFailedException(); } } catch (CryptoTestFailedException $ex) { @@ -529,7 +529,7 @@ private static function HMACTestVector() $key = str_repeat("\x0b", 20); $data = "Hi There"; $correct = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; - if (hash_hmac(self::HASH_FUNCTION, $data, $key) != $correct) { + if (hash_hmac(self::HASH_FUNCTION, $data, $key) !== $correct) { throw new CryptoTestFailedException(); } } @@ -610,11 +610,7 @@ private static function our_substr($str, $start, $length = NULL) // mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP // 5.3, so we have to find the length ourselves. if (!isset($length)) { - if ($start >= 0) { - $length = self::our_strlen($str) - $start; - } else { - $length = -$start; - } + $length = $start >= 0 ? self::our_strlen($str) - $start : -$start; } return mb_substr((string) $str, $start, $length, '8bit'); diff --git a/libraries/phpass/PasswordHash.php b/libraries/phpass/PasswordHash.php index fd0277a8bafc5..b7378eed02a2c 100644 --- a/libraries/phpass/PasswordHash.php +++ b/libraries/phpass/PasswordHash.php @@ -25,21 +25,21 @@ # requirements (there can be none), but merely suggestions. # class PasswordHash { - public $itoa64; + public $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; public $iteration_count_log2; public $random_state; function __construct($iteration_count_log2, public $portable_hashes) { - $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; - - if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) - $iteration_count_log2 = 8; - $this->iteration_count_log2 = $iteration_count_log2; + if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) { + $iteration_count_log2 = 8; + } + $this->iteration_count_log2 = $iteration_count_log2; $this->random_state = microtime(); - if (function_exists('getmypid')) - $this->random_state .= getmypid(); + if (function_exists('getmypid')) { + $this->random_state .= getmypid(); + } } function PasswordHash($iteration_count_log2, $portable_hashes) @@ -76,16 +76,20 @@ function encode64($input, $count) do { $value = ord($input[$i++]); $output .= $this->itoa64[$value & 0x3f]; - if ($i < $count) - $value |= ord($input[$i]) << 8; + if ($i < $count) { + $value |= ord($input[$i]) << 8; + } $output .= $this->itoa64[($value >> 6) & 0x3f]; - if ($i++ >= $count) - break; - if ($i < $count) - $value |= ord($input[$i]) << 16; + if ($i++ >= $count) { + break; + } + if ($i < $count) { + $value |= ord($input[$i]) << 16; + } $output .= $this->itoa64[($value >> 12) & 0x3f]; - if ($i++ >= $count) - break; + if ($i++ >= $count) { + break; + } $output .= $this->itoa64[($value >> 18) & 0x3f]; } while ($i < $count); @@ -105,23 +109,27 @@ function gensalt_private($input) function crypt_private($password, $setting) { $output = '*0'; - if (substr((string) $setting, 0, 2) === $output) - $output = '*1'; + if (substr((string) $setting, 0, 2) === $output) { + $output = '*1'; + } $id = substr((string) $setting, 0, 3); # We use "$P$", phpBB3 uses "$H$" for the same thing - if ($id !== '$P$' && $id !== '$H$') - return $output; + if ($id !== '$P$' && $id !== '$H$') { + return $output; + } $count_log2 = strpos((string) $this->itoa64, (string) $setting[3]); - if ($count_log2 < 7 || $count_log2 > 30) - return $output; + if ($count_log2 < 7 || $count_log2 > 30) { + return $output; + } $count = 1 << $count_log2; $salt = substr((string) $setting, 4, 8); - if (strlen($salt) !== 8) - return $output; + if (strlen($salt) !== 8) { + return $output; + } # We were kind of forced to use MD5 here since it's the only # cryptographic primitive that was available in all versions @@ -189,17 +197,20 @@ function HashPassword($password) $random = $this->get_random_bytes(16); $hash = crypt((string) $password, (string) $this->gensalt_blowfish($random)); - if (strlen($hash) === 60) - return $hash; + if (strlen($hash) === 60) { + return $hash; + } } - if (strlen((string) $random) < 6) - $random = $this->get_random_bytes(6); + if (strlen((string) $random) < 6) { + $random = $this->get_random_bytes(6); + } $hash = $this->crypt_private($password, $this->gensalt_private($random)); - if (strlen((string) $hash) === 34) - return $hash; + if (strlen((string) $hash) === 34) { + return $hash; + } # Returning '*' on error is safe here, but would _not_ be safe # in a crypt(3)-like function used _both_ for generating new @@ -210,8 +221,9 @@ function HashPassword($password) function CheckPassword($password, $stored_hash) { $hash = $this->crypt_private($password, $stored_hash); - if ($hash[0] === '*') - $hash = crypt((string) $password, (string) $stored_hash); + if ($hash[0] === '*') { + $hash = crypt((string) $password, (string) $stored_hash); + } # This is not constant-time. In order to keep the code simple, # for timing safety we currently rely on the salts being diff --git a/libraries/src/Access/Access.php b/libraries/src/Access/Access.php index 21f543d860c61..2ffa40230766c 100644 --- a/libraries/src/Access/Access.php +++ b/libraries/src/Access/Access.php @@ -833,7 +833,7 @@ public static function getGroupsByUser($userId, $recursive = true) $guestUsergroup = (int) ComponentHelper::getParams('com_users')->get('guest_usergroup', 1); // Guest user (if only the actually assigned group is requested) - if (empty($userId) && !$recursive) { + if ($userId === 0 && !$recursive) { $result = [$guestUsergroup]; } else { // Registered user and guest if all groups are requested @@ -843,7 +843,7 @@ public static function getGroupsByUser($userId, $recursive = true) $query = $db->getQuery(true) ->select($db->quoteName($recursive ? 'b.id' : 'a.id')); - if (empty($userId)) { + if ($userId === 0) { $query->from($db->quoteName('#__usergroups', 'a')) ->where($db->quoteName('a.id') . ' = :guest') ->bind(':guest', $guestUsergroup, ParameterType::INTEGER); @@ -870,11 +870,7 @@ public static function getGroupsByUser($userId, $recursive = true) // Clean up any NULL or duplicate values, just in case $result = ArrayHelper::toInteger($result); - if (empty($result)) { - $result = [1]; - } else { - $result = array_unique($result); - } + $result = empty($result) ? [1] : array_unique($result); } self::$groupsByUser[$storeId] = $result; @@ -939,7 +935,7 @@ public static function getUsersByGroup($groupId, $recursive = false) public static function getAuthorisedViewLevels($userId) { // Only load the view levels once. - if (empty(self::$viewLevels)) { + if (self::$viewLevels === []) { // Get a database object. $db = Factory::getDbo(); diff --git a/libraries/src/Access/Rules.php b/libraries/src/Access/Rules.php index ac10d22f0e771..bf57e4431579e 100644 --- a/libraries/src/Access/Rules.php +++ b/libraries/src/Access/Rules.php @@ -156,6 +156,7 @@ public function allow($action, $identity) if (isset($this->data[$action])) { return $this->data[$action]->allow($identity); } + return null; } /** diff --git a/libraries/src/Adapter/Adapter.php b/libraries/src/Adapter/Adapter.php index c320f7076d42c..5e52ff7716f1c 100644 --- a/libraries/src/Adapter/Adapter.php +++ b/libraries/src/Adapter/Adapter.php @@ -199,7 +199,7 @@ public function loadAllAdapters($options = []) $fileName = $file->getFilename(); // Only load for php files. - if (!$file->isFile() || $file->getExtension() != 'php') { + if (!$file->isFile() || $file->getExtension() !== 'php') { continue; } diff --git a/libraries/src/Application/AdministratorApplication.php b/libraries/src/Application/AdministratorApplication.php index f62b71cb3ba7d..3fb78edca020b 100644 --- a/libraries/src/Application/AdministratorApplication.php +++ b/libraries/src/Application/AdministratorApplication.php @@ -173,14 +173,16 @@ protected function doExecute() // Initialise the application $this->initialiseApp($options); - // Mark afterInitialise in the profiler. - JDEBUG ? $this->profiler->mark('afterInitialise') : null; + if (JDEBUG) { + $this->profiler->mark('afterInitialise'); + } // Route the application $this->route(); - // Mark afterRoute in the profiler. - JDEBUG ? $this->profiler->mark('afterRoute') : null; + if (JDEBUG) { + $this->profiler->mark('afterRoute'); + } /* * Check if the user is required to reset their password @@ -194,8 +196,9 @@ protected function doExecute() // Dispatch the application $this->dispatch(); - // Mark afterDispatch in the profiler. - JDEBUG ? $this->profiler->mark('afterDispatch') : null; + if (JDEBUG) { + $this->profiler->mark('afterDispatch'); + } } /** @@ -309,12 +312,7 @@ protected function initialiseApp($options = []) if (!LanguageHelper::exists($options['language'])) { $lang = $this->get('language', 'en-GB'); - if (LanguageHelper::exists($lang)) { - $options['language'] = $lang; - } else { - // As a last ditch fail to english - $options['language'] = 'en-GB'; - } + $options['language'] = LanguageHelper::exists($lang) ? $lang : 'en-GB'; } // Finish initialisation @@ -496,7 +494,7 @@ public function findOption(): string * component. This allows the /administrator URL to display something meaningful after logging in instead of an * error. */ - if (empty($option)) { + if ($option === '' || $option === '0') { $option = 'com_cpanel'; } diff --git a/libraries/src/Application/ApiApplication.php b/libraries/src/Application/ApiApplication.php index 580f6d954c09f..f1b7a3a7c2960 100644 --- a/libraries/src/Application/ApiApplication.php +++ b/libraries/src/Application/ApiApplication.php @@ -103,20 +103,23 @@ protected function doExecute() // Initialise the application $this->initialiseApp(); - // Mark afterInitialise in the profiler. - JDEBUG ? $this->profiler->mark('afterInitialise') : null; + if (JDEBUG) { + $this->profiler->mark('afterInitialise'); + } // Route the application $this->route(); - // Mark afterApiRoute in the profiler. - JDEBUG ? $this->profiler->mark('afterApiRoute') : null; + if (JDEBUG) { + $this->profiler->mark('afterApiRoute'); + } // Dispatch the application $this->dispatch(); - // Mark afterDispatch in the profiler. - JDEBUG ? $this->profiler->mark('afterDispatch') : null; + if (JDEBUG) { + $this->profiler->mark('afterDispatch'); + } } /** @@ -169,7 +172,7 @@ protected function respond($options = []) $forceCORS = (int) $this->get('cors'); - if ($forceCORS) { + if ($forceCORS !== 0) { /** * Enable CORS (Cross-origin resource sharing) * Obtain allowed CORS origin from Global Settings. @@ -312,10 +315,8 @@ protected function route() new AfterApiRouteEvent('onAfterApiRoute', ['subject' => $this]) ); - if (!isset($route['vars']['public']) || $route['vars']['public'] === false) { - if (!$this->login(['username' => ''], ['silent' => true, 'action' => 'core.login.api'])) { - throw new AuthenticationFailed(); - } + if ((!isset($route['vars']['public']) || $route['vars']['public'] === false) && !$this->login(['username' => ''], ['silent' => true, 'action' => 'core.login.api'])) { + throw new AuthenticationFailed(); } } diff --git a/libraries/src/Application/ApplicationHelper.php b/libraries/src/Application/ApplicationHelper.php index 8cc0681345f5b..14306ab581971 100644 --- a/libraries/src/Application/ApplicationHelper.php +++ b/libraries/src/Application/ApplicationHelper.php @@ -52,7 +52,7 @@ public static function getComponentName($default = null) $input = Factory::getApplication()->getInput(); $option = strtolower((string) $input->get('option', '')); - if (empty($option)) { + if ($option === '' || $option === '0') { $option = $default; } @@ -120,7 +120,7 @@ public static function stringURLSafe($string, $language = '') public static function getClientInfo($id = null, $byName = false) { // Only create the array if it is empty - if (empty(self::$_clients)) { + if (self::$_clients === []) { $obj = new \stdClass(); // Site Client diff --git a/libraries/src/Application/BaseApplication.php b/libraries/src/Application/BaseApplication.php index 655952c2b3b06..3d06dfa8ada57 100644 --- a/libraries/src/Application/BaseApplication.php +++ b/libraries/src/Application/BaseApplication.php @@ -30,6 +30,10 @@ */ abstract class BaseApplication extends AbstractApplication { + /** + * @var \Joomla\CMS\Input\Input + */ + public $input; use EventAware; use IdentityAware; diff --git a/libraries/src/Application/CLI/ColorStyle.php b/libraries/src/Application/CLI/ColorStyle.php index b0cb6f7bfe33d..4ddf4b42f1f23 100644 --- a/libraries/src/Application/CLI/ColorStyle.php +++ b/libraries/src/Application/CLI/ColorStyle.php @@ -105,7 +105,7 @@ final class ColorStyle implements \Stringable */ public function __construct(string $fg = '', string $bg = '', array $options = []) { - if ($fg) { + if ($fg !== '' && $fg !== '0') { if (\array_key_exists($fg, static::$knownColors) == false) { throw new \InvalidArgumentException( \sprintf( @@ -119,7 +119,7 @@ public function __construct(string $fg = '', string $bg = '', array $options = [ $this->fgColor = static::$fgBase + static::$knownColors[$fg]; } - if ($bg) { + if ($bg !== '' && $bg !== '0') { if (\array_key_exists($bg, static::$knownColors) == false) { throw new \InvalidArgumentException( \sprintf( diff --git a/libraries/src/Application/CLI/Output/Processor/ColorProcessor.php b/libraries/src/Application/CLI/Output/Processor/ColorProcessor.php index 559038925af4b..cb7dd5aa49c8f 100644 --- a/libraries/src/Application/CLI/Output/Processor/ColorProcessor.php +++ b/libraries/src/Application/CLI/Output/Processor/ColorProcessor.php @@ -123,11 +123,11 @@ public function process($string) { preg_match_all($this->tagFilter, $string, $matches); - if (!$matches) { + if ($matches === []) { return $string; } - foreach ($matches[0] as $i => $m) { + foreach (array_keys($matches[0]) as $i) { if (\array_key_exists($matches[1][$i], $this->styles)) { $string = $this->replaceColors($string, $matches[1][$i], $matches[2][$i], $this->styles[$matches[1][$i]]); } elseif (strpos($matches[1][$i], '=')) { diff --git a/libraries/src/Application/CMSApplication.php b/libraries/src/Application/CMSApplication.php index abb7dcf8e56f4..ff9fec68819da 100644 --- a/libraries/src/Application/CMSApplication.php +++ b/libraries/src/Application/CMSApplication.php @@ -281,7 +281,7 @@ private function sanityCheckSystemVariables() } // Stop when there are invalid variables - if ($invalidInputVariables) { + if ($invalidInputVariables !== []) { throw new \RuntimeException('Invalid input, aborting application.'); } } @@ -389,23 +389,16 @@ protected function checkUserRequireReset($option, $view, $layout, $tasks) // Check task or option/view/layout if (!empty($task)) { $tasks = explode(',', (string) $tasks); - // Check full task version "option/task" - if (array_search($this->input->getCmd('option', '') . '/' . $task, $tasks) === false) { - // Check short task version, must be on the same option of the view - if ($this->input->getCmd('option', '') !== $option || array_search($task, $tasks) === false) { - // Not permitted task - $redirect = true; - } - } - } else { - if ( - $this->input->getCmd('option', '') !== $option || $this->input->getCmd('view', '') !== $view - || $this->input->getCmd('layout', '') !== $layout - ) { - // Requested a different option/view/layout + // Check short task version, must be on the same option of the view + if (!in_array($this->input->getCmd('option', '') . '/' . $task, $tasks) && ($this->input->getCmd('option', '') !== $option || !in_array($task, $tasks))) { + // Not permitted task $redirect = true; } + } elseif ($this->input->getCmd('option', '') !== $option || $this->input->getCmd('view', '') !== $view + || $this->input->getCmd('layout', '') !== $layout) { + // Requested a different option/view/layout + $redirect = true; } if ($redirect) { @@ -489,7 +482,7 @@ public static function getInstance($name = null, $prefix = '\JApplication', ?Con // Create a CmsApplication object. $classname = $prefix . ucfirst((string) $name); - if (!$container) { + if (!$container instanceof \Joomla\DI\Container) { $container = Factory::getContainer(); } @@ -784,12 +777,7 @@ public function isHttpsForced($clientId = null) if ($clientId === 0 && $forceSsl === 2) { return true; } - - if ($clientId === 1 && $forceSsl >= 1) { - return true; - } - - return false; + return $clientId === 1 && $forceSsl >= 1; } /** @@ -856,7 +844,7 @@ public function login($credentials, $options = []) $denied_states = Authentication::STATUS_EXPIRED | Authentication::STATUS_DENIED; foreach ($authorisations as $authorisation) { - if ((int) $authorisation->status & $denied_states) { + if (((int) $authorisation->status & $denied_states) !== 0) { // Trigger onUserAuthorisationFailure Event. $dispatcher->dispatch('onUserAuthorisationFailure', new AuthorisationFailureEvent('onUserAuthorisationFailure', [ 'subject' => (array) $authorisation, @@ -1079,8 +1067,9 @@ protected function render() new AfterRenderEvent('onAfterRender', ['subject' => $this]) ); - // Mark afterRender in the profiler. - JDEBUG ? $this->profiler->mark('afterRender') : null; + if (JDEBUG) { + $this->profiler->mark('afterRender'); + } } /** diff --git a/libraries/src/Application/CliApplication.php b/libraries/src/Application/CliApplication.php index 9acaae1fc84ab..61c90e1998b2b 100644 --- a/libraries/src/Application/CliApplication.php +++ b/libraries/src/Application/CliApplication.php @@ -187,6 +187,7 @@ public function __get($name) E_USER_NOTICE ); } + return null; } /** diff --git a/libraries/src/Application/ConsoleApplication.php b/libraries/src/Application/ConsoleApplication.php index bb68e31ef43d4..049c65ac41f36 100644 --- a/libraries/src/Application/ConsoleApplication.php +++ b/libraries/src/Application/ConsoleApplication.php @@ -186,6 +186,7 @@ public function __get($name) E_USER_NOTICE ); } + return null; } /** diff --git a/libraries/src/Application/DaemonApplication.php b/libraries/src/Application/DaemonApplication.php index 33bf29caaf761..11b5100c1736c 100644 --- a/libraries/src/Application/DaemonApplication.php +++ b/libraries/src/Application/DaemonApplication.php @@ -236,7 +236,7 @@ public function isActive() fclose($fp); // Check to make sure that the process id exists as a positive integer. - if (!$pid) { + if ($pid === 0) { return false; } diff --git a/libraries/src/Application/MultiFactorAuthenticationHandler.php b/libraries/src/Application/MultiFactorAuthenticationHandler.php index c94a6cc39dd35..9e9134adede65 100644 --- a/libraries/src/Application/MultiFactorAuthenticationHandler.php +++ b/libraries/src/Application/MultiFactorAuthenticationHandler.php @@ -166,7 +166,7 @@ protected function isHandlingMultiFactorAuthentication(): bool if ( !$isMFAPending && !$isMFADisallowed && ($userOptions->get('mfaredirectonlogin', 0) == 1) - && !$user->guest && !$hasRejectedMultiFactorAuthenticationSetup && !empty(MfaHelper::getMfaMethods()) + && !$user->guest && !$hasRejectedMultiFactorAuthenticationSetup && MfaHelper::getMfaMethods() !== [] ) { $this->redirect( $userOptions->get('mfaredirecturl', '') ?: @@ -204,7 +204,7 @@ private function isMultiFactorAuthenticationPending(): bool $mfaMethods = MfaHelper::getMfaMethods(); // If no MFA Method is active we can't really display a Captive login page. - if (empty($mfaMethods)) { + if ($mfaMethods === []) { return false; } @@ -280,21 +280,16 @@ private function needsMultiFactorAuthenticationRedirection(): bool $task = strtolower($this->input->getCmd('task', '')); // Allow the frontend user to log out (in case they forgot their MFA code or something) - if (!$isAdmin && ($option == 'com_users') && \in_array($task, ['user.logout', 'user.menulogout'])) { + if (!$isAdmin && ($option === 'com_users') && \in_array($task, ['user.logout', 'user.menulogout'])) { return false; } // Allow the backend user to log out (in case they forgot their MFA code or something) - if ($isAdmin && ($option == 'com_login') && ($task == 'logout')) { + if ($isAdmin && ($option === 'com_login') && ($task === 'logout')) { return false; } - // Allow the Joomla update finalisation to run - if ($isAdmin && $option === 'com_joomlaupdate' && \in_array($task, ['update.finalise', 'update.cleanup', 'update.finaliseconfirm'])) { - return false; - } - - return true; + return !($isAdmin && $option === 'com_joomlaupdate' && \in_array($task, ['update.finalise', 'update.cleanup', 'update.finaliseconfirm'])); } /** @@ -503,13 +498,13 @@ private function decryptLegacyTFAString(string $secret, string $stringToDecrypt) $aes = new Aes($secret, 256); $decrypted = $aes->decryptString($stringToDecrypt); - if (!\is_string($decrypted) || empty($decrypted)) { + if (!\is_string($decrypted) || ($decrypted === '' || $decrypted === '0')) { $aes->setPassword($secret, true); $decrypted = $aes->decryptString($stringToDecrypt); } - if (!\is_string($decrypted) || empty($decrypted)) { + if (!\is_string($decrypted) || ($decrypted === '' || $decrypted === '0')) { return ''; } diff --git a/libraries/src/Application/SiteApplication.php b/libraries/src/Application/SiteApplication.php index f622680e2e4bc..caa1463679aaa 100644 --- a/libraries/src/Application/SiteApplication.php +++ b/libraries/src/Application/SiteApplication.php @@ -236,14 +236,16 @@ protected function doExecute() // Initialise the application $this->initialiseApp(); - // Mark afterInitialise in the profiler. - JDEBUG ? $this->profiler->mark('afterInitialise') : null; + if (JDEBUG) { + $this->profiler->mark('afterInitialise'); + } // Route the application $this->route(); - // Mark afterRoute in the profiler. - JDEBUG ? $this->profiler->mark('afterRoute') : null; + if (JDEBUG) { + $this->profiler->mark('afterRoute'); + } if (!$this->isHandlingMultiFactorAuthentication()) { /* @@ -259,8 +261,9 @@ protected function doExecute() // Dispatch the application $this->dispatch(); - // Mark afterDispatch in the profiler. - JDEBUG ? $this->profiler->mark('afterDispatch') : null; + if (JDEBUG) { + $this->profiler->mark('afterDispatch'); + } } /** @@ -394,10 +397,8 @@ public function getTemplate($params = false) { if (\is_object($this->template)) { if ($this->template->parent) { - if (!is_file(JPATH_THEMES . '/' . $this->template->template . '/index.php')) { - if (!is_file(JPATH_THEMES . '/' . $this->template->parent . '/index.php')) { - throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $this->template->template)); - } + if (!is_file(JPATH_THEMES . '/' . $this->template->template . '/index.php') && !is_file(JPATH_THEMES . '/' . $this->template->parent . '/index.php')) { + throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $this->template->template)); } } elseif (!is_file(JPATH_THEMES . '/' . $this->template->template . '/index.php')) { throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $this->template->template)); @@ -434,11 +435,7 @@ public function getTemplate($params = false) /** @var OutputController $cache */ $cache = $this->getCacheControllerFactory()->createCacheController('output', ['defaultgroup' => 'com_templates']); - if ($this->getLanguageFilter()) { - $tag = $this->getLanguage()->getTag(); - } else { - $tag = ''; - } + $tag = $this->getLanguageFilter() ? $this->getLanguage()->getTag() : ''; $cacheId = 'templates0' . $tag; @@ -475,13 +472,11 @@ public function getTemplate($params = false) $template_override = $this->input->getCmd('template', ''); // Only set template override if it is a valid template (= it exists and is enabled) - if (!empty($template_override)) { - if (is_file(JPATH_THEMES . '/' . $template_override . '/index.php')) { - foreach ($templates as $tmpl) { - if ($tmpl->template === $template_override) { - $template = $tmpl; - break; - } + if (!empty($template_override) && is_file(JPATH_THEMES . '/' . $template_override . '/index.php')) { + foreach ($templates as $tmpl) { + if ($tmpl->template === $template_override) { + $template = $tmpl; + break; } } } @@ -491,25 +486,20 @@ public function getTemplate($params = false) // Fallback template if (!empty($template->parent)) { - if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { - if (!is_file(JPATH_THEMES . '/' . $template->parent . '/index.php')) { - $this->enqueueMessage(Text::_('JERROR_ALERTNOTEMPLATE'), 'error'); - - // Try to find data for 'cassiopeia' template - $original_tmpl = $template->template; - - foreach ($templates as $tmpl) { - if ($tmpl->template === 'cassiopeia') { - $template = $tmpl; - break; - } - } - - // Check, the data were found and if template really exists - if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { - throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $original_tmpl)); + if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php') && !is_file(JPATH_THEMES . '/' . $template->parent . '/index.php')) { + $this->enqueueMessage(Text::_('JERROR_ALERTNOTEMPLATE'), 'error'); + // Try to find data for 'cassiopeia' template + $original_tmpl = $template->template; + foreach ($templates as $tmpl) { + if ($tmpl->template === 'cassiopeia') { + $template = $tmpl; + break; } } + // Check, the data were found and if template really exists + if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { + throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $original_tmpl)); + } } } elseif (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { $this->enqueueMessage(Text::_('JERROR_ALERTNOTEMPLATE'), 'error'); @@ -615,12 +605,7 @@ protected function initialiseApp($options = []) if (!LanguageHelper::exists($options['language'])) { $lang = $this->config->get('language', 'en-GB'); - if (LanguageHelper::exists($lang)) { - $options['language'] = $lang; - } else { - // As a last ditch fail to english - $options['language'] = 'en-GB'; - } + $options['language'] = LanguageHelper::exists($lang) ? $lang : 'en-GB'; } // Finish initialisation @@ -640,8 +625,9 @@ protected function loadLibraryLanguage() * Try the lib_joomla file in the current language (without allowing the loading of the file in the default language) * Fallback to the default language if necessary */ - $this->getLanguage()->load('lib_joomla', JPATH_SITE) - || $this->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR); + if (!$this->getLanguage()->load('lib_joomla', JPATH_SITE)) { + $this->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR); + } } /** diff --git a/libraries/src/Application/WebApplication.php b/libraries/src/Application/WebApplication.php index 48217f9710ea1..4472447882bca 100644 --- a/libraries/src/Application/WebApplication.php +++ b/libraries/src/Application/WebApplication.php @@ -440,14 +440,14 @@ protected function loadSystemUris($requestUri = null) // Get an explicitly set media URI is present. $mediaURI = trim((string) $this->get('media_uri', '')); - if ($mediaURI) { + if ($mediaURI !== '' && $mediaURI !== '0') { if (str_contains($mediaURI, '://')) { $this->set('uri.media.full', $mediaURI); $this->set('uri.media.path', $mediaURI); } else { // Normalise slashes. $mediaURI = trim($mediaURI, '/\\'); - $mediaURI = !empty($mediaURI) ? '/' . $mediaURI . '/' : '/'; + $mediaURI = $mediaURI === '' || $mediaURI === '0' ? '/' : '/' . $mediaURI . '/'; $this->set('uri.media.full', $this->get('uri.base.host') . $mediaURI); $this->set('uri.media.path', $mediaURI); } diff --git a/libraries/src/Authentication/Password/MD5Handler.php b/libraries/src/Authentication/Password/MD5Handler.php index 8719b5a719675..b5f1080b62c84 100644 --- a/libraries/src/Authentication/Password/MD5Handler.php +++ b/libraries/src/Authentication/Password/MD5Handler.php @@ -89,7 +89,7 @@ public function validatePassword($plaintext, $hashed) // Compile the hash to compare // If the salt is empty AND there is a ':' in the original hash, we must append ':' at the end - $testcrypt = md5($plaintext . $salt) . ($salt ? ':' . $salt : (str_contains($hashed, ':') ? ':' : '')); + $testcrypt = md5($plaintext . $salt) . ($salt !== '' && $salt !== '0' ? ':' . $salt : (str_contains($hashed, ':') ? ':' : '')); return Crypt::timingSafeCompare($hashed, $testcrypt); } diff --git a/libraries/src/Cache/Controller/CallbackController.php b/libraries/src/Cache/Controller/CallbackController.php index 9c420366a0ebd..bdde7dbe44b17 100644 --- a/libraries/src/Cache/Controller/CallbackController.php +++ b/libraries/src/Cache/Controller/CallbackController.php @@ -41,7 +41,7 @@ class CallbackController extends CacheController public function get($callback, $args = [], $id = false, $wrkarounds = false, $woptions = []) { if (!\is_array($args)) { - $referenceArgs = !empty($args) ? [&$args] : []; + $referenceArgs = empty($args) ? [] : [&$args]; } else { $referenceArgs = &$args; } @@ -122,11 +122,7 @@ public function get($callback, $args = [], $id = false, $wrkarounds = false, $wo $data = ['result' => $result]; - if ($wrkarounds) { - $data['output'] = Cache::setWorkarounds($output, $coptions); - } else { - $data['output'] = $output; - } + $data['output'] = $wrkarounds ? Cache::setWorkarounds($output, $coptions) : $output; // Restore document head data and merge module head data. if ($coptions['modulemode'] == 1) { diff --git a/libraries/src/Cache/Storage/ApcuStorage.php b/libraries/src/Cache/Storage/ApcuStorage.php index effefc95f122e..f7576b614375b 100644 --- a/libraries/src/Cache/Storage/ApcuStorage.php +++ b/libraries/src/Cache/Storage/ApcuStorage.php @@ -86,11 +86,7 @@ public function getAll() if ($namearr !== false && $namearr[0] == $secret && $namearr[1] === 'cache') { $group = $namearr[2]; - if (!isset($data[$group])) { - $item = new CacheStorageHelper($group); - } else { - $item = $data[$group]; - } + $item = $data[$group] ?? new CacheStorageHelper($group); $item->updateSize($key['mem_size']); diff --git a/libraries/src/Cache/Storage/FileStorage.php b/libraries/src/Cache/Storage/FileStorage.php index b5bd935ec0dce..73f1d6874fffd 100644 --- a/libraries/src/Cache/Storage/FileStorage.php +++ b/libraries/src/Cache/Storage/FileStorage.php @@ -110,29 +110,26 @@ public function get($id, $group, $checkTime = true) $path = $this->_getFilePath($id, $group); $close = false; - if ($checkTime == false || ($checkTime == true && $this->_checkExpire($id, $group) === true)) { - if (file_exists($path)) { - if (isset($this->_locked_files[$path])) { - $_fileopen = $this->_locked_files[$path]; - } else { - $_fileopen = @fopen($path, 'rb'); - - // There is no lock, we have to close file after store data - $close = true; - } - - if ($_fileopen) { - // On Windows system we can not use file_get_contents on the file locked by yourself - $data = stream_get_contents($_fileopen); + if (($checkTime == false || $checkTime == true && $this->_checkExpire($id, $group) === true) && file_exists($path)) { + if (isset($this->_locked_files[$path])) { + $_fileopen = $this->_locked_files[$path]; + } else { + $_fileopen = @fopen($path, 'rb'); + + // There is no lock, we have to close file after store data + $close = true; + } + if ($_fileopen) { + // On Windows system we can not use file_get_contents on the file locked by yourself + $data = stream_get_contents($_fileopen); - if ($close) { - @fclose($_fileopen); - } + if ($close) { + @fclose($_fileopen); + } - if ($data !== false) { - // Remove the initial die() statement - return str_replace('#x#', '', $data); - } + if ($data !== false) { + // Remove the initial die() statement + return str_replace('#x#', '', $data); } } } @@ -227,11 +224,7 @@ public function remove($id, $group) $path = $this->_getFilePath($id, $group); File::invalidateFileCache($path); - if (!@unlink($path)) { - return false; - } - - return true; + return @unlink($path); } /** @@ -252,7 +245,7 @@ public function clean($group, $mode = null) $return = true; $folder = $group; - if (trim($folder) == '') { + if (trim($folder) === '') { $mode = 'notgroup'; } @@ -297,7 +290,7 @@ public function gc() foreach ($files as $file) { $time = @filemtime($file); - if (($time + $this->_lifetime) < $this->_now || empty($time)) { + if (($time + $this->_lifetime) < $this->_now || ($time === 0 || $time === false)) { File::invalidateFileCache($file); $result |= @unlink($file); } @@ -352,7 +345,7 @@ public function lock($id, $group, $locktime) $returning->locklooped = true; } - if ($data_lock === true) { + if ($data_lock) { // Remember resource, flock release lock if you unset/close resource $this->_locked_files[$path] = $_fileopen; } @@ -408,19 +401,14 @@ protected function _checkExpire($id, $group) if (file_exists($path)) { $time = @filemtime($path); - if (($time + $this->_lifetime) < $this->_now || empty($time)) { + if (($time + $this->_lifetime) < $this->_now || ($time === 0 || $time === false)) { File::invalidateFileCache($path); @unlink($path); return false; } - // If, right now, the file does not exist then return false - if (@filesize($path) == 0) { - return false; - } - - return true; + return @filesize($path) != 0; } return false; @@ -445,7 +433,9 @@ protected function _getFilePath($id, $group) if (!is_dir($dir)) { // Make sure the index file is there $indexFile = $dir . '/index.html'; - @mkdir($dir) && file_put_contents($indexFile, ''); + if (@mkdir($dir)) { + file_put_contents($indexFile, ''); + } } // Make sure the folder exists @@ -491,7 +481,7 @@ protected function _deleteFolder($path) if (!empty($files) && !\is_array($files)) { File::invalidateFileCache($files); - if (@unlink($files) !== true) { + if (!@unlink($files)) { return false; } } elseif (!empty($files) && \is_array($files)) { @@ -501,7 +491,7 @@ protected function _deleteFolder($path) // In case of restricted permissions we delete it one way or the other as long as the owner is either the webserver or the ftp File::invalidateFileCache($file); - if (@unlink($file) !== true) { + if (!@unlink($file)) { Log::add(__METHOD__ . ' ' . Text::sprintf('JLIB_FILESYSTEM_DELETE_FAILED', basename($file)), Log::WARNING, 'jerror'); return false; @@ -515,7 +505,7 @@ protected function _deleteFolder($path) foreach ($folders as $folder) { if (is_link($folder)) { // Don't descend into linked directories, just delete the link. - if (@unlink($folder) !== true) { + if (!@unlink($folder)) { return false; } } elseif ($this->_deleteFolder($folder) !== true) { @@ -547,7 +537,7 @@ protected function _cleanPath($path, $ds = DIRECTORY_SEPARATOR) { $path = trim($path); - if (empty($path)) { + if ($path === '' || $path === '0') { return $this->_root; } @@ -596,14 +586,10 @@ protected function _filesInFolder( return $arr; } - if (\count($excludefilter)) { - $excludefilter = '/(' . implode('|', $excludefilter) . ')/'; - } else { - $excludefilter = ''; - } + $excludefilter = \count($excludefilter) ? '/(' . implode('|', $excludefilter) . ')/' : ''; while (($file = readdir($handle)) !== false) { - if (($file != '.') && ($file != '..') && (!\in_array($file, $exclude)) && (!$excludefilter || !preg_match($excludefilter, $file))) { + if (($file !== '.') && ($file !== '..') && (!\in_array($file, $exclude)) && (!$excludefilter || !preg_match($excludefilter, $file))) { $dir = $path . '/' . $file; $isDir = is_dir($dir); @@ -617,14 +603,8 @@ protected function _filesInFolder( $arr = array_merge($arr, $arr2); } - } else { - if (preg_match("/$filter/", $file)) { - if ($fullpath) { - $arr[] = $path . '/' . $file; - } else { - $arr[] = $file; - } - } + } elseif (preg_match("/$filter/", $file)) { + $arr[] = $fullpath ? $path . '/' . $file : $file; } } } @@ -673,17 +653,13 @@ protected function _folders( return $arr; } - if (\count($excludefilter)) { - $excludefilter_string = '/(' . implode('|', $excludefilter) . ')/'; - } else { - $excludefilter_string = ''; - } + $excludefilter_string = \count($excludefilter) ? '/(' . implode('|', $excludefilter) . ')/' : ''; while (($file = readdir($handle)) !== false) { if ( - ($file != '.') && ($file != '..') + ($file !== '.') && ($file !== '..') && (!\in_array($file, $exclude)) - && (empty($excludefilter_string) || !preg_match($excludefilter_string, $file)) + && ($excludefilter_string === '' || $excludefilter_string === '0' || !preg_match($excludefilter_string, $file)) ) { $dir = $path . '/' . $file; $isDir = is_dir($dir); @@ -691,11 +667,7 @@ protected function _folders( if ($isDir) { // Removes filtered directories if (preg_match("/$filter/", $file)) { - if ($fullpath) { - $arr[] = $dir; - } else { - $arr[] = $file; - } + $arr[] = $fullpath ? $dir : $file; } if ($recurse) { diff --git a/libraries/src/Cache/Storage/MemcachedStorage.php b/libraries/src/Cache/Storage/MemcachedStorage.php index 48202d10d820d..242e06513f9d3 100644 --- a/libraries/src/Cache/Storage/MemcachedStorage.php +++ b/libraries/src/Cache/Storage/MemcachedStorage.php @@ -127,7 +127,7 @@ protected function _getCacheId($id, $group) $length = \strlen($prefix); $cache_id = parent::_getCacheId($id, $group); - if ($length) { + if ($length !== 0) { // Memcached use suffix instead of prefix $cache_id = substr($cache_id, $length) . strrev($prefix); } @@ -193,11 +193,7 @@ public function getAll() if ($namearr !== false && $namearr[0] == $secret && $namearr[1] === 'cache') { $group = $namearr[2]; - if (!isset($data[$group])) { - $item = new CacheStorageHelper($group); - } else { - $item = $data[$group]; - } + $item = $data[$group] ?? new CacheStorageHelper($group); $item->updateSize($key->size); diff --git a/libraries/src/Cache/Storage/RedisStorage.php b/libraries/src/Cache/Storage/RedisStorage.php index 112382e4fcaca..d915e4e05ddf4 100644 --- a/libraries/src/Cache/Storage/RedisStorage.php +++ b/libraries/src/Cache/Storage/RedisStorage.php @@ -202,11 +202,7 @@ public function getAll() if ($namearr !== false && $namearr[0] == $secret && $namearr[1] === 'cache') { $group = $namearr[2]; - if (!isset($data[$group])) { - $item = new CacheStorageHelper($group); - } else { - $item = $data[$group]; - } + $item = $data[$group] ?? new CacheStorageHelper($group); $item->updateSize(\strlen($key) * 8); $data[$group] = $item; diff --git a/libraries/src/Captcha/Captcha.php b/libraries/src/Captcha/Captcha.php index 64ff355b5b5c8..19d7c12dfe12d 100644 --- a/libraries/src/Captcha/Captcha.php +++ b/libraries/src/Captcha/Captcha.php @@ -226,11 +226,11 @@ public function setupField(CaptchaField $field, \SimpleXMLElement $element) { if ($this->provider) { $this->provider->setupField($field, $element); - return; + return null; } if ($this->captcha === null) { - return; + return null; } $arg = ['field' => $field, 'element' => $element]; diff --git a/libraries/src/Categories/Categories.php b/libraries/src/Categories/Categories.php index 065fa0d445a16..89b6c1eac35d9 100644 --- a/libraries/src/Categories/Categories.php +++ b/libraries/src/Categories/Categories.php @@ -232,7 +232,7 @@ protected function _load($id) try { $db = $this->getDatabase(); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseInterface::class); } @@ -370,7 +370,7 @@ protected function _load($id) $results = $db->loadObjectList('id'); $childrenLoaded = false; - if (\count($results)) { + if (\count($results) > 0) { // Foreach categories foreach ($results as $result) { // Deal with root category @@ -396,7 +396,7 @@ protected function _load($id) // If the node's parent id is not in the _nodes list and the node is not root (doesn't have parent_id == 0), // then remove the node from the list - if (!(isset($this->_nodes[$result->parent_id]) || $result->parent_id == 0)) { + if (!isset($this->_nodes[$result->parent_id]) && $result->parent_id != 0) { unset($this->_nodes[$result->id]); continue; } @@ -416,7 +416,7 @@ protected function _load($id) // If the node's parent id is not in the _nodes list and the node is not root (doesn't have parent_id == 0), // then remove the node from the list - if (!(isset($this->_nodes[$result->parent_id]) || $result->parent_id == 0)) { + if (!isset($this->_nodes[$result->parent_id]) && $result->parent_id != 0) { unset($this->_nodes[$result->id]); continue; } diff --git a/libraries/src/Changelog/Changelog.php b/libraries/src/Changelog/Changelog.php index dbe0561a9766e..655c49a0bd617 100644 --- a/libraries/src/Changelog/Changelog.php +++ b/libraries/src/Changelog/Changelog.php @@ -274,7 +274,7 @@ public function endElement($parser, $name) $this->items = []; break; case 'CHANGELOG': - if (version_compare($this->currentChangelog->version->data, $this->matchVersion, '==') === true) { + if (version_compare($this->currentChangelog->version->data, $this->matchVersion, '==')) { $this->latest = $this->currentChangelog; } @@ -283,14 +283,14 @@ public function endElement($parser, $name) break; case 'CHANGELOGS': // If the latest item is set then we transfer it to where we want to - if (isset($this->latest)) { + if ($this->latest !== null) { foreach (get_object_vars($this->latest) as $key => $val) { $this->$key = $val; } unset($this->latest); unset($this->currentChangelog); - } elseif (isset($this->currentChangelog)) { + } elseif ($this->currentChangelog !== null) { // The update might be for an older version of j! unset($this->currentChangelog); } @@ -372,7 +372,7 @@ public function loadFromXml($url) xml_set_element_handler($this->xmlParser, 'startElement', 'endElement'); xml_set_character_data_handler($this->xmlParser, 'characterData'); - if (!xml_parse($this->xmlParser, $response->body)) { + if (xml_parse($this->xmlParser, $response->body) === 0) { Log::add( \sprintf( 'XML error: %s at line %d', diff --git a/libraries/src/Client/FtpClient.php b/libraries/src/Client/FtpClient.php index 9c6ca8b8948fe..77b97385da921 100644 --- a/libraries/src/Client/FtpClient.php +++ b/libraries/src/Client/FtpClient.php @@ -194,7 +194,7 @@ public function __construct(array $options = []) $this->setOptions($options); - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { BufferStreamHandler::stream_register(); } } @@ -298,7 +298,7 @@ public function connect($host = '127.0.0.1', $port = 21) } // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { $this->_conn = @ftp_connect($host, $port, $this->_timeout); if (!$this->_conn) { @@ -360,7 +360,7 @@ public function isConnected() public function login($user = 'anonymous', $pass = 'jftp@joomla.org') { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_login($this->_conn, $user, $pass) === false) { Log::add('JFtp::login: Unable to login', Log::WARNING, 'jerror'); @@ -402,7 +402,7 @@ public function login($user = 'anonymous', $pass = 'jftp@joomla.org') public function quit() { // If native FTP support is enabled lets use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { @ftp_close($this->_conn); return true; @@ -425,7 +425,7 @@ public function quit() public function pwd() { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (($ret = @ftp_pwd($this->_conn)) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -461,7 +461,7 @@ public function pwd() public function syst() { // If native FTP support is enabled lets use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (($ret = @ftp_systype($this->_conn)) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -503,7 +503,7 @@ public function syst() public function chdir($path) { // If native FTP support is enabled lets use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_chdir($this->_conn, $path) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -535,7 +535,7 @@ public function chdir($path) public function reinit() { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_site($this->_conn, 'REIN') === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -568,7 +568,7 @@ public function reinit() public function rename($from, $to) { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_rename($this->_conn, $from, $to) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -618,7 +618,7 @@ public function chmod($path, $mode) } // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_site($this->_conn, 'CHMOD ' . $mode . ' ' . $path) === false) { if (!IS_WIN) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -654,25 +654,19 @@ public function chmod($path, $mode) public function delete($path) { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { - if (@ftp_delete($this->_conn, $path) === false) { - if (@ftp_rmdir($this->_conn, $path) === false) { - Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); - - return false; - } + if (FTP_NATIVE !== 0) { + if (@ftp_delete($this->_conn, $path) === false && @ftp_rmdir($this->_conn, $path) === false) { + Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); + return false; } return true; } // Send delete file command and if that doesn't work, try to remove a directory - if (!$this->_putCmd('DELE ' . $path, 250)) { - if (!$this->_putCmd('RMD ' . $path, 250)) { - Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_NOT_EXPECTED_RESPONSE_PATH_SENT', __METHOD__, $this->_response, 250, $path), Log::WARNING, 'jerror'); - - return false; - } + if (!$this->_putCmd('DELE ' . $path, 250) && !$this->_putCmd('RMD ' . $path, 250)) { + Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_NOT_EXPECTED_RESPONSE_PATH_SENT', __METHOD__, $this->_response, 250, $path), Log::WARNING, 'jerror'); + return false; } return true; @@ -690,7 +684,7 @@ public function delete($path) public function mkdir($path) { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_mkdir($this->_conn, $path) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -722,7 +716,7 @@ public function mkdir($path) public function restart($point) { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { if (@ftp_site($this->_conn, 'REST ' . $point) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), Log::WARNING, 'jerror'); @@ -754,7 +748,7 @@ public function restart($point) public function create($path) { // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -818,7 +812,7 @@ public function read($remote, &$buffer) $mode = $this->_findMode($remote); // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -910,7 +904,7 @@ public function get($local, $remote) $mode = $this->_findMode($remote); // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -993,7 +987,7 @@ public function store($local, $remote = null) $mode = $this->_findMode($remote); // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -1056,7 +1050,7 @@ public function store($local, $remote = null) } $line = substr($line, $result); - } while ($line != ''); + } while ($line !== ''); } fclose($fp); @@ -1087,7 +1081,7 @@ public function write($remote, $buffer) $mode = $this->_findMode($remote); // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -1138,7 +1132,7 @@ public function write($remote, $buffer) } $buffer = substr($buffer, $result); - } while ($buffer != ''); + } while ($buffer !== ''); // Close the data connection port [Data transfer complete] fclose($this->_dataconn); @@ -1169,7 +1163,7 @@ public function append($remote, $buffer) $mode = $this->_findMode($remote); // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { throw new \RuntimeException(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), 36); @@ -1217,7 +1211,7 @@ public function append($remote, $buffer) } $buffer = substr($buffer, $result); - } while ($buffer != ''); + } while ($buffer !== ''); // Close the data connection port [Data transfer complete] fclose($this->_dataconn); @@ -1241,7 +1235,7 @@ public function append($remote, $buffer) */ public function size($remote) { - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { $size = ftp_size($this->_conn, $remote); // In case ftp_size fails, try the SIZE command directly. @@ -1250,7 +1244,7 @@ public function size($remote) $responseCode = substr($response[0], 0, 3); $responseMessage = substr($response[0], 4); - if ($responseCode != '213') { + if ($responseCode !== '213') { throw new \RuntimeException(Text::sprintf('JLIB_CLIENT_ERROR_FTP_BAD_RESPONSE', __METHOD__), 35); } @@ -1292,7 +1286,7 @@ public function listNames($path = null) $data = null; // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -1394,7 +1388,7 @@ public function listDetails($path = null, $type = 'all') $recurse = false; // If native FTP support is enabled let's use it... - if (FTP_NATIVE) { + if (FTP_NATIVE !== 0) { // Turn passive mode on if (@ftp_pasv($this->_conn, true) === false) { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE', __METHOD__), Log::WARNING, 'jerror'); @@ -1472,7 +1466,7 @@ public function listDetails($path = null, $type = 'all') . ' ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{1,2}:[0-9]{2})|[0-9]{4}) (.+)#', 'MAC' => '#([-dl][rwxstST-]+).* ?([0-9 ]*)?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*)' . ' ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)#', - 'WIN' => '#([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)#', + 'WIN' => '#(\d{2})-(\d{2})-(\d{2}) +(\d{2}):(\d{2})(AM|PM) +(\d+|) +(.+)#', ]; // Find out the format of the directory listing by matching one of the regexps @@ -1523,7 +1517,7 @@ public function listDetails($path = null, $type = 'all') continue; } - if (\count($tmp_array) && $tmp_array['name'] != '.' && $tmp_array['name'] != '..') { + if (\count($tmp_array) && $tmp_array['name'] !== '.' && $tmp_array['name'] !== '..') { $dir_list[] = $tmp_array; } } @@ -1558,7 +1552,7 @@ public function listDetails($path = null, $type = 'all') continue; } - if (\count($tmp_array) && $tmp_array['name'] != '.' && $tmp_array['name'] != '..') { + if (\count($tmp_array) && $tmp_array['name'] !== '.' && $tmp_array['name'] !== '..') { $dir_list[] = $tmp_array; } } @@ -1628,17 +1622,11 @@ protected function _verifyResponse($expected) // Did the server respond with the code we wanted? if (\is_array($expected)) { - if (\in_array($this->_responseCode, $expected)) { - $retval = true; - } else { - $retval = false; - } + $retval = \in_array($this->_responseCode, $expected); + } elseif ($this->_responseCode == $expected) { + $retval = true; } else { - if ($this->_responseCode == $expected) { - $retval = true; - } else { - $retval = false; - } + $retval = false; } return $retval; @@ -1688,7 +1676,7 @@ protected function _passive() $this->_responseMsg = $parts[0]; // If it's not 227, we weren't given an IP and port, which means it failed. - if ($this->_responseCode != '227') { + if ($this->_responseCode !== '227') { Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_PASSIVE_IP_OBTAIN', __METHOD__, $this->_responseMsg), Log::WARNING, 'jerror'); return false; @@ -1738,11 +1726,7 @@ protected function _findMode($fileName) $dot = strrpos($fileName, '.') + 1; $ext = substr($fileName, $dot); - if (\in_array($ext, $this->_autoAscii)) { - $mode = FTP_ASCII; - } else { - $mode = FTP_BINARY; - } + $mode = \in_array($ext, $this->_autoAscii) ? FTP_ASCII : FTP_BINARY; } elseif ($this->_type == FTP_ASCII) { $mode = FTP_ASCII; } else { @@ -1770,12 +1754,9 @@ protected function _mode($mode) return false; } - } else { - if (!$this->_putCmd('TYPE A', 200)) { - Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_MODE_ASCII', __METHOD__, $this->_response), Log::WARNING, 'jerror'); - - return false; - } + } elseif (!$this->_putCmd('TYPE A', 200)) { + Log::add(Text::sprintf('JLIB_CLIENT_ERROR_FTP_MODE_ASCII', __METHOD__, $this->_response), Log::WARNING, 'jerror'); + return false; } return true; diff --git a/libraries/src/Component/ComponentHelper.php b/libraries/src/Component/ComponentHelper.php index 90470d9263dd0..a0662aced3488 100644 --- a/libraries/src/Component/ComponentHelper.php +++ b/libraries/src/Component/ComponentHelper.php @@ -60,7 +60,7 @@ public static function getComponent($option, $strict = false) } $result = new ComponentRecord(); - $result->enabled = $strict ? false : true; + $result->enabled = !$strict; $result->setParams(new Registry()); return $result; @@ -177,7 +177,7 @@ public static function filterText($text) foreach ($tags as $tag) { $tag = trim($tag); - if ($tag) { + if ($tag !== '' && $tag !== '0') { $tempTags[] = $tag; } } @@ -185,7 +185,7 @@ public static function filterText($text) foreach ($attributes as $attribute) { $attribute = trim($attribute); - if ($attribute) { + if ($attribute !== '' && $attribute !== '0') { $tempAttributes[] = $attribute; } } @@ -225,11 +225,11 @@ public static function filterText($text) $filter = InputFilter::getInstance([], [], 1, 1); // Override filter's default forbidden tags and attributes - if ($customListTags) { + if ($customListTags !== []) { $filter->blockedTags = $customListTags; } - if ($customListAttributes) { + if ($customListAttributes !== []) { $filter->blockedAttributes = $customListAttributes; } } elseif ($forbiddenList) { @@ -246,12 +246,12 @@ public static function filterText($text) ); // Remove the allowed tags from filter's default forbidden list. - if ($allowedListTags) { + if ($allowedListTags !== []) { $filter->blockedTags = array_diff($filter->blockedTags, $allowedListTags); } // Remove the allowed attributes from filter's default forbidden list. - if ($allowedListAttributes) { + if ($allowedListAttributes !== []) { $filter->blockedAttributes = array_diff($filter->blockedAttributes, $allowedListAttributes); } } elseif ($allowedList) { @@ -288,8 +288,9 @@ public static function renderComponent($option, $params = []) if (!$app->isClient('api')) { // Load template language files. $template = $app->getTemplate(true)->template; - $lang->load('tpl_' . $template, JPATH_BASE) - || $lang->load('tpl_' . $template, JPATH_THEMES . "/$template"); + if (!$lang->load('tpl_' . $template, JPATH_BASE)) { + $lang->load('tpl_' . $template, JPATH_THEMES . "/$template"); + } } if (empty($option)) { diff --git a/libraries/src/Component/Router/RouterBase.php b/libraries/src/Component/Router/RouterBase.php index 0755c34336479..cc0d6c6fd9f49 100644 --- a/libraries/src/Component/Router/RouterBase.php +++ b/libraries/src/Component/Router/RouterBase.php @@ -48,17 +48,9 @@ abstract class RouterBase implements RouterInterface */ public function __construct($app = null, $menu = null) { - if ($app) { - $this->app = $app; - } else { - $this->app = Factory::getApplication(); - } + $this->app = $app ?: Factory::getApplication(); - if ($menu) { - $this->menu = $menu; - } else { - $this->menu = $this->app->getMenu(); - } + $this->menu = $menu ?: $this->app->getMenu(); } /** diff --git a/libraries/src/Component/Router/Rules/MenuRules.php b/libraries/src/Component/Router/Rules/MenuRules.php index 258df7ecf31a1..dd59baad358f8 100644 --- a/libraries/src/Component/Router/Rules/MenuRules.php +++ b/libraries/src/Component/Router/Rules/MenuRules.php @@ -64,11 +64,7 @@ public function __construct(RouterView $router) $this->router = $router; $sefPlugin = PluginHelper::getPlugin('system', 'sef'); - if ($sefPlugin) { - $this->sefparams = new Registry($sefPlugin->params); - } else { - $this->sefparams = new Registry(); - } + $this->sefparams = $sefPlugin ? new Registry($sefPlugin->params) : new Registry(); $this->buildLookup(); } @@ -114,7 +110,7 @@ public function preprocess(&$query) foreach ($active->query as $k => $v) { if (isset($query[$k]) && $v !== $query[$k]) { // Compare again without alias - if (\is_string($v) && $v == current(explode(':', (string) $query[$k], 2))) { + if (\is_string($v) && $v === current(explode(':', (string) $query[$k], 2))) { continue; } @@ -232,16 +228,13 @@ protected function buildLookup($language = '*') if (!isset($this->lookup[$language][$view . $layout])) { $this->lookup[$language][$view . $layout] = []; } - if (!isset($this->lookup[$language][$view])) { $this->lookup[$language][$view] = []; } - // If menuitem has no key set, we assume 0. if (!isset($item->query[$views[$view]->key])) { $item->query[$views[$view]->key] = 0; } - /** * Here it will become a bit tricky * language != * can override existing entries @@ -251,15 +244,13 @@ protected function buildLookup($language = '*') $this->lookup[$language][$view . $layout][$item->query[$views[$view]->key]] = $item->id; $this->lookup[$language][$view][$item->query[$views[$view]->key]] = $item->id; } - } else { + } elseif (!isset($this->lookup[$language][$view . $layout]) || $item->language !== '*') { /** * Here it will become a bit tricky * language != * can override existing entries * language == * cannot override existing entries */ - if (!isset($this->lookup[$language][$view . $layout]) || $item->language !== '*') { - $this->lookup[$language][$view . $layout] = $item->id; - } + $this->lookup[$language][$view . $layout] = $item->id; } } } diff --git a/libraries/src/Component/Router/Rules/NomenuRules.php b/libraries/src/Component/Router/Rules/NomenuRules.php index b4c2cbe5703fd..d49f49ba077ff 100644 --- a/libraries/src/Component/Router/Rules/NomenuRules.php +++ b/libraries/src/Component/Router/Rules/NomenuRules.php @@ -77,7 +77,7 @@ public function parse(&$segments, &$vars) $vars['view'] = array_shift($segments); $view = $views[$vars['view']]; - if (isset($view->key) && isset($segments[0])) { + if ($view->key !== null && isset($segments[0])) { if (\is_callable([$this->router, 'get' . ucfirst($view->name) . 'Id'])) { $input = $this->router->app->getInput(); if ($view->parent_key && $input->get($view->parent_key)) { diff --git a/libraries/src/Console/CheckJoomlaUpdatesCommand.php b/libraries/src/Console/CheckJoomlaUpdatesCommand.php index 7f31704b74245..1fcd4d0bc1ff8 100644 --- a/libraries/src/Console/CheckJoomlaUpdatesCommand.php +++ b/libraries/src/Console/CheckJoomlaUpdatesCommand.php @@ -122,11 +122,7 @@ public function getUpdateInfo() */ public function setUpdateInfo($info = null): void { - if (!$info) { - $this->updateInfo = $this->getUpdateInformationFromModel(); - } else { - $this->updateInfo = $info; - } + $this->updateInfo = $info ?: $this->getUpdateInformationFromModel(); } /** diff --git a/libraries/src/Console/ExtensionDiscoverListCommand.php b/libraries/src/Console/ExtensionDiscoverListCommand.php index db26185fa68d3..ca50a54f2a92d 100644 --- a/libraries/src/Console/ExtensionDiscoverListCommand.php +++ b/libraries/src/Console/ExtensionDiscoverListCommand.php @@ -93,7 +93,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in $discovered_extensions = $this->filterExtensionsBasedOnState($extensions, $state); - if (empty($discovered_extensions)) { + if ($discovered_extensions === []) { $this->ioStyle->note("There are no pending discovered extensions to install. Perhaps you need to run extension:discover first?"); return Command::SUCCESS; diff --git a/libraries/src/Console/ExtensionRemoveCommand.php b/libraries/src/Console/ExtensionRemoveCommand.php index fc7eee91b76b6..ef6e3ae913d88 100644 --- a/libraries/src/Console/ExtensionRemoveCommand.php +++ b/libraries/src/Console/ExtensionRemoveCommand.php @@ -126,10 +126,12 @@ private function configureIO(InputInterface $input, OutputInterface $output): vo $this->cliInput = $input; $this->ioStyle = new SymfonyStyle($input, $output); $language = Factory::getLanguage(); - $language->load('', JPATH_ADMINISTRATOR, null, false, false) || - $language->load('', JPATH_ADMINISTRATOR, null, true); - $language->load('com_installer', JPATH_ADMINISTRATOR, null, false, false) || - $language->load('com_installer', JPATH_ADMINISTRATOR, null, true); + if (!$language->load('', JPATH_ADMINISTRATOR, null, false, false)) { + $language->load('', JPATH_ADMINISTRATOR, null, true); + } + if (!$language->load('com_installer', JPATH_ADMINISTRATOR, null, false, false)) { + $language->load('com_installer', JPATH_ADMINISTRATOR, null, true); + } } /** diff --git a/libraries/src/Console/ExtensionsListCommand.php b/libraries/src/Console/ExtensionsListCommand.php index c4ee8327a95d2..f1a2147b01f72 100644 --- a/libraries/src/Console/ExtensionsListCommand.php +++ b/libraries/src/Console/ExtensionsListCommand.php @@ -138,11 +138,7 @@ public function getExtensions() */ public function setExtensions($extensions = null): void { - if (!$extensions) { - $this->extensions = $this->getAllExtensionsFromDB(); - } else { - $this->extensions = $extensions; - } + $this->extensions = $extensions ?: $this->getAllExtensionsFromDB(); } /** diff --git a/libraries/src/Console/FinderIndexCommand.php b/libraries/src/Console/FinderIndexCommand.php index 9cfa296bdd714..260ea6dd9d90d 100644 --- a/libraries/src/Console/FinderIndexCommand.php +++ b/libraries/src/Console/FinderIndexCommand.php @@ -246,10 +246,12 @@ private function configureIO(InputInterface $input, OutputInterface $output): vo $language = Factory::getLanguage(); } - $language->load('', JPATH_ADMINISTRATOR, null, false, false) || - $language->load('', JPATH_ADMINISTRATOR, null, true); - $language->load('finder_cli', JPATH_SITE, null, false, false) || - $language->load('finder_cli', JPATH_SITE, null, true); + if (!$language->load('', JPATH_ADMINISTRATOR, null, false, false)) { + $language->load('', JPATH_ADMINISTRATOR, null, true); + } + if (!$language->load('finder_cli', JPATH_SITE, null, false, false)) { + $language->load('finder_cli', JPATH_SITE, null, true); + } } /** @@ -401,15 +403,11 @@ private function index() if ($this->pause !== 0) { // Pausing Section - $skip = !($processingTime >= $this->minimumBatchProcessingTime); + $skip = $processingTime < $this->minimumBatchProcessingTime; $pause = 0; if ($this->pause === 'division' && $this->divisor > 0) { - if (!$skip) { - $pause = round($processingTime / $this->divisor); - } else { - $pause = 1; - } + $pause = $skip ? 1 : round($processingTime / $this->divisor); } elseif ($this->pause > 0) { $pause = $this->pause; } @@ -489,7 +487,7 @@ private function putFilters() } // Construct a comma-separated string from the taxonomy ids. - $taxonomyIds = empty($tids) ? '' : implode(',', $tids); + $taxonomyIds = $tids === [] ? '' : implode(',', $tids); // Update the filter with the new taxonomy ids. $query = $db->getQuery(true); diff --git a/libraries/src/Console/RemoveOldFilesCommand.php b/libraries/src/Console/RemoveOldFilesCommand.php index 26362cccdacd2..3caf8dfec9f9f 100644 --- a/libraries/src/Console/RemoveOldFilesCommand.php +++ b/libraries/src/Console/RemoveOldFilesCommand.php @@ -60,7 +60,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in if ($output->isVeryVerbose() || $output->isDebug()) { foreach ($status['files_checked'] as $file) { - $exists = \in_array($file, array_values($status['files_exist'])); + $exists = \in_array($file, $status['files_exist']); if ($exists) { $symfonyStyle->writeln('File Checked & Exists - ' . $file, OutputInterface::VERBOSITY_VERY_VERBOSE); @@ -70,7 +70,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in } foreach ($status['folders_checked'] as $folder) { - $exists = \in_array($folder, array_values($status['folders_exist'])); + $exists = \in_array($folder, $status['folders_exist']); if ($exists) { $symfonyStyle->writeln('Folder Checked & Exists - ' . $folder, OutputInterface::VERBOSITY_VERY_VERBOSE); diff --git a/libraries/src/Console/SetConfigurationCommand.php b/libraries/src/Console/SetConfigurationCommand.php index 634964a17de7f..bd768bf575e04 100644 --- a/libraries/src/Console/SetConfigurationCommand.php +++ b/libraries/src/Console/SetConfigurationCommand.php @@ -105,10 +105,12 @@ class SetConfigurationCommand extends AbstractCommand private function configureIO(InputInterface $input, OutputInterface $output) { $language = Factory::getLanguage(); - $language->load('', JPATH_INSTALLATION, null, false, false) || - $language->load('', JPATH_INSTALLATION, null, true); - $language->load('com_config', JPATH_ADMINISTRATOR, null, false, false) || - $language->load('com_config', JPATH_ADMINISTRATOR, null, true); + if (!$language->load('', JPATH_INSTALLATION, null, false, false)) { + $language->load('', JPATH_INSTALLATION, null, true); + } + if (!$language->load('com_config', JPATH_ADMINISTRATOR, null, false, false)) { + $language->load('com_config', JPATH_ADMINISTRATOR, null, true); + } $this->cliInput = $input; $this->ioStyle = new SymfonyStyle($input, $output); } @@ -283,7 +285,7 @@ public function checkDb($options): bool } // Validate database table prefix. - if (isset($options['dbprefix']) && !preg_match('#^[a-zA-Z]+[a-zA-Z0-9_]*$#', (string) $options['dbprefix'])) { + if (isset($options['dbprefix']) && !preg_match('#^[a-zA-Z]+\w*$#', (string) $options['dbprefix'])) { $this->ioStyle->error(Text::_('INSTL_DATABASE_PREFIX_MSG')); return false; @@ -317,12 +319,9 @@ public function checkDb($options): bool } // Workaround for UPPERCASE table prefix for PostgreSQL - if (\in_array($options['dbtype'], ['pgsql', 'postgresql'])) { - if (isset($options['dbprefix']) && strtolower((string) $options['dbprefix']) !== $options['dbprefix']) { - $this->ioStyle->error(Text::_('INSTL_DATABASE_FIX_LOWERCASE')); - - return false; - } + if (\in_array($options['dbtype'], ['pgsql', 'postgresql']) && (isset($options['dbprefix']) && strtolower((string) $options['dbprefix']) !== $options['dbprefix'])) { + $this->ioStyle->error(Text::_('INSTL_DATABASE_FIX_LOWERCASE')); + return false; } $app = $this->getApplication(); diff --git a/libraries/src/Console/TasksRunCommand.php b/libraries/src/Console/TasksRunCommand.php index 3d09eeecd8b1b..1c3a6bc3f0a14 100644 --- a/libraries/src/Console/TasksRunCommand.php +++ b/libraries/src/Console/TasksRunCommand.php @@ -91,7 +91,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in return Status::NO_TASK; } - if (!$records) { + if ($records === []) { $this->ioStyle->writeln('No tasks due!'); return Status::NO_TASK; @@ -104,7 +104,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in foreach ($records as $record) { $cStart = microtime(true); $task = $scheduler->runTask(['id' => $record->id, 'allowDisabled' => true, 'allowConcurrent' => true]); - $exit = empty($task) ? Status::NO_RUN : $task->getContent()['status']; + $exit = $task instanceof \Joomla\Component\Scheduler\Administrator\Task\Task ? $task->getContent()['status'] : Status::NO_RUN; $duration = microtime(true) - $cStart; $key = (\array_key_exists($exit, $outTextMap)) ? $exit : 'N/A'; $this->ioStyle->writeln(\sprintf($outTextMap[$key], $record->id, $record->title, $duration, $exit)); diff --git a/libraries/src/Console/TasksStateCommand.php b/libraries/src/Console/TasksStateCommand.php index f7fc3fc428a3e..c9c5a48fbe8d9 100644 --- a/libraries/src/Console/TasksStateCommand.php +++ b/libraries/src/Console/TasksStateCommand.php @@ -79,7 +79,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in $state = (string) $input->getOption('state'); // Try to validate and process ID, if passed - if (\strlen($id)) { + if (\strlen($id) !== 0) { if (!Task::isValidId($id)) { $this->ioStyle->error('Invalid id passed!'); @@ -90,7 +90,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in } // Try to validate and process state, if passed - if (\strlen($state)) { + if (\strlen($state) !== 0) { // If we get the logical state, we try to get the enumeration (but as a string) if (!is_numeric($state)) { $state = (string) ArrayHelper::arraySearch($state, Task::STATE_MAP); diff --git a/libraries/src/Console/UpdateCoreCommand.php b/libraries/src/Console/UpdateCoreCommand.php index 3b50c4ea83029..26229ffd8b93e 100644 --- a/libraries/src/Console/UpdateCoreCommand.php +++ b/libraries/src/Console/UpdateCoreCommand.php @@ -347,7 +347,7 @@ public function setUpdateInfo($data): void */ public function getUpdateModel() { - if (!isset($this->updateModel)) { + if ($this->updateModel === null) { $this->setUpdateModel(); } diff --git a/libraries/src/Crypt/Crypt.php b/libraries/src/Crypt/Crypt.php index 2b134dee8addc..1b37d4cc48494 100644 --- a/libraries/src/Crypt/Crypt.php +++ b/libraries/src/Crypt/Crypt.php @@ -57,7 +57,7 @@ public static function timingSafeCompare($known, $unknown) $safeLen = \strlen($known); $userLen = \strlen($unknown); - if ($userLen != $safeLen) { + if ($userLen !== $safeLen) { return false; } @@ -130,11 +130,7 @@ public static function safeSubstr($str, $start, $length = null) if ($exists) { // In PHP 5.3 mb_substr($str, 0, NULL, '8bit') returns an empty string, so we have to find the length ourselves. if ($length === null) { - if ($start >= 0) { - $length = static::safeStrlen($str) - $start; - } else { - $length = -$start; - } + $length = $start >= 0 ? static::safeStrlen($str) - $start : -$start; } return mb_substr($str, $start, $length, '8bit'); diff --git a/libraries/src/Date/Date.php b/libraries/src/Date/Date.php index 1100740d6bf83..504c8ba1c9343 100644 --- a/libraries/src/Date/Date.php +++ b/libraries/src/Date/Date.php @@ -106,11 +106,7 @@ public function __construct($date = 'now', $tz = null) // If the time zone object is not set, attempt to build it. if (!($tz instanceof \DateTimeZone)) { - if (\is_string($tz)) { - $tz = new \DateTimeZone($tz); - } else { - $tz = new \DateTimeZone('UTC'); - } + $tz = \is_string($tz) ? new \DateTimeZone($tz) : new \DateTimeZone('UTC'); } // Backup active time zone @@ -339,7 +335,7 @@ public function format($format, $local = false, $translate = true): string */ public function getOffsetFromGmt($hours = false) { - return (float) $hours ? ($this->tz->getOffset($this) / 3600) : $this->tz->getOffset($this); + return (float) $hours !== 0.0 ? ($this->tz->getOffset($this) / 3600) : $this->tz->getOffset($this); } /** @@ -417,7 +413,7 @@ public function toISO8601($local = false) */ public function toSql($local = false, ?DatabaseDriver $db = null) { - if ($db === null) { + if (!$db instanceof \Joomla\Database\DatabaseDriver) { $db = Factory::getDbo(); } diff --git a/libraries/src/Dispatcher/AbstractModuleDispatcher.php b/libraries/src/Dispatcher/AbstractModuleDispatcher.php index dc25399578e50..c58bf8e5a1594 100644 --- a/libraries/src/Dispatcher/AbstractModuleDispatcher.php +++ b/libraries/src/Dispatcher/AbstractModuleDispatcher.php @@ -128,9 +128,8 @@ protected function loadLanguage() $langPaths = $language->getPaths(); // Only load the module's language file if it hasn't been already - if (!$langPaths || (!isset($langPaths[$coreLanguageDirectory]) && !isset($langPaths[$extensionLanguageDirectory]))) { - // 1.5 or Core then 1.6 3PD - $language->load($this->module->module, $coreLanguageDirectory) || + // 1.5 or Core then 1.6 3PD + if ((!$langPaths || !isset($langPaths[$coreLanguageDirectory]) && !isset($langPaths[$extensionLanguageDirectory])) && !$language->load($this->module->module, $coreLanguageDirectory)) { $language->load($this->module->module, $extensionLanguageDirectory); } } diff --git a/libraries/src/Dispatcher/ApiDispatcher.php b/libraries/src/Dispatcher/ApiDispatcher.php index 1944a1d26d2b1..72194dc260f2f 100644 --- a/libraries/src/Dispatcher/ApiDispatcher.php +++ b/libraries/src/Dispatcher/ApiDispatcher.php @@ -31,9 +31,9 @@ final class ApiDispatcher extends ComponentDispatcher protected function loadLanguage() { // Load common and local language files. - $this->app->getLanguage()->load($this->option, JPATH_BASE) || - $this->app->getLanguage()->load($this->option, JPATH_ADMINISTRATOR) || - $this->app->getLanguage()->load($this->option, JPATH_COMPONENT_ADMINISTRATOR); + if (!$this->app->getLanguage()->load($this->option, JPATH_BASE) && !$this->app->getLanguage()->load($this->option, JPATH_ADMINISTRATOR)) { + $this->app->getLanguage()->load($this->option, JPATH_COMPONENT_ADMINISTRATOR); + } } /** diff --git a/libraries/src/Dispatcher/ComponentDispatcher.php b/libraries/src/Dispatcher/ComponentDispatcher.php index 6387f5a4e363f..b223f82d9e5d6 100644 --- a/libraries/src/Dispatcher/ComponentDispatcher.php +++ b/libraries/src/Dispatcher/ComponentDispatcher.php @@ -84,8 +84,9 @@ public function __construct(CMSApplicationInterface $app, Input $input, MVCFacto protected function loadLanguage() { // Load common and local language files. - $this->app->getLanguage()->load($this->option, JPATH_BASE) || - $this->app->getLanguage()->load($this->option, JPATH_COMPONENT); + if (!$this->app->getLanguage()->load($this->option, JPATH_BASE)) { + $this->app->getLanguage()->load($this->option, JPATH_COMPONENT); + } } /** diff --git a/libraries/src/Dispatcher/LegacyComponentDispatcher.php b/libraries/src/Dispatcher/LegacyComponentDispatcher.php index 7351673c5666b..f27162255cc43 100644 --- a/libraries/src/Dispatcher/LegacyComponentDispatcher.php +++ b/libraries/src/Dispatcher/LegacyComponentDispatcher.php @@ -62,7 +62,9 @@ public function dispatch() $lang = $this->app->getLanguage(); // Load common and local language files. - $lang->load($this->app->scope, JPATH_BASE) || $lang->load($this->app->scope, JPATH_COMPONENT); + if (!$lang->load($this->app->scope, JPATH_BASE)) { + $lang->load($this->app->scope, JPATH_COMPONENT); + } // Execute the component $loader = static function ($path) { diff --git a/libraries/src/Document/ErrorDocument.php b/libraries/src/Document/ErrorDocument.php index b1619728b9129..0f6f13b932d38 100644 --- a/libraries/src/Document/ErrorDocument.php +++ b/libraries/src/Document/ErrorDocument.php @@ -111,8 +111,8 @@ public function loadRenderer($type) public function render($cache = false, $params = []) { // If no error object is set return null - if (!isset($this->_error)) { - return; + if ($this->_error === null) { + return null; } // Set the status header @@ -149,8 +149,8 @@ public function render($cache = false, $params = []) public function renderBacktrace() { // If no error object is set return null - if (!isset($this->_error)) { - return; + if ($this->_error === null) { + return null; } // The back trace diff --git a/libraries/src/Document/Factory.php b/libraries/src/Document/Factory.php index e56a5def83025..9c15f3a4446b7 100644 --- a/libraries/src/Document/Factory.php +++ b/libraries/src/Document/Factory.php @@ -84,7 +84,7 @@ public function createDocument(string $type = 'html', array $attributes = []): D */ public function createRenderer(Document $document, string $type, string $docType = ''): RendererInterface { - $docType = $docType ? ucfirst($docType) : ucfirst($document->getType()); + $docType = $docType !== '' && $docType !== '0' ? ucfirst($docType) : ucfirst($document->getType()); // Determine the path and class $class = __NAMESPACE__ . '\\Renderer\\' . $docType . '\\' . ucfirst($type) . 'Renderer'; diff --git a/libraries/src/Document/HtmlDocument.php b/libraries/src/Document/HtmlDocument.php index e5f4b223e4cca..e925a1061f9e2 100644 --- a/libraries/src/Document/HtmlDocument.php +++ b/libraries/src/Document/HtmlDocument.php @@ -771,10 +771,11 @@ protected function _fetchTemplate($params = []) $lang = CmsFactory::getLanguage(); // 1.5 or core then 1.6 - $lang->load('tpl_' . $template, JPATH_BASE) + if (!($lang->load('tpl_' . $template, JPATH_BASE) || ($inherits !== '' && $lang->load('tpl_' . $inherits, JPATH_BASE)) - || $lang->load('tpl_' . $template, $directory . '/' . $template) - || ($inherits !== '' && $lang->load('tpl_' . $inherits, $directory . '/' . $inherits)); + || $lang->load('tpl_' . $template, $directory . '/' . $template)) && $inherits !== '') { + $lang->load('tpl_' . $inherits, $directory . '/' . $inherits); + } // Assign the variables $this->baseurl = Uri::base(true); diff --git a/libraries/src/Document/OpensearchDocument.php b/libraries/src/Document/OpensearchDocument.php index 2b2f045b8bc50..f8edc535d1275 100644 --- a/libraries/src/Document/OpensearchDocument.php +++ b/libraries/src/Document/OpensearchDocument.php @@ -93,7 +93,7 @@ public function __construct($options = []) if ($path == '') { $favicon->data = Uri::base() . 'favicon.ico'; } else { - if ($path[0] == '/') { + if ($path[0] === '/') { $path = substr($path, 1); } diff --git a/libraries/src/Document/Renderer/Html/MessageRenderer.php b/libraries/src/Document/Renderer/Html/MessageRenderer.php index 29891ed6e155e..108c3de67cb71 100644 --- a/libraries/src/Document/Renderer/Html/MessageRenderer.php +++ b/libraries/src/Document/Renderer/Html/MessageRenderer.php @@ -80,7 +80,7 @@ private function getData() $messages = Factory::getApplication()->getMessageQueue(); // Build the sorted message list - if (\is_array($messages) && !empty($messages)) { + if (\is_array($messages) && $messages !== []) { foreach ($messages as $msg) { if (isset($msg['type']) && isset($msg['message'])) { $lists[$msg['type']][] = $msg['message']; diff --git a/libraries/src/Document/Renderer/Html/MetasRenderer.php b/libraries/src/Document/Renderer/Html/MetasRenderer.php index 26b0b082e8595..8fdb3049b70ee 100644 --- a/libraries/src/Document/Renderer/Html/MetasRenderer.php +++ b/libraries/src/Document/Renderer/Html/MetasRenderer.php @@ -182,10 +182,8 @@ public function render($head, $params = [], $content = null) foreach ($this->_doc->_links as $link => $linkAtrr) { $buffer .= $tab . 'render($mod, $params, $content); - if ($frontediting && trim($moduleHtml) != '' && $user->authorise('module.edit.frontend', 'com_modules.module.' . $mod->id)) { + if ($frontediting && trim($moduleHtml) !== '' && $user->authorise('module.edit.frontend', 'com_modules.module.' . $mod->id)) { $displayData = ['moduleHtml' => &$moduleHtml, 'module' => $mod, 'position' => $position, 'menusediting' => $menusEditing]; LayoutHelper::render('joomla.edit.frontediting_modules', $displayData); } diff --git a/libraries/src/Document/Renderer/Html/ScriptsRenderer.php b/libraries/src/Document/Renderer/Html/ScriptsRenderer.php index 0be4e79426f20..86fb9cd377b0c 100644 --- a/libraries/src/Document/Renderer/Html/ScriptsRenderer.php +++ b/libraries/src/Document/Renderer/Html/ScriptsRenderer.php @@ -68,7 +68,7 @@ public function render($head, $params = [], $content = null) $asset = $item instanceof WebAssetItemInterface ? $item : null; // Add src attribute for non Asset item - if (!$asset) { + if (!$asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface) { $item['src'] = $key; } @@ -138,7 +138,7 @@ private function renderElement($item): string { $buffer = ''; $asset = $item instanceof WebAssetItemInterface ? $item : null; - $src = $asset ? $asset->getUri() : ($item['src'] ?? ''); + $src = $asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface ? $asset->getUri() : ($item['src'] ?? ''); // Make sure we have a src, and it not already rendered if (!$src || !empty($this->renderedSrc[$src])) { @@ -150,7 +150,7 @@ private function renderElement($item): string $mediaVersion = $this->_doc->getMediaVersion(); // Get the attributes and other options - if ($asset) { + if ($asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface) { $attribs = $asset->getAttributes(); $version = $asset->getVersion(); $conditional = $asset->getOption('conditional'); @@ -173,7 +173,7 @@ private function renderElement($item): string } else { $attribs = $item; $version = $attribs['options']['version'] ?? ''; - $conditional = !empty($attribs['options']['conditional']) ? $attribs['options']['conditional'] : null; + $conditional = empty($attribs['options']['conditional']) ? null : $attribs['options']['conditional']; } // Add "nonce" attribute if exist @@ -315,7 +315,7 @@ private function renderAttributes(array $attributes): string if (!($this->_doc->isHtml5() && $isNoValueAttrib)) { // Json encode value if it's an array. - $value = !\is_scalar($value) ? json_encode($value) : $value; + $value = \is_scalar($value) ? $value : json_encode($value); $buffer .= '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"'; } @@ -371,7 +371,7 @@ private function renderImportmap(array &$assets) unset($assets[$k]); } - if (!empty($importmap['imports'])) { + if (isset($importmap['imports']) && $importmap['imports'] !== []) { // Add polyfill when exists if (!empty($assets['es-module-shims'])) { $buffer .= $this->renderElement($assets['es-module-shims']); diff --git a/libraries/src/Document/Renderer/Html/StylesRenderer.php b/libraries/src/Document/Renderer/Html/StylesRenderer.php index 61adf99654c6b..75b7a3e8acd65 100644 --- a/libraries/src/Document/Renderer/Html/StylesRenderer.php +++ b/libraries/src/Document/Renderer/Html/StylesRenderer.php @@ -62,7 +62,7 @@ public function render($head, $params = [], $content = null) $asset = $item instanceof WebAssetItemInterface ? $item : null; // Add href attribute for non Asset item - if (!$asset) { + if (!$asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface) { $item['href'] = $key; } @@ -127,7 +127,7 @@ private function renderElement($item): string { $buffer = ''; $asset = $item instanceof WebAssetItemInterface ? $item : null; - $src = $asset ? $asset->getUri() : ($item['href'] ?? ''); + $src = $asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface ? $asset->getUri() : ($item['href'] ?? ''); // Make sure we have a src, and it not already rendered if (!$src || !empty($this->renderedSrc[$src])) { @@ -139,7 +139,7 @@ private function renderElement($item): string $mediaVersion = $this->_doc->getMediaVersion(); // Get the attributes and other options - if ($asset) { + if ($asset instanceof \Joomla\CMS\WebAsset\WebAssetItemInterface) { $attribs = $asset->getAttributes(); $version = $asset->getVersion(); $conditional = $asset->getOption('conditional'); @@ -162,7 +162,7 @@ private function renderElement($item): string } else { $attribs = $item; $version = $attribs['options']['version'] ?? ''; - $conditional = !empty($attribs['options']['conditional']) ? $attribs['options']['conditional'] : null; + $conditional = empty($attribs['options']['conditional']) ? null : $attribs['options']['conditional']; } // Add "nonce" attribute if exist @@ -313,7 +313,7 @@ private function renderAttributes(array $attributes): string if (!($this->_doc->isHtml5() && $isNoValueAttrib)) { // Json encode value if it's an array. - $value = !\is_scalar($value) ? json_encode($value) : $value; + $value = \is_scalar($value) ? $value : json_encode($value); $buffer .= '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"'; } diff --git a/libraries/src/Editor/AbstractEditorProvider.php b/libraries/src/Editor/AbstractEditorProvider.php index fd3efb5f1d6ff..dde6f3740c3ba 100644 --- a/libraries/src/Editor/AbstractEditorProvider.php +++ b/libraries/src/Editor/AbstractEditorProvider.php @@ -95,6 +95,6 @@ protected function displayButtons($buttons, array $options = []) { $list = $this->getButtons($buttons, $options); - return $list ? LayoutHelper::render('joomla.editors.buttons', $list) : ''; + return $list !== [] ? LayoutHelper::render('joomla.editors.buttons', $list) : ''; } } diff --git a/libraries/src/Editor/Button/ButtonsRegistry.php b/libraries/src/Editor/Button/ButtonsRegistry.php index 25c895b80652e..c5396e4b47129 100644 --- a/libraries/src/Editor/Button/ButtonsRegistry.php +++ b/libraries/src/Editor/Button/ButtonsRegistry.php @@ -139,7 +139,7 @@ public function initRegistry(array $options = []): ButtonsRegistryInterface continue; } - $options = !empty($props['options']) ? $props['options'] : []; + $options = empty($props['options']) ? [] : $props['options']; // Some very old buttons use string for options, but this does not work since Joomla 3, so we reset it here $options = \is_array($options) ? $options : []; unset($props['options']); diff --git a/libraries/src/Encrypt/AES/Mcrypt.php b/libraries/src/Encrypt/AES/Mcrypt.php index 207b70e46b375..788e8d84ce75f 100644 --- a/libraries/src/Encrypt/AES/Mcrypt.php +++ b/libraries/src/Encrypt/AES/Mcrypt.php @@ -175,12 +175,7 @@ public function isSupported() } $algorigthms = hash_algos(); - - if (!\in_array('sha256', $algorigthms)) { - return false; - } - - return true; + return \in_array('sha256', $algorigthms); } /** diff --git a/libraries/src/Encrypt/AES/OpenSSL.php b/libraries/src/Encrypt/AES/OpenSSL.php index 9925250da571b..d129f7928e8ae 100644 --- a/libraries/src/Encrypt/AES/OpenSSL.php +++ b/libraries/src/Encrypt/AES/OpenSSL.php @@ -200,12 +200,7 @@ public function isSupported() } $algorithms = hash_algos(); - - if (!\in_array('sha256', $algorithms)) { - return false; - } - - return true; + return \in_array('sha256', $algorithms); } /** diff --git a/libraries/src/Encrypt/Aes.php b/libraries/src/Encrypt/Aes.php index c86af4472704e..4decc8d11382d 100644 --- a/libraries/src/Encrypt/Aes.php +++ b/libraries/src/Encrypt/Aes.php @@ -188,12 +188,7 @@ public static function isSupported() } $algorithms = hash_algos(); - - if (!\in_array('sha256', $algorithms)) { - return false; - } - - return true; + return \in_array('sha256', $algorithms); } /** @@ -259,7 +254,7 @@ function hash_pbkdf2($algo, $password, $salt, $count, $length = 0, $rawOutput = } $output = ''; - $block_count = $length ? ceil($length / \strlen(hash($algo, '', $rawOutput))) : 1; + $block_count = $length !== 0 ? ceil($length / \strlen(hash($algo, '', $rawOutput))) : 1; for ($i = 1; $i <= $block_count; $i++) { $last = $xorsum = hash_hmac($algo, $salt . pack('N', $i), $password, true); @@ -275,6 +270,6 @@ function hash_pbkdf2($algo, $password, $salt, $count, $length = 0, $rawOutput = $output = bin2hex($output); } - return $length ? substr($output, 0, $length) : $output; + return $length !== 0 ? substr($output, 0, $length) : $output; } } diff --git a/libraries/src/Encrypt/Totp.php b/libraries/src/Encrypt/Totp.php index 6ed59e5fb0b6a..4cf7cfdd6ee99 100644 --- a/libraries/src/Encrypt/Totp.php +++ b/libraries/src/Encrypt/Totp.php @@ -62,11 +62,7 @@ public function __construct(/** { $this->_pinModulo = 10 ** $this->_passCodeLength; - if (\is_null($base32)) { - $this->_base32 = new Base32(); - } else { - $this->_base32 = $base32; - } + $this->_base32 = \is_null($base32) ? new Base32() : $base32; } /** diff --git a/libraries/src/Error/Renderer/CliRenderer.php b/libraries/src/Error/Renderer/CliRenderer.php index 52ca9a8052358..41997143f0e16 100644 --- a/libraries/src/Error/Renderer/CliRenderer.php +++ b/libraries/src/Error/Renderer/CliRenderer.php @@ -43,7 +43,7 @@ public function render(\Throwable $error): string { $buffer = PHP_EOL . 'Error occurred: ' . $error->getMessage() . PHP_EOL . $this->getTrace($error); - if ($prev = $error->getPrevious()) { + if ($prev = $error->getPrevious() instanceof \Throwable) { $buffer .= PHP_EOL . PHP_EOL . 'Previous Exception: ' . $prev->getMessage() . PHP_EOL . $this->getTrace($prev); } diff --git a/libraries/src/Event/MultiFactor/Callback.php b/libraries/src/Event/MultiFactor/Callback.php index 72d5be7bbb813..34ca8e984086b 100644 --- a/libraries/src/Event/MultiFactor/Callback.php +++ b/libraries/src/Event/MultiFactor/Callback.php @@ -48,7 +48,7 @@ public function __construct(string $method) */ public function setMethod(string $value): string { - if (empty($value)) { + if ($value === '' || $value === '0') { throw new \DomainException(\sprintf("Argument 'method' of event %s must be a non-empty string.", $this->name)); } diff --git a/libraries/src/Event/QuickIcon/GetIconEvent.php b/libraries/src/Event/QuickIcon/GetIconEvent.php index 4b7f47970dc98..a621e8e4146d1 100644 --- a/libraries/src/Event/QuickIcon/GetIconEvent.php +++ b/libraries/src/Event/QuickIcon/GetIconEvent.php @@ -60,7 +60,7 @@ public function __construct(string $name, array $arguments = []) */ public function setContext(string $value) { - if (empty($value)) { + if ($value === '' || $value === '0') { throw new \DomainException(\sprintf("Argument 'context' of event %s must be a non-empty string.", $this->name)); } diff --git a/libraries/src/Event/Result/ResultTypeObjectAware.php b/libraries/src/Event/Result/ResultTypeObjectAware.php index 9fa09be12242f..73cc5c99288a2 100644 --- a/libraries/src/Event/Result/ResultTypeObjectAware.php +++ b/libraries/src/Event/Result/ResultTypeObjectAware.php @@ -82,7 +82,7 @@ public function typeCheckResult($data): void } foreach ($this->resultAcceptableClasses as $className) { - if (is_a($data, $className)) { + if ($data instanceof $className) { return; } } diff --git a/libraries/src/Event/Table/AfterLoadEvent.php b/libraries/src/Event/Table/AfterLoadEvent.php index f2f49f657a33d..ec3eed62db185 100644 --- a/libraries/src/Event/Table/AfterLoadEvent.php +++ b/libraries/src/Event/Table/AfterLoadEvent.php @@ -60,7 +60,7 @@ public function __construct($name, array $arguments = []) */ protected function setResult($value) { - return $value ? true : false; + return $value; } /** diff --git a/libraries/src/Event/Table/AfterStoreEvent.php b/libraries/src/Event/Table/AfterStoreEvent.php index 61942b692fe42..c166ee7999d89 100644 --- a/libraries/src/Event/Table/AfterStoreEvent.php +++ b/libraries/src/Event/Table/AfterStoreEvent.php @@ -55,7 +55,7 @@ public function __construct($name, array $arguments = []) */ protected function setResult($value) { - return $value ? true : false; + return $value; } /** diff --git a/libraries/src/Event/Table/BeforeLoadEvent.php b/libraries/src/Event/Table/BeforeLoadEvent.php index b67007d52b854..a85a229da8928 100644 --- a/libraries/src/Event/Table/BeforeLoadEvent.php +++ b/libraries/src/Event/Table/BeforeLoadEvent.php @@ -58,7 +58,7 @@ public function __construct($name, array $arguments = []) */ protected function setReset($value) { - return $value ? true : false; + return (bool) $value; } /** diff --git a/libraries/src/Event/Table/BeforeStoreEvent.php b/libraries/src/Event/Table/BeforeStoreEvent.php index e53d7fad8362f..99a02fff295c8 100644 --- a/libraries/src/Event/Table/BeforeStoreEvent.php +++ b/libraries/src/Event/Table/BeforeStoreEvent.php @@ -58,7 +58,7 @@ public function __construct($name, array $arguments = []) */ protected function setUpdateNulls($value) { - return $value ? true : false; + return (bool) $value; } /** diff --git a/libraries/src/Event/User/AuthenticationEvent.php b/libraries/src/Event/User/AuthenticationEvent.php index f7c75ca1210fc..a782f802d06b6 100644 --- a/libraries/src/Event/User/AuthenticationEvent.php +++ b/libraries/src/Event/User/AuthenticationEvent.php @@ -70,11 +70,7 @@ public function isStopped() // Check Response status $response = $this->getAuthenticationResponse(); - if ($response->status === Authentication::STATUS_SUCCESS) { - return true; - } - - return false; + return $response->status === Authentication::STATUS_SUCCESS; } /** diff --git a/libraries/src/Feed/Feed.php b/libraries/src/Feed/Feed.php index 88513ca539f25..aa343e3957f06 100644 --- a/libraries/src/Feed/Feed.php +++ b/libraries/src/Feed/Feed.php @@ -85,7 +85,7 @@ public function __set($name, $value) } // Validate that any authors that are set are instances of JFeedPerson or null. - if (($name === 'author') && (!($value instanceof FeedPerson) || ($value === null))) { + if (($name === 'author') && (!($value instanceof FeedPerson) || (!$value instanceof \Joomla\CMS\Feed\FeedPerson))) { throw new \InvalidArgumentException( \sprintf( '%1$s "author" must be an instance of Joomla\\CMS\\Feed\\FeedPerson. %2$s given.', @@ -359,7 +359,7 @@ public function setAuthor($name, $email, $uri = null, $type = null) */ public function reverseItems() { - if (\is_array($this->entries) && !empty($this->entries)) { + if (\is_array($this->entries) && $this->entries !== []) { $this->entries = array_reverse($this->entries); } diff --git a/libraries/src/Feed/FeedEntry.php b/libraries/src/Feed/FeedEntry.php index 8a1ae410e7752..18dba12461a5e 100644 --- a/libraries/src/Feed/FeedEntry.php +++ b/libraries/src/Feed/FeedEntry.php @@ -80,7 +80,7 @@ public function __set($name, $value) } // Validate that any authors that are set are instances of JFeedPerson or null. - if (($name === 'author') && (!($value instanceof FeedPerson) || ($value === null))) { + if (($name === 'author') && (!($value instanceof FeedPerson) || (!$value instanceof \Joomla\CMS\Feed\FeedPerson))) { throw new \InvalidArgumentException( \sprintf( '%1$s "author" must be an instance of Joomla\\CMS\\Feed\\FeedPerson. %2$s given.', @@ -91,7 +91,7 @@ public function __set($name, $value) } // Validate that any sources that are set are instances of JFeed or null. - if (($name === 'source') && (!($value instanceof Feed) || ($value === null))) { + if (($name === 'source') && (!($value instanceof Feed) || (!$value instanceof \Joomla\CMS\Feed\Feed))) { throw new \InvalidArgumentException( \sprintf( '%1$s "source" must be an instance of Joomla\\CMS\\Feed\\Feed. %2$s given.', diff --git a/libraries/src/Feed/Parser/AtomParser.php b/libraries/src/Feed/Parser/AtomParser.php index 9f0ca5c2b4839..6a1b31c5a8b86 100644 --- a/libraries/src/Feed/Parser/AtomParser.php +++ b/libraries/src/Feed/Parser/AtomParser.php @@ -223,13 +223,13 @@ protected function processFeedEntry(FeedEntry $entry, \SimpleXMLElement $el) if (filter_var($entry->uri, FILTER_VALIDATE_URL) === false && !\is_null($el->link) && $el->link) { $link = $el->link; - if ($link->count()) { + if ($link->count() !== 0) { $link = $this->bestLinkForUri($link); } $uri = (string) $link['href']; - if ($uri) { + if ($uri !== '' && $uri !== '0') { $entry->uri = $uri; } } diff --git a/libraries/src/Filesystem/File.php b/libraries/src/Filesystem/File.php index 82aa3a46fcf26..54f8c5ea3eb17 100644 --- a/libraries/src/Filesystem/File.php +++ b/libraries/src/Filesystem/File.php @@ -155,25 +155,19 @@ public static function copy($src, $dest, $path = null, $useStreams = false) if ($FTPOptions['enabled'] == 1) { // Connect the FTP client $ftp = FtpClient::getInstance($FTPOptions['host'], $FTPOptions['port'], [], $FTPOptions['user'], $FTPOptions['pass']); - // If the parent folder doesn't exist we must create it if (!file_exists(\dirname($dest))) { Folder::create(\dirname($dest)); } - // Translate the destination path for the FTP account $dest = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dest), '/'); - if (!$ftp->store($src, $dest)) { // FTP connector throws an error return false; } - } else { - if (!@ copy($src, $dest)) { - Log::add(Text::sprintf('JLIB_FILESYSTEM_ERROR_COPY_FAILED_ERR01', $src, $dest), Log::WARNING, 'jerror'); - - return false; - } + } elseif (!@ copy($src, $dest)) { + Log::add(Text::sprintf('JLIB_FILESYSTEM_ERROR_COPY_FAILED_ERR01', $src, $dest), Log::WARNING, 'jerror'); + return false; } self::invalidateFileCache($dest); @@ -364,23 +358,18 @@ public static function move($src, $dest, $path = '', $useStreams = false) if ($FTPOptions['enabled'] == 1) { // Connect the FTP client $ftp = FtpClient::getInstance($FTPOptions['host'], $FTPOptions['port'], [], $FTPOptions['user'], $FTPOptions['pass']); - // Translate path for the FTP account $src = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $src), '/'); $dest = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dest), '/'); - // Use FTP rename to simulate move if (!$ftp->rename($src, $dest)) { Log::add(Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'), Log::WARNING, 'jerror'); return false; } - } else { - if (!@ rename($src, $dest)) { - Log::add(Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'), Log::WARNING, 'jerror'); - - return false; - } + } elseif (!@ rename($src, $dest)) { + Log::add(Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'), Log::WARNING, 'jerror'); + return false; } self::invalidateFileCache($dest); @@ -408,10 +397,8 @@ public static function write($file, $buffer, $useStreams = false) } // If the destination directory doesn't exist we need to create it - if (!file_exists(\dirname($file))) { - if (Folder::create(\dirname($file)) == false) { - return false; - } + if (!file_exists(\dirname($file)) && Folder::create(\dirname($file)) == false) { + return false; } if ($useStreams) { diff --git a/libraries/src/Filesystem/FilesystemHelper.php b/libraries/src/Filesystem/FilesystemHelper.php index c74293d34ac0e..d597473055f23 100644 --- a/libraries/src/Filesystem/FilesystemHelper.php +++ b/libraries/src/Filesystem/FilesystemHelper.php @@ -106,6 +106,7 @@ public static function remotefsize($url) return $ftpsize; } + return null; } /** diff --git a/libraries/src/Filesystem/Folder.php b/libraries/src/Filesystem/Folder.php index 34f3799f92931..24f6a6f4f81af 100644 --- a/libraries/src/Filesystem/Folder.php +++ b/libraries/src/Filesystem/Folder.php @@ -90,7 +90,7 @@ public static function copy($src, $dest, $path = '', $force = false, $useStreams switch (filetype($sfid)) { case 'dir': - if ($file != '.' && $file != '..') { + if ($file !== '.' && $file !== '..') { $ret = self::copy($sfid, $dfid, null, $force); if ($ret !== true) { @@ -121,7 +121,7 @@ public static function copy($src, $dest, $path = '', $force = false, $useStreams switch (filetype($sfid)) { case 'dir': - if ($file != '.' && $file != '..') { + if ($file !== '.' && $file !== '..') { $ret = self::copy($sfid, $dfid, null, $force, $useStreams); if ($ret !== true) { @@ -133,7 +133,6 @@ public static function copy($src, $dest, $path = '', $force = false, $useStreams case 'file': if ($useStreams) { $stream = Factory::getStream(); - if (!$stream->copy($sfid, $dfid)) { throw new \RuntimeException( \sprintf( @@ -143,10 +142,8 @@ public static function copy($src, $dest, $path = '', $force = false, $useStreams -1 ); } - } else { - if (!@copy($sfid, $dfid)) { - throw new \RuntimeException('Copy file failed', -1); - } + } elseif (!@copy($sfid, $dfid)) { + throw new \RuntimeException('Copy file failed', -1); } break; } @@ -223,16 +220,10 @@ public static function create($path = '', $mode = 0755) // If open_basedir is set we need to get the open_basedir that the path is in if ($obd != null) { - if (IS_WIN) { - $obdSeparator = ';'; - } else { - $obdSeparator = ':'; - } - + $obdSeparator = IS_WIN ? ';' : ':'; // Create the array of open_basedir paths $obdArray = explode($obdSeparator, $obd); $inBaseDir = false; - // Iterate through open_basedir paths looking for a match foreach ($obdArray as $test) { $test = Path::clean($test); @@ -242,7 +233,6 @@ public static function create($path = '', $mode = 0755) break; } } - if ($inBaseDir == false) { // Return false for JFolder::create because the path to be created is not in open_basedir Log::add(__METHOD__ . ': ' . Text::_('JLIB_FILESYSTEM_ERROR_FOLDER_PATH'), Log::WARNING, 'jerror'); @@ -314,11 +304,9 @@ public static function delete($path) // Remove all the files in folder if they exist; disable all filtering $files = self::files($path, '.', false, true, [], []); - if (!empty($files)) { - if (File::delete($files) !== true) { - // File::delete throws an error - return false; - } + if (!empty($files) && File::delete($files) !== true) { + // File::delete throws an error + return false; } // Remove sub-folders of folder; disable all filtering @@ -394,34 +382,27 @@ public static function move($src, $dest, $path = '', $useStreams = false) if ($useStreams) { $stream = Factory::getStream(); - if (!$stream->move($src, $dest)) { return Text::sprintf('JLIB_FILESYSTEM_ERROR_FOLDER_RENAME', $stream->getError()); } - + $ret = true; + } elseif ($FTPOptions['enabled'] == 1) { + // Connect the FTP client + $ftp = FtpClient::getInstance($FTPOptions['host'], $FTPOptions['port'], [], $FTPOptions['user'], $FTPOptions['pass']); + // Translate path for the FTP account + $src = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $src), '/'); + $dest = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dest), '/'); + // Use FTP rename to simulate move + if (!$ftp->rename($src, $dest)) { + return Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'); + } $ret = true; } else { - if ($FTPOptions['enabled'] == 1) { - // Connect the FTP client - $ftp = FtpClient::getInstance($FTPOptions['host'], $FTPOptions['port'], [], $FTPOptions['user'], $FTPOptions['pass']); - - // Translate path for the FTP account - $src = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $src), '/'); - $dest = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dest), '/'); - - // Use FTP rename to simulate move - if (!$ftp->rename($src, $dest)) { - return Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'); - } - - $ret = true; - } else { - if (!@rename($src, $dest)) { - return Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'); - } - - $ret = true; + if (!@rename($src, $dest)) { + return Text::_('JLIB_FILESYSTEM_ERROR_RENAME_FILE'); } + + $ret = true; } return $ret; @@ -481,11 +462,7 @@ public static function files( } // Compute the excludefilter string - if (\count($excludeFilter)) { - $excludeFilterString = '/(' . implode('|', $excludeFilter) . ')/'; - } else { - $excludeFilterString = ''; - } + $excludeFilterString = \count($excludeFilter) ? '/(' . implode('|', $excludeFilter) . ')/' : ''; // Get the files $arr = self::_items($path, $filter, $recurse, $full, $exclude, $excludeFilterString, true); @@ -536,11 +513,7 @@ public static function folders( } // Compute the excludefilter string - if (\count($excludeFilter)) { - $excludeFilterString = '/(' . implode('|', $excludeFilter) . ')/'; - } else { - $excludeFilterString = ''; - } + $excludeFilterString = \count($excludeFilter) ? '/(' . implode('|', $excludeFilter) . ')/' : ''; // Get the folders $arr = self::_items($path, $filter, $recurse, $full, $exclude, $excludeFilterString, false); @@ -583,7 +556,7 @@ protected static function _items($path, $filter, $recurse, $full, $exclude, $exc while (($file = readdir($handle)) !== false) { if ( - $file != '.' && $file != '..' && !\in_array($file, $exclude) + $file !== '.' && $file !== '..' && !\in_array($file, $exclude) && (empty($excludeFilterString) || !preg_match($excludeFilterString, $file)) ) { // Compute the fullpath @@ -594,13 +567,7 @@ protected static function _items($path, $filter, $recurse, $full, $exclude, $exc if (($isDir xor $findFiles) && preg_match("/$filter/", $file)) { // (fullpath is dir and folders are searched or fullpath is not dir and files are searched) and file matches the filter - if ($full) { - // Full path is requested - $arr[] = $fullpath; - } else { - // Filename is requested - $arr[] = $file; - } + $arr[] = $full ? $fullpath : $file; } if ($isDir && $recurse) { diff --git a/libraries/src/Filesystem/Path.php b/libraries/src/Filesystem/Path.php index 365028bb4c92b..fca1bc833daa5 100644 --- a/libraries/src/Filesystem/Path.php +++ b/libraries/src/Filesystem/Path.php @@ -84,7 +84,7 @@ public static function isOwner($path) File::write($test, $blank, false); // Test ownership - $return = (fileowner($test) == fileowner($path)); + $return = (fileowner($test) === fileowner($path)); // Delete the test file File::delete($test); diff --git a/libraries/src/Filesystem/Streams/StreamString.php b/libraries/src/Filesystem/Streams/StreamString.php index 0e87c69cb5ebc..7091766f80384 100644 --- a/libraries/src/Filesystem/Streams/StreamString.php +++ b/libraries/src/Filesystem/Streams/StreamString.php @@ -236,11 +236,7 @@ public function stream_tell() */ public function stream_eof() { - if ($this->pos > $this->len) { - return true; - } - - return false; + return $this->pos > $this->len; } /** diff --git a/libraries/src/Filter/InputFilter.php b/libraries/src/Filter/InputFilter.php index 3c9d6fe183357..e42ef628a498c 100644 --- a/libraries/src/Filter/InputFilter.php +++ b/libraries/src/Filter/InputFilter.php @@ -258,10 +258,8 @@ public static function isSafeFile($file, $options = []) $intendedName = array_shift($intendedNames); // 1. Null byte check - if ($options['null_byte']) { - if (strstr((string) $intendedName, "\x00")) { - return false; - } + if ($options['null_byte'] && strstr((string) $intendedName, "\x00")) { + return false; } // 2. PHP-in-extension check (.php, .php.xxx[.yyy[.zzz[...]]], .xxx[.yyy[.zzz[...]]].php) @@ -288,7 +286,7 @@ public static function isSafeFile($file, $options = []) || $options['shorttag_in_content'] || $options['phar_stub_in_content'] || ($options['fobidden_ext_in_content'] && !empty($options['forbidden_extensions'])) ) { - $fp = \strlen((string) $tempName) ? @fopen($tempName, 'r') : false; + $fp = \strlen((string) $tempName) !== 0 ? @fopen($tempName, 'r') : false; if ($fp !== false) { $data = ''; @@ -327,11 +325,9 @@ public static function isSafeFile($file, $options = []) } } - if ($collide) { - // These are suspicious text files which may have the short tag ( $v) { + foreach (array_keys($data[0]) as $k) { $result[$k] = static::decodeFileData([$data[0][$k], $data[1][$k], $data[2][$k], $data[3][$k], $data[4][$k]]); } @@ -424,7 +420,7 @@ protected function decode($source) { static $ttr = []; - if (!\count($ttr)) { + if (\count($ttr) === 0) { // Entity decode $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'ISO-8859-1'); diff --git a/libraries/src/Form/Field/AccessiblemediaField.php b/libraries/src/Form/Field/AccessiblemediaField.php index 4dd5fa29eaa40..79c758710d346 100644 --- a/libraries/src/Form/Field/AccessiblemediaField.php +++ b/libraries/src/Form/Field/AccessiblemediaField.php @@ -151,12 +151,8 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) * If the value is not empty and is not a valid JSON string, * it is most likely a custom field created in Joomla 3 and * the value is a string that contains the file name. - */ - if (is_file(JPATH_ROOT . '/' . $value)) { - $value = '{"imagefile":"' . $value . '","alt_text":""}'; - } else { - $value = ''; - } + */ + $value = is_file(JPATH_ROOT . '/' . $value) ? '{"imagefile":"' . $value . '","alt_text":""}' : ''; } } elseif ( !\is_object($value) diff --git a/libraries/src/Form/Field/AliastagField.php b/libraries/src/Form/Field/AliastagField.php index f2bdd2f7e0edc..909ffaa2457e3 100644 --- a/libraries/src/Form/Field/AliastagField.php +++ b/libraries/src/Form/Field/AliastagField.php @@ -60,8 +60,9 @@ protected function getOptions() foreach ($options as $item) { $parts = explode('.', $item->value); $extension = $parts[0]; - $lang->load($extension . '.sys', JPATH_ADMINISTRATOR) - || $lang->load($extension, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $extension)); + if (!$lang->load($extension . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load($extension, Path::clean(JPATH_ADMINISTRATOR . '/components/' . $extension)); + } $item->text = Text::_(strtoupper($extension) . '_TAGS_' . strtoupper($parts[1])); } diff --git a/libraries/src/Form/Field/CalendarField.php b/libraries/src/Form/Field/CalendarField.php index b7676db859ed5..7444618ee07d3 100644 --- a/libraries/src/Form/Field/CalendarField.php +++ b/libraries/src/Form/Field/CalendarField.php @@ -230,8 +230,8 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $this->filltable = (string) $this->element['filltable'] ?: 'true'; $this->timeformat = (int) $this->element['timeformat'] ?: 24; $this->singleheader = (string) $this->element['singleheader'] ?: 'false'; - $this->minyear = \strlen((string) $this->element['minyear']) ? (int) $this->element['minyear'] : null; - $this->maxyear = \strlen((string) $this->element['maxyear']) ? (int) $this->element['maxyear'] : null; + $this->minyear = \strlen((string) $this->element['minyear']) !== 0 ? (int) $this->element['minyear'] : null; + $this->maxyear = \strlen((string) $this->element['maxyear']) !== 0 ? (int) $this->element['maxyear'] : null; if ($this->maxyear < 0 || $this->minyear > 0) { $this->todaybutton = 'false'; diff --git a/libraries/src/Form/Field/CategoryField.php b/libraries/src/Form/Field/CategoryField.php index 42eb999bbbf1a..8e9579c44ef75 100644 --- a/libraries/src/Form/Field/CategoryField.php +++ b/libraries/src/Form/Field/CategoryField.php @@ -51,16 +51,16 @@ protected function getOptions() $language = (string) $this->element['language']; // Load the category options for a given extension. - if (!empty($extension)) { + if ($extension !== '' && $extension !== '0') { // Filter over published state or not depending upon if it is present. $filters = []; - if ($published) { + if ($published !== '' && $published !== '0') { $filters['filter.published'] = explode(',', $published); } // Filter over language depending upon if it is present. - if ($language) { + if ($language !== '' && $language !== '0') { $filters['filter.language'] = explode(',', $language); } @@ -71,7 +71,7 @@ protected function getOptions() } // Verify permissions. If the action attribute is set, then we scan the options. - if ((string) $this->element['action']) { + if ((string) $this->element['action'] !== '' && (string) $this->element['action'] !== '0') { // Get the current user object. $user = $this->getCurrentUser(); diff --git a/libraries/src/Form/Field/CheckboxField.php b/libraries/src/Form/Field/CheckboxField.php index 7681e9c3306e1..edb47ad4e9f11 100644 --- a/libraries/src/Form/Field/CheckboxField.php +++ b/libraries/src/Form/Field/CheckboxField.php @@ -82,7 +82,7 @@ public function __set($name, $value) { if ($name === 'checked') { $value = (string) $value; - $this->checked = ($value === 'true' || $value == $name || $value === '1'); + $this->checked = ($value === 'true' || $value === $name || $value === '1'); return; } @@ -109,7 +109,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) // Handle the default attribute $default = (string) $element['default']; - if ($default) { + if ($default !== '' && $default !== '0') { $test = $this->form->getValue((string) $element['name'], $group); $value = ($test == $default) ? $default : null; diff --git a/libraries/src/Form/Field/CheckboxesField.php b/libraries/src/Form/Field/CheckboxesField.php index 7dad536ddedf1..71b32c78b267b 100644 --- a/libraries/src/Form/Field/CheckboxesField.php +++ b/libraries/src/Form/Field/CheckboxesField.php @@ -147,7 +147,7 @@ protected function getLayoutData() $data = parent::getLayoutData(); // True if the field has 'value' set. In other words, it has been stored, don't use the default values. - $hasValue = (isset($this->value) && !empty($this->value)); + $hasValue = ($this->value !== null && !empty($this->value)); // If a value has been stored, use it. Otherwise, use the defaults. $checkedOptions = $hasValue ? $this->value : $this->checkedOptions; diff --git a/libraries/src/Form/Field/ColorField.php b/libraries/src/Form/Field/ColorField.php index 4af8e8f47276b..4f706eaa6daae 100644 --- a/libraries/src/Form/Field/ColorField.php +++ b/libraries/src/Form/Field/ColorField.php @@ -276,7 +276,7 @@ protected function getSimpleModeLayoutData() { $colors = strtolower((string) $this->colors); - if (empty($colors)) { + if ($colors === '' || $colors === '0') { $colors = [ 'none', '#049cdb', @@ -300,10 +300,8 @@ protected function getSimpleModeLayoutData() if ($count % 5 == 0) { $split = 5; - } else { - if ($count % 4 == 0) { - $split = 4; - } + } elseif ($count % 4 == 0) { + $split = 4; } } diff --git a/libraries/src/Form/Field/ComponentlayoutField.php b/libraries/src/Form/Field/ComponentlayoutField.php index 62a6c9a64c79e..10269c84b0f6f 100644 --- a/libraries/src/Form/Field/ComponentlayoutField.php +++ b/libraries/src/Form/Field/ComponentlayoutField.php @@ -62,7 +62,7 @@ protected function getInput() // Get the extension. $extension = (string) $this->element['extension']; - if (empty($extension) && ($this->form instanceof Form)) { + if (($extension === '' || $extension === '0') && ($this->form instanceof Form)) { $extension = $this->form->getValue('extension'); } @@ -85,8 +85,9 @@ protected function getInput() if ($extension && $view && $client) { // Load language file $lang = Factory::getLanguage(); - $lang->load($extension . '.sys', JPATH_ADMINISTRATOR) - || $lang->load($extension . '.sys', JPATH_ADMINISTRATOR . '/components/' . $extension); + if (!$lang->load($extension . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load($extension . '.sys', JPATH_ADMINISTRATOR . '/components/' . $extension); + } // Get the database object and a new query object. $db = $this->getDatabase(); @@ -114,7 +115,7 @@ protected function getInput() ->bind(':template', $template); } - if ($template_style_id) { + if ($template_style_id !== 0) { $query->join('LEFT', $db->quoteName('#__template_styles', 's'), $db->quoteName('s.template') . ' = ' . $db->quoteName('e.element')) ->where($db->quoteName('s.id') . ' = :style') ->bind(':style', $template_style_id, ParameterType::INTEGER); @@ -180,8 +181,9 @@ protected function getInput() if ($templates) { foreach ($templates as $template) { // Load language file - $lang->load('tpl_' . $template->element . '.sys', $client->path) - || $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element); + if (!$lang->load('tpl_' . $template->element . '.sys', $client->path)) { + $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element); + } $template_path = Path::clean( $client->path diff --git a/libraries/src/Form/Field/ComponentsField.php b/libraries/src/Form/Field/ComponentsField.php index f1fea01e44a48..1d542b4c4e676 100644 --- a/libraries/src/Form/Field/ComponentsField.php +++ b/libraries/src/Form/Field/ComponentsField.php @@ -66,8 +66,9 @@ protected function getOptions() // Load language $extension = $item->value; - $lang->load("$extension.sys", JPATH_ADMINISTRATOR) - || $lang->load("$extension.sys", JPATH_ADMINISTRATOR . '/components/' . $extension); + if (!$lang->load("$extension.sys", JPATH_ADMINISTRATOR)) { + $lang->load("$extension.sys", JPATH_ADMINISTRATOR . '/components/' . $extension); + } // Translate component name $item->text = Text::_($item->text); diff --git a/libraries/src/Form/Field/ContenttypeField.php b/libraries/src/Form/Field/ContenttypeField.php index f12cbc8973acd..32eda11f4c4a9 100644 --- a/libraries/src/Form/Field/ContenttypeField.php +++ b/libraries/src/Form/Field/ContenttypeField.php @@ -90,8 +90,9 @@ protected function getOptions() $comp = array_shift($parts); // Make sure the component sys.ini is loaded - $lang->load($comp . '.sys', JPATH_ADMINISTRATOR) - || $lang->load($comp . '.sys', JPATH_ADMINISTRATOR . '/components/' . $comp); + if (!$lang->load($comp . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load($comp . '.sys', JPATH_ADMINISTRATOR . '/components/' . $comp); + } $option->string = implode('_', $parts); $option->string = $comp . '_CONTENT_TYPE_' . $option->string; diff --git a/libraries/src/Form/Field/DatabaseconnectionField.php b/libraries/src/Form/Field/DatabaseconnectionField.php index 103b802e35049..7b8261b365770 100644 --- a/libraries/src/Form/Field/DatabaseconnectionField.php +++ b/libraries/src/Form/Field/DatabaseconnectionField.php @@ -76,7 +76,7 @@ protected function getOptions() // This will come into play if an application is installed that requires // a database that is not available on the server. - if (empty($options)) { + if ($options === []) { $options[''] = Text::_('JNONE'); } diff --git a/libraries/src/Form/Field/EditorField.php b/libraries/src/Form/Field/EditorField.php index 5f89fa0d524b4..c3c56cbcdad9d 100644 --- a/libraries/src/Form/Field/EditorField.php +++ b/libraries/src/Form/Field/EditorField.php @@ -164,7 +164,7 @@ public function __set($name, $value) case 'hide': $value = (string) $value; - $this->hide = $value ? explode(',', $value) : []; + $this->hide = $value !== '' && $value !== '0' ? explode(',', $value) : []; break; case 'editorType': @@ -211,11 +211,11 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) } elseif ($buttons === 'false' || $buttons === 'no' || $buttons === '0') { $this->buttons = false; } else { - $this->buttons = !empty($hide) ? explode(',', $buttons) : []; + $this->buttons = $hide === '' || $hide === '0' ? [] : explode(',', $buttons); } - $this->hide = !empty($hide) ? explode(',', (string) $this->element['hide']) : []; - $this->editorType = !empty($editorType) ? explode('|', trim($editorType)) : []; + $this->hide = $hide === '' || $hide === '0' ? [] : explode(',', (string) $this->element['hide']); + $this->editorType = $editorType === '' || $editorType === '0' ? [] : explode('|', trim($editorType)); } return $result; diff --git a/libraries/src/Form/Field/FilelistField.php b/libraries/src/Form/Field/FilelistField.php index 5fd03ebb21734..86fb49147be8b 100644 --- a/libraries/src/Form/Field/FilelistField.php +++ b/libraries/src/Form/Field/FilelistField.php @@ -206,10 +206,8 @@ protected function getOptions() if (\is_array($files)) { foreach ($files as $file) { // Check to see if the file is in the exclude mask. - if ($this->exclude) { - if (preg_match(\chr(1) . $this->exclude . \chr(1), (string) $file)) { - continue; - } + if ($this->exclude && preg_match(\chr(1) . $this->exclude . \chr(1), (string) $file)) { + continue; } // If the extension is to be stripped, do it. diff --git a/libraries/src/Form/Field/FolderlistField.php b/libraries/src/Form/Field/FolderlistField.php index c2ff63262078a..e36f31b1b3374 100644 --- a/libraries/src/Form/Field/FolderlistField.php +++ b/libraries/src/Form/Field/FolderlistField.php @@ -209,10 +209,8 @@ protected function getOptions() $folder = trim(str_replace($path, '', $folder), DIRECTORY_SEPARATOR); // Check to see if the file is in the exclude mask. - if ($this->exclude) { - if (preg_match(\chr(1) . $this->exclude . \chr(1), $folder)) { - continue; - } + if ($this->exclude && preg_match(\chr(1) . $this->exclude . \chr(1), $folder)) { + continue; } $options[] = HTMLHelper::_('select.option', $folder, $folder); diff --git a/libraries/src/Form/Field/GroupedlistField.php b/libraries/src/Form/Field/GroupedlistField.php index 9cf88ba6e76f8..e3078f7b0826c 100644 --- a/libraries/src/Form/Field/GroupedlistField.php +++ b/libraries/src/Form/Field/GroupedlistField.php @@ -92,7 +92,10 @@ protected function getGroups() case 'group': // The element is a // Get the group label. - if ($groupLabel = (string) $element['label']) { + $groupLabel = (string) $element['label']; + // The element is a + // Get the group label. + if ($groupLabel !== '' && $groupLabel !== '0') { $label = Text::_($groupLabel); } @@ -131,7 +134,7 @@ protected function getGroups() $groups[$label][] = $tmp; } - if ($groupLabel) { + if ($groupLabel !== '' && $groupLabel !== '0') { $label = \count($groups); } break; diff --git a/libraries/src/Form/Field/LimitboxField.php b/libraries/src/Form/Field/LimitboxField.php index 9773cfe97aa8d..62f79f0d02982 100644 --- a/libraries/src/Form/Field/LimitboxField.php +++ b/libraries/src/Form/Field/LimitboxField.php @@ -88,7 +88,7 @@ protected function getOptions() $limits[] = 0; } - if (!empty($limits)) { + if ($limits !== []) { foreach ($limits as $value) { $options[] = (object) [ 'value' => $value, diff --git a/libraries/src/Form/Field/ListField.php b/libraries/src/Form/Field/ListField.php index 4372a9b9f6296..ca3b0c75dda39 100644 --- a/libraries/src/Form/Field/ListField.php +++ b/libraries/src/Form/Field/ListField.php @@ -127,7 +127,7 @@ protected function getOptions() } $value = (string) $option['value']; - $text = trim((string) $option) != '' ? trim((string) $option) : $value; + $text = trim((string) $option) !== '' ? trim((string) $option) : $value; $disabled = (string) $option['disabled']; $disabled = ($disabled === 'true' || $disabled === 'disabled' || $disabled === '1'); @@ -152,7 +152,7 @@ protected function getOptions() $tmp['onclick'] = (string) $option['onclick']; $tmp['onchange'] = (string) $option['onchange']; - if ((string) $option['showon']) { + if ((string) $option['showon'] !== '' && (string) $option['showon'] !== '0') { $encodedConditions = json_encode( FormHelper::parseShowOnConditions((string) $option['showon'], $this->formControl, $this->group) ); diff --git a/libraries/src/Form/Field/MenuField.php b/libraries/src/Form/Field/MenuField.php index 976ddd7740257..a7563885dc6fc 100644 --- a/libraries/src/Form/Field/MenuField.php +++ b/libraries/src/Form/Field/MenuField.php @@ -63,7 +63,7 @@ protected function getGroups() ] ); - if (\strlen($clientId)) { + if (\strlen($clientId) !== 0) { $client = (int) $clientId; $query->where($db->quoteName('client_id') . ' = :client') ->bind(':client', $client, ParameterType::INTEGER); @@ -71,7 +71,7 @@ protected function getGroups() $menus = $db->setQuery($query)->loadObjectList(); - if ($accessType) { + if ($accessType !== '' && $accessType !== '0') { $user = $this->getCurrentUser(); foreach ($menus as $key => $menu) { @@ -109,7 +109,7 @@ protected function getGroups() $options = array_merge($opts, $menus); $groups = []; - if (\strlen($clientId)) { + if (\strlen($clientId) !== 0) { $groups[0] = $options; } else { foreach ($options as $option) { diff --git a/libraries/src/Form/Field/MenuitemField.php b/libraries/src/Form/Field/MenuitemField.php index 12fb00bef985b..75a072b7facf2 100644 --- a/libraries/src/Form/Field/MenuitemField.php +++ b/libraries/src/Form/Field/MenuitemField.php @@ -113,7 +113,7 @@ public function __set($name, $value) case 'published': case 'disable': $value = (string) $value; - $this->$name = $value ? explode(',', $value) : []; + $this->$name = $value !== '' && $value !== '0' ? explode(',', $value) : []; break; default: @@ -191,11 +191,7 @@ protected function getGroups() $levelPrefix = str_repeat('- ', max(0, $link->level - 1)); // Displays language code if not set to All - if ($link->language !== '*') { - $lang = ' (' . $link->language . ')'; - } else { - $lang = ''; - } + $lang = $link->language !== '*' ? ' (' . $link->language . ')' : ''; $groups[$menuTitle][] = HTMLHelper::_( 'select.option', @@ -218,11 +214,7 @@ protected function getGroups() $levelPrefix = str_repeat('- ', max(0, $link->level - 1)); // Displays language code if not set to All - if ($link->language !== '*') { - $lang = ' (' . $link->language . ')'; - } else { - $lang = ''; - } + $lang = $link->language !== '*' ? ' (' . $link->language . ')' : ''; $groups[$menu->title][] = HTMLHelper::_( 'select.option', diff --git a/libraries/src/Form/Field/ModalSelectField.php b/libraries/src/Form/Field/ModalSelectField.php index 3eb7a05ae4761..3e637bea0be67 100644 --- a/libraries/src/Form/Field/ModalSelectField.php +++ b/libraries/src/Form/Field/ModalSelectField.php @@ -117,10 +117,10 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) } // Prepare enabled actions - $this->__set('select', (string) $this->element['select'] != 'false'); - $this->__set('new', (string) $this->element['new'] == 'true'); - $this->__set('edit', (string) $this->element['edit'] == 'true'); - $this->__set('clear', (string) $this->element['clear'] != 'false'); + $this->__set('select', (string) $this->element['select'] !== 'false'); + $this->__set('new', (string) $this->element['new'] === 'true'); + $this->__set('edit', (string) $this->element['edit'] === 'true'); + $this->__set('clear', (string) $this->element['clear'] !== 'false'); // Prepare Urls and titles foreach ( diff --git a/libraries/src/Form/Field/ModulelayoutField.php b/libraries/src/Form/Field/ModulelayoutField.php index bf91717e4092b..fd2ec8c3e94c0 100644 --- a/libraries/src/Form/Field/ModulelayoutField.php +++ b/libraries/src/Form/Field/ModulelayoutField.php @@ -61,7 +61,7 @@ protected function getInput() // Get the module. $module = (string) $this->element['module']; - if (empty($module) && ($this->form instanceof Form)) { + if (($module === '' || $module === '0') && ($this->form instanceof Form)) { $module = $this->form->getValue('module'); } @@ -83,8 +83,9 @@ protected function getInput() if ($module && $client) { // Load language file $lang = Factory::getLanguage(); - $lang->load($module . '.sys', $client->path) - || $lang->load($module . '.sys', $client->path . '/modules/' . $module); + if (!$lang->load($module . '.sys', $client->path)) { + $lang->load($module . '.sys', $client->path . '/modules/' . $module); + } // Get the database object and a new query object. $db = $this->getDatabase(); @@ -112,7 +113,7 @@ protected function getInput() ->bind(':template', $template); } - if ($template_style_id) { + if ($template_style_id !== 0) { $query->join('LEFT', $db->quoteName('#__template_styles', 's'), $db->quoteName('s.template') . ' = ' . $db->quoteName('e.element')) ->where($db->quoteName('s.id') . ' = :style') ->bind(':style', $template_style_id, ParameterType::INTEGER); @@ -151,8 +152,9 @@ protected function getInput() if ($templates) { foreach ($templates as $template) { // Load language file - $lang->load('tpl_' . $template->element . '.sys', $client->path) - || $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element); + if (!$lang->load('tpl_' . $template->element . '.sys', $client->path)) { + $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element); + } $template_path = Path::clean($client->path . '/templates/' . $template->element . '/html/' . $module); diff --git a/libraries/src/Form/Field/NoteField.php b/libraries/src/Form/Field/NoteField.php index a4d2233df5b07..e56a5333e0111 100644 --- a/libraries/src/Form/Field/NoteField.php +++ b/libraries/src/Form/Field/NoteField.php @@ -69,20 +69,21 @@ protected function getLabel() if (!empty($this->class)) { $class[] = $this->class; } + $close = (string) $this->element['close']; - if ($close = (string) $this->element['close']) { + if ($close !== '' && $close !== '0') { HTMLHelper::_('bootstrap.alert'); $close = $close === 'true' ? 'alert' : $close; $html[] = ''; $class[] = 'alert-dismissible show'; } - $class = $class ? ' class="' . implode(' ', $class) . '"' : ''; - $title = $this->element['label'] ? (string) $this->element['label'] : ($this->element['title'] ? (string) $this->element['title'] : ''); + $class = $class !== [] ? ' class="' . implode(' ', $class) . '"' : ''; + $title = $this->element['label'] instanceof \SimpleXMLElement ? (string) $this->element['label'] : ($this->element['title'] ? (string) $this->element['title'] : ''); $heading = $this->element['heading'] ? (string) $this->element['heading'] : 'h4'; $description = (string) $this->element['description']; - $html[] = !empty($title) ? '<' . $heading . '>' . Text::_($title) . '' : ''; - $html[] = !empty($description) ? Text::_($description) : ''; + $html[] = $title === '' || $title === '0' ? '' : '<' . $heading . '>' . Text::_($title) . ''; + $html[] = $description === '' || $description === '0' ? '' : Text::_($description); return '
    ' . implode('', $html); } diff --git a/libraries/src/Form/Field/OrderingField.php b/libraries/src/Form/Field/OrderingField.php index dea44f9b5331d..b8b241609359e 100644 --- a/libraries/src/Form/Field/OrderingField.php +++ b/libraries/src/Form/Field/OrderingField.php @@ -120,12 +120,12 @@ protected function getInput() $attr = ''; // Initialize some field attributes. - $attr .= !empty($this->class) ? ' class="form-select' . $this->class . '"' : ' class="form-select"'; + $attr .= empty($this->class) ? ' class="form-select"' : ' class="form-select' . $this->class . '"'; $attr .= $this->disabled ? ' disabled' : ''; - $attr .= !empty($this->size) ? ' size="' . $this->size . '"' : ''; + $attr .= empty($this->size) ? '' : ' size="' . $this->size . '"'; // Initialize JavaScript field attributes. - $attr .= !empty($this->onchange) ? ' onchange="' . $this->onchange . '"' : ''; + $attr .= empty($this->onchange) ? '' : ' onchange="' . $this->onchange . '"'; $itemId = (int) $this->getItemId(); @@ -133,11 +133,11 @@ protected function getInput() // Create a read-only list (no name) with a hidden input to store the value. if ($this->readonly) { - $html[] = HTMLHelper::_('list.ordering', '', $query, trim($attr), $this->value, $itemId ? 0 : 1, $this->id); + $html[] = HTMLHelper::_('list.ordering', '', $query, trim($attr), $this->value, $itemId !== 0 ? 0 : 1, $this->id); $html[] = ''; } else { // Create a regular list. - $html[] = HTMLHelper::_('list.ordering', $this->name, $query, trim($attr), $this->value, $itemId ? 0 : 1, $this->id); + $html[] = HTMLHelper::_('list.ordering', $this->name, $query, trim($attr), $this->value, $itemId !== 0 ? 0 : 1, $this->id); } return implode('', $html); diff --git a/libraries/src/Form/Field/PasswordField.php b/libraries/src/Form/Field/PasswordField.php index 52102e95cf8fb..b76b54ca48a40 100644 --- a/libraries/src/Form/Field/PasswordField.php +++ b/libraries/src/Form/Field/PasswordField.php @@ -204,9 +204,9 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $meter = (string) $this->element['strengthmeter']; $this->meter = ($meter === 'true' || $meter === 'on' || $meter === '1'); $force = (string) $this->element['forcePassword']; - $this->force = (($force === 'true' || $force === 'on' || $force === '1') && $this->meter === true); + $this->force = (($force === 'true' || $force === 'on' || $force === '1') && $this->meter); $rules = (string) $this->element['rules']; - $this->rules = (($rules === 'true' || $rules === 'on' || $rules === '1') && $this->meter === true); + $this->rules = (($rules === 'true' || $rules === 'on' || $rules === '1') && $this->meter); // Set some initial values $this->minLength = 12; diff --git a/libraries/src/Form/Field/PluginsField.php b/libraries/src/Form/Field/PluginsField.php index 9d7091c3b16da..ab1f5cec94578 100644 --- a/libraries/src/Form/Field/PluginsField.php +++ b/libraries/src/Form/Field/PluginsField.php @@ -162,7 +162,9 @@ protected function getOptions() foreach ($options as $i => $item) { $source = JPATH_PLUGINS . '/' . $folder . '/' . $item->value; $extension = 'plg_' . $folder . '_' . $item->value; - $lang->load($extension . '.sys', JPATH_ADMINISTRATOR) || $lang->load($extension . '.sys', $source); + if (!$lang->load($extension . '.sys', JPATH_ADMINISTRATOR)) { + $lang->load($extension . '.sys', $source); + } $item->text = Text::_($item->text); // If we are using useglobal update the use global value text with the plugin text. diff --git a/libraries/src/Form/Field/PredefinedlistField.php b/libraries/src/Form/Field/PredefinedlistField.php index d5b518c95d33b..75855c287c755 100644 --- a/libraries/src/Form/Field/PredefinedlistField.php +++ b/libraries/src/Form/Field/PredefinedlistField.php @@ -101,7 +101,7 @@ protected function getOptions() $hash = md5($this->element); $type = strtolower($this->type); - if (!isset(static::$options[$type][$hash]) && !empty($this->predefinedOptions)) { + if (!isset(static::$options[$type][$hash]) && $this->predefinedOptions !== []) { static::$options[$type][$hash] = parent::getOptions(); $options = []; @@ -109,7 +109,7 @@ protected function getOptions() foreach ($this->predefinedOptions as $value => $text) { $val = (string) $value; - if (empty($this->optionsFilter) || \in_array($val, $this->optionsFilter, true)) { + if ($this->optionsFilter === [] || \in_array($val, $this->optionsFilter, true)) { $text = $this->translate ? Text::_($text) : $text; $options[] = (object) [ diff --git a/libraries/src/Form/Field/RulesField.php b/libraries/src/Form/Field/RulesField.php index cc80d9d463d45..5d9ffcc6e183a 100644 --- a/libraries/src/Form/Field/RulesField.php +++ b/libraries/src/Form/Field/RulesField.php @@ -243,10 +243,10 @@ protected function getInput() // Get the asset id. // Note that for global configuration, com_config injects asset_id = 1 into the form. $this->assetId = (int) $this->form->getValue($assetField); - $this->newItem = empty($this->assetId) && $this->isGlobalConfig === false && $section !== 'component'; + $this->newItem = ($this->assetId === null || $this->assetId === 0) && $this->isGlobalConfig === false && $section !== 'component'; // If the asset id is empty (component or new item). - if (empty($this->assetId)) { + if ($this->assetId === null || $this->assetId === 0) { // Get the component asset id as fallback. $db = $this->getDatabase(); $query = $db->getQuery(true) diff --git a/libraries/src/Form/Field/SpacerField.php b/libraries/src/Form/Field/SpacerField.php index d686ec7c3aaba..f29f61b479441 100644 --- a/libraries/src/Form/Field/SpacerField.php +++ b/libraries/src/Form/Field/SpacerField.php @@ -59,7 +59,7 @@ protected function getInput() protected function getLabel() { $html = []; - $class = !empty($this->class) ? ' class="' . $this->class . '"' : ''; + $class = empty($this->class) ? '' : ' class="' . $this->class . '"'; $html[] = ''; $html[] = ''; $html[] = ''; @@ -74,7 +74,7 @@ protected function getLabel() $text = $this->translateLabel ? Text::_($text) : $text; // Build the class for the label. - $class = !empty($this->description) ? 'hasPopover' : ''; + $class = empty($this->description) ? '' : 'hasPopover'; $class = $this->required == true ? $class . ' required' : $class; // Add the opening label tag and main attributes attributes. diff --git a/libraries/src/Form/Field/SqlField.php b/libraries/src/Form/Field/SqlField.php index f3ca8fe74bff4..1e673607ff79e 100644 --- a/libraries/src/Form/Field/SqlField.php +++ b/libraries/src/Form/Field/SqlField.php @@ -142,7 +142,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) // Check if its using the old way $this->query = (string) $this->element['query']; - if (empty($this->query)) { + if ($this->query === null || ($this->query === '' || $this->query === '0')) { // Get the query from the form $query = []; $defaults = []; @@ -166,7 +166,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $name = "sql_default_{$filter}"; $attrib = (string) $this->element[$name]; - if (!empty($attrib)) { + if ($attrib !== '' && $attrib !== '0') { $defaults[$filter] = $attrib; } } diff --git a/libraries/src/Form/Field/SubformField.php b/libraries/src/Form/Field/SubformField.php index 2bb7077b3c268..a87adc072823f 100644 --- a/libraries/src/Form/Field/SubformField.php +++ b/libraries/src/Form/Field/SubformField.php @@ -134,9 +134,9 @@ public function __set($name, $value) $this->layout = (string) $value; // Make sure the layout is not empty. - if (!$this->layout) { + if ($this->layout === '' || $this->layout === '0') { // Set default value depend from "multiple" mode - $this->layout = !$this->multiple ? 'joomla.form.field.subform.default' : 'joomla.form.field.subform.repeatable'; + $this->layout = $this->multiple ? 'joomla.form.field.subform.repeatable' : 'joomla.form.field.subform.default'; } break; @@ -195,7 +195,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $this->__set($attributeName, $element[$attributeName]); } - if ((string) $element['fieldname']) { + if ((string) $element['fieldname'] !== '' && (string) $element['fieldname'] !== '0') { $this->__set('fieldname', $element['fieldname']); } @@ -298,7 +298,7 @@ protected function getName($fieldName) // If we already have a name segment add the group control as another level. $groups = explode('.', $this->group); - if ($name) { + if ($name !== '' && $name !== '0') { foreach ($groups as $group) { $name .= '[' . $group . ']'; } @@ -312,7 +312,7 @@ protected function getName($fieldName) } // If we already have a name segment add the field name as another level. - if ($name) { + if ($name !== '' && $name !== '0') { $name .= '[' . $fieldName . ']'; } else { $name .= $fieldName; diff --git a/libraries/src/Form/Field/TagField.php b/libraries/src/Form/Field/TagField.php index d5e6afc8be28b..9cc0a7b78eb77 100644 --- a/libraries/src/Form/Field/TagField.php +++ b/libraries/src/Form/Field/TagField.php @@ -85,11 +85,7 @@ protected function getInput() if (!\is_array($this->value) && !empty($this->value)) { if ($this->value instanceof TagsHelper) { - if (empty($this->value->tags)) { - $this->value = []; - } else { - $this->value = $this->value->tags; - } + $this->value = empty($this->value->tags) ? [] : $this->value->tags; } // String in format 2,5,4 @@ -291,14 +287,9 @@ protected function prepareOptionsNested(&$options) */ public function isNested() { - if ($this->isNested === null) { - // If mode="nested" || ( mode not set & config = nested ) - if ( - isset($this->element['mode']) && (string) $this->element['mode'] === 'nested' - || !isset($this->element['mode']) && $this->comParams->get('tag_field_ajax_mode', 1) == 0 - ) { - $this->isNested = true; - } + // If mode="nested" || ( mode not set & config = nested ) + if ($this->isNested === null && (isset($this->element['mode']) && (string) $this->element['mode'] === 'nested' || !isset($this->element['mode']) && $this->comParams->get('tag_field_ajax_mode', 1) == 0)) { + $this->isNested = true; } return $this->isNested; diff --git a/libraries/src/Form/Field/TelephoneField.php b/libraries/src/Form/Field/TelephoneField.php index 2ca062c9b68a4..abbe3783a17f2 100644 --- a/libraries/src/Form/Field/TelephoneField.php +++ b/libraries/src/Form/Field/TelephoneField.php @@ -65,7 +65,7 @@ protected function getLayoutData() $data = parent::getLayoutData(); // Initialize some field attributes. - $maxLength = !empty($this->maxLength) ? ' maxlength="' . $this->maxLength . '"' : ''; + $maxLength = empty($this->maxLength) ? '' : ' maxlength="' . $this->maxLength . '"'; $extraData = [ 'maxLength' => $maxLength, diff --git a/libraries/src/Form/Field/TemplatestyleField.php b/libraries/src/Form/Field/TemplatestyleField.php index deb3b2439d698..1dc904aa128af 100644 --- a/libraries/src/Form/Field/TemplatestyleField.php +++ b/libraries/src/Form/Field/TemplatestyleField.php @@ -176,8 +176,9 @@ protected function getGroups() if ($styles) { foreach ($styles as $style) { $template = $style->template; - $lang->load('tpl_' . $template . '.sys', $client->path) - || $lang->load('tpl_' . $template . '.sys', $client->path . '/templates/' . $template); + if (!$lang->load('tpl_' . $template . '.sys', $client->path)) { + $lang->load('tpl_' . $template . '.sys', $client->path . '/templates/' . $template); + } $name = Text::_($style->name); // Initialize the group if necessary. diff --git a/libraries/src/Form/Field/TextField.php b/libraries/src/Form/Field/TextField.php index 65194808af2fb..1fe059174cff7 100644 --- a/libraries/src/Form/Field/TextField.php +++ b/libraries/src/Form/Field/TextField.php @@ -129,7 +129,7 @@ public function __set($name, $value) case 'dirname': $value = (string) $value; - $this->dirname = ($value == $name || $value === 'true' || $value === '1'); + $this->dirname = ($value === $name || $value === 'true' || $value === '1'); break; case 'inputmode': @@ -285,9 +285,9 @@ protected function getLayoutData() $data = parent::getLayoutData(); // Initialize some field attributes. - $maxLength = !empty($this->maxLength) ? ' maxlength="' . $this->maxLength . '"' : ''; - $inputmode = !empty($this->inputmode) ? ' inputmode="' . $this->inputmode . '"' : ''; - $dirname = !empty($this->dirname) ? ' dirname="' . $this->dirname . '"' : ''; + $maxLength = empty($this->maxLength) ? '' : ' maxlength="' . $this->maxLength . '"'; + $inputmode = empty($this->inputmode) ? '' : ' inputmode="' . $this->inputmode . '"'; + $dirname = empty($this->dirname) ? '' : ' dirname="' . $this->dirname . '"'; // Get the field options for the datalist. $options = (array) $this->getOptions(); diff --git a/libraries/src/Form/Field/TimezoneField.php b/libraries/src/Form/Field/TimezoneField.php index e99279a4ca2a7..594e014b77acc 100644 --- a/libraries/src/Form/Field/TimezoneField.php +++ b/libraries/src/Form/Field/TimezoneField.php @@ -143,7 +143,7 @@ protected function getGroups() } // Only add options where a locale exists. - if (!empty($locale)) { + if ($locale !== '' && $locale !== '0') { $groups[$group][$zone] = HTMLHelper::_('select.option', $zone, str_replace('_', ' ', $locale), 'value', 'text', false); } } diff --git a/libraries/src/Form/Field/TransitionField.php b/libraries/src/Form/Field/TransitionField.php index b9f0a78ffa2fe..77c7e93eed2e0 100644 --- a/libraries/src/Form/Field/TransitionField.php +++ b/libraries/src/Form/Field/TransitionField.php @@ -68,17 +68,9 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) if ($result) { $input = Factory::getApplication()->getInput(); - if (\strlen($element['extension'])) { - $this->extension = (string) $element['extension']; - } else { - $this->extension = $input->getCmd('extension'); - } + $this->extension = \strlen($element['extension']) !== 0 ? (string) $element['extension'] : $input->getCmd('extension'); - if (\strlen($element['workflow_stage'])) { - $this->workflowStage = (int) $element['workflow_stage']; - } else { - $this->workflowStage = $input->getInt('id'); - } + $this->workflowStage = \strlen($element['workflow_stage']) !== 0 ? (int) $element['workflow_stage'] : $input->getInt('id'); } return $result; @@ -134,7 +126,7 @@ protected function getGroups() $component = reset($parts); - if (\count($items)) { + if (\count($items) > 0) { $user = $this->getCurrentUser(); $items = array_filter( @@ -160,7 +152,7 @@ protected function getGroups() $groups = parent::getGroups(); - if (\count($items)) { + if (\count($items) > 0) { $groups[Text::_('COM_CONTENT_RUN_TRANSITION')] = $items; } diff --git a/libraries/src/Form/Field/UrlField.php b/libraries/src/Form/Field/UrlField.php index a7b8471bcdce5..71d31d858a6d5 100644 --- a/libraries/src/Form/Field/UrlField.php +++ b/libraries/src/Form/Field/UrlField.php @@ -64,7 +64,7 @@ protected function getLayoutData() $data = parent::getLayoutData(); // Initialize some field attributes. - $maxLength = !empty($this->maxLength) ? ' maxlength="' . $this->maxLength . '"' : ''; + $maxLength = empty($this->maxLength) ? '' : ' maxlength="' . $this->maxLength . '"'; // Note that the input type "url" is suitable only for external URLs, so if internal URLs are allowed // we have to use the input type "text" instead. diff --git a/libraries/src/Form/Field/WorkflowconditionField.php b/libraries/src/Form/Field/WorkflowconditionField.php index b0aacdc21598e..a6ab73f43affc 100644 --- a/libraries/src/Form/Field/WorkflowconditionField.php +++ b/libraries/src/Form/Field/WorkflowconditionField.php @@ -66,13 +66,13 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $success = parent::setup($element, $value, $group); if ($success) { - if (\strlen($element['extension'])) { + if (\strlen($element['extension']) !== 0) { $this->extension = (string) $element['extension']; } else { $this->extension = Factory::getApplication()->getInput()->getCmd('extension'); } - if (\strlen($element['hide_all'])) { + if (\strlen($element['hide_all']) !== 0) { $this->hideAll = (string) $element['hide_all'] === 'true' || (string) $element['hide_all'] === 'yes'; } } @@ -102,7 +102,7 @@ protected function getOptions() } foreach ($conditions as $value => $option) { - $text = trim((string) $option) != '' ? trim((string) $option) : $value; + $text = trim((string) $option) !== '' ? trim((string) $option) : $value; $selected = ((int) $this->value === $value); diff --git a/libraries/src/Form/Field/WorkflowstageField.php b/libraries/src/Form/Field/WorkflowstageField.php index 6145028899086..8bdbbdb9e356d 100644 --- a/libraries/src/Form/Field/WorkflowstageField.php +++ b/libraries/src/Form/Field/WorkflowstageField.php @@ -66,7 +66,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) $result = parent::setup($element, $value, $group); if ($result) { - if (\strlen($element['extension'])) { + if (\strlen($element['extension']) !== 0) { $this->extension = (string) $element['extension']; } else { $this->extension = Factory::getApplication()->getInput()->getCmd('extension'); diff --git a/libraries/src/Form/Filter/TelFilter.php b/libraries/src/Form/Filter/TelFilter.php index 2b3f073237f97..37e44f8cb809b 100644 --- a/libraries/src/Form/Filter/TelFilter.php +++ b/libraries/src/Form/Filter/TelFilter.php @@ -44,7 +44,7 @@ public function filter(\SimpleXMLElement $element, $value, $group = null, ?Regis $value = trim((string) $value); // Does it match the NANP pattern? - if (preg_match('/^(?:\+?1[-. ]?)?\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$/', $value) == 1) { + if (preg_match('/^(?:\+?1[-. ]?)?\(?([2-9][0-8]\d)\)?[-. ]?([2-9]\d{2})[-. ]?(\d{4})$/', $value) == 1) { $number = (string) preg_replace('/[^\d]/', '', $value); if (str_starts_with($number, '1')) { @@ -56,14 +56,14 @@ public function filter(\SimpleXMLElement $element, $value, $group = null, ?Regis } $result = '1.' . $number; - } elseif (preg_match('/^\+(?:[0-9] ?){6,14}[0-9]$/', $value) == 1) { + } elseif (preg_match('/^\+(?:\d ?){6,14}\d$/', $value) == 1) { // If not, does it match ITU-T? $countrycode = substr($value, 0, strpos($value, ' ')); $countrycode = (string) preg_replace('/[^\d]/', '', $countrycode); $number = strstr($value, ' '); $number = (string) preg_replace('/[^\d]/', '', $number); $result = $countrycode . '.' . $number; - } elseif (preg_match('/^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$/', $value) == 1) { + } elseif (preg_match('/^\+\d{1,3}\.\d{4,14}(?:x.+)?$/', $value) == 1) { // If not, does it match EPP? if (strstr($value, 'x')) { $xpos = strpos($value, 'x'); @@ -71,7 +71,7 @@ public function filter(\SimpleXMLElement $element, $value, $group = null, ?Regis } $result = str_replace('+', '', $value); - } elseif (preg_match('/[0-9]{1,3}\.[0-9]{4,14}$/', $value) == 1) { + } elseif (preg_match('/\d{1,3}\.\d{4,14}$/', $value) == 1) { // Maybe it is already ccc.nnnnnnn? $result = $value; } else { diff --git a/libraries/src/Form/Filter/UrlFilter.php b/libraries/src/Form/Filter/UrlFilter.php index 50a90e2ae45cd..54b47b235f37c 100644 --- a/libraries/src/Form/Filter/UrlFilter.php +++ b/libraries/src/Form/Filter/UrlFilter.php @@ -67,13 +67,7 @@ public function filter(\SimpleXMLElement $element, $value, $group = null, ?Regis $protocol = 'http'; // If it looks like an internal link, then add the root. - if (str_starts_with($value, 'index.php')) { - $value = Uri::root() . $value; - } else { - // Otherwise we treat it as an external link. - // Put the url back together. - $value = $protocol . '://' . $value; - } + $value = str_starts_with($value, 'index.php') ? Uri::root() . $value : $protocol . '://' . $value; } elseif (!$protocol && $element['relative']) { // If relative URLS are allowed we assume that URLs without protocols are internal. $host = Uri::getInstance('SERVER')->getHost(); diff --git a/libraries/src/Form/Form.php b/libraries/src/Form/Form.php index 3032f6891b2e4..13c2cecfbf7e5 100644 --- a/libraries/src/Form/Form.php +++ b/libraries/src/Form/Form.php @@ -275,12 +275,7 @@ public function getFieldset($set = null) $fields = []; // Get all of the field elements in the fieldset. - if ($set) { - $elements = $this->findFieldsByFieldset($set); - } else { - // Get all fields. - $elements = $this->findFieldsByGroup(); - } + $elements = $set ? $this->findFieldsByFieldset($set) : $this->findFieldsByGroup(); // If no field elements were found return empty. if (empty($elements)) { @@ -349,7 +344,7 @@ public function getFieldsets($group = null) } // Are we dealing with a fieldset element? - if ((string) $set['name']) { + if ((string) $set['name'] !== '' && (string) $set['name'] !== '0') { // Only create it if it doesn't already exist. if (empty($fieldsets[(string) $set['name']])) { // Build the fieldset object. @@ -362,28 +357,24 @@ public function getFieldsets($group = null) // Add the fieldset object to the list. $fieldsets[$fieldset->name] = $fieldset; } - } else { + } elseif (empty($fieldsets[(string) $set])) { // Must be dealing with a fieldset attribute. // Only create it if it doesn't already exist. - if (empty($fieldsets[(string) $set])) { - // Attempt to get the fieldset element for data (throughout the entire form document). - $tmp = $this->xml->xpath('//fieldset[@name="' . (string) $set . '"]'); - - // If no element was found, build a very simple fieldset object. - if (empty($tmp)) { - $fieldset = (object) ['name' => (string) $set, 'label' => '', 'description' => '']; - } else { - // Build the fieldset object from the element. - $fieldset = (object) ['name' => '', 'label' => '', 'description' => '']; + // Attempt to get the fieldset element for data (throughout the entire form document). + $tmp = $this->xml->xpath('//fieldset[@name="' . (string) $set . '"]'); + // If no element was found, build a very simple fieldset object. + if (empty($tmp)) { + $fieldset = (object) ['name' => (string) $set, 'label' => '', 'description' => '']; + } else { + // Build the fieldset object from the element. + $fieldset = (object) ['name' => '', 'label' => '', 'description' => '']; - foreach ($tmp[0]->attributes() as $name => $value) { - $fieldset->$name = (string) $value; - } + foreach ($tmp[0]->attributes() as $name => $value) { + $fieldset->$name = (string) $value; } - - // Add the fieldset object to the list. - $fieldsets[$fieldset->name] = $fieldset; } + // Add the fieldset object to the list. + $fieldsets[$fieldset->name] = $fieldset; } } @@ -512,11 +503,7 @@ public function getName() public function getValue($name, $group = null, $default = null) { // If a group is set use it. - if ($group) { - $return = $this->data->get($group . '.' . $name, $default); - } else { - $return = $this->data->get($name, $default); - } + $return = $group ? $this->data->get($group . '.' . $name, $default) : $this->data->get($name, $default); return $return; } @@ -1041,7 +1028,7 @@ public function filter($data, $group = null) $groups = array_map('strval', $attrs ?: []); $attrGroup = implode('.', $groups); - $key = $attrGroup ? $attrGroup . '.' . $name : $name; + $key = $attrGroup !== '' && $attrGroup !== '0' ? $attrGroup . '.' . $name : $name; // Filter the value if it exists. if ($input->exists($key)) { @@ -1123,7 +1110,7 @@ public function validate($data, $group = null) $groups = array_map('strval', $attrs ?: []); $attrGroup = implode('.', $groups); - $key = $attrGroup ? $attrGroup . '.' . $name : $name; + $key = $attrGroup !== '' && $attrGroup !== '0' ? $attrGroup . '.' . $name : $name; $fieldObj = $this->loadField($field, $attrGroup); @@ -1184,7 +1171,7 @@ public function postProcess($data, $group = null) $groups = array_map('strval', $attrs ?: []); $attrGroup = implode('.', $groups); - $key = $attrGroup ? $attrGroup . '.' . $name : $name; + $key = $attrGroup !== '' && $attrGroup !== '0' ? $attrGroup . '.' . $name : $name; // Filter the value if it exists. if ($input->exists($key)) { @@ -1230,7 +1217,7 @@ protected function findField($name, $group = null) } // Make sure something was found. - if (!$fields) { + if ($fields === []) { return false; } @@ -1383,7 +1370,7 @@ protected function &findGroup($group) // Make sure there is actually a group to find. $group = explode('.', $group); - if (\count($group)) { + if ($group !== []) { // Get any fields elements with the correct group name. $elements = $this->xml->xpath('//fields[@name="' . (string) $group[0] . '" and not(ancestor::field/form/*)]'); @@ -1414,7 +1401,7 @@ protected function &findGroup($group) // If the group names for the fields element match the valid names at this // level add the fields element. - if ($validNames == $names) { + if ($validNames === $names) { $tmp[] = $fields; } } @@ -1451,7 +1438,7 @@ protected function loadField($element, $group = null, $value = null) } // Get the field type. - $type = $element['type'] ? (string) $element['type'] : 'text'; + $type = $element['type'] instanceof \SimpleXMLElement ? (string) $element['type'] : 'text'; // Load the FormField object for the field. $field = FormHelper::loadFieldType($type); @@ -1460,7 +1447,7 @@ protected function loadField($element, $group = null, $value = null) try { $field->setDatabase($this->getDatabase()); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $field->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } } @@ -1691,7 +1678,7 @@ public static function getInstance($name, $data = null, $options = [], $replace if (!isset($forms[$name])) { $data = trim((string) $data); - if (empty($data)) { + if ($data === '' || $data === '0') { throw new \InvalidArgumentException(\sprintf('%1$s(%2$s, *%3$s*)', __METHOD__, $name, \gettype($data))); } @@ -1703,10 +1690,8 @@ public static function getInstance($name, $data = null, $options = [], $replace if ($forms[$name]->load($data, $replace, $xpath) == false) { throw new \RuntimeException(\sprintf('%s() could not load form', __METHOD__)); } - } else { - if ($forms[$name]->loadFile($data, $replace, $xpath) == false) { - throw new \RuntimeException(\sprintf('%s() could not load file', __METHOD__)); - } + } elseif ($forms[$name]->loadFile($data, $replace, $xpath) == false) { + throw new \RuntimeException(\sprintf('%s() could not load file', __METHOD__)); } } diff --git a/libraries/src/Form/FormField.php b/libraries/src/Form/FormField.php index 6755e00672afb..2b30e47e58894 100644 --- a/libraries/src/Form/FormField.php +++ b/libraries/src/Form/FormField.php @@ -424,7 +424,7 @@ public function __construct($form = null) } // Detect the field type if not set - if (!isset($this->type)) { + if ($this->type === null) { $parts = Normalise::fromCamelCase(static::class, true); if ($parts[0] === 'J') { @@ -501,6 +501,7 @@ public function __get($name) return $this->dataAttributes[$name]; } } + return null; } /** @@ -556,7 +557,7 @@ public function __set($name, $value) case 'multiple': // Allow for field classes to force the multiple values option. $value = (string) $value; - $value = $value === '' && isset($this->forceMultiple) ? (string) $this->forceMultiple : $value; + $value = $value === '' && (property_exists($this, 'forceMultiple') && $this->forceMultiple !== null) ? (string) $this->forceMultiple : $value; // No break @@ -595,12 +596,10 @@ public function __set($name, $value) // Detect data attribute(s) if (str_starts_with($name, 'data-')) { $this->dataAttributes[$name] = $value; + } elseif (property_exists(self::class, $name)) { + Log::add("Cannot access protected / private property $name of " . self::class); } else { - if (property_exists(self::class, $name)) { - Log::add("Cannot access protected / private property $name of " . self::class); - } else { - $this->$name = $value; - } + $this->$name = $value; } } } @@ -688,7 +687,7 @@ public function setup(\SimpleXMLElement $element, $value, $group = null) // Set the visibility. $this->hidden = ($this->hidden || strtolower((string) $this->element['type']) === 'hidden'); - $this->layout = !empty($this->element['layout']) ? (string) $this->element['layout'] : $this->layout; + $this->layout = empty($this->element['layout']) ? $this->layout : (string) $this->element['layout']; $this->parentclass = isset($this->element['parentclass']) ? (string) $this->element['parentclass'] : $this->parentclass; @@ -736,7 +735,7 @@ protected function getId($fieldId, $fieldName) // If the field is in a group add the group control to the field id. if ($this->group) { // If we already have an id segment add the group control as another level. - if ($id) { + if ($id !== '' && $id !== '0') { $id .= '_' . str_replace('.', '_', $this->group); } else { $id .= str_replace('.', '_', $this->group); @@ -858,7 +857,7 @@ protected function getName($fieldName) // If we already have a name segment add the group control as another level. $groups = explode('.', $this->group); - if ($name) { + if ($name !== '' && $name !== '0') { foreach ($groups as $group) { $name .= '[' . $group . ']'; } @@ -872,7 +871,7 @@ protected function getName($fieldName) } // If we already have a name segment add the field name as another level. - if ($name) { + if ($name !== '' && $name !== '0') { $name .= '[' . $fieldName . ']'; } else { $name .= $fieldName; @@ -1029,16 +1028,16 @@ public function renderField($options = []) } } - $options['inlineHelp'] = isset($this->form, $this->form->getXml()->config->inlinehelp['button']) - ? ((string) $this->form->getXml()->config->inlinehelp['button'] == 'show' ?: false) + $options['inlineHelp'] = $this->form !== null + ? ((string) $this->form->getXml()->config->inlinehelp['button'] === 'show' ?: false) : false; // Check if the field has showon in nested option $hasOptionShowOn = false; - if (!empty((array) $this->element->xpath('option'))) { + if ((array) $this->element->xpath('option') !== []) { foreach ($this->element->xpath('option') as $option) { - if ((string) $option['showon']) { + if ((string) $option['showon'] !== '' && (string) $option['showon'] !== '0') { $hasOptionShowOn = true; break; @@ -1184,7 +1183,7 @@ public function validate($value, $group = null, ?Registry $input = null) // Check if the field is required. $required = ((string) $this->element['required'] === 'true' || (string) $this->element['required'] === 'required'); - if ($this->element['label']) { + if ($this->element['label'] instanceof \SimpleXMLElement) { $fieldLabel = $this->element['label']; // Try to translate label if not set to false @@ -1203,9 +1202,11 @@ public function validate($value, $group = null, ?Registry $input = null) return new \RuntimeException($message); } + // Get the field validation rule. + $type = (string) $this->element['validate']; // Get the field validation rule. - if ($type = (string) $this->element['validate']) { + if ($type !== '' && $type !== '0') { // Load the FormRule object for the field. $rule = FormHelper::loadRuleType($type); @@ -1218,7 +1219,7 @@ public function validate($value, $group = null, ?Registry $input = null) try { $rule->setDatabase($this->getDatabase()); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $rule->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } } @@ -1243,7 +1244,7 @@ public function validate($value, $group = null, ?Registry $input = null) try { $rule->setDatabase($this->getDatabase()); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $rule->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } } @@ -1265,7 +1266,7 @@ public function validate($value, $group = null, ?Registry $input = null) // Does the field have a defined error message? $message = (string) $this->element['message']; - if ($message) { + if ($message !== '' && $message !== '0') { $message = Text::_($this->element['message']); } else { $message = Text::sprintf('JLIB_FORM_VALIDATE_FIELD_INVALID', $fieldLabel); @@ -1303,9 +1304,9 @@ public function postProcess($value, $group = null, ?Registry $input = null) */ protected function getLayoutData() { - $label = !empty($this->element['label']) ? (string) $this->element['label'] : null; + $label = empty($this->element['label']) ? null : (string) $this->element['label']; $label = $label && $this->translateLabel ? Text::_($label) : $label; - $description = !empty($this->description) ? $this->description : null; + $description = empty($this->description) ? null : $this->description; $description = !empty($description) && $this->translateDescription ? Text::_($description) : $description; $alt = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname); $options = [ diff --git a/libraries/src/Form/FormHelper.php b/libraries/src/Form/FormHelper.php index 8154916ef230c..25947943ea675 100644 --- a/libraries/src/Form/FormHelper.php +++ b/libraries/src/Form/FormHelper.php @@ -355,8 +355,7 @@ protected static function addPath($entity, $new = null) // Reference to an array with paths for current entity $paths = &self::$paths[$entity]; - // Force the new path(s) to an array. - settype($new, 'array'); + $new = (array) $new; // Add the new paths to the stack if not already there. foreach ($new as $path) { @@ -447,8 +446,7 @@ protected static function addPrefix($entity, $new = null) $prefixes[] = __NAMESPACE__ . '\\' . ucfirst($entity); } - // Force the new namespace(s) to an array. - settype($new, 'array'); + $new = (array) $new; // Add the new paths to the stack if not already there. foreach ($new as $prefix) { @@ -516,24 +514,20 @@ public static function parseShowOnConditions($showOn, $formControl = null, $grou if ($dotPos === false) { $field = $formPath ? $formPath . '[' . $showOnPartBlocks[0] . ']' : $showOnPartBlocks[0]; + } elseif ($dotPos === 0) { + $fieldName = substr($showOnPartBlocks[0], 1); + $field = $formControl ? $formControl . '[' . $fieldName . ']' : $fieldName; + } elseif ($formControl) { + $field = $formControl . ('[' . str_replace('.', '][', $showOnPartBlocks[0]) . ']'); } else { - if ($dotPos === 0) { - $fieldName = substr($showOnPartBlocks[0], 1); - $field = $formControl ? $formControl . '[' . $fieldName . ']' : $fieldName; - } else { - if ($formControl) { - $field = $formControl . ('[' . str_replace('.', '][', $showOnPartBlocks[0]) . ']'); - } else { - $groupParts = explode('.', $showOnPartBlocks[0]); - $field = array_shift($groupParts) . '[' . implode('][', $groupParts) . ']'; - } - } + $groupParts = explode('.', $showOnPartBlocks[0]); + $field = array_shift($groupParts) . '[' . implode('][', $groupParts) . ']'; } $showOnData[] = [ 'field' => $field, 'values' => explode(',', $showOnPartBlocks[1]), - 'sign' => $compareEqual === true ? '=' : '!=', + 'sign' => $compareEqual ? '=' : '!=', 'op' => $op, ]; diff --git a/libraries/src/Form/FormRule.php b/libraries/src/Form/FormRule.php index 5d1c17843254c..7faf529b1cdff 100644 --- a/libraries/src/Form/FormRule.php +++ b/libraries/src/Form/FormRule.php @@ -87,12 +87,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr if ($unicodePropertiesSupport) { $this->modifiers = (str_contains($this->modifiers, 'u')) ? $this->modifiers : $this->modifiers . 'u'; } - // Test the value against the regular expression. - if (preg_match(\chr(1) . $this->regex . \chr(1) . $this->modifiers, (string) $value)) { - return true; - } - - return false; + return (bool) preg_match(\chr(1) . $this->regex . \chr(1) . $this->modifiers, (string) $value); } } diff --git a/libraries/src/Form/Rule/CaptchaRule.php b/libraries/src/Form/Rule/CaptchaRule.php index 9e8e4573ecb5e..e7391519f4561 100644 --- a/libraries/src/Form/Rule/CaptchaRule.php +++ b/libraries/src/Form/Rule/CaptchaRule.php @@ -50,7 +50,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $default = $app->getParams()->get('captcha', $default); } - $plugin = $element['plugin'] ? (string) $element['plugin'] : $default; + $plugin = $element['plugin'] instanceof \SimpleXMLElement ? (string) $element['plugin'] : $default; $namespace = $element['namespace'] ?: $form->getName(); diff --git a/libraries/src/Form/Rule/ColorRule.php b/libraries/src/Form/Rule/ColorRule.php index 5e8b354847e6e..095d433f35ca0 100644 --- a/libraries/src/Form/Rule/ColorRule.php +++ b/libraries/src/Form/Rule/ColorRule.php @@ -46,22 +46,17 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr // If the field is empty and not required, the field is valid. $required = ((string) $element['required'] === 'true' || (string) $element['required'] === 'required'); - if (!$required && empty($value)) { + if (!$required && ($value === '' || $value === '0')) { return true; } - if ($value[0] != '#') { + if ($value[0] !== '#') { return false; } // Remove the leading # if present to validate the numeric part $value = ltrim($value, '#'); - // The value must be 6 or 3 characters long - if (!((\strlen($value) == 6 || \strlen($value) == 3) && ctype_xdigit($value))) { - return false; - } - - return true; + return (\strlen($value) == 6 || \strlen($value) == 3) && ctype_xdigit($value); } } diff --git a/libraries/src/Form/Rule/CssIdentifierRule.php b/libraries/src/Form/Rule/CssIdentifierRule.php index 67c80aba2ecf3..44fb9f66bf0b6 100644 --- a/libraries/src/Form/Rule/CssIdentifierRule.php +++ b/libraries/src/Form/Rule/CssIdentifierRule.php @@ -77,7 +77,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr /** * Full identifiers cannot start with a digit, two hyphens, or a hyphen followed by a digit. */ - if (preg_match('/^[0-9]/', $identifier) || preg_match('/^(-[0-9])|^(--)/', $identifier)) { + if (preg_match('/^\d/', $identifier) || preg_match('/^(-\d)|^(--)/', $identifier)) { return false; } } diff --git a/libraries/src/Form/Rule/EmailRule.php b/libraries/src/Form/Rule/EmailRule.php index bfda6f38f804a..75311b31e0dfa 100644 --- a/libraries/src/Form/Rule/EmailRule.php +++ b/libraries/src/Form/Rule/EmailRule.php @@ -140,11 +140,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr // All segments match, check whether to allow the domain or not. if ($status === $emailCount) { - if ($domain->rule == 0) { - $allowed = false; - } else { - $allowed = true; - } + $allowed = $domain->rule != 0; } } diff --git a/libraries/src/Form/Rule/EqualsRule.php b/libraries/src/Form/Rule/EqualsRule.php index c52908b943b18..79ada0e8ec821 100644 --- a/libraries/src/Form/Rule/EqualsRule.php +++ b/libraries/src/Form/Rule/EqualsRule.php @@ -48,7 +48,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $field = (string) $element['field']; // Check that a validation field is set. - if (!$field) { + if ($field === '' || $field === '0') { throw new \UnexpectedValueException(\sprintf('$field empty in %s::test', static::class)); } diff --git a/libraries/src/Form/Rule/FilePathRule.php b/libraries/src/Form/Rule/FilePathRule.php index 80d414a396cf3..8e5b36f9b4fd8 100644 --- a/libraries/src/Form/Rule/FilePathRule.php +++ b/libraries/src/Form/Rule/FilePathRule.php @@ -45,9 +45,9 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $value = trim((string) $value); // If the field is empty and not required, the field is valid. - $required = ((string) $element['required'] == 'true' || (string) $element['required'] == 'required'); + $required = ((string) $element['required'] === 'true' || (string) $element['required'] === 'required'); - if (!$required && empty($value)) { + if (!$required && ($value === '' || $value === '0')) { return true; } diff --git a/libraries/src/Form/Rule/FolderPathExistsRule.php b/libraries/src/Form/Rule/FolderPathExistsRule.php index 2e224b087ea5b..4eddf51497123 100644 --- a/libraries/src/Form/Rule/FolderPathExistsRule.php +++ b/libraries/src/Form/Rule/FolderPathExistsRule.php @@ -51,7 +51,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Spaces only would result in Joomla root which is not allowed - if (!trim((string) $value)) { + if (trim((string) $value) === '' || trim((string) $value) === '0') { return false; } diff --git a/libraries/src/Form/Rule/NotequalsRule.php b/libraries/src/Form/Rule/NotequalsRule.php index 6771602aed05c..1b122931605b7 100644 --- a/libraries/src/Form/Rule/NotequalsRule.php +++ b/libraries/src/Form/Rule/NotequalsRule.php @@ -48,19 +48,14 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr $field = (string) $element['field']; // Check that a validation field is set. - if (!$field) { + if ($field === '' || $field === '0') { throw new \UnexpectedValueException(\sprintf('$field empty in %s::test', static::class)); } - if ($input === null) { + if (!$input instanceof \Joomla\Registry\Registry) { throw new \InvalidArgumentException(\sprintf('The value for $input must not be null in %s', static::class)); } - // Test the two values against each other. - if ($value != $input->get($field)) { - return true; - } - - return false; + return $value != $input->get($field); } } diff --git a/libraries/src/Form/Rule/OptionsRule.php b/libraries/src/Form/Rule/OptionsRule.php index 8ce828fe6b87f..8c5f1dd4c93a7 100644 --- a/libraries/src/Form/Rule/OptionsRule.php +++ b/libraries/src/Form/Rule/OptionsRule.php @@ -58,7 +58,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr // Create the field $field = null; - if ($form) { + if ($form instanceof \Joomla\CMS\Form\Form) { $field = $form->getField((string) $element->attributes()->name, $group); } @@ -79,7 +79,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr // If all values are in the $options array, $diff will be empty and the options valid. $diff = array_diff($value, $options); - return empty($diff); + return $diff === []; } // In this case value must be a string diff --git a/libraries/src/Form/Rule/PasswordRule.php b/libraries/src/Form/Rule/PasswordRule.php index fa92514a94f31..93978c38ff26b 100644 --- a/libraries/src/Form/Rule/PasswordRule.php +++ b/libraries/src/Form/Rule/PasswordRule.php @@ -115,8 +115,8 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Minimum number of integers required - if (!empty($minimumIntegers)) { - $nInts = preg_match_all('/[0-9]/', (string) $value, $imatch); + if ($minimumIntegers !== 0) { + $nInts = preg_match_all('/\d/', (string) $value, $imatch); if ($nInts < $minimumIntegers) { Factory::getApplication()->enqueueMessage( @@ -129,7 +129,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Minimum number of symbols required - if (!empty($minimumSymbols)) { + if ($minimumSymbols !== 0) { $nsymbols = preg_match_all('[\W]', (string) $value, $smatch); if ($nsymbols < $minimumSymbols) { @@ -143,7 +143,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Minimum number of upper case ASCII characters required - if (!empty($minimumUppercase)) { + if ($minimumUppercase !== 0) { $nUppercase = preg_match_all('/[A-Z]/', (string) $value, $umatch); if ($nUppercase < $minimumUppercase) { @@ -157,7 +157,7 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Minimum number of lower case ASCII characters required - if (!empty($minimumLowercase)) { + if ($minimumLowercase !== 0) { $nLowercase = preg_match_all('/[a-z]/', (string) $value, $umatch); if ($nLowercase < $minimumLowercase) { @@ -171,22 +171,14 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // Minimum length option - if (!empty($minimumLength)) { - if (\strlen((string) $value) < $minimumLength) { - Factory::getApplication()->enqueueMessage( - Text::plural('JFIELD_PASSWORD_TOO_SHORT_N', $minimumLength), - 'error' - ); - - $validPassword = false; - } + if ($minimumLength !== 0 && \strlen((string) $value) < $minimumLength) { + Factory::getApplication()->enqueueMessage( + Text::plural('JFIELD_PASSWORD_TOO_SHORT_N', $minimumLength), + 'error' + ); + $validPassword = false; } - // If valid has violated any rules above return false. - if (!$validPassword) { - return false; - } - - return true; + return $validPassword; } } diff --git a/libraries/src/Form/Rule/RegexRule.php b/libraries/src/Form/Rule/RegexRule.php index 1204dd04a9d0d..3d2f1c7617ddc 100644 --- a/libraries/src/Form/Rule/RegexRule.php +++ b/libraries/src/Form/Rule/RegexRule.php @@ -42,11 +42,11 @@ class RegexRule extends FormRule */ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registry $input = null, ?Form $form = null) { - if ((string) $element['validate_regex']) { + if ((string) $element['validate_regex'] !== '' && (string) $element['validate_regex'] !== '0') { $this->regex = (string) $element['validate_regex']; } - if ((string) $element['validate_modifier']) { + if ((string) $element['validate_modifier'] !== '' && (string) $element['validate_modifier'] !== '0') { $this->modifiers = (string) $element['validate_modifier']; } diff --git a/libraries/src/Form/Rule/RulesRule.php b/libraries/src/Form/Rule/RulesRule.php index 764b1a39069ce..221314f29d3e9 100644 --- a/libraries/src/Form/Rule/RulesRule.php +++ b/libraries/src/Form/Rule/RulesRule.php @@ -69,10 +69,7 @@ protected function getValueActions($value) { $actions = []; - // Iterate over the asset actions and add to the actions. - foreach ((array) $value as $name => $rules) { - $actions[] = $name; - } + $actions = array_keys((array) $value); return $actions; } @@ -91,8 +88,8 @@ protected function getFieldActions(\SimpleXMLElement $element) $actions = []; // Initialise some field attributes. - $section = $element['section'] ? (string) $element['section'] : ''; - $component = $element['component'] ? (string) $element['component'] : ''; + $section = $element['section'] instanceof \SimpleXMLElement ? (string) $element['section'] : ''; + $component = $element['component'] instanceof \SimpleXMLElement ? (string) $element['component'] : ''; // Get the asset actions for the element. $elActions = Access::getActionsFromFile( diff --git a/libraries/src/Form/Rule/SubformRule.php b/libraries/src/Form/Rule/SubformRule.php index b34f40beab2cc..beecb50d98236 100644 --- a/libraries/src/Form/Rule/SubformRule.php +++ b/libraries/src/Form/Rule/SubformRule.php @@ -69,18 +69,14 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr return false; } } - } else { + } elseif ($subForm->validate($value) === false) { // Single value. - if ($subForm->validate($value) === false) { - // Pass the first error that occurred on the subform validation. - $errors = $subForm->getErrors(); - - if (!empty($errors[0])) { - return $errors[0]; - } - - return false; + // Pass the first error that occurred on the subform validation. + $errors = $subForm->getErrors(); + if (!empty($errors[0])) { + return $errors[0]; } + return false; } return true; diff --git a/libraries/src/Form/Rule/TelRule.php b/libraries/src/Form/Rule/TelRule.php index c050366eee3bb..da96f815698fe 100644 --- a/libraries/src/Form/Rule/TelRule.php +++ b/libraries/src/Form/Rule/TelRule.php @@ -58,9 +58,9 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr * @note that valid ITU-T and EPP must begin with +. */ $regexarray = [ - 'NANP' => '/^(?:\+?1[-. ]?)?\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$/', - 'ITU-T' => '/^\+(?:[0-9] ?){6,14}[0-9]$/', - 'EPP' => '/^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$/', + 'NANP' => '/^(?:\+?1[-. ]?)?\(?([2-9][0-8]\d)\)?[-. ]?([2-9]\d{2})[-. ]?(\d{4})$/', + 'ITU-T' => '/^\+(?:\d ?){6,14}\d$/', + 'EPP' => '/^\+\d{1,3}\.\d{4,14}(?:x.+)?$/', ]; if (isset($element['plan'])) { @@ -87,13 +87,8 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr * are allowed). */ $cleanvalue = preg_replace('/[+. \-(\)]/', '', (string) $value); - $regex = '/^[0-9]{7,15}?$/'; - - if (preg_match($regex, (string) $cleanvalue) == true) { - return true; - } - - return false; + $regex = '/^\d{7,15}?$/'; + return preg_match($regex, (string) $cleanvalue) == true; } return true; diff --git a/libraries/src/Form/Rule/TimeRule.php b/libraries/src/Form/Rule/TimeRule.php index 22d84c284f402..1b09510de6bfe 100644 --- a/libraries/src/Form/Rule/TimeRule.php +++ b/libraries/src/Form/Rule/TimeRule.php @@ -111,15 +111,12 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // If the hour input is equal to the set max but the minutes input is greater than zero return error message - if (\intval($max) === \intval($stringValue[0] . $stringValue[1])) { - if (\intval($element['min'][3] . $element['min'][4]) !== 0) { - Factory::getApplication()->enqueueMessage( - Text::_('JLIB_FORM_FIELD_INVALID_MAX_TIME'), - 'warning' - ); - - return false; - } + if (\intval($max) === \intval($stringValue[0] . $stringValue[1]) && \intval($element['min'][3] . $element['min'][4]) !== 0) { + Factory::getApplication()->enqueueMessage( + Text::_('JLIB_FORM_FIELD_INVALID_MAX_TIME'), + 'warning' + ); + return false; } } @@ -154,19 +151,12 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr } // If the step is set return same error messages as above but taking into a count that there 8 and not 5 symbols - if (isset($element['step'])) { - if ( - \strlen($stringValue) !== 8 - || \intval($stringValue[5]) !== 0 - || \intval($stringValue[6]) > 5 - ) { - Factory::getApplication()->enqueueMessage( - Text::_('JLIB_FORM_FIELD_INVALID_TIME_INPUT_SECONDS'), - 'warning' - ); - - return false; - } + if (isset($element['step']) && (\strlen($stringValue) !== 8 || \intval($stringValue[5]) !== 0 || \intval($stringValue[6]) > 5)) { + Factory::getApplication()->enqueueMessage( + Text::_('JLIB_FORM_FIELD_INVALID_TIME_INPUT_SECONDS'), + 'warning' + ); + return false; } return true; diff --git a/libraries/src/Form/Rule/UrlRule.php b/libraries/src/Form/Rule/UrlRule.php index 5c082aead5188..0b1a649db1fc9 100644 --- a/libraries/src/Form/Rule/UrlRule.php +++ b/libraries/src/Form/Rule/UrlRule.php @@ -87,14 +87,9 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr return false; } - // The best we can do for the rest is make sure that the path exists and is valid UTF-8. - if (!\array_key_exists('path', $urlParts) || !StringHelper::valid((string) $urlParts['path'])) { - return false; - } - // The internal URL seems to be good. - return true; + return \array_key_exists('path', $urlParts) && StringHelper::valid((string) $urlParts['path']); } // Scheme found, check all parts found. @@ -121,11 +116,6 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr if (\array_key_exists('port', $urlParts) && 0 === (int) $urlParts['port']) { return false; } - - if (\array_key_exists('path', $urlParts) && !StringHelper::valid((string) $urlParts['path'])) { - return false; - } - - return true; + return !(\array_key_exists('path', $urlParts) && !StringHelper::valid((string) $urlParts['path'])); } } diff --git a/libraries/src/Form/Rule/UsernameRule.php b/libraries/src/Form/Rule/UsernameRule.php index 304b19b7a1c79..0faa4ca873297 100644 --- a/libraries/src/Form/Rule/UsernameRule.php +++ b/libraries/src/Form/Rule/UsernameRule.php @@ -68,11 +68,6 @@ public function test(\SimpleXMLElement $element, $value, $group = null, ?Registr // Set and query the database. $db->setQuery($query); $duplicate = (bool) $db->loadResult(); - - if ($duplicate) { - return false; - } - - return true; + return !$duplicate; } } diff --git a/libraries/src/HTML/HTMLHelper.php b/libraries/src/HTML/HTMLHelper.php index bc22c63435c4c..765a3da050a91 100644 --- a/libraries/src/HTML/HTMLHelper.php +++ b/libraries/src/HTML/HTMLHelper.php @@ -178,10 +178,8 @@ final public static function _(string $key, ...$methodArgs) } // If calling a method from this class, do not allow access to internal methods - if ($className === self::class) { - if (!((new \ReflectionMethod($className, $func))->isPublic())) { - throw new \InvalidArgumentException('Access to internal class methods is not allowed.'); - } + if ($className === self::class && !((new \ReflectionMethod($className, $func))->isPublic())) { + throw new \InvalidArgumentException('Access to internal class methods is not allowed.'); } $toCall = [$className, $func]; @@ -770,7 +768,7 @@ public static function stylesheet($file, $options = [], $attribs = []) // If only path is required if ($options['pathOnly']) { if (\count($includes) === 0) { - return; + return null; } if (\count($includes) === 1) { @@ -791,6 +789,7 @@ public static function stylesheet($file, $options = [], $attribs = []) $document->addStyleSheet($include, $options, $attribs); } + return null; } /** @@ -817,7 +816,7 @@ public static function script($file, $options = [], $attribs = []) // If only path is required if ($options['pathOnly']) { if (\count($includes) === 0) { - return; + return null; } if (\count($includes) === 1) { @@ -838,6 +837,7 @@ public static function script($file, $options = [], $attribs = []) $document->addScript($include, $options, $attribs); } + return null; } /** @@ -955,11 +955,7 @@ public static function tooltip($tooltip, $title = '', $image = 'tooltip.png', $t $text = static::image($image, $alt, null, true); } - if ($href) { - $tip = '' . $text . ''; - } else { - $tip = $text; - } + $tip = $href ? '' . $text . '' : $text; if ($class === 'hasTip') { // Still using MooTools tooltips! @@ -996,7 +992,7 @@ public static function tooltipText($title = '', $content = '', $translate = true // Don't process empty strings if ($content !== '' || $title !== '') { // Split title into title and content if the title contains '::' (old Mootools format). - if ($content === '' && !(!str_contains($title, '::'))) { + if ($content === '' && (bool) str_contains($title, '::')) { [$title, $content] = explode('::', $title, 2); } diff --git a/libraries/src/HTML/Helpers/AdminLanguage.php b/libraries/src/HTML/Helpers/AdminLanguage.php index 8b54fcdb2cee8..09858d75610b6 100644 --- a/libraries/src/HTML/Helpers/AdminLanguage.php +++ b/libraries/src/HTML/Helpers/AdminLanguage.php @@ -44,7 +44,7 @@ abstract class AdminLanguage */ public static function existing($all = false, $translate = false) { - if (empty(static::$items)) { + if (static::$items === []) { $languages = []; $admin_languages = LanguageHelper::getKnownLanguages(JPATH_ADMINISTRATOR); diff --git a/libraries/src/HTML/Helpers/Behavior.php b/libraries/src/HTML/Helpers/Behavior.php index 3799531a1551d..b584513e494ef 100644 --- a/libraries/src/HTML/Helpers/Behavior.php +++ b/libraries/src/HTML/Helpers/Behavior.php @@ -165,7 +165,7 @@ public static function highlighter(array $terms, $start = 'highlighter-start', $ { $terms = array_filter($terms, 'strlen'); - if (!empty($terms)) { + if ($terms !== []) { $doc = Factory::getDocument(); $doc->getWebAssetManager()->useScript('highlight'); diff --git a/libraries/src/HTML/Helpers/Bootstrap.php b/libraries/src/HTML/Helpers/Bootstrap.php index be08a53c89332..1435dc29dd3eb 100644 --- a/libraries/src/HTML/Helpers/Bootstrap.php +++ b/libraries/src/HTML/Helpers/Bootstrap.php @@ -666,7 +666,7 @@ public static function startAccordion($selector = 'myAccordian', $options = []): $opt = []; $opt['parent'] = isset($options['parent']) ? ($options['parent'] == true ? '#' . preg_replace('/^[\.#]/', '', $selector) : $options['parent']) : ''; - $opt['toggle'] = isset($options['toggle']) ? (bool) $options['toggle'] : !($opt['parent'] === false || isset($options['active'])); + $opt['toggle'] = isset($options['toggle']) ? (bool) $options['toggle'] : $opt['parent'] !== false && !isset($options['active']); $opt['active'] = (string) ($options['active'] ?? ''); // Initialise with the Joomla specifics @@ -709,7 +709,7 @@ public static function addSlide($selector, $text, $id, $class = ''): string $collapsed = static::$loaded[self::class . '::startAccordion'][$selector]['active'] === $id ? '' : ' collapsed'; $parent = static::$loaded[self::class . '::startAccordion'][$selector]['parent'] ? 'data-bs-parent="' . static::$loaded[self::class . '::startAccordion'][$selector]['parent'] . '"' : ''; - $class = (!empty($class)) ? ' ' . $class : ''; + $class = (empty($class)) ? '' : ' ' . $class; $ariaExpanded = $in === 'show'; return <<addScriptOptions( 'draggable-list', [ diff --git a/libraries/src/HTML/Helpers/Grid.php b/libraries/src/HTML/Helpers/Grid.php index 8dd523b468ece..eb3674120fe77 100644 --- a/libraries/src/HTML/Helpers/Grid.php +++ b/libraries/src/HTML/Helpers/Grid.php @@ -140,11 +140,7 @@ public static function checkedOut(&$row, $i, $identifier = 'id') $user = Factory::getUser(); $userid = $user->id; - if ($row instanceof Table) { - $result = $row->isCheckedOut($userid); - } else { - $result = false; - } + $result = $row instanceof Table ? $row->isCheckedOut($userid) : false; if ($result) { return static::_checkedOut($row); diff --git a/libraries/src/HTML/Helpers/JGrid.php b/libraries/src/HTML/Helpers/JGrid.php index c93a0bb4c77fb..afae2ecd82e85 100644 --- a/libraries/src/HTML/Helpers/JGrid.php +++ b/libraries/src/HTML/Helpers/JGrid.php @@ -228,7 +228,7 @@ public static function published( $tip = empty($tips) ? false : implode('
    ', $tips); // Add tips and special titles - foreach ($states as $key => $state) { + foreach (array_keys($states) as $key) { // Create special titles for published items if ($key == 1) { $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_ITEM'; diff --git a/libraries/src/HTML/Helpers/Menu.php b/libraries/src/HTML/Helpers/Menu.php index a4885061ac346..c52691f7d0ddf 100644 --- a/libraries/src/HTML/Helpers/Menu.php +++ b/libraries/src/HTML/Helpers/Menu.php @@ -161,10 +161,10 @@ public static function menuItems($config = []) $user = Factory::getUser(); - $aclcheck = !empty($config['checkacl']) ? (int) $config['checkacl'] : 0; + $aclcheck = empty($config['checkacl']) ? 0 : (int) $config['checkacl']; foreach ($menus as &$menu) { - if ($aclcheck) { + if ($aclcheck !== 0) { $action = $aclcheck == $menu->id ? 'edit' : 'create'; if (!$user->authorise('core.' . $action, 'com_menus.menu.' . $menu->id)) { @@ -344,7 +344,7 @@ public static function linkOptions($all = false, $unassigned = false, $clientId // Code that adds menu name to Display of Page(s) $mitems = []; - if ($all | $unassigned) { + if (($all | $unassigned) !== 0) { $mitems[] = HTMLHelper::_('select.option', '', Text::_('JOPTION_MENUS')); if ($all) { @@ -411,11 +411,7 @@ public static function treerecurse($id, $indent, $list, &$children, $maxlevel = foreach ($children[$id] as $v) { $id = $v->id; - if ($v->parent_id == 0) { - $txt = $v->title; - } else { - $txt = $pre . $v->title; - } + $txt = $v->parent_id == 0 ? $v->title : $pre . $v->title; $list[$id] = $v; $list[$id]->treename = $indent . $txt; diff --git a/libraries/src/HTML/Helpers/Select.php b/libraries/src/HTML/Helpers/Select.php index fbacd5643e7de..652e0488cbb33 100644 --- a/libraries/src/HTML/Helpers/Select.php +++ b/libraries/src/HTML/Helpers/Select.php @@ -385,7 +385,7 @@ public static function option($value, $text = '', $optKey = 'value', $optText = $obj = new \stdClass(); $obj->{$options['option.key']} = $value; - $obj->{$options['option.text']} = trim($text) ? $text : $value; + $obj->{$options['option.text']} = trim($text) !== '' && trim($text) !== '0' ? $text : $value; /* * If a label is provided, save it. If no label is provided and there is @@ -569,11 +569,7 @@ public static function options($arr, $optKey = 'value', $optText = 'text', $sele $label = htmlentities((string) $label); } - if (\is_array($attr)) { - $attr = ArrayHelper::toString($attr); - } else { - $attr = trim((string) $attr); - } + $attr = \is_array($attr) ? ArrayHelper::toString($attr) : trim((string) $attr); $extra = ($id ? ' id="' . $id . '"' : '') . ($label ? ' label="' . $label . '"' : '') . ($attr ? ' ' . $attr : '') . $extra; diff --git a/libraries/src/Help/Help.php b/libraries/src/Help/Help.php index 9e8afda5ad849..5f6a4ddedbfa2 100644 --- a/libraries/src/Help/Help.php +++ b/libraries/src/Help/Help.php @@ -76,10 +76,8 @@ public static function createUrl($ref, $useComponent = false, $override = null, } // If the URL is local then make sure we have a valid file extension on the URL. - if ($local) { - if (!preg_match('#\.html$|\.xml$#i', $ref)) { - $url .= '.html'; - } + if ($local && !preg_match('#\.html$|\.xml$#i', $ref)) { + $url .= '.html'; } /* diff --git a/libraries/src/Helper/AuthenticationHelper.php b/libraries/src/Helper/AuthenticationHelper.php index 5d82bf3aa47ca..979c07e7231ab 100644 --- a/libraries/src/Helper/AuthenticationHelper.php +++ b/libraries/src/Helper/AuthenticationHelper.php @@ -105,7 +105,7 @@ public static function getLoginButtons(string $formId): array foreach ($results as $result) { // Did we get garbage back from the plugin? - if (!\is_array($result) || empty($result)) { + if (!\is_array($result) || $result === []) { continue; } diff --git a/libraries/src/Helper/MediaHelper.php b/libraries/src/Helper/MediaHelper.php index ac194a4649c7d..ac4f07cd4cdef 100644 --- a/libraries/src/Helper/MediaHelper.php +++ b/libraries/src/Helper/MediaHelper.php @@ -174,7 +174,7 @@ public static function checkFileExtension($extension, $component = 'com_media', $executables = array_merge(self::EXECUTABLES, InputFilter::FORBIDDEN_FILE_EXTENSIONS); // Remove allowed executables from array - if (\count($allowedExecutables)) { + if (\count($allowedExecutables) > 0) { $executables = array_diff($executables, $allowedExecutables); } @@ -184,13 +184,8 @@ public static function checkFileExtension($extension, $component = 'com_media', $allowable = array_map('trim', explode(',', (string) $params->get('restrict_uploads_extensions', 'bmp,gif,jpg,jpeg,png,webp,avif,ico,mp3,m4a,mp4a,ogg,mp4,mp4v,mpeg,mov,odg,odp,ods,odt,pdf,ppt,txt,xcf,xls,csv'))); $ignored = array_map('trim', explode(',', (string) $params->get('ignore_extensions', ''))); - - if ($extension == '' || $extension == false || (!\in_array($extension, $allowable, true) && !\in_array($extension, $ignored, true))) { - return false; - } - // We don't check mime at all or it passes the checks - return true; + return !($extension == '' || $extension == false || !\in_array($extension, $allowable, true) && !\in_array($extension, $ignored, true)); } /** @@ -245,7 +240,7 @@ public function canUpload($file, $component = 'com_media', $allowedExecutables = $check = array_intersect($filetypes, $executables); - if (!empty($check)) { + if ($check !== []) { $app->enqueueMessage(Text::_('JLIB_MEDIA_ERROR_WARNFILETYPE'), 'error'); return false; @@ -354,11 +349,7 @@ public static function imageResize($width, $height, $target) * formula accordingly. This is so this script will work * dynamically with any size image */ - if ($width > $height) { - $percentage = ($target / $width); - } else { - $percentage = ($target / $height); - } + $percentage = $width > $height ? $target / $width : $target / $height; // Gets the new value and applies the percentage, then rounds the value $width = round($width * $percentage); diff --git a/libraries/src/Helper/ModuleHelper.php b/libraries/src/Helper/ModuleHelper.php index 71a4feacc74ed..3ab8682beef1c 100644 --- a/libraries/src/Helper/ModuleHelper.php +++ b/libraries/src/Helper/ModuleHelper.php @@ -52,13 +52,11 @@ public static function &getModule($name, $title = null) foreach ($modules as $module) { // Match the name of the module - if ($module->name === $name || $module->module === $name) { - // Match the title if we're looking for a specific instance of the module - if (!$title || $module->title === $title) { - // Found it - $result = $module; - break; - } + // Match the title if we're looking for a specific instance of the module + if (($module->name === $name || $module->module === $name) && (!$title || $module->title === $title)) { + // Found it + $result = $module; + break; } } @@ -94,7 +92,7 @@ public static function &getModules($position) } // Prepend a dummy module for template preview if no module is published in the position - if (empty($result) && $input->getBool('tp') && ComponentHelper::getParams('com_templates')->get('template_positions_display')) { + if ($result === [] && $input->getBool('tp') && ComponentHelper::getParams('com_templates')->get('template_positions_display')) { $dummy = static::createDummyModule(); $dummy->title = $position; $dummy->position = $position; diff --git a/libraries/src/Helper/RouteHelper.php b/libraries/src/Helper/RouteHelper.php index b63349b08d789..587157709d758 100644 --- a/libraries/src/Helper/RouteHelper.php +++ b/libraries/src/Helper/RouteHelper.php @@ -82,7 +82,7 @@ public function getRoute($id, $typealias, $link = '', $language = null, $catid = $needles = []; - if (isset($this->view)) { + if ($this->view !== null) { $needles[$this->view] = [(int) $id]; } @@ -201,7 +201,7 @@ protected function findItem($needles = []) // If not found, return language specific home link $default = $menus->getDefault($language); - return !empty($default->id) ? $default->id : null; + return empty($default->id) ? null : $default->id; } /** diff --git a/libraries/src/Helper/TagsHelper.php b/libraries/src/Helper/TagsHelper.php index bf7dbcc6323a8..c57397f159f9d 100644 --- a/libraries/src/Helper/TagsHelper.php +++ b/libraries/src/Helper/TagsHelper.php @@ -115,7 +115,7 @@ public function addTagMapping($ucmId, TableInterface $table, $tags = []) // Prevent saving duplicate tags $tags = array_values(array_unique($tags)); - if (!$tags) { + if ($tags === []) { return true; } @@ -167,15 +167,13 @@ public static function convertPathsToNames($tags) $aliases = []; foreach ($tags as $tag) { - if (!empty($tag->path)) { - if ($pathParts = explode('/', $tag->path)) { - $aliases = array_merge($aliases, $pathParts); - } + if (!empty($tag->path) && $pathParts = explode('/', $tag->path)) { + $aliases = array_merge($aliases, $pathParts); } } // Get the aliases titles in one single query and map the results - if ($aliases) { + if ($aliases !== []) { // Remove duplicates $aliases = array_values(array_unique($aliases)); @@ -203,18 +201,11 @@ public static function convertPathsToNames($tags) foreach ($tags as $tag) { $namesPath = []; - if (!empty($tag->path)) { - if ($pathParts = explode('/', $tag->path)) { - foreach ($pathParts as $alias) { - if (isset($aliasesMapper[$alias])) { - $namesPath[] = $aliasesMapper[$alias]['title']; - } else { - $namesPath[] = $alias; - } - } - - $tag->text = implode('/', $namesPath); + if (!empty($tag->path) && $pathParts = explode('/', $tag->path)) { + foreach ($pathParts as $alias) { + $namesPath[] = isset($aliasesMapper[$alias]) ? $aliasesMapper[$alias]['title'] : $alias; } + $tag->text = implode('/', $namesPath); } } } @@ -236,7 +227,7 @@ public static function convertPathsToNames($tags) public function createTagsFromField($tags) { if (empty($tags) || $tags[0] == '') { - return; + return null; } // We will use the tags table to store them @@ -470,7 +461,7 @@ public function getMultipleItemTags($contentType, array $ids, $getTagData = true public function getTagIds($ids, $prefix) { if (empty($ids)) { - return; + return null; } /** @@ -708,7 +699,7 @@ public function getTagNames($tagIds) { $tagNames = []; - if (\is_array($tagIds) && \count($tagIds) > 0) { + if (\is_array($tagIds) && $tagIds !== []) { $tagIds = ArrayHelper::toInteger($tagIds); $db = Factory::getDbo(); @@ -756,6 +747,7 @@ public function getTagTreeArray($id, &$tagTreeArray = []) return $tagTreeArray; } + return null; } /** @@ -883,13 +875,13 @@ public function preStoreProcess(TableInterface $table, $newTags = []) } // New items with no tags bypass this step. - if ((!empty($newTags) && \is_string($newTags) || (isset($newTags[0]) && $newTags[0] != '')) || isset($this->oldTags)) { + if ((!empty($newTags) && \is_string($newTags) || (isset($newTags[0]) && $newTags[0] != '')) || $this->oldTags !== null) { if (\is_array($newTags)) { $newTags = implode(',', $newTags); } // We need to process tags if the tags have changed or if we have a new row - $this->tagsChanged = (empty($this->oldTags) && !empty($newTags)) || (!empty($this->oldTags) && $this->oldTags != $newTags) || !$table->$key; + $this->tagsChanged = (empty($this->oldTags) && ($newTags !== '' && $newTags !== '0')) || (!empty($this->oldTags) && $this->oldTags != $newTags) || !$table->$key; } } @@ -1045,18 +1037,13 @@ public function tagItem($ucmId, TableInterface $table, $tags = [], $replace = tr if ($replace) { $newTags = $tags; } else { - if ($tags == []) { - $newTags = $table->newTags; - } else { - $newTags = $tags; - } - - if ($oldTags[0] != '') { + $newTags = $tags == [] ? $table->newTags : $tags; + if ($oldTags[0] !== '') { $newTags = array_unique(array_merge($newTags, $oldTags)); } } - if (\is_array($newTags) && \count($newTags) > 0 && $newTags[0] != '') { + if (\is_array($newTags) && $newTags !== [] && $newTags[0] != '') { $result = $result && $this->addTagMapping($ucmId, $table, $newTags); } @@ -1090,7 +1077,7 @@ public function unTagItem($contentId, TableInterface $table, $tags = []) ->bind(':type', $this->typeAlias) ->bind(':id', $id, ParameterType::INTEGER); - if (\is_array($tags) && \count($tags) > 0) { + if (\is_array($tags) && $tags !== []) { $tags = ArrayHelper::toInteger($tags); $query->whereIn($db->quoteName('tag_id'), $tags); @@ -1114,7 +1101,7 @@ public function getTags($tagIds) { $tagNames = []; - if (\is_array($tagIds) && \count($tagIds) > 0) { + if (\is_array($tagIds) && $tagIds !== []) { $tagIds = ArrayHelper::toInteger($tagIds); $db = Factory::getDbo(); diff --git a/libraries/src/Helper/UserGroupsHelper.php b/libraries/src/Helper/UserGroupsHelper.php index 40a7cc98554df..58cbf59ea4dbd 100644 --- a/libraries/src/Helper/UserGroupsHelper.php +++ b/libraries/src/Helper/UserGroupsHelper.php @@ -83,7 +83,7 @@ public function __construct(array $groups = [], $mode = self::MODE_INSTANCE) { $this->mode = (int) $mode; - if ($groups) { + if ($groups !== []) { $this->setGroups($groups); } } @@ -113,7 +113,7 @@ public static function getInstance() // Only here to avoid code style issues... $groups = []; - static::$instance = new static($groups, static::MODE_SINGLETON); + static::$instance = new self($groups, self::MODE_SINGLETON); } return static::$instance; @@ -183,7 +183,7 @@ public function has($id) */ private function isSingleton() { - return $this->mode === static::MODE_SINGLETON; + return $this->mode === self::MODE_SINGLETON; } /** diff --git a/libraries/src/Http/HttpFactory.php b/libraries/src/Http/HttpFactory.php index 85412d1e728df..549f0ec12d318 100644 --- a/libraries/src/Http/HttpFactory.php +++ b/libraries/src/Http/HttpFactory.php @@ -70,7 +70,7 @@ public static function getAvailableDriver($options = [], $default = null) if (\is_null($default)) { $availableAdapters = static::getHttpTransports(); } else { - settype($default, 'array'); + $default = (array) $default; $availableAdapters = $default; } diff --git a/libraries/src/Http/Transport/CurlTransport.php b/libraries/src/Http/Transport/CurlTransport.php index c885d57dd48c1..38506f8fcd1f0 100644 --- a/libraries/src/Http/Transport/CurlTransport.php +++ b/libraries/src/Http/Transport/CurlTransport.php @@ -172,7 +172,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers if (!\is_string($content)) { $message = curl_error($ch); - if (empty($message)) { + if ($message === '' || $message === '0') { // Error but nothing from cURL? Create our own $message = 'No HTTP response received'; } @@ -246,7 +246,7 @@ protected function getResponse($content, $info) } // Get the response code from the first offset of the response headers. - preg_match('/[0-9]{3}/', array_shift($headers), $matches); + preg_match('/\d{3}/', array_shift($headers), $matches); $code = \count($matches) ? $matches[0] : null; @@ -286,12 +286,7 @@ public static function isSupported() private function redirectsAllowed() { $curlVersion = curl_version(); - // If open_basedir is enabled we also need to check if libcurl version is 7.19.4 or higher - if (!\ini_get('open_basedir') || version_compare($curlVersion['version'], '7.19.4', '>=')) { - return true; - } - - return false; + return !\ini_get('open_basedir') || version_compare($curlVersion['version'], '7.19.4', '>='); } } diff --git a/libraries/src/Http/Transport/SocketTransport.php b/libraries/src/Http/Transport/SocketTransport.php index 45c10da198e7a..8a7c8f4a0aeba 100644 --- a/libraries/src/Http/Transport/SocketTransport.php +++ b/libraries/src/Http/Transport/SocketTransport.php @@ -163,7 +163,7 @@ protected function getResponse($content) $body = empty($response[1]) ? '' : $response[1]; // Get the response code from the first offset of the response headers. - preg_match('/[0-9]{3}/', array_shift($headers), $matches); + preg_match('/\d{3}/', array_shift($headers), $matches); $code = $matches[0]; if (!is_numeric($code)) { @@ -241,14 +241,14 @@ protected function connect(UriInterface $uri, $timeout = null) if (!$connection) { // Error but nothing from php? Create our own - if (!$err) { + if ($err === '' || $err === '0') { $err = \sprintf('Could not connect to host: %s:%s', $host, $port); } throw new \Exception($err); } } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } finally { restore_error_handler(); } diff --git a/libraries/src/Http/Transport/StreamTransport.php b/libraries/src/Http/Transport/StreamTransport.php index 23d016d546e60..79587744df3de 100644 --- a/libraries/src/Http/Transport/StreamTransport.php +++ b/libraries/src/Http/Transport/StreamTransport.php @@ -53,17 +53,10 @@ public function request($method, UriInterface $uri, $data = null, array $headers // If data exists let's encode it and make sure our Content-Type header is set. if (isset($data)) { // If the data is a scalar value simply add it to the stream context options. - if (\is_scalar($data)) { - $options['content'] = $data; - } else { - // Otherwise we need to encode the value first. - $options['content'] = http_build_query($data); - } - + $options['content'] = \is_scalar($data) ? $data : http_build_query($data); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; } - // Add the relevant headers. $headers['Content-Length'] = \strlen($options['content']); } @@ -157,7 +150,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers throw new \Exception(\sprintf('Could not connect to resource: %s', $uri)); } } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } finally { restore_error_handler(); } @@ -196,7 +189,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers protected function getResponse(array $headers, $body) { // Get the response code from the first offset of the response headers. - preg_match('/[0-9]{3}/', (string) array_shift($headers), $matches); + preg_match('/\d{3}/', (string) array_shift($headers), $matches); $code = $matches[0]; if (!is_numeric($code)) { diff --git a/libraries/src/Image/Image.php b/libraries/src/Image/Image.php index 9a3d926244cf0..47253b66d25c3 100644 --- a/libraries/src/Image/Image.php +++ b/libraries/src/Image/Image.php @@ -117,7 +117,7 @@ public function __construct($source = null) } // Determine which image types are supported by GD, but only once. - if (empty(static::$formats)) { + if (static::$formats === []) { $info = gd_info(); static::$formats[IMAGETYPE_JPEG] = $info['JPEG Support']; static::$formats[IMAGETYPE_PNG] = $info['PNG Support']; @@ -127,7 +127,7 @@ public function __construct($source = null) } // If the source input is a resource, set it as the image handle. - if ($source && (\is_object($source) && $source::class == 'GdImage')) { + if ($source && (\is_object($source) && $source::class === 'GdImage')) { $this->handle = $source; } elseif (!empty($source) && \is_string($source)) { // If the source input is not empty, assume it is a path and populate the image handle. @@ -258,7 +258,7 @@ public function generateThumbs($thumbSizes, $creationMethod = self::SCALE_INSIDE // Process thumbs $generated = []; - if (!empty($thumbSizes)) { + if ($thumbSizes !== []) { foreach ($thumbSizes as $thumbSize) { // Desired thumbnail size $size = explode('x', strtolower((string) $thumbSize)); @@ -433,7 +433,7 @@ public function crop($width, $height, $left = null, $top = null, $createNew = tr } if ($ict >= 0 && $ict < $ctot) { $rgba = imagecolorsforindex($this->getHandle(), $ict); - if (!empty($rgba)) { + if ($rgba !== []) { $color = imagecolorallocatealpha( $handle, $rgba['red'], @@ -543,11 +543,7 @@ public function getPath() public function isLoaded() { // Make sure the resource handle is valid. - if (!(\is_object($this->handle) && $this->handle::class == 'GdImage')) { - return false; - } - - return true; + return \is_object($this->handle) && $this->handle::class === 'GdImage'; } /** @@ -729,7 +725,7 @@ public function resize($width, $height, $createNew = true, $scaleMethod = self:: } if ($ict >= 0 && $ict < $ctot) { $rgba = imagecolorsforindex($this->getHandle(), $ict); - if (!empty($rgba)) { + if ($rgba !== []) { $color = imagecolorallocatealpha( $handle, $rgba['red'], @@ -1029,11 +1025,7 @@ protected function prepareDimensions($width, $height, $scaleMethod) $rx = ($width > 0) ? ($this->getWidth() / $width) : 0; $ry = ($height > 0) ? ($this->getHeight() / $height) : 0; - if ($scaleMethod != self::SCALE_OUTSIDE) { - $ratio = max($rx, $ry); - } else { - $ratio = min($rx, $ry); - } + $ratio = $scaleMethod != self::SCALE_OUTSIDE ? max($rx, $ry) : min($rx, $ry); $dimensions->width = (int) round($this->getWidth() / $ratio); $dimensions->height = (int) round($this->getHeight() / $ratio); @@ -1062,7 +1054,7 @@ protected function sanitizeHeight($height, $width) $height ??= $width; // If we were given a percentage, calculate the integer value. - if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', (string) $height)) { + if (preg_match('/^\d+(\.\d+)?\%$/', (string) $height)) { $height = (int) round($this->getHeight() * (float) str_replace('%', '', $height) / 100); } else { // Else do some rounding so we come out with a sane integer value. $height = (int) round((float) $height); @@ -1101,7 +1093,7 @@ protected function sanitizeWidth($width, $height) $width ??= $height; // If we were given a percentage, calculate the integer value. - if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', (string) $width)) { + if (preg_match('/^\d+(\.\d+)?\%$/', (string) $width)) { $width = (int) round($this->getWidth() * (float) str_replace('%', '', $width) / 100); } else { // Else do some rounding so we come out with a sane integer value. $width = (int) round((float) $width); diff --git a/libraries/src/Image/ImageFilter.php b/libraries/src/Image/ImageFilter.php index d79a7d205aab2..8d3bd089a94f9 100644 --- a/libraries/src/Image/ImageFilter.php +++ b/libraries/src/Image/ImageFilter.php @@ -43,7 +43,7 @@ public function __construct($handle) } // Make sure the file handle is valid. - if (!(\is_object($handle) && $handle::class == 'GdImage')) { + if (!(\is_object($handle) && $handle::class === 'GdImage')) { throw new \InvalidArgumentException('The image handle is invalid for the image filter.'); } diff --git a/libraries/src/Input/Cli.php b/libraries/src/Input/Cli.php index 2fb194ce48384..7f2967427061c 100644 --- a/libraries/src/Input/Cli.php +++ b/libraries/src/Input/Cli.php @@ -61,11 +61,7 @@ class Cli extends Input */ public function __construct(?array $source = null, array $options = []) { - if (isset($options['filter'])) { - $this->filter = $options['filter']; - } else { - $this->filter = InputFilter::getInstance(); - } + $this->filter = $options['filter'] ?? InputFilter::getInstance(); // Get the command line options $this->parseArguments(); diff --git a/libraries/src/Input/Cookie.php b/libraries/src/Input/Cookie.php index 5c5038d783b18..06e7093a57fc1 100644 --- a/libraries/src/Input/Cookie.php +++ b/libraries/src/Input/Cookie.php @@ -38,11 +38,7 @@ class Cookie extends Input */ public function __construct(?array $source = null, array $options = []) { - if (isset($options['filter'])) { - $this->filter = $options['filter']; - } else { - $this->filter = InputFilter::getInstance(); - } + $this->filter = $options['filter'] ?? InputFilter::getInstance(); // Set the data source. $this->data = &$_COOKIE; diff --git a/libraries/src/Input/Files.php b/libraries/src/Input/Files.php index 09f57e6b7a943..9a92ab5492317 100644 --- a/libraries/src/Input/Files.php +++ b/libraries/src/Input/Files.php @@ -50,11 +50,7 @@ class Files extends Input */ public function __construct(?array $source = null, array $options = []) { - if (isset($options['filter'])) { - $this->filter = $options['filter']; - } else { - $this->filter = InputFilter::getInstance(); - } + $this->filter = $options['filter'] ?? InputFilter::getInstance(); // Set the data source. $this->data = &$_FILES; @@ -123,7 +119,7 @@ protected function decodeData(array $data) $result = []; if (\is_array($data[0])) { - foreach ($data[0] as $k => $v) { + foreach (array_keys($data[0]) as $k) { $result[$k] = $this->decodeData([$data[0][$k], $data[1][$k], $data[2][$k], $data[3][$k], $data[4][$k]]); } diff --git a/libraries/src/Input/Input.php b/libraries/src/Input/Input.php index 244c2b6777d1d..bc0679521beb4 100644 --- a/libraries/src/Input/Input.php +++ b/libraries/src/Input/Input.php @@ -162,12 +162,10 @@ public function getArray(array $vars = [], $datasource = null, $defaultFilter = */ protected function getArrayRecursive(array $vars = [], $datasource = null, $defaultFilter = 'unknown', $recursion = false) { - if (empty($vars) && \is_null($datasource)) { + if ($vars === [] && \is_null($datasource)) { $vars = $this->data; - } else { - if (!$recursion) { - $defaultFilter = null; - } + } elseif (!$recursion) { + $defaultFilter = null; } $results = []; diff --git a/libraries/src/Input/Json.php b/libraries/src/Input/Json.php index 55a526e3b3ee7..35e6084c1342c 100644 --- a/libraries/src/Input/Json.php +++ b/libraries/src/Input/Json.php @@ -50,11 +50,7 @@ class Json extends Input */ public function __construct(?array $source = null, array $options = []) { - if (isset($options['filter'])) { - $this->filter = $options['filter']; - } else { - $this->filter = InputFilter::getInstance(); - } + $this->filter = $options['filter'] ?? InputFilter::getInstance(); if (\is_null($source)) { $this->_raw = file_get_contents('php://input'); diff --git a/libraries/src/Installer/Adapter/ComponentAdapter.php b/libraries/src/Installer/Adapter/ComponentAdapter.php index 06bda49d4a825..576cf7a19686a 100644 --- a/libraries/src/Installer/Adapter/ComponentAdapter.php +++ b/libraries/src/Installer/Adapter/ComponentAdapter.php @@ -220,15 +220,13 @@ protected function copyBaseFiles() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_administrator') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } } @@ -246,16 +244,14 @@ protected function createExtensionRoot() // If the component directory does not exist, let's create it $created = false; - if (!file_exists($this->parent->getPath('extension_site'))) { - if (!$created = Folder::create($this->parent->getPath('extension_site'))) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), - $this->parent->getPath('extension_site') - ) - ); - } + if (!file_exists($this->parent->getPath('extension_site')) && !$created = Folder::create($this->parent->getPath('extension_site'))) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), + $this->parent->getPath('extension_site') + ) + ); } /* @@ -274,16 +270,14 @@ protected function createExtensionRoot() // If the component admin directory does not exist, let's create it $created = false; - if (!file_exists($this->parent->getPath('extension_administrator'))) { - if (!$created = Folder::create($this->parent->getPath('extension_administrator'))) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), - $this->parent->getPath('extension_administrator') - ) - ); - } + if (!file_exists($this->parent->getPath('extension_administrator')) && !$created = Folder::create($this->parent->getPath('extension_administrator'))) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), + $this->parent->getPath('extension_administrator') + ) + ); } /* @@ -302,16 +296,14 @@ protected function createExtensionRoot() // If the component API directory does not exist, let's create it $created = false; - if (!file_exists($this->parent->getPath('extension_api'))) { - if (!$created = Folder::create($this->parent->getPath('extension_api'))) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), - $this->parent->getPath('extension_api') - ) - ); - } + if (!file_exists($this->parent->getPath('extension_api')) && !$created = Folder::create($this->parent->getPath('extension_api'))) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)), + $this->parent->getPath('extension_api') + ) + ); } /* @@ -355,16 +347,14 @@ protected function finaliseInstall() } // We will copy the manifest file to its appropriate place. - if ($this->route !== 'discover_install') { - if (!$this->parent->copyManifest()) { - // Install failed, roll back changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_COPY_SETUP', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if ($this->route !== 'discover_install' && !$this->parent->copyManifest()) { + // Install failed, roll back changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_COPY_SETUP', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } // Time to build the admin menus @@ -469,31 +459,25 @@ protected function finaliseUninstall(): bool } // Now we need to delete the installation directories. This is the final step in uninstalling the component. - if (trim($this->extension->element)) { + if (trim($this->extension->element) !== '' && trim($this->extension->element) !== '0') { $retval = true; // Delete the component site directory - if (is_dir($this->parent->getPath('extension_site'))) { - if (!Folder::delete($this->parent->getPath('extension_site'))) { - Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_SITE'), Log::WARNING, 'jerror'); - $retval = false; - } + if (is_dir($this->parent->getPath('extension_site')) && !Folder::delete($this->parent->getPath('extension_site'))) { + Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_SITE'), Log::WARNING, 'jerror'); + $retval = false; } // Delete the component admin directory - if (is_dir($this->parent->getPath('extension_administrator'))) { - if (!Folder::delete($this->parent->getPath('extension_administrator'))) { - Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_ADMIN'), Log::WARNING, 'jerror'); - $retval = false; - } + if (is_dir($this->parent->getPath('extension_administrator')) && !Folder::delete($this->parent->getPath('extension_administrator'))) { + Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_ADMIN'), Log::WARNING, 'jerror'); + $retval = false; } // Delete the component API directory - if (is_dir($this->parent->getPath('extension_api'))) { - if (!Folder::delete($this->parent->getPath('extension_api'))) { - Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_API'), Log::WARNING, 'jerror'); - $retval = false; - } + if (is_dir($this->parent->getPath('extension_api')) && !Folder::delete($this->parent->getPath('extension_api'))) { + Log::add(Text::_('JLIB_INSTALLER_ERROR_COMP_UNINSTALL_FAILED_REMOVE_DIRECTORY_API'), Log::WARNING, 'jerror'); + $retval = false; } // Now we will no longer need the extension object, so let's delete it @@ -876,7 +860,7 @@ protected function storeExtension($deleteExisting = false) } // Namespace is optional - if (isset($this->manifest->namespace)) { + if (property_exists($this->manifest, 'namespace') && $this->manifest->namespace !== null) { $this->extension->namespace = (string) $this->manifest->namespace; } @@ -1023,11 +1007,11 @@ protected function _buildAdminMenus($componentId = null) // Set the menu link $request = []; - if ((string) $menuElement->attributes()->task) { + if ((string) $menuElement->attributes()->task !== '' && (string) $menuElement->attributes()->task !== '0') { $request[] = 'task=' . $menuElement->attributes()->task; } - if ((string) $menuElement->attributes()->view) { + if ((string) $menuElement->attributes()->view !== '' && (string) $menuElement->attributes()->view !== '0') { $request[] = 'view=' . $menuElement->attributes()->view; } @@ -1071,32 +1055,32 @@ protected function _buildAdminMenus($componentId = null) } // Set the sub menu link - if ((string) $child->attributes()->link) { + if ((string) $child->attributes()->link !== '' && (string) $child->attributes()->link !== '0') { $data['link'] = 'index.php?' . $child->attributes()->link; } else { $request = []; - if ((string) $child->attributes()->act) { + if ((string) $child->attributes()->act !== '' && (string) $child->attributes()->act !== '0') { $request[] = 'act=' . $child->attributes()->act; } - if ((string) $child->attributes()->task) { + if ((string) $child->attributes()->task !== '' && (string) $child->attributes()->task !== '0') { $request[] = 'task=' . $child->attributes()->task; } - if ((string) $child->attributes()->controller) { + if ((string) $child->attributes()->controller !== '' && (string) $child->attributes()->controller !== '0') { $request[] = 'controller=' . $child->attributes()->controller; } - if ((string) $child->attributes()->view) { + if ((string) $child->attributes()->view !== '' && (string) $child->attributes()->view !== '0') { $request[] = 'view=' . $child->attributes()->view; } - if ((string) $child->attributes()->layout) { + if ((string) $child->attributes()->layout !== '' && (string) $child->attributes()->layout !== '0') { $request[] = 'layout=' . $child->attributes()->layout; } - if ((string) $child->attributes()->sub) { + if ((string) $child->attributes()->sub !== '' && (string) $child->attributes()->sub !== '0') { $request[] = 'sub=' . $child->attributes()->sub; } diff --git a/libraries/src/Installer/Adapter/FileAdapter.php b/libraries/src/Installer/Adapter/FileAdapter.php index 270fde40575e2..6eb98e3e5cee4 100644 --- a/libraries/src/Installer/Adapter/FileAdapter.php +++ b/libraries/src/Installer/Adapter/FileAdapter.php @@ -148,16 +148,14 @@ protected function finaliseInstall() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } } @@ -271,11 +269,7 @@ protected function removeExtensionFiles() $target = (string) $eFiles->attributes()->target; // Create folder path - if (empty($target)) { - $targetFolder = JPATH_ROOT; - } else { - $targetFolder = JPATH_ROOT . '/' . $target; - } + $targetFolder = $target === '' || $target === '0' ? JPATH_ROOT : JPATH_ROOT . '/' . $target; $folderList = []; @@ -472,12 +466,7 @@ protected function extensionExistsInSystem($extension = null) } $id = $db->loadResult(); - - if (empty($id)) { - return false; - } - - return true; + return !empty($id); } /** @@ -509,7 +498,7 @@ protected function populateFilesAndFolderList() $folderName = $jRootPath; foreach ($arrList as $dir) { - if (empty($dir)) { + if ($dir === '' || $dir === '0') { continue; } @@ -522,8 +511,8 @@ protected function populateFilesAndFolderList() } // Create folder path - $sourceFolder = empty($folder) ? $packagePath : $packagePath . '/' . $folder; - $targetFolder = empty($target) ? $jRootPath : $jRootPath . '/' . $target; + $sourceFolder = $folder === '' || $folder === '0' ? $packagePath : $packagePath . '/' . $folder; + $targetFolder = $target === '' || $target === '0' ? $jRootPath : $jRootPath . '/' . $target; // Check if source folder exists if (!is_dir(Path::clean($sourceFolder))) { @@ -536,7 +525,7 @@ protected function populateFilesAndFolderList() } // Check if all children exists - if (\count($eFiles->children())) { + if (\count($eFiles->children()) > 0) { // Loop through all filenames elements foreach ($eFiles->children() as $eFileName) { $path = []; diff --git a/libraries/src/Installer/Adapter/LanguageAdapter.php b/libraries/src/Installer/Adapter/LanguageAdapter.php index d068de49acc51..3845a9c5aafd2 100644 --- a/libraries/src/Installer/Adapter/LanguageAdapter.php +++ b/libraries/src/Installer/Adapter/LanguageAdapter.php @@ -251,9 +251,11 @@ public function install() } $this->setManifest($this->parent->getManifest()); + // Get the client application target + $cname = (string) $this->getManifest()->attributes()->client; // Get the client application target - if ($cname = (string) $this->getManifest()->attributes()->client) { + if ($cname !== '' && $cname !== '0') { // Attempt to map the client to a base path $client = ApplicationHelper::getClientInfo($cname, true); @@ -303,7 +305,7 @@ protected function _install($cname, $basePath, $clientId, &$element) $tag = (string) $this->getManifest()->tag; // Check if we found the tag - if we didn't, we may be trying to install from an older language package - if (!$tag) { + if ($tag === '' || $tag === '0') { $this->parent->abort(Text::sprintf('JLIB_INSTALLER_ABORT', Text::_('JLIB_INSTALLER_ERROR_NO_LANGUAGE_TAG'))); return false; @@ -410,7 +412,7 @@ protected function _install($cname, $basePath, $clientId, &$element) // Get the language description $description = (string) $this->getManifest()->description; - if ($description) { + if ($description !== '' && $description !== '0') { $this->parent->set('message', Text::_($description)); } else { $this->parent->set('message', ''); @@ -533,7 +535,7 @@ public function update() $tag = (string) $xml->tag; // Check if we found the tag - if we didn't, we may be trying to install from an older language package - if (!$tag) { + if ($tag === '' || $tag === '0') { $this->parent->abort(Text::sprintf('JLIB_INSTALLER_ABORT', Text::_('JLIB_INSTALLER_ERROR_NO_LANGUAGE_TAG'))); return false; @@ -545,7 +547,7 @@ public function update() $this->parent->setPath('extension_site', $basePath . '/language/' . $tag); // Do we have a meta file in the file list? In other words... is this a core language pack? - if (\count($xml->files->children())) { + if (\count($xml->files->children()) > 0) { foreach ($xml->files->children() as $file) { if ((string) $file->attributes()->file === 'meta') { $this->core = true; @@ -775,11 +777,7 @@ private function resetUserLanguage(): void $db->setQuery($query); $users = $db->loadObjectList(); - if ($client->name === 'administrator') { - $param_name = 'admin_language'; - } else { - $param_name = 'language'; - } + $param_name = $client->name === 'administrator' ? 'admin_language' : 'language'; $count = 0; @@ -805,7 +803,7 @@ private function resetUserLanguage(): void } } - if (!empty($count)) { + if ($count !== 0) { Log::add(Text::plural('JLIB_INSTALLER_NOTICE_LANG_RESET_USERS', $count), Log::NOTICE, 'jerror'); } } diff --git a/libraries/src/Installer/Adapter/LibraryAdapter.php b/libraries/src/Installer/Adapter/LibraryAdapter.php index 18ee3815463b5..9d30846c42436 100644 --- a/libraries/src/Installer/Adapter/LibraryAdapter.php +++ b/libraries/src/Installer/Adapter/LibraryAdapter.php @@ -139,16 +139,14 @@ protected function finaliseInstall() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } } @@ -283,13 +281,10 @@ protected function removeExtensionFiles() // @todo: Change this so it walked up the path backwards so we clobber multiple empties // If the folder is empty, let's delete it - if (is_dir(Path::clean($this->parent->getPath('extension_root')))) { - if (is_dir($this->parent->getPath('extension_root'))) { - $files = Folder::files($this->parent->getPath('extension_root')); - - if (!\count($files)) { - Folder::delete($this->parent->getPath('extension_root')); - } + if (is_dir(Path::clean($this->parent->getPath('extension_root'))) && is_dir($this->parent->getPath('extension_root'))) { + $files = Folder::files($this->parent->getPath('extension_root')); + if (!\count($files)) { + Folder::delete($this->parent->getPath('extension_root')); } } @@ -321,7 +316,7 @@ protected function setupInstallPaths() { $group = (string) $this->getManifest()->libraryname; - if (!$group) { + if ($group === '' || $group === '0') { throw new \RuntimeException(Text::_('JLIB_INSTALLER_ABORT_LIB_INSTALL_NOFILE')); } diff --git a/libraries/src/Installer/Adapter/ModuleAdapter.php b/libraries/src/Installer/Adapter/ModuleAdapter.php index 5fdedae1726c7..5a450880e1dfb 100644 --- a/libraries/src/Installer/Adapter/ModuleAdapter.php +++ b/libraries/src/Installer/Adapter/ModuleAdapter.php @@ -99,16 +99,14 @@ protected function copyBaseFiles() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } } @@ -188,16 +186,14 @@ protected function finaliseInstall() } // Lastly, we will copy the manifest file to its appropriate place. - if ($this->route !== 'discover_install') { - if (!$this->parent->copyManifest(-1)) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_COPY_SETUP', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if ($this->route !== 'discover_install' && !$this->parent->copyManifest(-1)) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_COPY_SETUP', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } @@ -244,7 +240,7 @@ protected function finaliseUninstall(): bool } // Do we have any module copies? - if (\count($modules)) { + if (\count($modules) > 0) { // Ensure the list is sane $modules = ArrayHelper::toInteger($modules); @@ -317,16 +313,16 @@ public function getElement($element = null) } // Joomla 4 Module. - if ((string) $this->getManifest()->element) { + if ((string) $this->getManifest()->element !== '' && (string) $this->getManifest()->element !== '0') { return (string) $this->getManifest()->element; } - if (!\count($this->getManifest()->files->children())) { + if (\count($this->getManifest()->files->children()) === 0) { return $element; } foreach ($this->getManifest()->files->children() as $file) { - if ((string) $file->attributes()->module) { + if ((string) $file->attributes()->module !== '' && (string) $file->attributes()->module !== '0') { // Joomla 3 (legacy) Module. return strtolower((string) $file->attributes()->module); } @@ -455,7 +451,7 @@ protected function setupInstallPaths() // Get the target application $cname = (string) $this->getManifest()->attributes()->client; - if ($cname) { + if ($cname !== '' && $cname !== '0') { // Attempt to map the client to a base path $client = ApplicationHelper::getClientInfo($cname, true); diff --git a/libraries/src/Installer/Adapter/PackageAdapter.php b/libraries/src/Installer/Adapter/PackageAdapter.php index 256a205d10a74..80b3d12eef7ff 100644 --- a/libraries/src/Installer/Adapter/PackageAdapter.php +++ b/libraries/src/Installer/Adapter/PackageAdapter.php @@ -123,7 +123,7 @@ protected function copyBaseFiles() if ($attributes) { $folder = (string) $attributes->folder; - if ($folder) { + if ($folder !== '' && $folder !== '0') { $source .= '/' . $folder; } } @@ -220,7 +220,7 @@ protected function finaliseInstall() } // Set the package ID for each of the installed extensions to track the relationship - if (!empty($this->installedIds)) { + if ($this->installedIds !== []) { $db = $this->getDatabase(); $query = $db->getQuery(true) ->update($db->quoteName('#__extensions')) @@ -282,16 +282,14 @@ protected function finaliseInstall() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } } @@ -461,7 +459,7 @@ protected function setupInstallPaths() { $packagepath = (string) $this->getManifest()->packagename; - if (empty($packagepath)) { + if ($packagepath === '' || $packagepath === '0') { throw new \RuntimeException( Text::sprintf( 'JLIB_INSTALLER_ABORT_PACK_INSTALL_NO_PACK', @@ -610,16 +608,14 @@ protected function triggerManifestScript($method) case 'uninstall': case 'update': // The install, uninstall, and update methods only pass this object as a param - if ($this->parent->manifestClass->$method($this) === false) { - if ($method !== 'uninstall') { - // The script failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', - Text::_('JLIB_INSTALLER_' . $this->route) - ) - ); - } + if ($this->parent->manifestClass->$method($this) === false && $method !== 'uninstall') { + // The script failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', + Text::_('JLIB_INSTALLER_' . $this->route) + ) + ); } break; diff --git a/libraries/src/Installer/Adapter/PluginAdapter.php b/libraries/src/Installer/Adapter/PluginAdapter.php index 58d8df7c2bb41..7021089c783d0 100644 --- a/libraries/src/Installer/Adapter/PluginAdapter.php +++ b/libraries/src/Installer/Adapter/PluginAdapter.php @@ -109,16 +109,14 @@ protected function copyBaseFiles() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . $this->route) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . $this->route) + ) + ); } } } @@ -178,16 +176,14 @@ protected function finaliseInstall() } // Lastly, we will copy the manifest file to its appropriate place. - if ($this->route !== 'discover_install') { - if (!$this->parent->copyManifest(-1)) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_COPY_SETUP', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if ($this->route !== 'discover_install' && !$this->parent->copyManifest(-1)) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_COPY_SETUP', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } @@ -239,14 +235,14 @@ public function getElement($element = null) // Backward Compatibility // @todo Deprecate in future version - if (!\count($this->getManifest()->files->children())) { + if (\count($this->getManifest()->files->children()) === 0) { return $element; } $type = (string) $this->getManifest()->attributes()->type; foreach ($this->getManifest()->files->children() as $file) { - if ((string) $file->attributes()->$type) { + if ((string) $file->attributes()->$type !== '' && (string) $file->attributes()->$type !== '0') { $element = (string) $file->attributes()->$type; break; @@ -294,16 +290,16 @@ public function loadLanguage($path = null) $group = strtolower((string) $this->getManifest()->attributes()->group); $name = ''; - if (\count($element->children())) { + if (\count($element->children()) > 0) { foreach ($element->children() as $file) { - if ((string) $file->attributes()->plugin) { + if ((string) $file->attributes()->plugin !== '' && (string) $file->attributes()->plugin !== '0') { $name = strtolower((string) $file->attributes()->plugin); break; } } } - if ($name) { + if ($name !== '' && $name !== '0') { $extension = "plg_{$group}_{$name}"; $source = $path ?: JPATH_PLUGINS . "/$group/$name"; $folder = (string) $element->attributes()->folder; @@ -379,7 +375,7 @@ protected function setupInstallPaths() { $this->group = (string) $this->getManifest()->attributes()->group; - if (empty($this->element) && empty($this->group)) { + if (empty($this->element) && ($this->group === null || ($this->group === '' || $this->group === '0'))) { throw new \RuntimeException( Text::sprintf( 'JLIB_INSTALLER_ABORT_PLG_INSTALL_NO_FILE', diff --git a/libraries/src/Installer/Adapter/TemplateAdapter.php b/libraries/src/Installer/Adapter/TemplateAdapter.php index 03128b0d1b3ce..f30a7827910e5 100644 --- a/libraries/src/Installer/Adapter/TemplateAdapter.php +++ b/libraries/src/Installer/Adapter/TemplateAdapter.php @@ -116,15 +116,13 @@ protected function copyBaseFiles() $path['src'] = $this->parent->getPath('source') . '/' . $this->manifest_script; $path['dest'] = $this->parent->getPath('extension_root') . '/' . $this->manifest_script; - if ($this->parent->isOverwrite() || !file_exists($path['dest'])) { - if (!$this->parent->copyFiles([$path])) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_MANIFEST', - Text::_('JLIB_INSTALLER_' . strtoupper($this->getRoute())) - ) - ); - } + if (($this->parent->isOverwrite() || !file_exists($path['dest'])) && !$this->parent->copyFiles([$path])) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_MANIFEST', + Text::_('JLIB_INSTALLER_' . strtoupper($this->getRoute())) + ) + ); } } } @@ -156,16 +154,14 @@ protected function finaliseInstall() } // Lastly, we will copy the manifest file to its appropriate place. - if ($this->route !== 'discover_install') { - if (!$this->parent->copyManifest(-1)) { - // Install failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_COPY_SETUP', - Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) - ) - ); - } + if ($this->route !== 'discover_install' && !$this->parent->copyManifest(-1)) { + // Install failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_COPY_SETUP', + Text::_('JLIB_INSTALLER_' . strtoupper($this->route)) + ) + ); } } @@ -279,7 +275,7 @@ public function loadLanguage($path = null) $client = (string) $this->getManifest()->attributes()->client; // Load administrator language if not set. - if (!$client) { + if ($client === '' || $client === '0') { $client = 'ADMINISTRATOR'; } @@ -413,7 +409,7 @@ protected function setupInstallPaths() // Get the client application target $cname = (string) $this->getManifest()->attributes()->client; - if ($cname) { + if ($cname !== '' && $cname !== '0') { // Attempt to map the client to a base path $client = ApplicationHelper::getClientInfo($cname, true); diff --git a/libraries/src/Installer/Installer.php b/libraries/src/Installer/Installer.php index a49e14b84e652..94d99dc5e9a2d 100644 --- a/libraries/src/Installer/Installer.php +++ b/libraries/src/Installer/Installer.php @@ -217,7 +217,7 @@ public static function getInstance($basepath = __DIR__, $classprefix = '\\Joomla */ public static function splitSql(?string $sql): array { - if (empty($sql)) { + if ($sql === null || $sql === '' || $sql === '0') { return []; } @@ -309,7 +309,7 @@ public static function splitSql(?string $sql): array $query = trim($query); - if ($query) { + if ($query !== '' && $query !== '0') { if (($i === $end - 1) && ($current !== ';')) { $query .= ';'; } @@ -352,11 +352,7 @@ public function setOverwrite($state = false) { $tmp = $this->overwrite; - if ($state) { - $this->overwrite = true; - } else { - $this->overwrite = false; - } + $this->overwrite = $state; return $tmp; } @@ -438,11 +434,7 @@ public function setUpgrade($state = false) { $tmp = $this->upgrade; - if ($state) { - $this->upgrade = true; - } else { - $this->upgrade = false; - } + $this->upgrade = $state; return $tmp; } @@ -475,7 +467,7 @@ public function getManifest() */ public function getPath($name, $default = null) { - return (!empty($this->paths[$name])) ? $this->paths[$name] : $default; + return (empty($this->paths[$name])) ? $default : $this->paths[$name]; } /** @@ -843,12 +835,7 @@ public function update($path = null) 'installer' => clone $this, 'eid' => $result, ])); - - if ($result !== false) { - return true; - } - - return false; + return $result !== false; } /** @@ -934,12 +921,7 @@ public function refreshManifestCache($eid) } $result = $adapter->refreshManifestCache(); - - if ($result !== false) { - return true; - } - - return false; + return $result !== false; } $this->abort(Text::_('JLIB_INSTALLER_ABORT_REFRESH_MANIFEST_CACHE_VALID')); @@ -1083,7 +1065,7 @@ public function parseSQLFiles($element) // Create an array of queries from the sql file $queries = self::splitSql($buffer); - if (\count($queries) === 0) { + if ($queries === []) { // No queries to process continue; } @@ -1131,7 +1113,7 @@ public function setSchemaVersion(\SimpleXMLElement $schema, $eid) return; } - if (\count($schemapaths)) { + if (\count($schemapaths) > 0) { $dbDriver = $db->getServerType(); $schemapath = ''; @@ -1195,7 +1177,7 @@ public function parseSchemaUpdates(\SimpleXMLElement $schema, $eid) $db = $this->getDatabase(); $schemapaths = $schema->children(); - if (!\count($schemapaths)) { + if (\count($schemapaths) === 0) { return $updateCount; } @@ -1437,7 +1419,7 @@ public function parseFiles(\SimpleXMLElement $element, $cid = 0, $oldFiles = nul if ($oldFiles && ($oldFiles instanceof \SimpleXMLElement)) { $oldEntries = $oldFiles->children(); - if (\count($oldEntries)) { + if (\count($oldEntries) > 0) { $deletions = $this->findDeletedFiles($oldEntries, $element->children()); foreach ($deletions['folders'] as $deleted_folder) { @@ -1642,7 +1624,7 @@ public function parseMedia(\SimpleXMLElement $element, $cid = 0) // Here we set the folder we are going to copy the files to. // Default 'media' Files are copied to the JPATH_BASE/media folder - $folder = ((string) $element->attributes()->destination) ? '/' . $element->attributes()->destination : null; + $folder = ((string) $element->attributes()->destination !== '' && (string) $element->attributes()->destination !== '0') ? '/' . $element->attributes()->destination : null; $destination = Path::clean(JPATH_ROOT . '/media' . $folder); // Here we set the folder we are going to copy the files from. @@ -1725,7 +1707,7 @@ public function getParams() // Iterating through the fieldsets: foreach ($fieldsets as $fieldset) { - if (!\count($fieldset->children())) { + if (\count($fieldset->children()) === 0) { // Either the tag does not exist or has no children therefore we return zero files processed. return '{}'; } @@ -1778,7 +1760,7 @@ public function copyFiles($files, $overwrite = null) * $files must be an array of filenames. Verify that it is an array with * at least one file to copy. */ - if (\is_array($files) && \count($files) > 0) { + if (\is_array($files) && $files !== []) { foreach ($files as $file) { // Get the source and destination paths $filesource = Path::clean($file['src']); @@ -1869,11 +1851,7 @@ public function removeFiles($element, $cid = 0) $retval = true; // Get the client info if we're using a specific client - if ($cid > -1) { - $client = ApplicationHelper::getClientInfo($cid); - } else { - $client = null; - } + $client = $cid > -1 ? ApplicationHelper::getClientInfo($cid) : null; // Get the array of file nodes to process $files = $element->children(); @@ -1891,11 +1869,7 @@ public function removeFiles($element, $cid = 0) */ switch ($element->getName()) { case 'media': - if ((string) $element->attributes()->destination) { - $folder = (string) $element->attributes()->destination; - } else { - $folder = ''; - } + $folder = (string) $element->attributes()->destination ?: ''; $source = $client->path . '/media/' . $folder; @@ -1904,15 +1878,13 @@ public function removeFiles($element, $cid = 0) case 'languages': $lang_client = (string) $element->attributes()->client; - if ($lang_client) { + if ($lang_client !== '' && $lang_client !== '0') { $client = ApplicationHelper::getClientInfo($lang_client, true); $source = $client->path . '/language'; + } elseif ($client) { + $source = $client->path . '/language'; } else { - if ($client) { - $source = $client->path . '/language'; - } else { - $source = ''; - } + $source = ''; } break; @@ -1956,11 +1928,7 @@ public function removeFiles($element, $cid = 0) // Actually delete the files/folders - if (is_dir($path)) { - $val = Folder::delete($path); - } else { - $val = File::delete($path); - } + $val = is_dir($path) ? Folder::delete($path) : File::delete($path); if ($val === false) { Log::add('Failed to delete ' . $path, Log::WARNING, 'jerror'); @@ -1968,7 +1936,7 @@ public function removeFiles($element, $cid = 0) } } - if (!empty($folder)) { + if ($folder !== '' && $folder !== '0') { Folder::delete($source); } @@ -2026,7 +1994,7 @@ public function findManifest() $xmlfiles = array_unique(array_merge($parentXmlfiles, $allXmlFiles)); // If at least one XML file exists - if (!empty($xmlfiles)) { + if ($xmlfiles !== []) { foreach ($xmlfiles as $file) { // Is it a valid Joomla installation manifest file? $manifest = $this->isManifest($file); @@ -2081,12 +2049,12 @@ public function isManifest($file) // If we cannot load the XML file return null if (!$xml) { - return; + return null; } // Check for a valid XML root tag. if ($xml->getName() !== 'extension') { - return; + return null; } // Valid manifest file return the object @@ -2186,7 +2154,7 @@ public function findDeletedFiles($oldFiles, $newFiles) foreach ($container_parts as $part) { // Iterate through each part // Add a slash if its not empty - if (!empty($container)) { + if ($container !== '' && $container !== '0') { $container .= '/'; } @@ -2205,24 +2173,20 @@ public function findDeletedFiles($oldFiles, $newFiles) foreach ($oldFiles as $file) { switch ($file->getName()) { case 'folder': - if (!\in_array((string) $file, $folders)) { - // See whether the folder exists in the new list - if (!\in_array((string) $file, $containers)) { - // Check if the folder exists as a container in the new list - // If it's not in the new list or a container then delete it - $folders_deleted[] = (string) $file; - } + // See whether the folder exists in the new list + if (!\in_array((string) $file, $folders) && !\in_array((string) $file, $containers)) { + // Check if the folder exists as a container in the new list + // If it's not in the new list or a container then delete it + $folders_deleted[] = (string) $file; } break; case 'file': default: - if (!\in_array((string) $file, $files)) { - // Look if the file exists in the new list - if (!\in_array(\dirname((string) $file), $folders)) { - // Look if the file is now potentially in a folder - $files_deleted[] = (string) $file; - } + // Look if the file exists in the new list + if (!\in_array((string) $file, $files) && !\in_array(\dirname((string) $file), $folders)) { + // Look if the file is now potentially in a folder + $files_deleted[] = (string) $file; } break; } @@ -2319,16 +2283,16 @@ public static function parseXMLInstallFile($path) $data['group'] = (string) $xml->group; // Child template specific fields. - if (isset($xml->inheritable)) { - $data['inheritable'] = (string) $xml->inheritable === '0' ? false : true; + if (property_exists($xml, 'inheritable') && $xml->inheritable !== null) { + $data['inheritable'] = (string) $xml->inheritable !== '0'; } // Child template specific fields. - if (isset($xml->namespace) && (string) $xml->namespace !== '') { + if (property_exists($xml, 'namespace') && $xml->namespace !== null && (string) $xml->namespace !== '') { $data['namespace'] = (string) $xml->namespace; } - if (isset($xml->parent) && (string) $xml->parent !== '') { + if (property_exists($xml, 'parent') && $xml->parent !== null && (string) $xml->parent !== '') { $data['parent'] = (string) $xml->parent; } @@ -2337,7 +2301,7 @@ public static function parseXMLInstallFile($path) $data['filename'] = File::stripExt($filename); foreach ($xml->files->children() as $oneFile) { - if ((string) $oneFile->attributes()->plugin) { + if ((string) $oneFile->attributes()->plugin !== '' && (string) $oneFile->attributes()->plugin !== '0') { $data['filename'] = (string) $oneFile->attributes()->plugin; break; } diff --git a/libraries/src/Installer/InstallerAdapter.php b/libraries/src/Installer/InstallerAdapter.php index 6fed7d5fd1e1b..00d41b85a67fe 100644 --- a/libraries/src/Installer/InstallerAdapter.php +++ b/libraries/src/Installer/InstallerAdapter.php @@ -308,16 +308,14 @@ protected function createExtensionRoot() // If the extension directory does not exist, lets create it $created = false; - if (!file_exists($this->parent->getPath('extension_root'))) { - if (!$created = Folder::create($this->parent->getPath('extension_root'))) { - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', - Text::_('JLIB_INSTALLER_' . $this->route), - $this->parent->getPath('extension_root') - ) - ); - } + if (!file_exists($this->parent->getPath('extension_root')) && !$created = Folder::create($this->parent->getPath('extension_root'))) { + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_CREATE_DIRECTORY', + Text::_('JLIB_INSTALLER_' . $this->route), + $this->parent->getPath('extension_root') + ) + ); } /* @@ -348,11 +346,7 @@ public function discover_install() // Get the extension's description $description = (string) $this->getManifest()->description; - if ($description) { - $this->parent->message = Text::_($description); - } else { - $this->parent->message = ''; - } + $this->parent->message = $description !== '' && $description !== '0' ? Text::_($description) : ''; // Set the extension's name and element $this->name = $this->getName(); @@ -466,7 +460,7 @@ protected function doDatabaseTransactions() $route = $this->route === 'discover_install' ? 'install' : $this->route; // Let's run the install queries for the component - if (isset($this->getManifest()->{$route}->sql)) { + if (property_exists($this->getManifest()->{$route}, 'sql') && $this->getManifest()->{$route}->sql !== null) { $result = $this->parent->parseSQLFiles($this->getManifest()->{$route}->sql); if ($result === false) { @@ -479,7 +473,7 @@ protected function doDatabaseTransactions() } // If installing with success and there is an uninstall script, add an installer rollback step to rollback if needed - if ($route === 'install' && isset($this->getManifest()->uninstall->sql)) { + if ($route === 'install' && (property_exists($this->getManifest()->uninstall, 'sql') && $this->getManifest()->uninstall->sql !== null)) { $this->parent->pushStep(['type' => 'query', 'script' => $this->getManifest()->uninstall->sql]); } } @@ -501,7 +495,9 @@ protected function doDatabaseTransactions() protected function doLoadLanguage($extension, $source, $base = JPATH_ADMINISTRATOR) { $lang = Factory::getLanguage(); - $lang->load($extension . '.sys', $source) || $lang->load($extension . '.sys', $base); + if (!$lang->load($extension . '.sys', $source)) { + $lang->load($extension . '.sys', $base); + } } /** @@ -645,7 +641,7 @@ public function install() $description = (string) $this->getManifest()->description; $this->parent->message = ''; - if ($description) { + if ($description !== '' && $description !== '0') { $this->parent->message = Text::_($description); } @@ -931,7 +927,7 @@ protected function setupScriptfile() $manifestScript = (string) $this->getManifest()->scriptfile; // When no script file, do nothing - if (!$manifestScript) { + if ($manifestScript === '' || $manifestScript === '0') { return; } @@ -1055,19 +1051,16 @@ protected function triggerManifestScript($method) case 'preflight': case 'postflight': // The preflight and postflight take the route as a param - if ($this->parent->manifestClass->$method($this->route, $this) === false) { - if ($method !== 'postflight') { - // Clean and close the output buffer - ob_end_clean(); - - // The script failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', - Text::_('JLIB_INSTALLER_' . $this->route) - ) - ); - } + if ($this->parent->manifestClass->$method($this->route, $this) === false && $method !== 'postflight') { + // Clean and close the output buffer + ob_end_clean(); + // The script failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', + Text::_('JLIB_INSTALLER_' . $this->route) + ) + ); } break; @@ -1075,19 +1068,16 @@ protected function triggerManifestScript($method) case 'uninstall': case 'update': // The install, uninstall, and update methods only pass this object as a param - if ($this->parent->manifestClass->$method($this) === false) { - if ($method !== 'uninstall') { - // Clean and close the output buffer - ob_end_clean(); - - // The script failed, rollback changes - throw new \RuntimeException( - Text::sprintf( - 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', - Text::_('JLIB_INSTALLER_' . $this->route) - ) - ); - } + if ($this->parent->manifestClass->$method($this) === false && $method !== 'uninstall') { + // Clean and close the output buffer + ob_end_clean(); + // The script failed, rollback changes + throw new \RuntimeException( + Text::sprintf( + 'JLIB_INSTALLER_ABORT_INSTALL_CUSTOM_INSTALL_FAILURE', + Text::_('JLIB_INSTALLER_' . $this->route) + ) + ); } break; } @@ -1122,13 +1112,13 @@ public function uninstall($id) } // Joomla 4: Locked extensions cannot be removed. - if (isset($this->extension->locked) && $this->extension->locked) { + if ($this->extension->locked !== null && $this->extension->locked) { Log::add(Text::_('JLIB_INSTALLER_ERROR_UNINSTALL_LOCKED_EXTENSION'), Log::WARNING, 'jerror'); return false; } - if (!isset($this->extension->locked) && $this->extension->protected) { + if ($this->extension->locked === null && $this->extension->protected) { // Joomla 3 ('locked' property does not exist yet): Protected extensions cannot be removed. Log::add(Text::_('JLIB_INSTALLER_ERROR_UNINSTALL_PROTECTED_EXTENSION'), Log::WARNING, 'jerror'); diff --git a/libraries/src/Installer/InstallerExtension.php b/libraries/src/Installer/InstallerExtension.php index 7d29fe56a30b8..392a13ec97de4 100644 --- a/libraries/src/Installer/InstallerExtension.php +++ b/libraries/src/Installer/InstallerExtension.php @@ -119,7 +119,7 @@ class InstallerExtension */ public function __construct(?\SimpleXMLElement $element = null) { - if ($element) { + if ($element instanceof \SimpleXMLElement) { $this->type = (string) $element->attributes()->type; $this->id = (string) $element->attributes()->id; diff --git a/libraries/src/Installer/InstallerHelper.php b/libraries/src/Installer/InstallerHelper.php index bbad0b587ad0e..55fb5ae001787 100644 --- a/libraries/src/Installer/InstallerHelper.php +++ b/libraries/src/Installer/InstallerHelper.php @@ -118,11 +118,7 @@ public static function downloadPackage($url, $target = false) $tmpPath = Factory::getApplication()->get('tmp_path'); // Set the target path if not given - if (!$target) { - $target = $tmpPath . '/' . self::getFilenameFromUrl($url); - } else { - $target = $tmpPath . '/' . basename($target); - } + $target = $target ? $tmpPath . '/' . basename($target) : $tmpPath . '/' . self::getFilenameFromUrl($url); // Fix Indirect Modification of Overloaded Property $body = $response->body; @@ -207,10 +203,8 @@ public static function unpack($packageFilename, $alwaysReturnArray = false) */ $dirList = array_merge((array) Folder::files($extractdir, ''), (array) Folder::folders($extractdir, '')); - if (\count($dirList) === 1) { - if (is_dir(Path::clean($extractdir . '/' . $dirList[0]))) { - $extractdir = Path::clean($extractdir . '/' . $dirList[0]); - } + if (\count($dirList) === 1 && is_dir(Path::clean($extractdir . '/' . $dirList[0]))) { + $extractdir = Path::clean($extractdir . '/' . $dirList[0]); } /* diff --git a/libraries/src/Installer/InstallerScript.php b/libraries/src/Installer/InstallerScript.php index 018811cdef233..ac91ca48cd50b 100644 --- a/libraries/src/Installer/InstallerScript.php +++ b/libraries/src/Installer/InstallerScript.php @@ -134,11 +134,7 @@ public function preflight($type, $parent) $extensionType = substr($this->extension, 0, 3); // Modules parameters are located in the module table - else in the extension table - if ($extensionType === 'mod') { - $this->paramTable = '#__modules'; - } else { - $this->paramTable = '#__extensions'; - } + $this->paramTable = $extensionType === 'mod' ? '#__modules' : '#__extensions'; // Abort if the extension being installed is not newer than the currently installed version if (!$this->allowDowngrades && strtolower($type) === 'update') { @@ -242,12 +238,7 @@ public function setParams($paramArray = null, $type = 'edit', $id = 0) foreach ($paramArray as $name => $value) { if ($type === 'edit') { // Add or edit the new variable(s) to the existing params - if (\is_array($value)) { - // Convert an array into a json encoded string - $params[(string) $name] = array_values($value); - } else { - $params[(string) $name] = (string) $value; - } + $params[(string) $name] = \is_array($value) ? array_values($value) : (string) $value; } elseif ($type === 'remove') { // Unset the parameter from the array unset($params[(string) $name]); @@ -316,7 +307,7 @@ public function getItemArray($element, $table, $column, $identifier) */ public function removeFiles() { - if (!empty($this->deleteFiles)) { + if ($this->deleteFiles !== []) { foreach ($this->deleteFiles as $file) { if (is_file(JPATH_ROOT . $file) && !File::delete(JPATH_ROOT . $file)) { echo Text::sprintf('JLIB_INSTALLER_ERROR_FILE_FOLDER', $file) . '
    '; @@ -324,7 +315,7 @@ public function removeFiles() } } - if (!empty($this->deleteFolders)) { + if ($this->deleteFolders !== []) { foreach ($this->deleteFolders as $folder) { if (is_dir(Path::clean(JPATH_ROOT . $folder)) && !Folder::delete(JPATH_ROOT . $folder)) { echo Text::sprintf('JLIB_INSTALLER_ERROR_FILE_FOLDER', $folder) . '
    '; @@ -342,7 +333,7 @@ public function removeFiles() */ public function moveCliFiles() { - if (!empty($this->cliScriptFiles)) { + if ($this->cliScriptFiles !== []) { foreach ($this->cliScriptFiles as $file) { $name = basename((string) $file); diff --git a/libraries/src/Installer/Manifest/LibraryManifest.php b/libraries/src/Installer/Manifest/LibraryManifest.php index 8851de89cf55e..49370ac8796bf 100644 --- a/libraries/src/Installer/Manifest/LibraryManifest.php +++ b/libraries/src/Installer/Manifest/LibraryManifest.php @@ -109,7 +109,7 @@ protected function loadManifestFromData(\SimpleXMLElement $xml) $this->packagerurl = (string) $xml->packagerurl; $this->update = (string) $xml->update; - if (isset($xml->files) && isset($xml->files->file) && \count($xml->files->file)) { + if (property_exists($xml, 'files') && $xml->files !== null && (property_exists($xml->files, 'file') && $xml->files->file !== null) && \count($xml->files->file)) { foreach ($xml->files->file as $file) { $this->filelist[] = (string) $file; } diff --git a/libraries/src/Installer/Manifest/PackageManifest.php b/libraries/src/Installer/Manifest/PackageManifest.php index eab6fa036a6b8..0fda37b836e60 100644 --- a/libraries/src/Installer/Manifest/PackageManifest.php +++ b/libraries/src/Installer/Manifest/PackageManifest.php @@ -102,7 +102,7 @@ protected function loadManifestFromData(\SimpleXMLElement $xml) $this->scriptfile = (string) $xml->scriptfile; $this->version = (string) $xml->version; - if (isset($xml->blockChildUninstall)) { + if (property_exists($xml, 'blockChildUninstall') && $xml->blockChildUninstall !== null) { $value = (string) $xml->blockChildUninstall; if ($value === '1' || $value === 'true') { @@ -110,7 +110,7 @@ protected function loadManifestFromData(\SimpleXMLElement $xml) } } - if (isset($xml->files->file) && \count($xml->files->file)) { + if (property_exists($xml->files, 'file') && $xml->files->file !== null && \count($xml->files->file)) { foreach ($xml->files->file as $file) { // NOTE: JInstallerExtension doesn't expect a string. // DO NOT CAST $file @@ -119,7 +119,7 @@ protected function loadManifestFromData(\SimpleXMLElement $xml) } // Handle cases where package contains folders - if (isset($xml->files->folder) && \count($xml->files->folder)) { + if (property_exists($xml->files, 'folder') && $xml->files->folder !== null && \count($xml->files->folder)) { foreach ($xml->files->folder as $folder) { // NOTE: JInstallerExtension doesn't expect a string. // DO NOT CAST $folder diff --git a/libraries/src/Language/Associations.php b/libraries/src/Language/Associations.php index 34e993e0422a2..be30ffeb066b1 100644 --- a/libraries/src/Language/Associations.php +++ b/libraries/src/Language/Associations.php @@ -176,18 +176,14 @@ public static function isEnabled() // Status of language filter parameter. static $enabled = false; - if (Multilanguage::isEnabled()) { - // If already tested, don't test again. - if (!$tested) { - $plugin = PluginHelper::getPlugin('system', 'languagefilter'); - - if (!empty($plugin)) { - $params = new Registry($plugin->params); - $enabled = (bool) $params->get('item_associations', true); - } - - $tested = true; + // If already tested, don't test again. + if (Multilanguage::isEnabled() && !$tested) { + $plugin = PluginHelper::getPlugin('system', 'languagefilter'); + if (!empty($plugin)) { + $params = new Registry($plugin->params); + $enabled = (bool) $params->get('item_associations', true); } + $tested = true; } return $enabled; diff --git a/libraries/src/Language/Language.php b/libraries/src/Language/Language.php index b8ab9bd4cfcc4..cca6389106768 100644 --- a/libraries/src/Language/Language.php +++ b/libraries/src/Language/Language.php @@ -106,8 +106,6 @@ class Language extends BaseLanguage */ public function __construct($lang = null, $debug = false) { - $this->strings = []; - if ($lang == null) { $lang = $this->default; } @@ -242,7 +240,6 @@ public function _($string, $jsSafe = false, $interpretBackSlashes = true) if (isset($this->strings[$key])) { $string = $this->strings[$key]; - // Store debug information if ($this->debug) { $value = Factory::getApplication()->get('debug_lang_const', true) ? $string : $key; @@ -256,21 +253,16 @@ public function _($string, $jsSafe = false, $interpretBackSlashes = true) $this->used[$key][] = $caller; } - } else { - if ($this->debug) { - $info = []; - $info['trace'] = $this->getTrace(); - $info['key'] = $key; - $info['string'] = $string; - - if (!\array_key_exists($key, $this->orphans)) { - $this->orphans[$key] = []; - } - - $this->orphans[$key][] = $info; - - $string = '??' . $string . '??'; + } elseif ($this->debug) { + $info = []; + $info['trace'] = $this->getTrace(); + $info['key'] = $key; + $info['string'] = $string; + if (!\array_key_exists($key, $this->orphans)) { + $this->orphans[$key] = []; } + $this->orphans[$key][] = $info; + $string = '??' . $string . '??'; } if ($jsSafe) { @@ -713,11 +705,9 @@ protected function parse($fileName) $strings = []; // Debug the ini file if needed. - if ($this->debug && is_file($fileName)) { - if (!$this->debugFile($fileName)) { - // We didn't find any errors but there's a parser warning. - $this->errorfiles[$fileName] = 'PHP parser errors :' . $e->getMessage(); - } + if ($this->debug && is_file($fileName) && !$this->debugFile($fileName)) { + // We didn't find any errors but there's a parser warning. + $this->errorfiles[$fileName] = 'PHP parser errors :' . $e->getMessage(); } } @@ -794,7 +784,7 @@ public function debugFile(string $filename): int } // Check if we encountered any errors. - if (\count($errors)) { + if ($errors !== []) { $this->errorfiles[$filename] = $errors; } diff --git a/libraries/src/Language/LanguageHelper.php b/libraries/src/Language/LanguageHelper.php index 376b258b4dcaa..928cc0e410f94 100644 --- a/libraries/src/Language/LanguageHelper.php +++ b/libraries/src/Language/LanguageHelper.php @@ -116,11 +116,11 @@ public static function detectLanguage() $Jinstall_lang = $systemLang->lang_code; if (\strlen($Jinstall_lang) < 6) { - if (strtolower($browserLang) == strtolower(substr($systemLang->lang_code, 0, \strlen($browserLang)))) { + if (strtolower($browserLang) === strtolower(substr($systemLang->lang_code, 0, \strlen($browserLang)))) { return $systemLang->lang_code; } - if ($primary_browserLang == substr($systemLang->lang_code, 0, 2)) { + if ($primary_browserLang === substr($systemLang->lang_code, 0, 2)) { $primaryDetectedLang = $systemLang->lang_code; } } @@ -148,7 +148,7 @@ public static function getLanguages($key = 'default') { static $languages = []; - if (!\count($languages)) { + if (\count($languages) === 0) { // Installation uses available languages if (Factory::getApplication()->isClient('installation')) { $languages[$key] = []; @@ -463,7 +463,7 @@ public static function parseIniFile($fileName, $debug = false) } } catch (\Exception $e) { if ($debug) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } return []; @@ -558,7 +558,7 @@ public static function getMetadata($lang) } if (empty($result)) { - return; + return null; } return $result; @@ -590,7 +590,7 @@ public static function getKnownLanguages($basePath = JPATH_BASE) */ public static function getLanguagePath($basePath = JPATH_BASE, $language = null) { - return $basePath . '/language' . (!empty($language) ? '/' . $language : ''); + return $basePath . '/language' . (empty($language) ? '' : '/' . $language); } /** @@ -655,12 +655,12 @@ public static function parseXMLLanguageFile($path) $xml = simplexml_load_file($path); if (!$xml) { - return; + return null; } // Check that it's a metadata file if ((string) $xml->getName() !== 'metafile') { - return; + return null; } $metadata = []; diff --git a/libraries/src/Language/Text.php b/libraries/src/Language/Text.php index 803f9e77a3feb..d9fcc1eb85678 100644 --- a/libraries/src/Language/Text.php +++ b/libraries/src/Language/Text.php @@ -107,10 +107,10 @@ private static function passSprintf(&$string, $jsSafe = false, $interpretBackSla $first_part = array_shift($string_parts); // Replace custom named placeholders with sprintf style placeholders - $first_part = preg_replace('/\[\[%([0-9]+):[^\]]*\]\]/', '%\1$s', $first_part); + $first_part = preg_replace('/\[\[%(\d+):[^\]]*\]\]/', '%\1$s', $first_part); // Check if string contains sprintf placeholders - if (!preg_match('/%([0-9]+\$)?s/', (string) $first_part)) { + if (!preg_match('/%(\d+\$)?s/', (string) $first_part)) { return false; } @@ -211,7 +211,7 @@ public static function plural($string, $n) } // Not found so revert to the original. - $key = !$found ? $string : $key; + $key = $found ? $key : $string; if (\is_array($args[$count - 1])) { $args[0] = $lang->_( @@ -276,7 +276,7 @@ public static function sprintf($string) } // Replace custom named placeholders with sprintf style placeholders - $args[0] = preg_replace('/\[\[%([0-9]+):[^\]]*\]\]/', '%\1$s', $args[0]); + $args[0] = preg_replace('/\[\[%(\d+):[^\]]*\]\]/', '%\1$s', $args[0]); return \call_user_func_array('sprintf', $args); } @@ -342,11 +342,7 @@ public static function script($string = null, $jsSafe = false, $interpretBackSla $interpretBackSlashes = (bool) $jsSafe['interpretBackSlashes']; } - if (\array_key_exists('jsSafe', $jsSafe)) { - $jsSafe = (bool) $jsSafe['jsSafe']; - } else { - $jsSafe = false; - } + $jsSafe = \array_key_exists('jsSafe', $jsSafe) ? (bool) $jsSafe['jsSafe'] : false; } // Add the string to the array if not null. diff --git a/libraries/src/Log/Log.php b/libraries/src/Log/Log.php index 6a452ada98ea7..c8441aed2eb84 100644 --- a/libraries/src/Log/Log.php +++ b/libraries/src/Log/Log.php @@ -373,17 +373,15 @@ protected function findLoggers($priority, $category) // Let's go iterate over the loggers and get all the ones we need. foreach ((array) $this->lookup as $signature => $rules) { // Check to make sure the priority matches the logger. - if ($priority & $rules->priorities) { + if (($priority & $rules->priorities) !== 0) { if ($rules->exclude) { // If either there are no set categories or the category (including the empty case) is not in the list of excluded categories, add this logger. if (empty($rules->categories) || !\in_array($category, $rules->categories)) { $loggers[] = $signature; } - } else { + } elseif (empty($rules->categories) || \in_array($category, $rules->categories)) { // If either there are no set categories (meaning all) or the specific category is set, add this logger. - if (empty($rules->categories) || \in_array($category, $rules->categories)) { - $loggers[] = $signature; - } + $loggers[] = $signature; } } } diff --git a/libraries/src/Log/Logger/FormattedtextLogger.php b/libraries/src/Log/Logger/FormattedtextLogger.php index 4ee0be252a03e..ba633e4aa81fc 100644 --- a/libraries/src/Log/Logger/FormattedtextLogger.php +++ b/libraries/src/Log/Logger/FormattedtextLogger.php @@ -127,7 +127,7 @@ public function __construct(array &$options) public function __destruct() { // Nothing to do - if (!$this->defer || empty($this->deferredEntries)) { + if (!$this->defer || $this->deferredEntries === []) { return; } @@ -153,7 +153,7 @@ public function __destruct() */ public function __wakeup() { - if ($this->defer && !empty($this->deferredEntries)) { + if ($this->defer && $this->deferredEntries !== []) { throw new \RuntimeException('Can not unserialize in defer mode'); } } @@ -202,7 +202,7 @@ public function addEntry(LogEntry $entry) protected function formatLine(LogEntry $entry) { // Set some default field values if not already set. - if (!isset($entry->clientIP)) { + if (!property_exists($entry, 'clientIP') || $entry->clientIP === null) { $ip = IpHelper::getIp(); if ($ip !== '') { @@ -211,7 +211,7 @@ protected function formatLine(LogEntry $entry) } // If the time field is missing or the date field isn't only the date we need to rework it. - if ((\strlen($entry->date) != 10) || !isset($entry->time)) { + if ((\strlen($entry->date) != 10) || (!property_exists($entry, 'time') || $entry->time === null)) { // Get the date and time strings in GMT. $entry->datetime = $entry->date->toISO8601(); $entry->time = $entry->date->format('H:i:s', false); diff --git a/libraries/src/Log/Logger/SyslogLogger.php b/libraries/src/Log/Logger/SyslogLogger.php index 7597f82ab12c0..374e845817fd8 100644 --- a/libraries/src/Log/Logger/SyslogLogger.php +++ b/libraries/src/Log/Logger/SyslogLogger.php @@ -64,11 +64,7 @@ public function __construct(array &$options) } // If the option to add the process id to Syslog entries is set use it, otherwise default to true. - if (isset($this->options['sys_add_pid'])) { - $this->options['sys_add_pid'] = (bool) $this->options['sys_add_pid']; - } else { - $this->options['sys_add_pid'] = true; - } + $this->options['sys_add_pid'] = isset($this->options['sys_add_pid']) ? (bool) $this->options['sys_add_pid'] : true; // If the option to also send Syslog entries to STDERR is set use it, otherwise default to false. if (isset($this->options['sys_use_stderr'])) { diff --git a/libraries/src/MVC/Controller/AdminController.php b/libraries/src/MVC/Controller/AdminController.php index 30ec59d7c0b96..9ac5b1569f0d1 100644 --- a/libraries/src/MVC/Controller/AdminController.php +++ b/libraries/src/MVC/Controller/AdminController.php @@ -114,7 +114,7 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null, $r = [0 => '', 1 => '', 2 => $reflect->getShortName()]; - if ($reflect->getNamespaceName()) { + if ($reflect->getNamespaceName() !== '' && $reflect->getNamespaceName() !== '0') { $r[2] = str_replace('Controller', '', $r[2]); } elseif (!preg_match('/(.*)Controller(.*)/i', $reflect->getShortName(), $r)) { throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_GET_NAME', __METHOD__), 500); @@ -142,7 +142,7 @@ public function delete() // Remove zero values resulting from input filter $cid = array_filter($cid); - if (empty($cid)) { + if ($cid === []) { $this->getLogger()->warning(Text::_($this->text_prefix . '_NO_ITEM_SELECTED'), ['category' => 'jerror']); } else { // Get the model. @@ -204,7 +204,7 @@ public function publish() // Remove zero values resulting from input filter $cid = array_filter($cid); - if (empty($cid)) { + if ($cid === []) { $this->getLogger()->warning(Text::_($this->text_prefix . '_NO_ITEM_SELECTED'), ['category' => 'jerror']); } else { // Get the model. @@ -233,7 +233,7 @@ public function publish() $ntext = $this->text_prefix . '_N_ITEMS_TRASHED'; } - if (\count($cid)) { + if ($cid !== []) { $this->setMessage(Text::plural($ntext, \count($cid))); } } catch (\Exception $e) { @@ -439,7 +439,7 @@ public function runTransition() // Remove zero values resulting from input filter $pks = array_filter($pks); - if (!\count($pks)) { + if ($pks === []) { return false; } diff --git a/libraries/src/MVC/Controller/ApiController.php b/libraries/src/MVC/Controller/ApiController.php index f338b7d2dc0b8..fee8fbfeb7bcf 100644 --- a/libraries/src/MVC/Controller/ApiController.php +++ b/libraries/src/MVC/Controller/ApiController.php @@ -160,7 +160,7 @@ public function displayItem($id = null) ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $modelName = $this->input->get('model', Inflector::singularize($this->contentType)); @@ -175,7 +175,7 @@ public function displayItem($id = null) try { $modelName = $model->getName(); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $model->setState($modelName . '.id', $id); @@ -228,7 +228,7 @@ public function displayList() ['base_path' => $this->basePath, 'layout' => $viewLayout, 'contentType' => $this->contentType] ); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $modelName = $this->input->get('model', $this->contentType); @@ -348,7 +348,7 @@ public function edit() try { $table = $model->getTable(); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $recordId = $this->input->getInt('id'); @@ -397,7 +397,7 @@ protected function save($recordKey = null) try { $table = $model->getTable(); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $key = $table->getKeyName(); @@ -405,17 +405,14 @@ protected function save($recordKey = null) $checkin = property_exists($table, $table->getColumnAlias('checked_out')); $data[$key] = $recordKey; - if ($this->input->getMethod() === 'PATCH') { - if ($recordKey && $table->load($recordKey)) { - $fields = $table->getFields(); - - foreach ($fields as $field) { - if (\array_key_exists($field->Field, $data)) { - continue; - } - - $data[$field->Field] = $table->{$field->Field}; + if ($this->input->getMethod() === 'PATCH' && ($recordKey && $table->load($recordKey))) { + $fields = $table->getFields(); + foreach ($fields as $field) { + if (\array_key_exists($field->Field, $data)) { + continue; } + + $data[$field->Field] = $table->{$field->Field}; } } @@ -444,11 +441,7 @@ protected function save($recordKey = null) // Push up to three validation messages out to the user. for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) { - if ($errors[$i] instanceof \Exception) { - $messages[] = "{$errors[$i]->getMessage()}"; - } else { - $messages[] = "{$errors[$i]}"; - } + $messages[] = $errors[$i] instanceof \Exception ? "{$errors[$i]->getMessage()}" : "{$errors[$i]}"; } throw new InvalidParameterException(implode("\n", $messages)); @@ -466,7 +459,7 @@ protected function save($recordKey = null) try { $modelName = $model->getName(); } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } // Ensure we have the record ID in case we created a new article diff --git a/libraries/src/MVC/Controller/BaseController.php b/libraries/src/MVC/Controller/BaseController.php index c3bd8edb64d9b..de470e2329754 100644 --- a/libraries/src/MVC/Controller/BaseController.php +++ b/libraries/src/MVC/Controller/BaseController.php @@ -84,7 +84,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var string * @since 3.0 */ - protected $message; + protected $message = null; /** * Redirect message type. @@ -92,7 +92,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var string * @since 3.0 */ - protected $messageType; + protected $messageType = 'message'; /** * Array of class methods @@ -100,7 +100,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var array * @since 3.0 */ - protected $methods; + protected $methods = []; /** * The name of the controller @@ -124,7 +124,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var array * @since 3.0 */ - protected $paths; + protected $paths = []; /** * URL for redirection. @@ -132,7 +132,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var string * @since 3.0 */ - protected $redirect; + protected $redirect = null; /** * Current or most recently performed task. @@ -148,7 +148,7 @@ class BaseController implements ControllerInterface, DispatcherAwareInterface, L * @var array * @since 3.0 */ - protected $taskMap; + protected $taskMap = []; /** * Hold a JInput object for easier access to the input variables. @@ -225,11 +225,7 @@ public static function createFileName($type, $parts = []) switch ($type) { case 'controller': if (!empty($parts['format'])) { - if ($parts['format'] === 'html') { - $parts['format'] = ''; - } else { - $parts['format'] = '.' . $parts['format']; - } + $parts['format'] = $parts['format'] === 'html' ? '' : '.' . $parts['format']; } else { $parts['format'] = ''; } @@ -238,11 +234,7 @@ public static function createFileName($type, $parts = []) break; case 'view': - if (!empty($parts['type'])) { - $parts['type'] = '.' . $parts['type']; - } else { - $parts['type'] = ''; - } + $parts['type'] = empty($parts['type']) ? '' : '.' . $parts['type']; $filename = strtolower($parts['name'] . '/view' . $parts['type'] . '.php'); break; @@ -367,13 +359,6 @@ public static function getInstance($prefix, $config = []) */ public function __construct($config = [], ?MVCFactoryInterface $factory = null, ?CMSApplicationInterface $app = null, ?Input $input = null) { - $this->methods = []; - $this->message = null; - $this->messageType = 'message'; - $this->paths = []; - $this->redirect = null; - $this->taskMap = []; - $this->app = $app ?: Factory::getApplication(); $this->input = $input ?: $this->app->getInput(); @@ -411,19 +396,11 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null, // Set the view name if (empty($this->name)) { - if (\array_key_exists('name', $config)) { - $this->name = $config['name']; - } else { - $this->name = $this->getName(); - } + $this->name = \array_key_exists('name', $config) ? $config['name'] : $this->getName(); } // Set a base path for use by the controller - if (\array_key_exists('base_path', $config)) { - $this->basePath = $config['base_path']; - } else { - $this->basePath = JPATH_COMPONENT; - } + $this->basePath = \array_key_exists('base_path', $config) ? $config['base_path'] : JPATH_COMPONENT; // If the default task is set, register it as such if (\array_key_exists('default_task', $config)) { @@ -672,17 +649,11 @@ public function display($cachable = false, $urlparams = []) $option = $this->input->get('option'); if (\is_array($urlparams)) { - if (!empty($this->app->registeredurlparams)) { - $registeredurlparams = $this->app->registeredurlparams; - } else { - $registeredurlparams = new \stdClass(); - } - + $registeredurlparams = empty($this->app->registeredurlparams) ? new \stdClass() : $this->app->registeredurlparams; foreach ($urlparams as $key => $value) { // Add your safe URL parameters with variable type as value {@see InputFilter::clean()}. $registeredurlparams->$key = $value; } - $this->app->registeredurlparams = $registeredurlparams; } diff --git a/libraries/src/MVC/Controller/FormController.php b/libraries/src/MVC/Controller/FormController.php index 5576c439988ab..35b82c4ccd648 100644 --- a/libraries/src/MVC/Controller/FormController.php +++ b/libraries/src/MVC/Controller/FormController.php @@ -35,6 +35,7 @@ */ class FormController extends BaseController implements FormFactoryAwareInterface { + public $extension; use FormFactoryAwareTrait; /** @@ -858,10 +859,8 @@ public function reload($key = null, $urlVar = null) if (isset($filteredData[$field->group][$fieldName])) { $data[$field->group][$fieldName] = $filteredData[$field->group][$fieldName]; } - } else { - if (isset($filteredData[$fieldName])) { - $data[$fieldName] = $filteredData[$fieldName]; - } + } elseif (isset($filteredData[$fieldName])) { + $data[$fieldName] = $filteredData[$fieldName]; } } } diff --git a/libraries/src/MVC/Factory/MVCFactory.php b/libraries/src/MVC/Factory/MVCFactory.php index 1a159087aa81d..e3cdbf5bafa08 100644 --- a/libraries/src/MVC/Factory/MVCFactory.php +++ b/libraries/src/MVC/Factory/MVCFactory.php @@ -111,7 +111,7 @@ public function createController($name, $prefix, array $config, CMSApplicationIn $this->setUserFactoryOnObject($controller); $this->setMailerFactoryOnObject($controller); - if ($controller instanceof LoggerAwareInterface && $this->logger !== null) { + if ($controller instanceof LoggerAwareInterface && $this->logger instanceof \Psr\Log\LoggerInterface) { $controller->setLogger($this->logger); } @@ -166,7 +166,7 @@ public function createModel($name, $prefix = '', array $config = []) try { $model->setDatabase($this->getDatabase()); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $model->setDatabase(Factory::getContainer()->get(DatabaseInterface::class)); } } @@ -262,7 +262,7 @@ public function createTable($name, $prefix = '', array $config = []) try { $db = \array_key_exists('dbo', $config) ? $config['dbo'] : $this->getDatabase(); } catch (DatabaseNotFoundException) { - @trigger_error(\sprintf('Database must be set, this will not be caught anymore in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database must be set, this will not be caught anymore in 5.0.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseInterface::class); } @@ -285,7 +285,7 @@ public function createTable($name, $prefix = '', array $config = []) */ protected function getClassName(string $suffix, string $prefix) { - if (!$prefix) { + if ($prefix === '' || $prefix === '0') { $prefix = Factory::getApplication(); } diff --git a/libraries/src/MVC/Model/AdminModel.php b/libraries/src/MVC/Model/AdminModel.php index ada01072f6948..698d2e4230ac9 100644 --- a/libraries/src/MVC/Model/AdminModel.php +++ b/libraries/src/MVC/Model/AdminModel.php @@ -458,9 +458,9 @@ protected function batchCopy($value, $pks, $contexts) $this->table->id = 0; // Unpublish because we are making a copy - if (isset($this->table->published)) { + if ($this->table->published !== null) { $this->table->published = 0; - } elseif (isset($this->table->state)) { + } elseif ($this->table->state !== null) { $this->table->state = 0; } @@ -779,7 +779,7 @@ public function checkin($pks = []) $table = $this->getTable(); $count = 0; - if (empty($pks)) { + if ($pks === []) { $pks = [(int) $this->getState($this->getName() . '.id')]; } @@ -816,7 +816,7 @@ public function checkin($pks = []) */ public function checkout($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id'); + $pk = (empty($pk)) ? (int) $this->getState($this->getName() . '.id') : $pk; return parent::checkout($pk); } @@ -985,7 +985,7 @@ protected function generateNewTitle($categoryId, $alias, $title) */ public function getItem($pk = null) { - $pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id'); + $pk = (empty($pk)) ? (int) $this->getState($this->getName() . '.id') : $pk; $table = $this->getTable(); if ($pk > 0) { @@ -1123,7 +1123,7 @@ public function publish(&$pks, $value = 1) } // Check if there are items to change - if (!\count($pks)) { + if ($pks === []) { return true; } @@ -1219,7 +1219,7 @@ public function reorder($pks, $delta = 0) } } - if ($allowed === false && empty($pks)) { + if ($allowed === false && $pks === []) { $result = null; } @@ -1689,11 +1689,7 @@ protected function redirectToAssociations($data) $targetLang = implode(',', $targetLang); $targetId = $data['associations'][$targetLang]; - if ($targetId) { - $target = '&target=' . $targetLang . '%3A' . $targetId . '%3Aedit'; - } else { - $target = '&target=' . $targetLang . '%3A0%3Aadd'; - } + $target = $targetId ? '&target=' . $targetLang . '%3A' . $targetId . '%3Aedit' : '&target=' . $targetLang . '%3A0%3Aadd'; } $app->redirect( diff --git a/libraries/src/MVC/Model/BaseDatabaseModel.php b/libraries/src/MVC/Model/BaseDatabaseModel.php index 68a3f5391f486..ae0743f7cf99d 100644 --- a/libraries/src/MVC/Model/BaseDatabaseModel.php +++ b/libraries/src/MVC/Model/BaseDatabaseModel.php @@ -105,7 +105,7 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null) $db = \array_key_exists('dbo', $config) ? $config['dbo'] : Factory::getDbo(); if ($db) { - @trigger_error(\sprintf('Database is not available in constructor in 6.0.'), E_USER_DEPRECATED); + @trigger_error('Database is not available in constructor in 6.0.', E_USER_DEPRECATED); $this->setDatabase($db); // Is needed, when models use the deprecated MVC DatabaseAwareTrait, as the trait is overriding the local functions @@ -127,7 +127,7 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null) $this->event_clean_cache = 'onContentCleanCache'; } - if ($factory) { + if ($factory instanceof \Joomla\CMS\MVC\Factory\MVCFactoryInterface) { $this->setMVCFactory($factory); return; @@ -280,12 +280,7 @@ public function isCheckedOut($item) { $table = $this->getTable(); $checkedOutField = $table->getColumnAlias('checked_out'); - - if (property_exists($item, $checkedOutField) && $item->{$checkedOutField} != $this->getCurrentUser()->id) { - return true; - } - - return false; + return property_exists($item, $checkedOutField) && $item->{$checkedOutField} != $this->getCurrentUser()->id; } /** @@ -418,7 +413,7 @@ public function getDbo() */ public function setDbo(?DatabaseInterface $db = null) { - if ($db === null) { + if (!$db instanceof \Joomla\Database\DatabaseInterface) { return; } diff --git a/libraries/src/MVC/Model/BaseModel.php b/libraries/src/MVC/Model/BaseModel.php index a3389c756c8b1..4778f1f181d4d 100644 --- a/libraries/src/MVC/Model/BaseModel.php +++ b/libraries/src/MVC/Model/BaseModel.php @@ -60,11 +60,7 @@ public function __construct($config = []) { // Set the view name if (empty($this->name)) { - if (\array_key_exists('name', $config)) { - $this->name = $config['name']; - } else { - $this->name = $this->getName(); - } + $this->name = \array_key_exists('name', $config) ? $config['name'] : $this->getName(); } // Set the model state diff --git a/libraries/src/MVC/Model/FormBehaviorTrait.php b/libraries/src/MVC/Model/FormBehaviorTrait.php index 07535a2b85898..c70c72d3a5753 100644 --- a/libraries/src/MVC/Model/FormBehaviorTrait.php +++ b/libraries/src/MVC/Model/FormBehaviorTrait.php @@ -97,18 +97,11 @@ protected function loadForm($name, $source = null, $options = [], $clear = false if ($form->load($source, false, $xpath) == false) { throw new \RuntimeException('Form::loadForm could not load form'); } - } else { - if ($form->loadFile($source, false, $xpath) == false) { - throw new \RuntimeException('Form::loadForm could not load file'); - } + } elseif ($form->loadFile($source, false, $xpath) == false) { + throw new \RuntimeException('Form::loadForm could not load file'); } - if (isset($options['load_data']) && $options['load_data']) { - // Get the data for the form. - $data = $this->loadFormData(); - } else { - $data = []; - } + $data = isset($options['load_data']) && $options['load_data'] ? $this->loadFormData() : []; // Allow for additional modification of the form, and events to be triggered. // We pass the data because plugins may require it. diff --git a/libraries/src/MVC/Model/LegacyModelLoaderTrait.php b/libraries/src/MVC/Model/LegacyModelLoaderTrait.php index c3ecf05aad701..f4e8e6d9866a2 100644 --- a/libraries/src/MVC/Model/LegacyModelLoaderTrait.php +++ b/libraries/src/MVC/Model/LegacyModelLoaderTrait.php @@ -76,7 +76,7 @@ public static function getInstance($type, $prefix = '', $config = []) $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); - if ($model = self::createModelFromComponent($type, $prefix, $config)) { + if ($model = self::createModelFromComponent($type, $prefix, $config) instanceof \Joomla\CMS\MVC\Model\ModelInterface) { return $model; } diff --git a/libraries/src/MVC/Model/ListModel.php b/libraries/src/MVC/Model/ListModel.php index f77b1c1dd334f..61da38e323f9f 100644 --- a/libraries/src/MVC/Model/ListModel.php +++ b/libraries/src/MVC/Model/ListModel.php @@ -152,7 +152,7 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null) * @deprecated 4.0 will be removed in 6.0 * Use $this->filterForbiddenList instead */ - if (!empty($this->filterBlacklist)) { + if ($this->filterBlacklist !== []) { $this->filterForbiddenList = array_merge($this->filterBlacklist, $this->filterForbiddenList); } @@ -160,7 +160,7 @@ public function __construct($config = [], ?MVCFactoryInterface $factory = null) * @deprecated 4.0 will be removed in 6.0 * Use $this->listForbiddenList instead */ - if (!empty($this->listBlacklist)) { + if ($this->listBlacklist !== []) { $this->listForbiddenList = array_merge($this->listBlacklist, $this->listForbiddenList); } } diff --git a/libraries/src/MVC/Model/WorkflowBehaviorTrait.php b/libraries/src/MVC/Model/WorkflowBehaviorTrait.php index 232f6bcabee96..d0ceb944f2971 100644 --- a/libraries/src/MVC/Model/WorkflowBehaviorTrait.php +++ b/libraries/src/MVC/Model/WorkflowBehaviorTrait.php @@ -76,7 +76,7 @@ public function setUpWorkflow($extension) $this->extension = array_shift($parts); - if (\count($parts)) { + if ($parts !== []) { $this->section = array_shift($parts); } @@ -234,13 +234,13 @@ public function batchWorkflowStage(int $value, array $pks, array $contexts) // Get workflow stage information $stage = $workflow->getMVCFactory()->createTable('Stage', 'Administrator'); - if (empty($value) || !$stage->load($value)) { + if ($value === 0 || !$stage->load($value)) { Factory::getApplication()->enqueueMessage(Text::sprintf('JGLOBAL_BATCH_WORKFLOW_STAGE_ROW_NOT_FOUND'), 'error'); return false; } - if (empty($pks)) { + if ($pks === []) { Factory::getApplication()->enqueueMessage(Text::sprintf('JGLOBAL_BATCH_WORKFLOW_STAGE_ROW_NOT_FOUND'), 'error'); return false; diff --git a/libraries/src/MVC/View/AbstractView.php b/libraries/src/MVC/View/AbstractView.php index 948deff6aea57..0ec595928d94e 100644 --- a/libraries/src/MVC/View/AbstractView.php +++ b/libraries/src/MVC/View/AbstractView.php @@ -105,11 +105,7 @@ public function __construct($config = []) { // Set the view name if (empty($this->_name)) { - if (\array_key_exists('name', $config)) { - $this->_name = $config['name']; - } else { - $this->_name = $this->getName(); - } + $this->_name = \array_key_exists('name', $config) ? $config['name'] : $this->getName(); } // Set the component name if passed @@ -154,11 +150,7 @@ public function get($property, $default = null) ); // If $model is null we use the default model - if ($default === null) { - $model = $this->_defaultModel; - } else { - $model = strtolower($default); - } + $model = $default === null ? $this->_defaultModel : strtolower($default); // First check to make sure the model requested exists if (isset($this->_models[$model])) { diff --git a/libraries/src/MVC/View/CategoriesView.php b/libraries/src/MVC/View/CategoriesView.php index 739e4439b1efa..d5505a513754c 100644 --- a/libraries/src/MVC/View/CategoriesView.php +++ b/libraries/src/MVC/View/CategoriesView.php @@ -25,6 +25,11 @@ */ class CategoriesView extends HtmlView { + /** + * @var string + */ + public $pageclass_sfx; + public $maxLevelcat; /** * State data * @@ -70,7 +75,7 @@ class CategoriesView extends HtmlView * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * - * @return void|boolean + * @return bool|null * * @since 3.2 * @throws \Exception @@ -84,7 +89,7 @@ public function display($tpl = null) $app = Factory::getApplication(); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { $app->enqueueMessage($errors, 'error'); return false; @@ -117,6 +122,7 @@ public function display($tpl = null) $this->prepareDocument(); parent::display($tpl); + return null; } /** diff --git a/libraries/src/MVC/View/CategoryFeedView.php b/libraries/src/MVC/View/CategoryFeedView.php index 42c3f55f68c50..346e6ca33b8a6 100644 --- a/libraries/src/MVC/View/CategoryFeedView.php +++ b/libraries/src/MVC/View/CategoryFeedView.php @@ -27,6 +27,7 @@ */ class CategoryFeedView extends AbstractView { + public $viewName; /** * Execute and display a template script. * diff --git a/libraries/src/MVC/View/CategoryView.php b/libraries/src/MVC/View/CategoryView.php index c526af2cef695..5e93296b8ffea 100644 --- a/libraries/src/MVC/View/CategoryView.php +++ b/libraries/src/MVC/View/CategoryView.php @@ -27,6 +27,15 @@ */ class CategoryView extends HtmlView { + /** + * @var string + */ + public $pageclass_sfx; + public $maxLevel; + public $parent; + public $user; + public $pathway; + public $menu; /** * State data * @@ -169,7 +178,7 @@ public function commonCategoryDisplay() $pagination = $this->get('Pagination'); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } @@ -191,7 +200,7 @@ public function commonCategoryDisplay() $itemElement->event = new \stdClass(); // For some plugins. - !empty($itemElement->description) ? $itemElement->text = $itemElement->description : $itemElement->text = ''; + empty($itemElement->description) ? $itemElement->text = '' : $itemElement->text = $itemElement->description; Factory::getApplication()->triggerEvent('onContentPrepare', [$this->extension . '.category', $itemElement, $itemElement->params, 0]); diff --git a/libraries/src/MVC/View/Event/OnGetApiFields.php b/libraries/src/MVC/View/Event/OnGetApiFields.php index fcacdf0f8d004..4ac0de5fac71c 100644 --- a/libraries/src/MVC/View/Event/OnGetApiFields.php +++ b/libraries/src/MVC/View/Event/OnGetApiFields.php @@ -92,7 +92,7 @@ public function __construct($name, array $arguments = []) */ protected function setType($value) { - if (!\in_array($value, [static::ITEM, static::LIST])) { + if (!\in_array($value, [self::ITEM, self::LIST])) { throw new \BadMethodCallException("Argument 'type' of event {$this->name} must be a valid value"); } @@ -110,7 +110,7 @@ protected function setType($value) */ protected function setFields($value) { - if (!\is_array($value) || \is_array($value) && empty($value)) { + if (!\is_array($value) || $value === []) { throw new \BadMethodCallException("Argument 'fields' of event {$this->name} must be be an array and not empty"); } diff --git a/libraries/src/MVC/View/FormView.php b/libraries/src/MVC/View/FormView.php index 326d578b411a2..5240324c2f3c8 100644 --- a/libraries/src/MVC/View/FormView.php +++ b/libraries/src/MVC/View/FormView.php @@ -105,11 +105,7 @@ public function __construct(array $config) $this->helpLink = $config['help_link']; } - if (isset($config['toolbar_icon'])) { - $this->toolbarIcon = $config['toolbar_icon']; - } else { - $this->toolbarIcon = 'pencil-2 ' . $this->getName() . '-add'; - } + $this->toolbarIcon = $config['toolbar_icon'] ?? 'pencil-2 ' . $this->getName() . '-add'; // Set default value for $canDo to avoid fatal error if child class doesn't set value for this property // Return a CanDo object to prevent any BC break, will be changed in 7.0 to Registry @@ -131,7 +127,7 @@ public function display($tpl = null) $this->initializeView(); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } diff --git a/libraries/src/MVC/View/HtmlView.php b/libraries/src/MVC/View/HtmlView.php index 971dd02cb2318..5767e1757de4f 100644 --- a/libraries/src/MVC/View/HtmlView.php +++ b/libraries/src/MVC/View/HtmlView.php @@ -32,6 +32,12 @@ */ class HtmlView extends AbstractView implements CurrentUserInterface { + /** + * @var string + */ + public $baseurl; + public $this; + public $form; use CurrentUserTrait; /** @@ -126,11 +132,7 @@ public function __construct($config = []) } // Set a base path for use by the view - if (\array_key_exists('base_path', $config)) { - $this->_basePath = $config['base_path']; - } else { - $this->_basePath = JPATH_COMPONENT; - } + $this->_basePath = \array_key_exists('base_path', $config) ? $config['base_path'] : JPATH_COMPONENT; // Set the default template search path if (\array_key_exists('template_path', $config)) { @@ -181,11 +183,7 @@ public function display($tpl = null) { $app = Factory::getApplication(); - if ($this->option) { - $component = $this->option; - } else { - $component = ApplicationHelper::getComponentName(); - } + $component = $this->option ?: ApplicationHelper::getComponentName(); $context = $component . '.' . $this->getName(); @@ -376,9 +374,9 @@ public function loadTemplate($tpl = null) $lang = Factory::getApplication()->getLanguage(); } - $lang->load('tpl_' . $template->template, JPATH_BASE) - || $lang->load('tpl_' . $template->parent, JPATH_THEMES . '/' . $template->parent) - || $lang->load('tpl_' . $template->template, JPATH_THEMES . '/' . $template->template); + if (!$lang->load('tpl_' . $template->template, JPATH_BASE) && !$lang->load('tpl_' . $template->parent, JPATH_THEMES . '/' . $template->parent)) { + $lang->load('tpl_' . $template->template, JPATH_THEMES . '/' . $template->template); + } // Change the template folder if alternative layout is in different template if (isset($layoutTemplate) && $layoutTemplate !== '_' && $layoutTemplate != $template->template) { @@ -404,7 +402,7 @@ public function loadTemplate($tpl = null) unset($tpl, $file); // Never allow a 'this' property - if (isset($this->this)) { + if (property_exists($this, 'this') && $this->this !== null) { unset($this->this); } @@ -460,11 +458,7 @@ public function loadHelper($hlp = null) */ protected function _setPath($type, $path) { - if ($this->option) { - $component = $this->option; - } else { - $component = ApplicationHelper::getComponentName(); - } + $component = $this->option ?: ApplicationHelper::getComponentName(); $app = Factory::getApplication(); @@ -477,30 +471,22 @@ protected function _setPath($type, $path) // Get the active template object $template = $app->getTemplate(true); - // Always add the fallback directories as last resort - switch (strtolower($type)) { - case 'template': - // Set the alternative template search dir - if (isset($app)) { - if ($component) { - $component = preg_replace('/[^A-Z0-9_\.-]/i', '', $component); - } - - $name = $this->getName(); - - if (!empty($template->parent)) { - // Parent template's overrides - $this->_addPath('template', JPATH_THEMES . '/' . $template->parent . '/html/' . $component . '/' . $name); - - // Child template's overrides - $this->_addPath('template', JPATH_THEMES . '/' . $template->template . '/html/' . $component . '/' . $name); + // Set the alternative template search dir + if (strtolower($type) === 'template' && isset($app)) { + if ($component) { + $component = preg_replace('/[^A-Z0-9_\.-]/i', '', $component); + } + $name = $this->getName(); + if (!empty($template->parent)) { + // Parent template's overrides + $this->_addPath('template', JPATH_THEMES . '/' . $template->parent . '/html/' . $component . '/' . $name); - break; - } + // Child template's overrides + $this->_addPath('template', JPATH_THEMES . '/' . $template->template . '/html/' . $component . '/' . $name); - $this->_addPath('template', JPATH_THEMES . '/' . $template->template . '/html/' . $component . '/' . $name); - } - break; + return; + } + $this->_addPath('template', JPATH_THEMES . '/' . $template->template . '/html/' . $component . '/' . $name); } } diff --git a/libraries/src/MVC/View/JsonApiView.php b/libraries/src/MVC/View/JsonApiView.php index a288e5fc90b40..e7d3a36bf3fa2 100644 --- a/libraries/src/MVC/View/JsonApiView.php +++ b/libraries/src/MVC/View/JsonApiView.php @@ -131,7 +131,7 @@ public function displayList(?array $items = null) $pagination = $model->getPagination(); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } @@ -188,7 +188,7 @@ public function displayList(?array $items = null) $collection = (new Collection($items, $this->serializer)) ->fields([$this->type => $eventResult->getAllPropertiesToRender()]); - if (!empty($this->relationship)) { + if ($this->relationship !== []) { $collection->with($this->relationship); } @@ -220,7 +220,7 @@ public function displayItem($item = null) } // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } @@ -242,7 +242,7 @@ public function displayItem($item = null) $element = (new Resource($item, $this->serializer)) ->fields([$this->type => $eventResult->getAllPropertiesToRender()]); - if (!empty($this->relationship)) { + if ($this->relationship !== []) { $element->with($eventResult->getAllRelationsToRender()); } diff --git a/libraries/src/MVC/View/JsonView.php b/libraries/src/MVC/View/JsonView.php index 479a30e26d615..ad9e609845979 100644 --- a/libraries/src/MVC/View/JsonView.php +++ b/libraries/src/MVC/View/JsonView.php @@ -74,11 +74,7 @@ public function __construct($config = []) } // Set a base path for use by the view - if (\array_key_exists('base_path', $config)) { - $this->_basePath = $config['base_path']; - } else { - $this->_basePath = JPATH_COMPONENT; - } + $this->_basePath = \array_key_exists('base_path', $config) ? $config['base_path'] : JPATH_COMPONENT; } /** diff --git a/libraries/src/MVC/View/ListView.php b/libraries/src/MVC/View/ListView.php index e5b6d0dc91bb3..5f949b852986d 100644 --- a/libraries/src/MVC/View/ListView.php +++ b/libraries/src/MVC/View/ListView.php @@ -123,11 +123,7 @@ public function __construct(array $config) $this->toolbarTitle = strtoupper($this->option . '_MANAGER_' . $this->getName()); } - if (isset($config['toolbar_icon'])) { - $this->toolbarIcon = $config['toolbar_icon']; - } else { - $this->toolbarIcon = strtolower($this->getName()); - } + $this->toolbarIcon = $config['toolbar_icon'] ?? strtolower($this->getName()); if (isset($config['supports_batch'])) { $this->supportsBatch = $config['supports_batch']; @@ -157,7 +153,7 @@ public function display($tpl = null) $this->initializeView(); // Check for errors. - if (\count($errors = $this->get('Errors'))) { + if (\count($errors = $this->get('Errors')) > 0) { throw new GenericDataException(implode("\n", $errors), 500); } diff --git a/libraries/src/Mail/MailTemplate.php b/libraries/src/Mail/MailTemplate.php index 71934374a0364..4162653a83fd3 100644 --- a/libraries/src/Mail/MailTemplate.php +++ b/libraries/src/Mail/MailTemplate.php @@ -112,11 +112,7 @@ public function __construct(/** */ protected $language, ?Mail $mailer = null) { - if ($mailer) { - $this->mailer = $mailer; - } else { - $this->mailer = Factory::getMailer(); - } + $this->mailer = $mailer ?: Factory::getMailer(); } /** @@ -335,7 +331,7 @@ public function send() } // Add the logo to the mail as inline attachment - if ($logo) { + if ($logo !== '' && $logo !== '0') { $logo = Path::check(JPATH_ROOT . '/' . HTMLHelper::_('cleanImageURL', $logo)->url); if (is_file(urldecode($logo))) { # Attach the logo as inline attachment @@ -392,7 +388,7 @@ public function send() $this->mailer->addReplyTo($replyTo, $replyToName); } - if (trim((string) $config->get('attachment_folder', ''))) { + if (trim((string) $config->get('attachment_folder', '')) !== '' && trim((string) $config->get('attachment_folder', '')) !== '0') { $folderPath = rtrim(Path::check(JPATH_ROOT . '/' . $config->get('attachment_folder')), \DIRECTORY_SEPARATOR); if ($folderPath && $folderPath !== Path::clean(JPATH_ROOT) && is_dir($folderPath)) { @@ -609,7 +605,7 @@ public static function deleteTemplate($key) protected function getAttachmentName(string $file, string $name): string { // If no name is given, do not process it further - if (!trim($name)) { + if (trim($name) === '' || trim($name) === '0') { return ''; } diff --git a/libraries/src/Mail/MailerFactory.php b/libraries/src/Mail/MailerFactory.php index 6836b8bf88936..c5f20ade8e1d0 100644 --- a/libraries/src/Mail/MailerFactory.php +++ b/libraries/src/Mail/MailerFactory.php @@ -53,7 +53,7 @@ public function createMailer(?Registry $settings = null): MailerInterface { $configuration = new Registry($this->defaultConfiguration); - if ($settings) { + if ($settings instanceof \Joomla\Registry\Registry) { $configuration->merge($settings); } diff --git a/libraries/src/Menu/AbstractMenu.php b/libraries/src/Menu/AbstractMenu.php index eabff47616c84..f9e287994bd72 100644 --- a/libraries/src/Menu/AbstractMenu.php +++ b/libraries/src/Menu/AbstractMenu.php @@ -282,11 +282,9 @@ public function getItems($attributes, $values, $firstonly = false) $test = false; break; } - } else { - if ($item->{$attributes[$i]} != $values[$i]) { - $test = false; - break; - } + } elseif ($item->{$attributes[$i]} != $values[$i]) { + $test = false; + break; } } diff --git a/libraries/src/Menu/SiteMenu.php b/libraries/src/Menu/SiteMenu.php index fae79b29b7d3b..addf03e9d667d 100644 --- a/libraries/src/Menu/SiteMenu.php +++ b/libraries/src/Menu/SiteMenu.php @@ -72,7 +72,7 @@ public function __construct($options = []) $this->language = isset($options['language']) && $options['language'] instanceof Language ? $options['language'] : Factory::getLanguage(); if (!isset($options['db']) || !($options['db'] instanceof DatabaseDriver)) { - @trigger_error(\sprintf('Database will be mandatory in 5.0.'), E_USER_DEPRECATED); + @trigger_error('Database will be mandatory in 5.0.', E_USER_DEPRECATED); $options['db'] = Factory::getContainer()->get(DatabaseDriver::class); } @@ -278,5 +278,6 @@ public function getDefault($language = '*') if (\array_key_exists('*', $this->default)) { return $items[$this->default['*']]; } + return null; } } diff --git a/libraries/src/Microdata/Microdata.php b/libraries/src/Microdata/Microdata.php index eeb59a7654e9e..3fb18a8f76d73 100644 --- a/libraries/src/Microdata/Microdata.php +++ b/libraries/src/Microdata/Microdata.php @@ -307,11 +307,7 @@ public function fallback($type, $property) } // Control if the $Property exist in the given $Type and setup it, otherwise leave it 'NULL' - if (static::isPropertyInType($this->fallbackType, $property)) { - $this->fallbackProperty = $property; - } else { - $this->fallbackProperty = null; - } + $this->fallbackProperty = static::isPropertyInType($this->fallbackType, $property) ? $property : null; return $this; } @@ -792,14 +788,10 @@ public static function htmlTag($tag, $content, $property = '', $scope = '', $inv } // Depending on the case, the $scope must precede the $property, or otherwise - if ($invert) { - $tmp = implode(' ', [$property, $scope]); - } else { - $tmp = implode(' ', [$scope, $property]); - } + $tmp = $invert ? implode(' ', [$property, $scope]) : implode(' ', [$scope, $property]); $tmp = trim($tmp); - $tmp = ($tmp) ? ' ' . $tmp : ''; + $tmp = ($tmp !== '' && $tmp !== '0') ? ' ' . $tmp : ''; // Control if it is an empty element without a closing tag if ($tag === 'meta') { diff --git a/libraries/src/Object/LegacyPropertyManagementTrait.php b/libraries/src/Object/LegacyPropertyManagementTrait.php index 68f1c8e7b5787..37add057a441b 100644 --- a/libraries/src/Object/LegacyPropertyManagementTrait.php +++ b/libraries/src/Object/LegacyPropertyManagementTrait.php @@ -84,7 +84,7 @@ public function getProperties($public = true) $vars = get_object_vars($this); if ($public) { - foreach ($vars as $key => $value) { + foreach (array_keys($vars) as $key) { if (str_starts_with($key, '_')) { unset($vars[$key]); } diff --git a/libraries/src/Pagination/Pagination.php b/libraries/src/Pagination/Pagination.php index fbbd9c9fd9333..38ba5edb80ebb 100644 --- a/libraries/src/Pagination/Pagination.php +++ b/libraries/src/Pagination/Pagination.php @@ -156,7 +156,7 @@ public function __construct($total, $limitstart, $limit, /** $this->limitstart = 0; } - if (!$this->limit) { + if ($this->limit === 0) { $this->limit = $total; $this->limitstart = 0; } @@ -186,11 +186,7 @@ public function __construct($total, $limitstart, $limit, /** if ($this->pagesStart + $displayedPages > $this->pagesTotal) { $this->pagesStop = $this->pagesTotal; - if ($this->pagesTotal < $displayedPages) { - $this->pagesStart = 1; - } else { - $this->pagesStart = $this->pagesTotal - $displayedPages + 1; - } + $this->pagesStart = $this->pagesTotal < $displayedPages ? 1 : $this->pagesTotal - $displayedPages + 1; } else { $this->pagesStop = $this->pagesStart + $displayedPages - 1; } @@ -337,11 +333,7 @@ public function getResultsCounter() $fromResult = $this->limitstart + 1; // If the limit is reached before the end of the list. - if ($this->limitstart + $this->limit < $this->total) { - $toResult = $this->limitstart + $this->limit; - } else { - $toResult = $this->total; - } + $toResult = $this->limitstart + $this->limit < $this->total ? $this->limitstart + $this->limit : $this->total; // If there are results found. if ($this->total > 0) { diff --git a/libraries/src/Pathway/SitePathway.php b/libraries/src/Pathway/SitePathway.php index d60ce71db0f99..836ec5d046b74 100644 --- a/libraries/src/Pathway/SitePathway.php +++ b/libraries/src/Pathway/SitePathway.php @@ -43,11 +43,7 @@ public function __construct(?SiteApplication $app = null) $menus = $menu->getMenu(); // Look for the home menu - if (Multilanguage::isEnabled()) { - $home = $menu->getDefault($lang->getTag()); - } else { - $home = $menu->getDefault(); - } + $home = Multilanguage::isEnabled() ? $menu->getDefault($lang->getTag()) : $menu->getDefault(); if (\is_object($home) && ($item->id != $home->id)) { foreach ($item->tree as $menupath) { diff --git a/libraries/src/Plugin/CMSPlugin.php b/libraries/src/Plugin/CMSPlugin.php index 8b373a758c319..395688903cc8f 100644 --- a/libraries/src/Plugin/CMSPlugin.php +++ b/libraries/src/Plugin/CMSPlugin.php @@ -175,7 +175,7 @@ public function loadLanguage($extension = '', $basePath = JPATH_ADMINISTRATOR) } $extension = strtolower($extension); - $lang = $this->getApplication() ? $this->getApplication()->getLanguage() : Factory::getLanguage(); + $lang = $this->getApplication() instanceof \Joomla\CMS\Application\CMSApplicationInterface ? $this->getApplication()->getLanguage() : Factory::getLanguage(); // If language already loaded, don't load it again. if ($lang->getPaths($extension)) { diff --git a/libraries/src/Plugin/PluginHelper.php b/libraries/src/Plugin/PluginHelper.php index b2681071f3282..4cf8a5cf6f062 100644 --- a/libraries/src/Plugin/PluginHelper.php +++ b/libraries/src/Plugin/PluginHelper.php @@ -166,7 +166,7 @@ public static function importPlugin($type, $plugin = null, $autocreate = true, ? // Check for the default args, if so we can optimise cheaply $defaults = false; - if ($plugin === null && $autocreate === true && $dispatcher === null) { + if ($plugin === null && $autocreate === true && !$dispatcher instanceof \Joomla\Event\DispatcherInterface) { $defaults = true; } diff --git a/libraries/src/Profiler/Profiler.php b/libraries/src/Profiler/Profiler.php index bbe8cfd85e4f2..605372872f5a8 100644 --- a/libraries/src/Profiler/Profiler.php +++ b/libraries/src/Profiler/Profiler.php @@ -31,13 +31,13 @@ class Profiler * @var array The buffer of profiling messages. * @since 3.0.0 */ - protected $buffer = null; + protected $buffer = []; /** * @var array The profiling messages. * @since 3.0.0 */ - protected $marks = null; + protected $marks = []; /** * @var float The previous time marker @@ -70,8 +70,6 @@ public function __construct(/** protected $prefix = '') { $this->start = microtime(1); - $this->marks = []; - $this->buffer = []; } /** diff --git a/libraries/src/Response/JsonResponse.php b/libraries/src/Response/JsonResponse.php index 999154239ca7e..f11cd634d0f82 100644 --- a/libraries/src/Response/JsonResponse.php +++ b/libraries/src/Response/JsonResponse.php @@ -87,7 +87,7 @@ public function __construct($response = null, /** } // If messages exist add them to the output - if (\count($lists)) { + if ($lists !== []) { $this->messages = $lists; } } diff --git a/libraries/src/Router/ApiRouter.php b/libraries/src/Router/ApiRouter.php index d05b9314f7023..cc1b119a29ed1 100644 --- a/libraries/src/Router/ApiRouter.php +++ b/libraries/src/Router/ApiRouter.php @@ -101,23 +101,18 @@ public function parseApiRoute($method = 'GET') // Iterate through all of the known routes looking for a match. foreach ($this->routes as $route) { - if (\in_array($method, $route->getMethods())) { - if (preg_match($route->getRegex(), ltrim($routePath, '/'), $matches)) { - // If we have gotten this far then we have a positive match. - $vars = $route->getDefaults(); - - foreach ($route->getRouteVariables() as $i => $var) { - $vars[$var] = $matches[$i + 1]; - } - - $controller = preg_split("/[.]+/", (string) $route->getController()); - - return [ - 'controller' => $controller[0], - 'task' => $controller[1], - 'vars' => $vars, - ]; + if (\in_array($method, $route->getMethods()) && preg_match($route->getRegex(), ltrim($routePath, '/'), $matches)) { + // If we have gotten this far then we have a positive match. + $vars = $route->getDefaults(); + foreach ($route->getRouteVariables() as $i => $var) { + $vars[$var] = $matches[$i + 1]; } + $controller = preg_split("/[.]+/", (string) $route->getController()); + return [ + 'controller' => $controller[0], + 'task' => $controller[1], + 'vars' => $vars, + ]; } } diff --git a/libraries/src/Router/Router.php b/libraries/src/Router/Router.php index 891ce5331c086..e14a86ff55296 100644 --- a/libraries/src/Router/Router.php +++ b/libraries/src/Router/Router.php @@ -194,11 +194,7 @@ public function build($url) return clone $this->cache[$key]; } - if ($url instanceof Uri) { - $uri = $url; - } else { - $uri = $this->createUri($url); - } + $uri = $url instanceof Uri ? $url : $this->createUri($url); // Do the preprocess stage of the URL build process $this->processBuildRules($uri, self::PROCESS_BEFORE); @@ -244,11 +240,7 @@ public function setVar($key, $value, $create = true) */ public function setVars($vars = [], $merge = true) { - if ($merge) { - $this->vars = array_merge($this->vars, $vars); - } else { - $this->vars = $vars; - } + $this->vars = $merge ? array_merge($this->vars, $vars) : $vars; } /** diff --git a/libraries/src/Router/SiteRouter.php b/libraries/src/Router/SiteRouter.php index 1f623367a9f41..967716ec1c896 100644 --- a/libraries/src/Router/SiteRouter.php +++ b/libraries/src/Router/SiteRouter.php @@ -178,7 +178,7 @@ public function parseFormat(&$router, &$uri) $route = $uri->getPath(); // Identify format - if (!(str_ends_with($route, 'index.php') || str_ends_with($route, '/')) && $suffix = pathinfo($route, PATHINFO_EXTENSION)) { + if (!str_ends_with($route, 'index.php') && !str_ends_with($route, '/') && $suffix = pathinfo($route, PATHINFO_EXTENSION)) { $uri->setVar('format', $suffix); $route = str_replace('.' . $suffix, '', $route); $uri->setPath($route); @@ -280,7 +280,7 @@ public function parseSefRoute(&$router, &$uri) if (!empty($route) && $uri->getVar('option')) { $segments = explode('/', $route); - if (\count($segments)) { + if ($segments !== []) { // Handle component route $component = preg_replace('/[^A-Z0-9_\.-]/i', '', (string) $uri->getVar('option')); $crouter = $this->getComponentRouter($component); @@ -376,10 +376,8 @@ public function buildInit(&$router, &$uri) } // If Itemid is given, but no option, set the option from the menu item - if ($itemid && !$uri->getVar('option')) { - if ($item = $this->menu->getItem($itemid)) { - $uri->setVar('option', $item->component); - } + if ($itemid && !$uri->getVar('option') && $item = $this->menu->getItem($itemid)) { + $uri->setVar('option', $item->component); } } @@ -453,7 +451,7 @@ public function buildSefRoute(&$router, &$uri) // Build the application route if ($item !== null && $query['option'] === $item->component) { if (!$item->home) { - $tmp = $tmp ? $item->route . '/' . $tmp : $item->route; + $tmp = $tmp !== '' && $tmp !== '0' ? $item->route . '/' . $tmp : $item->route; } unset($query['Itemid']); @@ -509,7 +507,7 @@ public function buildFormat(&$router, &$uri) $route = $uri->getPath(); // Identify format - if (!(str_ends_with($route, 'index.php') || str_ends_with($route, '/')) && $format = $uri->getVar('format', 'html')) { + if (!str_ends_with($route, 'index.php') && !str_ends_with($route, '/') && $format = $uri->getVar('format', 'html')) { $route .= '.' . $format; $uri->setPath($route); $uri->delVar('format'); @@ -532,11 +530,7 @@ public function buildRewrite(&$router, &$uri) $route = $uri->getPath(); // Transform the route - if ($route === 'index.php') { - $route = ''; - } else { - $route = str_replace('index.php/', '', $route); - } + $route = $route === 'index.php' ? '' : str_replace('index.php/', '', $route); $uri->setPath($route); } diff --git a/libraries/src/Schema/ChangeItem/PostgresqlChangeItem.php b/libraries/src/Schema/ChangeItem/PostgresqlChangeItem.php index 907c6880e3d8f..9245dcbbb65ee 100644 --- a/libraries/src/Schema/ChangeItem/PostgresqlChangeItem.php +++ b/libraries/src/Schema/ChangeItem/PostgresqlChangeItem.php @@ -128,11 +128,7 @@ protected function buildCheckQuery() $type = substr($type, 0, $pos); } - if ($pos = strpos($type, '(')) { - $datatype = substr($type, 0, $pos); - } else { - $datatype = $type; - } + $datatype = $pos = strpos($type, '(') ? substr($type, 0, $pos) : $type; if ($datatype === 'varchar') { $datatype = 'character varying'; @@ -264,13 +260,7 @@ protected function buildCheckQuery() } // Set fields based on results - if ($this->checkQuery = $result) { - // Unchecked status - $this->checkStatus = 0; - } else { - // Skipped - $this->checkStatus = -1; - } + $this->checkStatus = $this->checkQuery = $result ? 0 : -1; } /** diff --git a/libraries/src/Schemaorg/SchemaorgPluginTrait.php b/libraries/src/Schemaorg/SchemaorgPluginTrait.php index bbdd2e059234e..23be7fb0827a5 100644 --- a/libraries/src/Schemaorg/SchemaorgPluginTrait.php +++ b/libraries/src/Schemaorg/SchemaorgPluginTrait.php @@ -121,7 +121,7 @@ protected function convertToArray(array $schema, array $repeatableFields) $result[] = $value; } - if (empty($result)) { + if ($result === []) { unset($schema[$repeatableField]); continue; @@ -173,23 +173,9 @@ protected function checkAllowedAndForbiddenlist($context) { $allowedlist = array_filter((array) $this->params->get('allowedlist', [])); $forbiddenlist = array_filter((array) $this->params->get('forbiddenlist', [])); - - if (!empty($allowedlist)) { - foreach ($allowedlist as $allowed) { - if ($context === $allowed) { - return true; - } - } - - return false; + if ($allowedlist !== []) { + return in_array($context, $allowedlist, true); } - - foreach ($forbiddenlist as $forbidden) { - if ($context === $forbidden) { - return false; - } - } - - return true; + return !in_array($context, $forbiddenlist, true); } } diff --git a/libraries/src/Schemaorg/SchemaorgPrepareDurationTrait.php b/libraries/src/Schemaorg/SchemaorgPrepareDurationTrait.php index 3a51799d2c37b..6d14e16997b0c 100644 --- a/libraries/src/Schemaorg/SchemaorgPrepareDurationTrait.php +++ b/libraries/src/Schemaorg/SchemaorgPrepareDurationTrait.php @@ -35,7 +35,7 @@ protected function prepareDuration($duration) return null; } - $newDuration = 'PT' . (!empty($duration['hour']) ? (int) $duration['hour'] . 'H' : '') . (!empty($duration['min']) ? (int) $duration['min'] . 'M' : ''); + $newDuration = 'PT' . (empty($duration['hour']) ? '' : (int) $duration['hour'] . 'H') . (empty($duration['min']) ? '' : (int) $duration['min'] . 'M'); return $newDuration !== 'PT' ? $newDuration : null; } diff --git a/libraries/src/Serializer/JoomlaSerializer.php b/libraries/src/Serializer/JoomlaSerializer.php index 70dad8978239c..1ce3aeaed8633 100644 --- a/libraries/src/Serializer/JoomlaSerializer.php +++ b/libraries/src/Serializer/JoomlaSerializer.php @@ -109,13 +109,6 @@ public function getRelationship($model, $name) /** @var Events\OnGetApiRelation $eventResult */ $eventResult = Factory::getApplication()->getDispatcher()->dispatch('onGetApiRelation', $event); - - $relationship = $eventResult->getRelationship(); - - if ($relationship instanceof Relationship) { - return $relationship; - } - - return null; + return $eventResult->getRelationship(); } } diff --git a/libraries/src/Service/Provider/Database.php b/libraries/src/Service/Provider/Database.php index 9361923d05050..0072da2bec824 100644 --- a/libraries/src/Service/Provider/Database.php +++ b/libraries/src/Service/Provider/Database.php @@ -67,10 +67,8 @@ function (Container $container) { $dbtype = 'mysql'; } - if (strtolower($dbtype) === 'mysql') { - if (!MysqlDriver::isSupported()) { - $dbtype = 'mysqli'; - } + if (strtolower($dbtype) === 'mysql' && !MysqlDriver::isSupported()) { + $dbtype = 'mysqli'; } /* diff --git a/libraries/src/String/PunycodeHelper.php b/libraries/src/String/PunycodeHelper.php index 769c7a1e5781e..732a50d90dcab 100644 --- a/libraries/src/String/PunycodeHelper.php +++ b/libraries/src/String/PunycodeHelper.php @@ -98,7 +98,7 @@ public static function urlToPunycode($uri) $newuri .= $parsed['scheme'] . '://'; } - if (!empty($newhost)) { + if ($newhost !== '' && $newhost !== '0') { $newuri .= $newhost; } @@ -160,7 +160,7 @@ public static function urlToUTF8($uri) $newuri .= $parsed['scheme'] . '://'; } - if (!empty($newhost)) { + if ($newhost !== '' && $newhost !== '0') { $newuri .= $newhost; } @@ -205,7 +205,7 @@ public static function emailToPunycode($email) // Not addressing UTF-8 user names $newEmail = $explodedAddress[0]; - if (!empty($explodedAddress[1])) { + if (isset($explodedAddress[1]) && ($explodedAddress[1] !== '' && $explodedAddress[1] !== '0')) { $domainExploded = explode('.', $explodedAddress[1]); $newdomain = ''; @@ -238,7 +238,7 @@ public static function emailToUTF8($email) // Not addressing UTF-8 user names $newEmail = $explodedAddress[0]; - if (!empty($explodedAddress[1])) { + if (isset($explodedAddress[1]) && ($explodedAddress[1] !== '' && $explodedAddress[1] !== '0')) { $domainExploded = explode('.', $explodedAddress[1]); $newdomain = ''; diff --git a/libraries/src/TUF/TufFetcher.php b/libraries/src/TUF/TufFetcher.php index 785dcb3156512..71f1bbf45138c 100644 --- a/libraries/src/TUF/TufFetcher.php +++ b/libraries/src/TUF/TufFetcher.php @@ -118,6 +118,7 @@ public function getValidUpdate() } $this->rollBackTufMetadata(); + return null; } /** diff --git a/libraries/src/Table/Category.php b/libraries/src/Table/Category.php index bb23fd1b76f85..2a6f467290564 100644 --- a/libraries/src/Table/Category.php +++ b/libraries/src/Table/Category.php @@ -166,7 +166,7 @@ public function check() } // Check for a title. - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_CATEGORY')); return false; @@ -174,13 +174,13 @@ public function check() $this->alias = trim($this->alias); - if (empty($this->alias)) { + if ($this->alias === '' || $this->alias === '0') { $this->alias = $this->title; } $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); - if (trim(str_replace('-', '', $this->alias)) == '') { + if (trim(str_replace('-', '', $this->alias)) === '') { $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } @@ -235,7 +235,7 @@ public function store($updateNulls = true) $user = $this->getCurrentUser(); // Set created date if not set. - if (!(int) $this->created_time) { + if ((int) $this->created_time === 0) { $this->created_time = $date; } @@ -244,7 +244,7 @@ public function store($updateNulls = true) $this->modified_user_id = $user->id; $this->modified_time = $date; } else { - if (!(int) ($this->modified_time)) { + if ((int) ($this->modified_time) === 0) { $this->modified_time = $this->created_time; } diff --git a/libraries/src/Table/Content.php b/libraries/src/Table/Content.php index 55a5f4cabfe83..aec13ecc5f7ad 100644 --- a/libraries/src/Table/Content.php +++ b/libraries/src/Table/Content.php @@ -197,30 +197,30 @@ public function check() return false; } - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('COM_CONTENT_WARNING_PROVIDE_VALID_NAME')); return false; } - if (trim($this->alias) == '') { + if (trim($this->alias) === '') { $this->alias = $this->title; } $this->alias = ApplicationHelper::stringURLSafe($this->alias, $this->language); - if (trim(str_replace('-', '', $this->alias)) == '') { + if (trim(str_replace('-', '', $this->alias)) === '') { $this->alias = Factory::getDate()->format('Y-m-d-H-i-s'); } // Check for a valid category. - if (!$this->catid = (int) $this->catid) { + if ($this->catid = (int) $this->catid === 0) { $this->setError(Text::_('JLIB_DATABASE_ERROR_CATEGORY_REQUIRED')); return false; } - if (trim(str_replace(' ', '', $this->fulltext)) == '') { + if (trim(str_replace(' ', '', $this->fulltext)) === '') { $this->fulltext = ''; } @@ -230,22 +230,22 @@ public function check() */ if (!$this->id) { // Images can be an empty json string - if (!isset($this->images)) { + if ($this->images === null) { $this->images = '{}'; } // URLs can be an empty json string - if (!isset($this->urls)) { + if ($this->urls === null) { $this->urls = '{}'; } // Attributes (article params) can be an empty json string - if (!isset($this->attribs)) { + if ($this->attribs === null) { $this->attribs = '{}'; } // Metadata can be an empty json string - if (!isset($this->metadata)) { + if ($this->metadata === null) { $this->metadata = '{}'; } @@ -288,7 +288,7 @@ public function check() $cleanKeys = []; foreach ($keys as $key) { - if (trim($key)) { + if (trim($key) !== '' && trim($key) !== '0') { // Ignore blank keywords $cleanKeys[] = trim($key); } @@ -322,7 +322,7 @@ public function store($updateNulls = true) $user = $this->getCurrentUser(); // Set created date if not set. - if (!(int) $this->created) { + if ((int) $this->created === 0) { $this->created = $date; } @@ -340,7 +340,7 @@ public function store($updateNulls = true) } // Set modified to created date if not set - if (!(int) $this->modified) { + if ((int) $this->modified === 0) { $this->modified = $this->created; } diff --git a/libraries/src/Table/ContentHistory.php b/libraries/src/Table/ContentHistory.php index 15f2457b0de4b..07139d95719e0 100644 --- a/libraries/src/Table/ContentHistory.php +++ b/libraries/src/Table/ContentHistory.php @@ -36,7 +36,17 @@ class ContentHistory extends Table implements CurrentUserInterface * @var array * @since 3.2 */ - public $ignoreChanges = []; + public $ignoreChanges = [ + 'modified_by', + 'modified_user_id', + 'modified', + 'modified_time', + 'checked_out', + 'checked_out_time', + 'version', + 'hits', + 'path', + ]; /** * Array of object fields to convert to integers before calculating SHA1 hash. Some values are stored differently @@ -46,7 +56,7 @@ class ContentHistory extends Table implements CurrentUserInterface * @var array * @since 3.2 */ - public $convertToInt = []; + public $convertToInt = ['publish_up', 'publish_down', 'ordering', 'featured']; /** * Constructor @@ -59,18 +69,6 @@ class ContentHistory extends Table implements CurrentUserInterface public function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher = null) { parent::__construct('#__history', 'version_id', $db, $dispatcher); - $this->ignoreChanges = [ - 'modified_by', - 'modified_user_id', - 'modified', - 'modified_time', - 'checked_out', - 'checked_out_time', - 'version', - 'hits', - 'path', - ]; - $this->convertToInt = ['publish_up', 'publish_down', 'ordering', 'featured']; } /** @@ -90,7 +88,7 @@ public function store($updateNulls = false) array_pop($typeAlias); $typeTable->load(['type_alias' => implode('.', $typeAlias)]); - if (!isset($this->sha1_hash)) { + if ($this->sha1_hash === null) { $this->sha1_hash = $this->getSha1($this->version_data, $typeTable); } @@ -118,7 +116,7 @@ public function getSha1($jsonData, ContentType $typeTable) { $object = \is_object($jsonData) ? $jsonData : json_decode((string) $jsonData); - if (isset($typeTable->content_history_options) && \is_object(json_decode($typeTable->content_history_options))) { + if ($typeTable->content_history_options !== null && \is_object(json_decode($typeTable->content_history_options))) { $options = json_decode($typeTable->content_history_options); $this->ignoreChanges = $options->ignoreChanges ?? $this->ignoreChanges; $this->convertToInt = $options->convertToInt ?? $this->convertToInt; diff --git a/libraries/src/Table/ContentType.php b/libraries/src/Table/ContentType.php index 8f4daa846c1ad..50e858dbf1ac0 100644 --- a/libraries/src/Table/ContentType.php +++ b/libraries/src/Table/ContentType.php @@ -57,13 +57,13 @@ public function check() // Check for valid name. if (trim($this->type_title) === '') { - throw new \UnexpectedValueException(\sprintf('The title is empty')); + throw new \UnexpectedValueException('The title is empty'); } $this->type_title = ucfirst($this->type_title); if (empty($this->type_alias)) { - throw new \UnexpectedValueException(\sprintf('The type_alias is empty')); + throw new \UnexpectedValueException('The type_alias is empty'); } return true; @@ -142,17 +142,13 @@ public function getContentTable() $result = false; $tableInfo = json_decode($this->table); - if (\is_object($tableInfo) && isset($tableInfo->special)) { - if (\is_object($tableInfo->special) && isset($tableInfo->special->type) && isset($tableInfo->special->prefix)) { - $class = $tableInfo->special->class ?? \Joomla\CMS\Table\Table::class; - - if (!class_implements($class, \Joomla\CMS\Table\TableInterface::class)) { - // This isn't an instance of TableInterface. Stop. - throw new \RuntimeException('Class must be an instance of Joomla\\CMS\\Table\\TableInterface'); - } - - $result = $class::getInstance($tableInfo->special->type, $tableInfo->special->prefix); + if (\is_object($tableInfo) && isset($tableInfo->special) && (\is_object($tableInfo->special) && isset($tableInfo->special->type) && isset($tableInfo->special->prefix))) { + $class = $tableInfo->special->class ?? \Joomla\CMS\Table\Table::class; + if (!class_implements($class, \Joomla\CMS\Table\TableInterface::class)) { + // This isn't an instance of TableInterface. Stop. + throw new \RuntimeException('Class must be an instance of Joomla\\CMS\\Table\\TableInterface'); } + $result = $class::getInstance($tableInfo->special->type, $tableInfo->special->prefix); } return $result; diff --git a/libraries/src/Table/CoreContent.php b/libraries/src/Table/CoreContent.php index 6ce6a5619b0cd..43ca7d7ebda6b 100644 --- a/libraries/src/Table/CoreContent.php +++ b/libraries/src/Table/CoreContent.php @@ -141,7 +141,7 @@ public function check() $clean_keys = []; foreach ($keys as $key) { - if (trim($key)) { + if (trim($key) !== '' && trim($key) !== '0') { // Ignore blank keywords $clean_keys[] = trim($key); } @@ -238,7 +238,7 @@ public function store($updateNulls = true) } else { // New content item. A content item core_created_time and core_created_user_id field can be set by the user, // so we don't touch either of these if they are set. - if (!(int) $this->core_created_time) { + if ((int) $this->core_created_time === 0) { $this->core_created_time = $date->toSql(); } @@ -246,7 +246,7 @@ public function store($updateNulls = true) $this->core_created_user_id = $user->id; } - if (!(int) $this->core_modified_time) { + if ((int) $this->core_modified_time === 0) { $this->core_modified_time = $this->core_created_time; } diff --git a/libraries/src/Table/Extension.php b/libraries/src/Table/Extension.php index 08195a8aeab67..dd92017b63d19 100644 --- a/libraries/src/Table/Extension.php +++ b/libraries/src/Table/Extension.php @@ -83,7 +83,7 @@ public function check() } // Check for valid name - if (trim($this->name) == '' || trim($this->element) == '') { + if (trim($this->name) === '' || trim($this->element) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_EXTENSION')); return false; diff --git a/libraries/src/Table/Language.php b/libraries/src/Table/Language.php index 78eb9534deae4..2a12a6fc6bfca 100644 --- a/libraries/src/Table/Language.php +++ b/libraries/src/Table/Language.php @@ -54,7 +54,7 @@ public function check() return false; } - if (trim($this->title) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_LANGUAGE_NO_TITLE')); return false; diff --git a/libraries/src/Table/Menu.php b/libraries/src/Table/Menu.php index a84b089214d35..7b2f65fe61307 100644 --- a/libraries/src/Table/Menu.php +++ b/libraries/src/Table/Menu.php @@ -177,7 +177,7 @@ public function store($updateNulls = true) $table = new self($db, $this->getDispatcher()); $originalAlias = trim($this->alias); - $this->alias = !$originalAlias ? $this->title : $originalAlias; + $this->alias = $originalAlias === '' || $originalAlias === '0' ? $this->title : $originalAlias; $this->alias = ApplicationHelper::stringURLSafe(trim($this->alias), $this->language); if ($this->parent_id == 1 && $this->client_id == 0) { @@ -227,17 +227,15 @@ public function store($updateNulls = true) $otherMenuItemId = (int) $db->setQuery($query)->loadResult(); - if ($otherMenuItemId) { + if ($otherMenuItemId !== 0) { $table->load(['id' => $otherMenuItemId]); $error = true; } } - } else { + } elseif ($table->load($itemSearch) && ($table->id != $this->id || $this->id == 0)) { // Check if the alias already exists. For monolingual site. // If there is a menu item at the same level with the same alias (in any language). - if ($table->load($itemSearch) && ($table->id != $this->id || $this->id == 0)) { - $error = true; - } + $error = true; } // The alias already exists. Enqueue an error message. @@ -257,20 +255,17 @@ public function store($updateNulls = true) } } - if ($this->home == '1') { - // Verify that the home page for this language is unique per client id - if ($table->load(['home' => '1', 'language' => $this->language, 'client_id' => (int) $this->client_id])) { - if ($table->checked_out && $table->checked_out != $this->checked_out) { - $this->setError(Text::_('JLIB_DATABASE_ERROR_MENU_DEFAULT_CHECKIN_USER_MISMATCH')); + // Verify that the home page for this language is unique per client id + if ($this->home == '1' && $table->load(['home' => '1', 'language' => $this->language, 'client_id' => (int) $this->client_id])) { + if ($table->checked_out && $table->checked_out != $this->checked_out) { + $this->setError(Text::_('JLIB_DATABASE_ERROR_MENU_DEFAULT_CHECKIN_USER_MISMATCH')); - return false; - } - - $table->home = 0; - $table->checked_out = null; - $table->checked_out_time = null; - $table->store(); + return false; } + $table->home = 0; + $table->checked_out = null; + $table->checked_out_time = null; + $table->store(); } if (!parent::store($updateNulls)) { diff --git a/libraries/src/Table/Nested.php b/libraries/src/Table/Nested.php index 588d5012bddc6..f40eb21013e82 100644 --- a/libraries/src/Table/Nested.php +++ b/libraries/src/Table/Nested.php @@ -208,7 +208,7 @@ public function isLeaf($pk = null) // Get the node by primary key. if (empty($node)) { // Error message set in getNode method. - return; + return null; } // The node is a leaf node. @@ -738,23 +738,18 @@ public function store($updateNulls = false) ->from($this->_tbl) ->where('parent_id = 0') ->order('lft DESC'); - $query->setLimit(1); $this->_db->setQuery($query); $reference = $this->_db->loadObject(); - if ($this->_debug) { $this->_logtable(false); } - } else { + } elseif (!$reference = $this->_getNode($this->_location_id)) { // We have a real node set as a location reference. // Get the reference node by primary key. - if (!$reference = $this->_getNode($this->_location_id)) { - // Error message set in getNode method. - $this->_unlock(); - - return false; - } + // Error message set in getNode method. + $this->_unlock(); + return false; } // Get the reposition data for shifting the tree and re-inserting the node. @@ -798,12 +793,10 @@ public function store($updateNulls = false) * or just updating its data fields. */ // If the location has been set, move the node to its new location. - if ($this->_location_id > 0) { - // Skip recursiveUpdatePublishedColumn method, it will be called later. - if (!$this->moveByReference($this->_location_id, $this->_location, $this->$k, false)) { - // Error message set in move method. - return false; - } + // Skip recursiveUpdatePublishedColumn method, it will be called later. + if ($this->_location_id > 0 && !$this->moveByReference($this->_location_id, $this->_location, $this->$k, false)) { + // Error message set in move method. + return false; } // Lock the table for writing. @@ -825,10 +818,8 @@ public function store($updateNulls = false) // Restore previous callable dispatcher state: $this->setDispatcher($oldDispatcher); - if ($result) { - if ($this->_debug) { - $this->_logtable(); - } + if ($result && $this->_debug) { + $this->_logtable(); } // Unlock the table for writing. @@ -1372,7 +1363,7 @@ public function saveorder($idArray = null, $lftArray = null) $query = $this->_db->getQuery(true); // Validate arguments - if (\is_array($idArray) && \is_array($lftArray) && \count($idArray) == \count($lftArray)) { + if (\is_array($idArray) && \is_array($lftArray) && \count($idArray) === \count($lftArray)) { for ($i = 0, $count = \count($idArray); $i < $count; $i++) { // Do an update to change the lft values in the table for each id $query->clear() diff --git a/libraries/src/Table/Table.php b/libraries/src/Table/Table.php index 7dcdcf4cee151..ea816916ebc26 100644 --- a/libraries/src/Table/Table.php +++ b/libraries/src/Table/Table.php @@ -175,11 +175,7 @@ public function __construct(/** $this->_tbl_keys = $key; - if (\count($key) == 1) { - $this->_autoincrement = true; - } else { - $this->_autoincrement = false; - } + $this->_autoincrement = \count($key) == 1; // Set the singular table key for backwards compatibility. $this->_tbl_key = $this->getKeyName(); @@ -356,11 +352,10 @@ public static function addIncludePath($path = null) self::$_includePaths = [__DIR__]; } - // Convert the passed path(s) to add to an array. - settype($path, 'array'); + $path = (array) $path; // If we have new paths to add, do so. - if (!empty($path)) { + if ($path !== []) { // Check and add each individual new path. foreach ($path as $dir) { // Sanitize path. @@ -557,11 +552,7 @@ public function setDbo(DatabaseDriver $db) */ public function setRules($input) { - if ($input instanceof Rules) { - $this->_rules = $input; - } else { - $this->_rules = new Rules($input); - } + $this->_rules = $input instanceof Rules ? $input : new Rules($input); } /** @@ -673,10 +664,8 @@ public function bind($src, $ignore = []) // Bind the source value, excluding the ignored fields. foreach ($this->getProperties() as $k => $v) { // Only process fields not in the ignore array. - if (!\in_array($k, $ignore)) { - if (isset($src[$k])) { - $this->$k = $src[$k]; - } + if (!\in_array($k, $ignore) && isset($src[$k])) { + $this->$k = $src[$k]; } } @@ -738,7 +727,7 @@ public function load($keys = null, $reset = true) // Load by primary key. $keyCount = \count($this->_tbl_keys); - if ($keyCount) { + if ($keyCount !== 0) { if ($keyCount > 1) { throw new \InvalidArgumentException('Table has multiple primary keys specified, only one primary key value provided.'); } @@ -774,12 +763,7 @@ public function load($keys = null, $reset = true) $row = $this->_db->loadAssoc(); // Check that we have a result. - if (empty($row)) { - $result = false; - } else { - // Bind the object with the row and return. - $result = $this->bind($row); - } + $result = empty($row) ? false : $this->bind($row); // Post-processing by observers $event = AbstractEvent::create( @@ -1049,12 +1033,9 @@ public function delete($pk = null) $name = $this->_getAssetName(); $asset = new Asset($this->getDbo(), $this->getDispatcher()); - if ($asset->loadByName($name)) { - if (!$asset->delete()) { - $this->setError($asset->getError()); - - return false; - } + if ($asset->loadByName($name) && !$asset->delete()) { + $this->setError($asset->getError()); + return false; } } @@ -1275,11 +1256,7 @@ public function hasPrimaryKey() $this->_db->setQuery($query); $count = $this->_db->loadResult(); - if ($count == 1) { - $empty = false; - } else { - $empty = true; - } + $empty = $count != 1; } return !$empty; @@ -1447,10 +1424,8 @@ public function getNextOrder($where = '') public function getPrimaryKey(array $keys = []) { foreach ($this->_tbl_keys as $key) { - if (!isset($keys[$key])) { - if (!empty($this->$key)) { - $keys[$key] = $this->$key; - } + if (!isset($keys[$key]) && !empty($this->$key)) { + $keys[$key] = $this->$key; } } @@ -1689,7 +1664,7 @@ public function publish($pks = null, $state = 1, $userId = 0) } // If there are no primary keys set check to see if the instance key is set. - if (empty($pks)) { + if ($pks === null || $pks === []) { $pk = []; foreach ($this->_tbl_keys as $key) { diff --git a/libraries/src/Table/Update.php b/libraries/src/Table/Update.php index 8c1029cb37a99..4146468c5611f 100644 --- a/libraries/src/Table/Update.php +++ b/libraries/src/Table/Update.php @@ -65,7 +65,7 @@ public function check() } // Check for valid name - if (trim($this->name) == '' || trim($this->element) == '') { + if (trim($this->name) === '' || trim($this->element) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_EXTENSION')); return false; diff --git a/libraries/src/Table/UpdateSite.php b/libraries/src/Table/UpdateSite.php index eae9f525b0f1a..7b8e36b33b81a 100644 --- a/libraries/src/Table/UpdateSite.php +++ b/libraries/src/Table/UpdateSite.php @@ -57,7 +57,7 @@ public function check() } // Check for valid name - if (trim($this->name) == '' || trim($this->location) == '') { + if (trim($this->name) === '' || trim($this->location) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_EXTENSION')); return false; diff --git a/libraries/src/Table/User.php b/libraries/src/Table/User.php index bb0e7c4c60b83..70f2c37c4016b 100644 --- a/libraries/src/Table/User.php +++ b/libraries/src/Table/User.php @@ -105,7 +105,7 @@ public function load($userId = null, $reset = true) $this->_db->setQuery($query); $data = (array) $this->_db->loadAssoc(); - if (!\count($data)) { + if ($data === []) { return false; } @@ -368,7 +368,7 @@ public function store($updateNulls = true) $result = $this->_db->loadObjectList(); // Loop through them and check if database contains something $this->groups does not - if (\count($result)) { + if (\count($result) > 0) { $mapGroupId = []; foreach ($result as $map) { @@ -380,7 +380,7 @@ public function store($updateNulls = true) } } - if (\count($mapGroupId)) { + if ($mapGroupId !== []) { $query->clear() ->delete($this->_db->quoteName('#__user_usergroup_map')) ->where($this->_db->quoteName('user_id') . ' = :uid') diff --git a/libraries/src/Table/Usergroup.php b/libraries/src/Table/Usergroup.php index 1b4c4a23cd1dc..1390730351fc9 100644 --- a/libraries/src/Table/Usergroup.php +++ b/libraries/src/Table/Usergroup.php @@ -57,7 +57,7 @@ public function check() } // Validate the title. - if ((trim($this->title)) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_USERGROUP_TITLE')); return false; @@ -303,7 +303,7 @@ public function delete($oid = null) } } - if (!empty($matchIds)) { + if ($matchIds !== []) { $query->clear() ->update($db->quoteName('#__viewlevels')) ->set($db->quoteName('rules') . ' = ' . str_repeat('REPLACE(', 4 * \count($ids)) . $db->quoteName('rules') . implode(')', $replace) . ')') diff --git a/libraries/src/Table/ViewLevel.php b/libraries/src/Table/ViewLevel.php index 41b01443b7132..51a0269f2f5e1 100644 --- a/libraries/src/Table/ViewLevel.php +++ b/libraries/src/Table/ViewLevel.php @@ -51,10 +51,8 @@ public function __construct(DatabaseDriver $db, ?DispatcherInterface $dispatcher public function bind($array, $ignore = '') { // Bind the rules as appropriate. - if (isset($array['rules'])) { - if (\is_array($array['rules'])) { - $array['rules'] = json_encode($array['rules']); - } + if (isset($array['rules']) && \is_array($array['rules'])) { + $array['rules'] = json_encode($array['rules']); } return parent::bind($array, $ignore); @@ -78,7 +76,7 @@ public function check() } // Validate the title. - if ((trim($this->title)) == '') { + if (trim($this->title) === '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_VIEWLEVEL')); return false; diff --git a/libraries/src/Toolbar/Toolbar.php b/libraries/src/Toolbar/Toolbar.php index 3e59718b1bee3..27c3516acf25b 100644 --- a/libraries/src/Toolbar/Toolbar.php +++ b/libraries/src/Toolbar/Toolbar.php @@ -100,7 +100,7 @@ public function __construct(/** protected $_name = 'toolbar', ?ToolbarFactoryInterface $factory = null) { // At 5.0, require the factory to be injected - if (!$factory) { + if (!$factory instanceof \Joomla\CMS\Toolbar\ToolbarFactoryInterface) { @trigger_error( \sprintf( 'As of Joomla! 5.0, a %1$s must be provided to a %2$s object when creating it.', diff --git a/libraries/src/Toolbar/ToolbarButton.php b/libraries/src/Toolbar/ToolbarButton.php index d8b7ecb48e593..9a34e075585d1 100644 --- a/libraries/src/Toolbar/ToolbarButton.php +++ b/libraries/src/Toolbar/ToolbarButton.php @@ -436,14 +436,14 @@ public function __call(string $name, array $args) { // Getter if (stripos($name, 'get') === 0) { - $fieldName = static::findOptionName(lcfirst(substr($name, 3))); + $fieldName = $this->findOptionName(lcfirst(substr($name, 3))); if ($fieldName !== false) { return $this->getOption($fieldName); } } else { // Setter - $fieldName = static::findOptionName($name); + $fieldName = $this->findOptionName($name); if ($fieldName !== false) { if (!\array_key_exists(0, $args)) { @@ -478,7 +478,7 @@ public function __call(string $name, array $args) * * @since 4.0.0 */ - private static function findOptionName(string $name) + private function findOptionName(string $name) { $accessors = static::getAccessors(); diff --git a/libraries/src/UCM/UCMBase.php b/libraries/src/UCM/UCMBase.php index 2fbc2b6580564..7e63eb5ea916d 100644 --- a/libraries/src/UCM/UCMBase.php +++ b/libraries/src/UCM/UCMBase.php @@ -72,7 +72,7 @@ public function __construct($alias = null, ?UCMType $type = null) */ protected function store($data, ?TableInterface $table = null, $primaryKey = null) { - if (!$table) { + if (!$table instanceof \Joomla\CMS\Table\TableInterface) { $table = Table::getInstance('Ucm'); } diff --git a/libraries/src/UCM/UCMContent.php b/libraries/src/UCM/UCMContent.php index af0fdee40c7ab..3e29b0b7e1df4 100644 --- a/libraries/src/UCM/UCMContent.php +++ b/libraries/src/UCM/UCMContent.php @@ -55,7 +55,7 @@ public function __construct(?TableInterface $table = null, $alias = null, ?UCMTy { parent::__construct($alias, $type); - if ($table) { + if ($table instanceof \Joomla\CMS\Table\TableInterface) { $this->table = $table; } else { $tableObject = json_decode($this->type->type->table); diff --git a/libraries/src/UCM/UCMType.php b/libraries/src/UCM/UCMType.php index be26f721c3d73..2aa078811e827 100644 --- a/libraries/src/UCM/UCMType.php +++ b/libraries/src/UCM/UCMType.php @@ -240,7 +240,7 @@ public function fieldmapExpand($assoc = false) */ public function __get($ucmField) { - if (!isset($this->fieldmap)) { + if (!property_exists($this, 'fieldmap') || $this->fieldmap === null) { $this->fieldmapExpand(false); } diff --git a/libraries/src/Updater/Adapter/CollectionAdapter.php b/libraries/src/Updater/Adapter/CollectionAdapter.php index 46047c9038327..56ef273976965 100644 --- a/libraries/src/Updater/Adapter/CollectionAdapter.php +++ b/libraries/src/Updater/Adapter/CollectionAdapter.php @@ -225,7 +225,7 @@ public function findUpdate($options) xml_set_object($this->xmlParser, $this); xml_set_element_handler($this->xmlParser, '_startElement', '_endElement'); - if (!xml_parse($this->xmlParser, $response->body)) { + if (xml_parse($this->xmlParser, $response->body) === 0) { // If the URL is missing the .xml extension, try appending it and retry loading the update if (!$this->appendExtension && (!str_ends_with($this->_url, '.xml'))) { $options['append_extension'] = true; diff --git a/libraries/src/Updater/Adapter/ExtensionAdapter.php b/libraries/src/Updater/Adapter/ExtensionAdapter.php index e0fb830685c9e..3411f1b26cadd 100644 --- a/libraries/src/Updater/Adapter/ExtensionAdapter.php +++ b/libraries/src/Updater/Adapter/ExtensionAdapter.php @@ -140,13 +140,11 @@ protected function _endElement($parser, $name) $supportedDbs = $this->currentUpdate->supported_databases; // MySQL and MariaDB use the same database driver but not the same version numbers - if ($dbType === 'mysql') { - // Check whether we have a MariaDB version string and extract the proper version from it - if (stripos($dbVersion, 'mariadb') !== false) { - // MariaDB: Strip off any leading '5.5.5-', if present - $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); - $dbType = 'mariadb'; - } + // Check whether we have a MariaDB version string and extract the proper version from it + if ($dbType === 'mysql' && stripos($dbVersion, 'mariadb') !== false) { + // MariaDB: Strip off any leading '5.5.5-', if present + $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); + $dbType = 'mariadb'; } // $supportedDbs has uppercase keys because they are XML attribute names @@ -210,7 +208,7 @@ protected function _endElement($parser, $name) // If the PHP version and minimum stability checks pass, consider this version as a possible update if ($phpMatch && $stabilityMatch && $dbMatch) { - if (isset($this->latest)) { + if ($this->latest !== null) { // We already have a possible update. Check the version. if (version_compare($this->currentUpdate->version, $this->latest->version, '>') == 1) { $this->latest = $this->currentUpdate; @@ -284,7 +282,7 @@ public function findUpdate($options) xml_set_element_handler($this->xmlParser, '_startElement', '_endElement'); xml_set_character_data_handler($this->xmlParser, '_characterData'); - if (!xml_parse($this->xmlParser, $response->body)) { + if (xml_parse($this->xmlParser, $response->body) === 0) { // If the URL is missing the .xml extension, try appending it and retry loading the update if (!$this->appendExtension && (!str_ends_with($this->_url, '.xml'))) { $options['append_extension'] = true; @@ -301,7 +299,7 @@ public function findUpdate($options) xml_parser_free($this->xmlParser); - if (isset($this->latest)) { + if ($this->latest !== null) { if (isset($this->latest->client) && \strlen($this->latest->client)) { /** * The client_id in the update XML manifest can be either an integer (backwards diff --git a/libraries/src/Updater/Adapter/TufAdapter.php b/libraries/src/Updater/Adapter/TufAdapter.php index 15b41926ac42f..d0282e4ef5c76 100644 --- a/libraries/src/Updater/Adapter/TufAdapter.php +++ b/libraries/src/Updater/Adapter/TufAdapter.php @@ -111,7 +111,7 @@ public function getUpdateTargets($options) // or "only" env related constraints fail - the later one is the existing behavior of the XML updater if ( $constraintChecker->check($version, $options['minimum_stability'] ?? Updater::STABILITY_STABLE) === true - || !empty((array) $constraintChecker->getFailedEnvironmentConstraints()) + || (array) $constraintChecker->getFailedEnvironmentConstraints() !== [] ) { return [$version]; } diff --git a/libraries/src/Updater/ConstraintChecker.php b/libraries/src/Updater/ConstraintChecker.php index 74af955f8c8c4..773f24f60c07e 100644 --- a/libraries/src/Updater/ConstraintChecker.php +++ b/libraries/src/Updater/ConstraintChecker.php @@ -147,16 +147,8 @@ protected function checkTargetplatform(array $targetPlatform) { // Lower case and remove the exclamation mark $product = strtolower((string) InputFilter::getInstance()->clean(Version::PRODUCT, 'cmd')); - // Check that the product matches and that the version matches (optionally a regexp) - if ( - $product === $targetPlatform["name"] - && preg_match('/^' . $targetPlatform["version"] . '/', (string) JVERSION) - ) { - return true; - } - - return false; + return $product === $targetPlatform["name"] && preg_match('/^' . $targetPlatform["version"] . '/', (string) JVERSION); } /** @@ -200,13 +192,11 @@ protected function checkSupportedDatabases(array $supportedDatabases) $dbVersion = $db->getVersion(); // MySQL and MariaDB use the same database driver but not the same version numbers - if ($dbType === 'mysql') { - // Check whether we have a MariaDB version string and extract the proper version from it - if (stripos($dbVersion, 'mariadb') !== false) { - // MariaDB: Strip off any leading '5.5.5-', if present - $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); - $dbType = 'mariadb'; - } + // Check whether we have a MariaDB version string and extract the proper version from it + if ($dbType === 'mysql' && stripos($dbVersion, 'mariadb') !== false) { + // MariaDB: Strip off any leading '5.5.5-', if present + $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); + $dbType = 'mariadb'; } // Do we have an entry for the database? @@ -243,12 +233,7 @@ protected function checkSupportedDatabases(array $supportedDatabases) protected function checkStability(string $stability, $minimumStability = Updater::STABILITY_STABLE) { $stabilityInt = $this->stabilityToInteger($stability); - - if ($stabilityInt < $minimumStability) { - return false; - } - - return true; + return $stabilityInt >= $minimumStability; } /** diff --git a/libraries/src/Updater/Update.php b/libraries/src/Updater/Update.php index fce3d00e00918..adf770cc3a0ef 100644 --- a/libraries/src/Updater/Update.php +++ b/libraries/src/Updater/Update.php @@ -425,13 +425,11 @@ public function _endElement($parser, $name) $supportedDbs = $this->currentUpdate->supported_databases; // MySQL and MariaDB use the same database driver but not the same version numbers - if ($dbType === 'mysql') { - // Check whether we have a MariaDB version string and extract the proper version from it - if (stripos($dbVersion, 'mariadb') !== false) { - // MariaDB: Strip off any leading '5.5.5-', if present - $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); - $dbType = 'mariadb'; - } + // Check whether we have a MariaDB version string and extract the proper version from it + if ($dbType === 'mysql' && stripos($dbVersion, 'mariadb') !== false) { + // MariaDB: Strip off any leading '5.5.5-', if present + $dbVersion = preg_replace('/^5\.5\.5-/', '', $dbVersion); + $dbType = 'mariadb'; } // Do we have an entry for the database? @@ -464,13 +462,13 @@ public function _endElement($parser, $name) } if ( - !isset($this->latest) + $this->latest === null || version_compare($this->currentUpdate->version->_data, $this->latest->version->_data, '>') ) { $this->latest = $this->currentUpdate; } } elseif ( - !isset($this->otherUpdateInfo) + $this->otherUpdateInfo === null || version_compare($otherUpdateInfo->version, $this->otherUpdateInfo->version, '>') ) { $this->otherUpdateInfo = $otherUpdateInfo; @@ -479,7 +477,7 @@ public function _endElement($parser, $name) break; case 'UPDATES': // If the latest item is set then we transfer it to where we want to - if (isset($this->latest)) { + if ($this->latest !== null) { // This is an optional tag and therefore we need to be sure that this is gone and only used when set by the update itself unset($this->downloadSources); @@ -489,7 +487,7 @@ public function _endElement($parser, $name) unset($this->latest); unset($this->currentUpdate); - } elseif (isset($this->currentUpdate)) { + } elseif ($this->currentUpdate !== null) { // The update might be for an older version of j! unset($this->currentUpdate); } @@ -564,7 +562,7 @@ public function loadFromTuf(TufMetadata $metadataTable, string $url, $minimumSta foreach ($data['signed']['targets'] as $target) { // Check if this target is newer than the current version - if (isset($this->latest) && version_compare($target['custom']['version'], $this->latest->version, '<')) { + if ($this->latest !== null && version_compare($target['custom']['version'], $this->latest->version, '<')) { continue; } @@ -607,7 +605,7 @@ public function loadFromTuf(TufMetadata $metadataTable, string $url, $minimumSta } // If the latest item is set then we transfer it to where we want to - if (isset($this->latest)) { + if ($this->latest !== null) { foreach ($this->downloadSources as $source) { $this->downloadurl = (object) [ '_data' => $source->url, @@ -662,7 +660,7 @@ public function loadFromXml($url, $minimumStability = Updater::STABILITY_STABLE, xml_set_element_handler($this->xmlParser, '_startElement', '_endElement'); xml_set_character_data_handler($this->xmlParser, '_characterData'); - if (!xml_parse($this->xmlParser, $response->body)) { + if (xml_parse($this->xmlParser, $response->body) === 0) { Log::add( \sprintf( 'XML error: %s at line %d', diff --git a/libraries/src/Updater/UpdateAdapter.php b/libraries/src/Updater/UpdateAdapter.php index 6630414580c07..3448ae55eef25 100644 --- a/libraries/src/Updater/UpdateAdapter.php +++ b/libraries/src/Updater/UpdateAdapter.php @@ -147,7 +147,7 @@ protected function toggleUpdateSite($updateSiteId, $enabled = true) $updateSiteId = (int) $updateSiteId; $enabled = (bool) $enabled ? 1 : 0; - if (empty($updateSiteId)) { + if ($updateSiteId === 0) { return; } @@ -178,7 +178,7 @@ protected function getUpdateSiteName($updateSiteId) { $updateSiteId = (int) $updateSiteId; - if (empty($updateSiteId)) { + if ($updateSiteId === 0) { return ''; } diff --git a/libraries/src/Updater/Updater.php b/libraries/src/Updater/Updater.php index 0f8b478ef7637..0ec83e90d3e5f 100644 --- a/libraries/src/Updater/Updater.php +++ b/libraries/src/Updater/Updater.php @@ -216,7 +216,7 @@ private function getUpdateSites($eid = 0) if (\is_array($eid)) { $query->whereIn($db->quoteName('b.extension_id'), $eid); - } elseif ($eid = (int) $eid) { + } elseif ($eid = (int) $eid !== 0) { $query->where($db->quoteName('b.extension_id') . ' = :eid') ->bind(':eid', $eid, ParameterType::INTEGER); } @@ -276,7 +276,7 @@ private function getUpdateObjectsForSite($updateSite, $minimumStability = self:: $extraId = (int) $extraUpdateSite['update_site_id']; // Do not try to fetch the same update site twice - if (($thisId == $extraId) || ($thisUrl == $extraUrl)) { + if (($thisId === $extraId) || ($thisUrl === $extraUrl)) { continue; } @@ -374,7 +374,7 @@ private function getSitesWithUpdates($timestamp = 0) ->select('DISTINCT ' . $db->quoteName('update_site_id')) ->from($db->quoteName('#__updates')); - if ($timestamp) { + if ($timestamp !== 0) { $subQuery = $db->getQuery(true) ->select($db->quoteName('update_site_id')) ->from($db->quoteName('#__update_sites')) diff --git a/libraries/src/Uri/Uri.php b/libraries/src/Uri/Uri.php index 4ab32dab79c85..fd08df0fdba2d 100644 --- a/libraries/src/Uri/Uri.php +++ b/libraries/src/Uri/Uri.php @@ -128,21 +128,21 @@ public static function getInstance($uri = 'SERVER') public static function base($pathonly = false) { // Get the base request path. - if (empty(static::$base)) { + if (static::$base === []) { $config = Factory::getContainer()->get('config'); $uri = static::getInstance(); $live_site = ($uri->isSsl()) ? str_replace('http://', 'https://', $config->get('live_site', '')) : $config->get('live_site', ''); - if (trim((string) $live_site) != '') { + if (trim((string) $live_site) !== '') { $uri = static::getInstance($live_site); static::$base['prefix'] = $uri->toString(['scheme', 'host', 'port']); static::$base['path'] = rtrim($uri->toString(['path']), '/\\'); - if (\defined('JPATH_BASE') && \defined('JPATH_ADMINISTRATOR') && JPATH_BASE == JPATH_ADMINISTRATOR) { + if (\defined('JPATH_BASE') && \defined('JPATH_ADMINISTRATOR') && JPATH_BASE === JPATH_ADMINISTRATOR) { static::$base['path'] .= '/administrator'; } - if (\defined('JPATH_BASE') && \defined('JPATH_API') && JPATH_BASE == JPATH_API) { + if (\defined('JPATH_BASE') && \defined('JPATH_API') && JPATH_BASE === JPATH_API) { static::$base['path'] .= '/api'; } } else { @@ -245,18 +245,8 @@ public static function isInternal($url) $uri = static::getInstance($url); $base = $uri->toString(['scheme', 'host', 'port', 'path']); $host = $uri->toString(['scheme', 'host', 'port']); - // @see UriTest - if ( - empty($host) && str_starts_with($uri->path, 'index.php') - || !empty($host) && preg_match('#^' . preg_quote(static::base(), '#') . '#', $base) - || !empty($host) && $host === static::getInstance(static::base())->host && str_contains($uri->path, 'index.php') - || !empty($host) && $base === $host && preg_match('#^' . preg_quote($base, '#') . '#', static::base()) - ) { - return true; - } - - return false; + return empty($host) && str_starts_with($uri->path, 'index.php') || !empty($host) && preg_match('#^' . preg_quote(static::base(), '#') . '#', $base) || !empty($host) && $host === static::getInstance(static::base())->host && str_contains($uri->path, 'index.php') || !empty($host) && $base === $host && preg_match('#^' . preg_quote($base, '#') . '#', static::base()); } /** diff --git a/libraries/src/User/User.php b/libraries/src/User/User.php index d0741050f2322..24b85b234e857 100644 --- a/libraries/src/User/User.php +++ b/libraries/src/User/User.php @@ -665,11 +665,7 @@ public function bind(&$array) if (\array_key_exists('params', $array)) { $this->_params->loadArray($array['params']); - if (\is_array($array['params'])) { - $params = (string) $this->_params; - } else { - $params = $array['params']; - } + $params = \is_array($array['params']) ? (string) $this->_params : $array['params']; $this->params = $params; } @@ -885,11 +881,7 @@ public function load($id) } // The user is no longer a guest - if ($this->id != 0) { - $this->guest = 0; - } else { - $this->guest = 1; - } + $this->guest = $this->id != 0 ? 0 : 1; return true; } diff --git a/libraries/src/User/UserHelper.php b/libraries/src/User/UserHelper.php index 025d21e4f15b4..2286ac6df6dc1 100644 --- a/libraries/src/User/UserHelper.php +++ b/libraries/src/User/UserHelper.php @@ -371,7 +371,7 @@ public static function activateUser($activation) $id = (int) $db->loadResult(); // Is it a valid user to activate? - if ($id) { + if ($id !== 0) { $user = User::getInstance($id); $user->block = 0; @@ -549,11 +549,7 @@ public static function getShortHashedUserAgent() $uaString = $ua->userAgent; $browserVersion = $ua->browserVersion; - if ($browserVersion) { - $uaShort = str_replace($browserVersion, 'abcd', $uaString); - } else { - $uaShort = $uaString; - } + $uaShort = $browserVersion ? str_replace($browserVersion, 'abcd', $uaString) : $uaString; return md5(Uri::base() . $uaShort); } diff --git a/libraries/src/Version.php b/libraries/src/Version.php index a16c8dd5e34c9..2c2db42a9f09f 100644 --- a/libraries/src/Version.php +++ b/libraries/src/Version.php @@ -182,7 +182,7 @@ public function getShortVersion(): string { $version = self::MAJOR_VERSION . '.' . self::MINOR_VERSION . '.' . self::PATCH_VERSION; - if (!empty(self::EXTRA_VERSION)) { + if (self::EXTRA_VERSION !== '' && self::EXTRA_VERSION !== '0') { $version .= '-' . self::EXTRA_VERSION; } @@ -225,7 +225,7 @@ public function getUserAgent(string $suffix = '', bool $mask = false, bool $addV } // If masked pretend to look like Mozilla 5.0 but still identify ourselves. - return ($mask ? 'Mozilla/5.0 ' : '') . self::PRODUCT . '/' . $this->getShortVersion() . ($suffix ? ' ' . $suffix : ''); + return ($mask ? 'Mozilla/5.0 ' : '') . self::PRODUCT . '/' . $this->getShortVersion() . ($suffix !== '' && $suffix !== '0' ? ' ' . $suffix : ''); } /** @@ -287,7 +287,7 @@ public function refreshMediaVersion(): Version public function setMediaVersion(string $mediaVersion): Version { // Do not allow empty media versions - if (!empty($mediaVersion)) { + if ($mediaVersion !== '' && $mediaVersion !== '0') { self::$mediaVersion = $mediaVersion; $this->getMediaVersionCache() diff --git a/libraries/src/Versioning/Versioning.php b/libraries/src/Versioning/Versioning.php index c121196bab239..cd53f4df2c2c8 100644 --- a/libraries/src/Versioning/Versioning.php +++ b/libraries/src/Versioning/Versioning.php @@ -101,7 +101,7 @@ public static function store($typeAlias, $id, $data, $note = '') $aliasParts = explode('.', $typeAlias); // Don't store unless we have a non-zero item id - if (!$historyTable->item_id) { + if ($historyTable->item_id === '' || $historyTable->item_id === '0') { return true; } diff --git a/libraries/src/WebAsset/WebAssetManager.php b/libraries/src/WebAsset/WebAssetManager.php index 821cf8099c73f..b7f53a9f0421f 100644 --- a/libraries/src/WebAsset/WebAssetManager.php +++ b/libraries/src/WebAsset/WebAssetManager.php @@ -767,7 +767,7 @@ protected function enableDependencies(?string $type = null, ?WebAssetItem $asset return $this; } - if ($asset) { + if ($asset instanceof \Joomla\CMS\WebAsset\WebAssetItem) { // Get all dependencies of given asset recursively $allDependencies = $this->getDependenciesForAsset($type, $asset, true); diff --git a/libraries/src/WebAsset/WebAssetRegistry.php b/libraries/src/WebAsset/WebAssetRegistry.php index 070331a7d982a..716d5a0b8feb2 100644 --- a/libraries/src/WebAsset/WebAssetRegistry.php +++ b/libraries/src/WebAsset/WebAssetRegistry.php @@ -240,7 +240,7 @@ public function createAsset( array $dependencies = [] ): WebAssetItem { $nameSpace = \array_key_exists('namespace', $options) ? $options['namespace'] : __NAMESPACE__ . '\\AssetItem'; - $className = \array_key_exists('class', $options) ? $options['class'] : null; + $className = $options['class'] ?? null; if ($className && class_exists($nameSpace . '\\' . $className)) { $className = $nameSpace . '\\' . $className; @@ -387,7 +387,7 @@ protected function parseRegistryFile($path) 'registryFile' => $path, ]; - $namespace = \array_key_exists('namespace', $data) ? $data['namespace'] : null; + $namespace = $data['namespace'] ?? null; // Prepare WebAssetItem instances foreach ($data['assets'] as $i => $item) { diff --git a/libraries/src/WebAuthn/Server.php b/libraries/src/WebAuthn/Server.php index c56f2f660a027..d0a0074ea1060 100644 --- a/libraries/src/WebAuthn/Server.php +++ b/libraries/src/WebAuthn/Server.php @@ -105,7 +105,7 @@ final class Server * @var string[] * @since 5.0.0 */ - private array $selectedAlgorithms; + private array $selectedAlgorithms = ['RS256', 'RS512', 'PS256', 'PS512', 'ES256', 'ES512', 'Ed25519']; /** * Constructor @@ -146,8 +146,6 @@ public function __construct(/** $this->coseAlgorithmManagerFactory->add('ES384', new ECDSA\ES384()); $this->coseAlgorithmManagerFactory->add('ES512', new ECDSA\ES512()); $this->coseAlgorithmManagerFactory->add('Ed25519', new EdDSA\Ed25519()); - - $this->selectedAlgorithms = ['RS256', 'RS512', 'PS256', 'PS512', 'ES256', 'ES512', 'Ed25519']; $this->tokenBindingHandler = new IgnoreTokenBindingHandler(); $this->extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler(); } @@ -311,7 +309,7 @@ public function loadAndCheckAttestationResponse(string $data, PublicKeyCredentia * * BTW, the documentation of the library is wrong... */ - if (!empty($this->metadataStatementRepository)) { + if ($this->metadataStatementRepository instanceof \Webauthn\MetadataService\MetadataStatementRepository) { $refObj = new \ReflectionObject($authenticatorAttestationResponseValidator); $refProp = $refObj->getProperty('metadataStatementRepository'); $refProp->setAccessible(true); diff --git a/libraries/src/Workflow/Workflow.php b/libraries/src/Workflow/Workflow.php index d9dfc1a6ab6bc..5f2c667dd6496 100644 --- a/libraries/src/Workflow/Workflow.php +++ b/libraries/src/Workflow/Workflow.php @@ -109,14 +109,14 @@ public function __construct(string $extension, ?CMSApplication $app = null, ?Dat $this->extension = $extension; // Initialise default objects if none have been provided - if ($app === null) { + if (!$app instanceof \Joomla\CMS\Application\CMSApplication) { @trigger_error('From 6.0 declaring the app dependency will be mandatory.', E_USER_DEPRECATED); $app = Factory::getApplication(); } $this->app = $app; - if ($db === null) { + if (!$db instanceof \Joomla\Database\DatabaseDriver) { @trigger_error('From 6.0 declaring the database dependency will be mandatory.', E_USER_DEPRECATED); $db = Factory::getContainer()->get(DatabaseDriver::class); } @@ -198,7 +198,7 @@ public function getDefaultStageByCategory($catId = 0) } // Check if the workflow exists - if ($workflow_id = (int) $workflow_id) { + if ($workflow_id = (int) $workflow_id !== 0) { $query = $this->db->getQuery(true); $query->select( @@ -227,7 +227,7 @@ public function getDefaultStageByCategory($catId = 0) $stage_id = (int) $this->db->setQuery($query)->loadResult(); - if (!empty($stage_id)) { + if ($stage_id !== 0) { return $stage_id; } } @@ -261,7 +261,7 @@ public function getDefaultStageByCategory($catId = 0) $stage_id = (int) $this->db->setQuery($query)->loadResult(); // Last check if we have a workflow ID - if (!empty($stage_id)) { + if ($stage_id !== 0) { return $stage_id; } @@ -281,7 +281,7 @@ public function getValidTransition(array $pks, int $transitionId) $pks = ArrayHelper::toInteger($pks); $pks = array_filter($pks); - if (!\count($pks)) { + if ($pks === []) { return null; } @@ -348,7 +348,7 @@ public function executeTransition(array $pks, int $transitionId): bool $pks = ArrayHelper::toInteger($pks); $pks = array_filter($pks); - if (!\count($pks)) { + if ($pks === []) { return true; } diff --git a/libraries/src/Workflow/WorkflowPluginTrait.php b/libraries/src/Workflow/WorkflowPluginTrait.php index 6accd4391a7ec..fd80bdd95ab5a 100644 --- a/libraries/src/Workflow/WorkflowPluginTrait.php +++ b/libraries/src/Workflow/WorkflowPluginTrait.php @@ -68,7 +68,7 @@ protected function enhanceWorkflowTransitionForm(Form $form, $data) protected function getWorkflow(?int $workflowId = null) { $app = $this->getApplication() ?? $this->app; - $workflowId = !empty($workflowId) ? $workflowId : $app->getInput()->getInt('workflow_id'); + $workflowId = $workflowId === null || $workflowId === 0 ? $app->getInput()->getInt('workflow_id') : $workflowId; if (\is_array($workflowId)) { return false; @@ -105,24 +105,10 @@ protected function checkAllowedAndForbiddenlist($context) { $allowedlist = array_filter((array) $this->params->get('allowedlist', [])); $forbiddenlist = array_filter((array) $this->params->get('forbiddenlist', [])); - - if (!empty($allowedlist)) { - foreach ($allowedlist as $allowed) { - if ($context === $allowed) { - return true; - } - } - - return false; - } - - foreach ($forbiddenlist as $forbidden) { - if ($context === $forbidden) { - return false; - } + if ($allowedlist !== []) { + return in_array($context, $allowedlist, true); } - - return true; + return !in_array($context, $forbiddenlist, true); } /** @@ -138,15 +124,6 @@ protected function checkExtensionSupport($context, $functionality) $parts = explode('.', $context); $component = ($this->getApplication() ?? $this->app)->bootComponent($parts[0]); - - if ( - !$component instanceof WorkflowServiceInterface - || !$component->isWorkflowActive($context) - || !$component->supportFunctionality($functionality, $context) - ) { - return false; - } - - return true; + return !(!$component instanceof WorkflowServiceInterface || !$component->isWorkflowActive($context) || !$component->supportFunctionality($functionality, $context)); } } diff --git a/modules/mod_articles/src/Helper/ArticlesHelper.php b/modules/mod_articles/src/Helper/ArticlesHelper.php index 1e8b6fe70fbdf..0d9593c984c96 100644 --- a/modules/mod_articles/src/Helper/ArticlesHelper.php +++ b/modules/mod_articles/src/Helper/ArticlesHelper.php @@ -110,17 +110,17 @@ public function getArticles(Registry $params, SiteApplication $app) } } else { // Return right away if show_on_article_page option is off - return; + return null; } break; default: // Return right away if not on the category or article views - return; + return null; } } else { // Return right away if not on a com_content page - return; + return null; } break; @@ -251,13 +251,13 @@ public function getArticles(Registry $params, SiteApplication $app) if ( $ex_or_include_articles === 1 && $isArticleAndShouldExcluded - && empty($articlesList) + && $articlesList === [] ) { $filterInclude = false; $articlesList[] = $currentArticleId; } - if (!empty($articlesList)) { + if ($articlesList !== []) { $articles->setState('filter.article_id', $articlesList); $articles->setState('filter.article_id.include', $filterInclude); } @@ -292,11 +292,7 @@ public function getArticles(Registry $params, SiteApplication $app) $option = $input->get('option'); $view = $input->get('view'); - if ($option === 'com_content' && $view === 'article') { - $active_article_id = $input->getInt('id'); - } else { - $active_article_id = 0; - } + $active_article_id = $option === 'com_content' && $view === 'article' ? $input->getInt('id') : 0; // Prepare data for display using display options foreach ($items as &$item) { @@ -470,11 +466,7 @@ public static function groupBy($list, $fieldName, $direction, $fieldNameToKeep = $grouped[$item->$fieldName] = []; } - if ($fieldNameToKeep === null) { - $grouped[$item->$fieldName][$key] = $item; - } else { - $grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep; - } + $grouped[$item->$fieldName][$key] = $fieldNameToKeep === null ? $item : $item->$fieldNameToKeep; unset($list[$key]); } @@ -581,7 +573,7 @@ public static function groupByTags($list, $direction = 'ksort') $direction($grouped); - if ($untagged) { + if ($untagged !== []) { $grouped['MOD_ARTICLES_UNTAGGED'] = $untagged; } diff --git a/modules/mod_articles_category/src/Helper/ArticlesCategoryHelper.php b/modules/mod_articles_category/src/Helper/ArticlesCategoryHelper.php index 0bfe5b5aed0c2..b2a87a1321d2e 100644 --- a/modules/mod_articles_category/src/Helper/ArticlesCategoryHelper.php +++ b/modules/mod_articles_category/src/Helper/ArticlesCategoryHelper.php @@ -105,17 +105,17 @@ public function getArticles(Registry $params, SiteApplication $app) } } else { // Return right away if show_on_article_page option is off - return; + return null; } break; default: // Return right away if not on the category or article views - return; + return null; } } else { // Return right away if not on a com_content page - return; + return null; } break; @@ -232,11 +232,7 @@ public function getArticles(Registry $params, SiteApplication $app) $option = $input->get('option'); $view = $input->get('view'); - if ($option === 'com_content' && $view === 'article') { - $active_article_id = $input->getInt('id'); - } else { - $active_article_id = 0; - } + $active_article_id = $option === 'com_content' && $view === 'article' ? $input->getInt('id') : 0; // Prepare data for display using display options foreach ($items as &$item) { @@ -433,11 +429,7 @@ public static function groupBy($list, $fieldName, $direction, $fieldNameToKeep = $grouped[$item->$fieldName] = []; } - if ($fieldNameToKeep === null) { - $grouped[$item->$fieldName][$key] = $item; - } else { - $grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep; - } + $grouped[$item->$fieldName][$key] = $fieldNameToKeep === null ? $item : $item->$fieldNameToKeep; unset($list[$key]); } @@ -544,7 +536,7 @@ public static function groupByTags($list, $direction = 'ksort') $direction($grouped); - if ($untagged) { + if ($untagged !== []) { $grouped['MOD_ARTICLES_CATEGORY_UNTAGGED'] = $untagged; } diff --git a/modules/mod_banners/src/Helper/BannersHelper.php b/modules/mod_banners/src/Helper/BannersHelper.php index fd34cfe1cae9c..237a5cf549ecb 100644 --- a/modules/mod_banners/src/Helper/BannersHelper.php +++ b/modules/mod_banners/src/Helper/BannersHelper.php @@ -56,10 +56,8 @@ public function getBanners(Registry $params, CMSApplication $app) $banners = $model->getItems(); - if ($banners) { - if ($config->get('track_robots_impressions', 1) == 1 || !Browser::getInstance()->isRobot()) { - $model->impress(); - } + if ($banners && ($config->get('track_robots_impressions', 1) == 1 || !Browser::getInstance()->isRobot())) { + $model->impress(); } return $banners; diff --git a/modules/mod_breadcrumbs/tmpl/default.php b/modules/mod_breadcrumbs/tmpl/default.php index df9b5f81cb8d1..36133d09c89f4 100644 --- a/modules/mod_breadcrumbs/tmpl/default.php +++ b/modules/mod_breadcrumbs/tmpl/default.php @@ -114,7 +114,7 @@ } } - if ($itemsCounter) { + if ($itemsCounter !== 0) { /** @var WebAssetManager $wa */ $wa = $app->getDocument()->getWebAssetManager(); $prettyPrint = JDEBUG ? JSON_PRETTY_PRINT : 0; diff --git a/modules/mod_feed/src/Helper/FeedHelper.php b/modules/mod_feed/src/Helper/FeedHelper.php index a716ab862962a..d11776855487a 100644 --- a/modules/mod_feed/src/Helper/FeedHelper.php +++ b/modules/mod_feed/src/Helper/FeedHelper.php @@ -53,6 +53,7 @@ public function getFeedInformation($params) if ($rssDoc) { return $rssDoc; } + return null; } /** diff --git a/modules/mod_finder/tmpl/default.php b/modules/mod_finder/tmpl/default.php index c48c3dbabdc46..3391d40ea7614 100644 --- a/modules/mod_finder/tmpl/default.php +++ b/modules/mod_finder/tmpl/default.php @@ -23,7 +23,7 @@ . ' placeholder="' . Text::_('MOD_FINDER_SEARCH_VALUE') . '">'; $showLabel = $params->get('show_label', 1); -$labelClass = (!$showLabel ? 'visually-hidden ' : '') . 'finder'; +$labelClass = ($showLabel ? '' : 'visually-hidden ') . 'finder'; $label = ''; $output = ''; diff --git a/modules/mod_languages/src/Helper/LanguagesHelper.php b/modules/mod_languages/src/Helper/LanguagesHelper.php index f4cd09068730b..d5625b5321833 100644 --- a/modules/mod_languages/src/Helper/LanguagesHelper.php +++ b/modules/mod_languages/src/Helper/LanguagesHelper.php @@ -121,13 +121,11 @@ public function getLanguages(&$params) $language->link = Route::_('index.php?lang=' . $language->sef . '&Itemid=' . $itemid); } elseif ($active && $active->language === '*') { $language->link = Route::_('index.php?lang=' . $language->sef . '&Itemid=' . $active->id); + } elseif ($language->active) { + $language->link = Uri::getInstance()->toString(['path', 'query']); } else { - if ($language->active) { - $language->link = Uri::getInstance()->toString(['path', 'query']); - } else { - $itemid = isset($homes[$language->lang_code]) ? $homes[$language->lang_code]->id : $homes['*']->id; - $language->link = Route::_('index.php?lang=' . $language->sef . '&Itemid=' . $itemid); - } + $itemid = isset($homes[$language->lang_code]) ? $homes[$language->lang_code]->id : $homes['*']->id; + $language->link = Route::_('index.php?lang=' . $language->sef . '&Itemid=' . $itemid); } } else { $language->link = Route::_('&Itemid=' . $homes['*']->id); diff --git a/modules/mod_login/src/Helper/LoginHelper.php b/modules/mod_login/src/Helper/LoginHelper.php index 990729c9cb8f1..bbf8e90824f9c 100644 --- a/modules/mod_login/src/Helper/LoginHelper.php +++ b/modules/mod_login/src/Helper/LoginHelper.php @@ -62,7 +62,7 @@ public static function getType() { $user = Factory::getUser(); - return (!$user->guest) ? 'logout' : 'login'; + return ($user->guest) ? 'login' : 'logout'; } /** diff --git a/modules/mod_menu/src/Helper/MenuHelper.php b/modules/mod_menu/src/Helper/MenuHelper.php index 6ca33af4bc0e3..cdd06dfd4d65f 100644 --- a/modules/mod_menu/src/Helper/MenuHelper.php +++ b/modules/mod_menu/src/Helper/MenuHelper.php @@ -192,11 +192,7 @@ public static function getList(&$params) public static function getBase(&$params) { // Get base menu item from parameters - if ($params->get('base')) { - $base = Factory::getApplication()->getMenu()->getItem($params->get('base')); - } else { - $base = false; - } + $base = $params->get('base') ? Factory::getApplication()->getMenu()->getItem($params->get('base')) : false; // Use active menu item if no base found if (!$base) { diff --git a/modules/mod_random_image/tmpl/default.php b/modules/mod_random_image/tmpl/default.php index bc13921ff2e77..be7001981c5f7 100644 --- a/modules/mod_random_image/tmpl/default.php +++ b/modules/mod_random_image/tmpl/default.php @@ -13,7 +13,7 @@ use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; -if (!count($images)) { +if (count($images) === 0) { echo Text::_('MOD_RANDOM_IMAGE_NO_IMAGES'); return; diff --git a/modules/mod_related_items/src/Helper/RelatedItemsHelper.php b/modules/mod_related_items/src/Helper/RelatedItemsHelper.php index 98c842f1cb120..93e18e480b550 100644 --- a/modules/mod_related_items/src/Helper/RelatedItemsHelper.php +++ b/modules/mod_related_items/src/Helper/RelatedItemsHelper.php @@ -76,7 +76,7 @@ public function getRelatedArticles(Registry $params, SiteApplication $app): arra $related = []; $query = $db->getQuery(true); - if ($id) { + if ($id !== 0) { // Select the meta keywords from the item $query->select($db->quoteName('metakey')) ->from($db->quoteName('#__content')) @@ -100,12 +100,12 @@ public function getRelatedArticles(Registry $params, SiteApplication $app): arra foreach ($keys as $key) { $key = trim($key); - if ($key) { + if ($key !== '' && $key !== '0') { $likes[] = $db->escape($key); } } - if (\count($likes)) { + if ($likes !== []) { // Select other items based on the metakey field 'like' the keys found $query->clear() ->select($db->quoteName('a.id')) @@ -156,7 +156,7 @@ public function getRelatedArticles(Registry $params, SiteApplication $app): arra return []; } - if (\count($articleIds)) { + if (\count($articleIds) > 0) { $articles->setState('filter.article_id', $articleIds); $articles->setState('filter.published', 1); $related = $articles->getItems(); @@ -166,7 +166,7 @@ public function getRelatedArticles(Registry $params, SiteApplication $app): arra } } - if (\count($related)) { + if (\count($related) > 0) { // Prepare data for display using display options foreach ($related as &$item) { $item->slug = $item->id . ':' . $item->alias; diff --git a/modules/mod_syndicate/tmpl/default.php b/modules/mod_syndicate/tmpl/default.php index 03a1d9737d868..7b1e08c4b022f 100644 --- a/modules/mod_syndicate/tmpl/default.php +++ b/modules/mod_syndicate/tmpl/default.php @@ -16,7 +16,7 @@ $textClass = ($params->get('display_text', 1) ? '' : 'class="visually-hidden"'); $linkText = ''; -$linkText .= '' . (!empty($text) ? $text : Text::_('MOD_SYNDICATE_DEFAULT_FEED_ENTRIES')) . ''; +$linkText .= '' . (empty($text) ? Text::_('MOD_SYNDICATE_DEFAULT_FEED_ENTRIES') : $text) . ''; $attribs = [ 'class' => 'mod-syndicate syndicate-module' diff --git a/modules/mod_tags_popular/tmpl/cloud.php b/modules/mod_tags_popular/tmpl/cloud.php index acde2a96d38c4..1f8687b689db6 100644 --- a/modules/mod_tags_popular/tmpl/cloud.php +++ b/modules/mod_tags_popular/tmpl/cloud.php @@ -20,7 +20,7 @@ ?>
    +if (count($list) === 0) : ?>
    @@ -40,11 +40,7 @@ $countdiff = $maxcount - $mincount; foreach ($list as $item) : - if ($countdiff === 0) : - $fontsize = $minsize; - else : - $fontsize = $minsize + (($maxsize - $minsize) / $countdiff) * ($item->count - $mincount); - endif; + $fontsize = $countdiff === 0 ? $minsize : $minsize + (($maxsize - $minsize) / $countdiff) * ($item->count - $mincount); ?> diff --git a/modules/mod_tags_popular/tmpl/default.php b/modules/mod_tags_popular/tmpl/default.php index e60fa55b04459..581934f52d8ed 100644 --- a/modules/mod_tags_popular/tmpl/default.php +++ b/modules/mod_tags_popular/tmpl/default.php @@ -16,7 +16,7 @@ ?>
    - +
    diff --git a/modules/mod_whosonline/src/Helper/WhosonlineHelper.php b/modules/mod_whosonline/src/Helper/WhosonlineHelper.php index 84ad110af5f23..bbe2cc7621f37 100644 --- a/modules/mod_whosonline/src/Helper/WhosonlineHelper.php +++ b/modules/mod_whosonline/src/Helper/WhosonlineHelper.php @@ -53,7 +53,7 @@ public static function getOnlineCount() $sessions = []; } - if (\count($sessions)) { + if ($sessions !== []) { foreach ($sessions as $session) { // If guest increase guest count by 1 if ($session->guest == 1) { diff --git a/plugins/actionlog/joomla/src/Extension/Joomla.php b/plugins/actionlog/joomla/src/Extension/Joomla.php index e883d5624bdc5..b728e01b67bb1 100644 --- a/plugins/actionlog/joomla/src/Extension/Joomla.php +++ b/plugins/actionlog/joomla/src/Extension/Joomla.php @@ -160,7 +160,7 @@ public function onContentAfterSave(Model\AfterSaveEvent $event): void $params = $this->getActionLogParams($context); // Not found a valid content type, don't process further - if ($params === null) { + if (!$params instanceof \stdClass) { return; } @@ -220,7 +220,7 @@ public function onContentAfterDelete(Model\AfterDeleteEvent $event): void $params = $this->getActionLogParams($context); // Not found a valid content type, don't process further - if ($params === null) { + if (!$params instanceof \stdClass) { return; } @@ -268,7 +268,7 @@ public function onContentChangeState(Model\AfterChangeStateEvent $event): void $params = $this->getActionLogParams($context); // Not found a valid content type, don't process further - if ($params === null) { + if (!$params instanceof \stdClass) { return; } @@ -540,7 +540,7 @@ public function onExtensionAfterSave(Model\AfterSaveEvent $event): void $params = $this->getActionLogParams($context); // Not found a valid content type, don't process further - if ($params === null) { + if (!$params instanceof \stdClass) { return; } @@ -595,7 +595,7 @@ public function onExtensionAfterDelete(Model\AfterDeleteEvent $event): void $params = $this->getActionLogParams($context); // Not found a valid content type, don't process further - if ($params === null) { + if (!$params instanceof \stdClass) { return; } diff --git a/plugins/api-authentication/token/src/Extension/Token.php b/plugins/api-authentication/token/src/Extension/Token.php index e5229b2a720f9..6557ae8e91783 100644 --- a/plugins/api-authentication/token/src/Extension/Token.php +++ b/plugins/api-authentication/token/src/Extension/Token.php @@ -185,7 +185,7 @@ public function onUserAuthenticate(AuthenticationEvent $event): void } $referenceTokenData = $this->getTokenSeedForUser($userId); - $referenceTokenData = empty($referenceTokenData) ? '' : $referenceTokenData; + $referenceTokenData = $referenceTokenData === null || $referenceTokenData === '' || $referenceTokenData === '0' ? '' : $referenceTokenData; $referenceTokenData = base64_decode($referenceTokenData); $referenceHMAC = hash_hmac($algo, $referenceTokenData, (string) $siteSecret); @@ -235,7 +235,7 @@ public function onUserAuthenticate(AuthenticationEvent $event): void $user = $this->getUserFactory()->loadUserById($userId); // Disallow login for blocked, inactive or password reset required users - if ($user->block || !empty(trim($user->activation)) || $user->requireReset) { + if ($user->block || !in_array(trim($user->activation), ['', '0'], true) || $user->requireReset) { $response->status = Authentication::STATUS_DENIED; return; @@ -383,13 +383,13 @@ private function isInAllowedUserGroup($userId) } // No specifically allowed user groups: allow ALL user groups. - if (empty($allowedUserGroups)) { + if ($allowedUserGroups === []) { return true; } $groups = $user->getAuthorisedGroups(); $intersection = array_intersect($groups, $allowedUserGroups); - return !empty($intersection); + return $intersection !== []; } } diff --git a/plugins/authentication/ldap/src/Extension/Ldap.php b/plugins/authentication/ldap/src/Extension/Ldap.php index 86713f0eb6c4b..03a230e499efc 100644 --- a/plugins/authentication/ldap/src/Extension/Ldap.php +++ b/plugins/authentication/ldap/src/Extension/Ldap.php @@ -303,9 +303,10 @@ private function searchByString(string $search, LdapInterface $ldap) foreach (explode(';', $search) as $key => $result) { $results = $ldap->query($dn, '(' . str_replace('\3b', ';', $result) . ')')->execute(); - if (\count($results)) { + if (\count($results) > 0) { return $results[0]; } } + return null; } } diff --git a/plugins/behaviour/versionable/src/Extension/Versionable.php b/plugins/behaviour/versionable/src/Extension/Versionable.php index 84e5f0c57cc9f..10628c29f9100 100644 --- a/plugins/behaviour/versionable/src/Extension/Versionable.php +++ b/plugins/behaviour/versionable/src/Extension/Versionable.php @@ -94,7 +94,7 @@ public function onTableAfterStore(AfterStoreEvent $event) return; } - if (!(\is_object($table) && $table instanceof VersionableTableInterface)) { + if (!($table instanceof VersionableTableInterface)) { return; } @@ -134,7 +134,7 @@ public function onTableBeforeDelete(BeforeDeleteEvent $event) /** @var VersionableTableInterface $table */ $table = $event['subject']; - if (!(\is_object($table) && $table instanceof VersionableTableInterface)) { + if (!($table instanceof VersionableTableInterface)) { return; } diff --git a/plugins/content/fields/src/Extension/Fields.php b/plugins/content/fields/src/Extension/Fields.php index 60f38b7a76558..76359e9900acd 100644 --- a/plugins/content/fields/src/Extension/Fields.php +++ b/plugins/content/fields/src/Extension/Fields.php @@ -90,7 +90,7 @@ private function prepare($string, $context, $item) $regex = '/{(field|fieldgroup)\s+(.*?)}/i'; preg_match_all($regex, $string, $matches, PREG_SET_ORDER); - if (!$matches) { + if ($matches === []) { return $string; } @@ -119,7 +119,7 @@ private function prepare($string, $context, $item) if ($match[1] === 'field' && $id) { if (isset($fieldsById[$id])) { - $layout = !empty($explode[1]) ? trim($explode[1]) : $fieldsById[$id]->params->get('layout', 'render'); + $layout = empty($explode[1]) ? $fieldsById[$id]->params->get('layout', 'render') : trim($explode[1]); $output = FieldsHelper::render( $context, 'field.' . $layout, @@ -139,7 +139,7 @@ private function prepare($string, $context, $item) } if ($renderFields) { - $layout = !empty($explode[1]) ? trim($explode[1]) : 'render'; + $layout = empty($explode[1]) ? 'render' : trim($explode[1]); $output = FieldsHelper::render( $context, 'fields.' . $layout, diff --git a/plugins/content/joomla/src/Extension/Joomla.php b/plugins/content/joomla/src/Extension/Joomla.php index 25eabcb617b10..13e6906c511bd 100644 --- a/plugins/content/joomla/src/Extension/Joomla.php +++ b/plugins/content/joomla/src/Extension/Joomla.php @@ -124,7 +124,7 @@ public function onContentAfterSave($context, $article, $isNew): void $db->setQuery($query); $users = (array) $db->loadColumn(); - if (empty($users)) { + if ($users === []) { return; } @@ -282,7 +282,7 @@ private function injectContentSchema(string $context, Registry $schema) ->createCacheController('Callback', ['lifetime' => $app->get('cachetime'), 'caching' => $enableCache, 'defaultgroup' => 'schemaorg']); // Add article data - if ($view == 'article' && $id > 0) { + if ($view === 'article' && $id > 0) { $additionalSchemas = $cache->get(function ($id) use ($component, $baseId) { $model = $component->createModel('Article', 'Site'); @@ -437,7 +437,7 @@ private function createArticleSchema(object $article) $categories[] = $article->category_title; } - if (!empty($categories)) { + if ($categories !== []) { $schema['articleSection'] = implode(', ', $categories); } @@ -507,7 +507,7 @@ private function injectContactSchema(string $context, Registry $schema) ->createCacheController('Callback', ['lifetime' => $app->get('cachetime'), 'caching' => $enableCache, 'defaultgroup' => 'schemaorg']); // Add contact data - if ($view == 'contact' && $id > 0) { + if ($view === 'contact' && $id > 0) { $additionalSchema = $cache->get(function ($id) use ($component, $baseId) { $model = $component->createModel('Contact', 'Site'); @@ -725,7 +725,7 @@ private function workflowNotUsed($pk) $section = ''; - if (!empty($parts[1])) { + if (isset($parts[1]) && ($parts[1] !== '' && $parts[1] !== '0')) { $section = $parts[1]; } @@ -862,7 +862,7 @@ private function countItemsInStage(array $stageIds, string $extension): bool $section = ''; - if (!empty($parts[1])) { + if (isset($parts[1]) && ($parts[1] !== '' && $parts[1] !== '0')) { $section = $parts[1]; } @@ -870,7 +870,7 @@ private function countItemsInStage(array $stageIds, string $extension): bool $table = $component->getWorkflowTableBySection($section); - if (empty($stageIds) || !$table) { + if ($stageIds === [] || !$table) { return false; } @@ -920,7 +920,7 @@ private function countItemsInChildren($table, $catid, $data) } // Make sure we only do the query if we have some categories to look in - if (\count($childCategoryIds)) { + if ($childCategoryIds !== []) { // Count the items in this category $query = $db->getQuery(true) ->select('COUNT(' . $db->quoteName('id') . ')') diff --git a/plugins/content/loadmodule/src/Extension/LoadModule.php b/plugins/content/loadmodule/src/Extension/LoadModule.php index 56025f88d46b2..0f63ce7b63a32 100644 --- a/plugins/content/loadmodule/src/Extension/LoadModule.php +++ b/plugins/content/loadmodule/src/Extension/LoadModule.php @@ -87,7 +87,7 @@ public function onContentPrepare($context, &$article, &$params, $page = 0) preg_match_all($regex, $article->text, $matches, PREG_SET_ORDER); // No matches, skip this - if ($matches) { + if ($matches !== []) { foreach ($matches as $match) { $matcheslist = explode(',', $match[1]); @@ -114,7 +114,7 @@ public function onContentPrepare($context, &$article, &$params, $page = 0) preg_match_all($regexmod, $article->text, $matchesmod, PREG_SET_ORDER); // If no matches, skip this - if ($matchesmod) { + if ($matchesmod !== []) { foreach ($matchesmod as $matchmod) { $matchesmodlist = explode(',', $matchmod[1]); @@ -150,7 +150,7 @@ public function onContentPrepare($context, &$article, &$params, $page = 0) preg_match_all($regexmodid, $article->text, $matchesmodid, PREG_SET_ORDER); // If no matches, skip this - if ($matchesmodid) { + if ($matchesmodid !== []) { foreach ($matchesmodid as $match) { $id = trim($match[1]); $output = $this->loadID($id); diff --git a/plugins/content/vote/tmpl/rating.php b/plugins/content/vote/tmpl/rating.php index d3ac3263ebf42..ce07d4adba24a 100644 --- a/plugins/content/vote/tmpl/rating.php +++ b/plugins/content/vote/tmpl/rating.php @@ -82,7 +82,7 @@ ?>