From 3b33708ae46abaf2d2725ac196c156b32d56f249 Mon Sep 17 00:00:00 2001 From: Karyna Date: Wed, 27 Oct 2021 13:34:45 +0200 Subject: [PATCH] Fixes for the issues in app/code found by Unit Tests for PHP 8.1 compatibility --- app/code/Magento/Catalog/Helper/Image.php | 3 +- .../Catalog/Helper/Product/Configuration.php | 59 ++++++++++--------- app/code/Magento/Catalog/Model/Category.php | 8 ++- .../Catalog/Model/ProductRepository.php | 7 ++- .../Adminhtml/Product/Attribute/SaveTest.php | 8 ++- .../Test/Unit/Model/Category/FileInfoTest.php | 3 + .../Model/Import/Product.php | 2 +- .../Import/Product/Type/AbstractType.php | 7 +-- .../Import/Product/Validator/Quantity.php | 6 +- .../Model/Import/Product/Validator/Weight.php | 4 +- .../Model/Import/Product/ValidatorTest.php | 6 +- .../Checkout/Model/DefaultConfigProvider.php | 4 +- app/code/Magento/Cms/Model/Wysiwyg/Config.php | 8 ++- .../Form/Field/Select/Allowspecific.php | 3 +- .../Model/Config/Backend/Email/Sender.php | 2 +- .../Magento/Contact/Controller/Index/Post.php | 15 +++-- app/code/Magento/Cron/Model/Schedule.php | 3 +- .../Component/Listing/Column/AccountLock.php | 22 +------ app/code/Magento/Developer/Helper/Data.php | 2 +- .../Helper/Catalog/Product/Configuration.php | 2 +- .../Model/Adapter/Elasticsearch.php | 4 +- .../Model/Client/Elasticsearch.php | 2 +- .../Console/Command/IndexerReindexCommand.php | 3 +- app/code/Magento/MediaStorage/App/Media.php | 9 ++- .../Magento/Quote/Model/QueryResolver.php | 6 +- .../ReleaseNotification/Model/Viewer/Log.php | 2 +- .../Condition/CanViewNotificationTest.php | 2 +- app/code/Magento/Sales/Model/Order.php | 8 +-- .../Sales/Model/Order/Pdf/AbstractPdf.php | 6 +- .../Magento/SalesRule/Model/RulesApplier.php | 2 +- app/code/Magento/SalesRule/Model/Utility.php | 11 ++-- .../Model/Carrier/AbstractCarrierOnline.php | 4 +- .../Sitemap/Test/Unit/Model/SitemapTest.php | 4 ++ app/code/Magento/Store/Model/Store.php | 4 ++ .../Wishlist/Test/Unit/Model/WishlistTest.php | 3 +- 35 files changed, 134 insertions(+), 110 deletions(-) diff --git a/app/code/Magento/Catalog/Helper/Image.php b/app/code/Magento/Catalog/Helper/Image.php index de32f6b7637d4..35f3eb73174e0 100644 --- a/app/code/Magento/Catalog/Helper/Image.php +++ b/app/code/Magento/Catalog/Helper/Image.php @@ -16,6 +16,7 @@ * * @api * @SuppressWarnings(PHPMD.TooManyFields) + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @since 100.0.2 */ class Image extends AbstractHelper implements ArgumentInterface @@ -787,7 +788,7 @@ protected function getImageFile() */ protected function parseSize($string) { - $size = explode('x', strtolower($string)); + $size = explode('x', strtolower((string) $string)); if (count($size) == 2) { return ['width' => $size[0] > 0 ? $size[0] : null, 'height' => $size[1] > 0 ? $size[1] : null]; } diff --git a/app/code/Magento/Catalog/Helper/Product/Configuration.php b/app/code/Magento/Catalog/Helper/Product/Configuration.php index 5b8f6fad6e18a..62af591a8ea5f 100644 --- a/app/code/Magento/Catalog/Helper/Product/Configuration.php +++ b/app/code/Magento/Catalog/Helper/Product/Configuration.php @@ -86,39 +86,40 @@ public function getCustomOptions(\Magento\Catalog\Model\Product\Configuration\It $optionIds = $item->getOptionByCode('option_ids'); if ($optionIds) { $options = []; - foreach (explode(',', $optionIds->getValue()) as $optionId) { + foreach (explode(',', (string) $optionIds->getValue()) as $optionId) { $option = $product->getOptionById($optionId); - if ($option) { - $itemOption = $item->getOptionByCode('option_' . $option->getId()); - /** @var $group \Magento\Catalog\Model\Product\Option\Type\DefaultType */ - $group = $option->groupFactory($option->getType()) - ->setOption($option) - ->setConfigurationItem($item) - ->setConfigurationItemOption($itemOption); - - if ('file' == $option->getType()) { - $downloadParams = $item->getFileDownloadParams(); - if ($downloadParams) { - $url = $downloadParams->getUrl(); - if ($url) { - $group->setCustomOptionDownloadUrl($url); - } - $urlParams = $downloadParams->getUrlParams(); - if ($urlParams) { - $group->setCustomOptionUrlParams($urlParams); - } + if (!$option) { + continue; + } + $itemOption = $item->getOptionByCode('option_' . $option->getId()); + /** @var $group \Magento\Catalog\Model\Product\Option\Type\DefaultType */ + $group = $option->groupFactory($option->getType()) + ->setOption($option) + ->setConfigurationItem($item) + ->setConfigurationItemOption($itemOption); + + if ('file' == $option->getType()) { + $downloadParams = $item->getFileDownloadParams(); + if ($downloadParams) { + $url = $downloadParams->getUrl(); + if ($url) { + $group->setCustomOptionDownloadUrl($url); + } + $urlParams = $downloadParams->getUrlParams(); + if ($urlParams) { + $group->setCustomOptionUrlParams($urlParams); } } - - $options[] = [ - 'label' => $option->getTitle(), - 'value' => $group->getFormattedOptionValue($itemOption->getValue()), - 'print_value' => $group->getPrintableOptionValue($itemOption->getValue()), - 'option_id' => $option->getId(), - 'option_type' => $option->getType(), - 'custom_view' => $group->isCustomizedView(), - ]; } + + $options[] = [ + 'label' => $option->getTitle(), + 'value' => $group->getFormattedOptionValue($itemOption->getValue()), + 'print_value' => $group->getPrintableOptionValue($itemOption->getValue()), + 'option_id' => $option->getId(), + 'option_type' => $option->getType(), + 'custom_view' => $group->isCustomizedView(), + ]; } } diff --git a/app/code/Magento/Catalog/Model/Category.php b/app/code/Magento/Catalog/Model/Category.php index 95d9483ef04ba..9fe7ff0211602 100644 --- a/app/code/Magento/Catalog/Model/Category.php +++ b/app/code/Magento/Catalog/Model/Category.php @@ -72,7 +72,9 @@ class Category extends \Magento\Catalog\Model\AbstractModel implements const CACHE_TAG = 'cat_c'; - /**#@-*/ + /** + * @var string + */ protected $_eventPrefix = 'catalog_category'; /** @@ -852,7 +854,7 @@ public function getPathIds() { $ids = $this->getData('path_ids'); if ($ids === null) { - $ids = explode('/', $this->getPath()); + $ids = explode('/', (string) $this->getPath()); $this->setData('path_ids', $ids); } return $ids; @@ -866,7 +868,7 @@ public function getPathIds() public function getLevel() { if (!$this->hasLevel()) { - return count(explode('/', $this->getPath())) - 1; + return count(explode('/', (string) $this->getPath())) - 1; } return $this->getData(self::KEY_LEVEL); } diff --git a/app/code/Magento/Catalog/Model/ProductRepository.php b/app/code/Magento/Catalog/Model/ProductRepository.php index fdee74c9559c7..c99c5707332c4 100644 --- a/app/code/Magento/Catalog/Model/ProductRepository.php +++ b/app/code/Magento/Catalog/Model/ProductRepository.php @@ -38,6 +38,7 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterface { @@ -347,7 +348,7 @@ protected function getCacheKey($data) } } $serializeData = $this->serializer->serialize($serializeData); - return sha1($serializeData); + return sha1((string) $serializeData); } /** @@ -520,8 +521,10 @@ protected function processMediaGallery(ProductInterface $product, $mediaGalleryE /** * @inheritdoc + * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function save(ProductInterface $product, $saveOptions = false) { @@ -779,6 +782,7 @@ public function cleanCache() private function getMediaGalleryProcessor() { if (null === $this->mediaProcessor) { + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->mediaProcessor = \Magento\Framework\App\ObjectManager::getInstance() ->get(MediaGalleryProcessor::class); } @@ -795,6 +799,7 @@ private function getMediaGalleryProcessor() private function getCollectionProcessor() { if (!$this->collectionProcessor) { + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->collectionProcessor = \Magento\Framework\App\ObjectManager::getInstance()->get( // phpstan:ignore "Class Magento\Catalog\Model\Api\SearchCriteria\ProductCollectionProcessor not found." \Magento\Catalog\Model\Api\SearchCriteria\ProductCollectionProcessor::class diff --git a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php index 681cef8489796..6c633c334bc08 100644 --- a/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Controller/Adminhtml/Product/Attribute/SaveTest.php @@ -121,7 +121,10 @@ class SaveTest extends AttributeTest protected function setUp(): void { parent::setUp(); - $this->filterManagerMock = $this->createMock(FilterManager::class); + $this->filterManagerMock = $this->getMockBuilder(FilterManager::class) + ->setMethods(['stripTags']) + ->disableOriginalConstructor() + ->getMock(); $this->productHelperMock = $this->createMock(ProductHelper::class); $this->attributeSetMock = $this->createMock(AttributeSetInterface::class); $this->builderMock = $this->createMock(Build::class); @@ -173,6 +176,9 @@ protected function setUp(): void $this->attributeFactoryMock ->method('create') ->willReturn($this->productAttributeMock); + $this->filterManagerMock + ->method('stripTags') + ->willReturn(''); } /** diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php index 96948ed8d1aa8..59e11bcadd6a8 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Category/FileInfoTest.php @@ -116,6 +116,9 @@ function ($arg) use ($baseDirectory, $pubDirectory) { $this->pubDirectory->method('getAbsolutePath') ->willReturn('/a/b/c/pub/'); + $this->store->method('getBaseUrl') + ->willReturn(''); + $this->model = new FileInfo( $this->filesystem, $this->mime, diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product.php b/app/code/Magento/CatalogImportExport/Model/Import/Product.php index 6729d64dab1a3..033e83ce0e7e5 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product.php @@ -3119,7 +3119,7 @@ private function parseMultipleValues($labelRow) */ private function isSkuExist($sku) { - $sku = strtolower($sku); + $sku = strtolower((string) $sku); return isset($this->_oldSku[$sku]); } diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php index bd17cfd2cd7f1..fb3b79e9109d3 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php @@ -23,8 +23,6 @@ abstract class AbstractType { /** - * Common attributes cache - * * @var array */ public static $commonAttributesCache = []; @@ -149,8 +147,6 @@ abstract class AbstractType protected $metadataPool; /** - * Product entity link field - * * @var string */ private $productEntityLinkField; @@ -343,7 +339,7 @@ protected function attachAttributesById($attributeSetName, $attributeIds) 'apply_to' => $attribute->getApplyTo(), 'type' => \Magento\ImportExport\Model\Import::getAttributeType($attribute), 'default_value' => strlen( - $attribute->getDefaultValue() + (string) $attribute->getDefaultValue() ) ? $attribute->getDefaultValue() : null, 'options' => $this->_entityModel->getAttributeOptions( $attribute, @@ -597,6 +593,7 @@ public function saveData() protected function getMetadataPool() { if (!$this->metadataPool) { + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->metadataPool = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\EntityManager\MetadataPool::class); } diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Quantity.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Quantity.php index 21566c955ba2f..d525f5a7734b2 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Quantity.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Quantity.php @@ -8,12 +8,12 @@ use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface; /** - * Class Quantity + * Quantity Validator */ class Quantity extends AbstractImportValidator implements RowValidatorInterface { /** - * {@inheritdoc} + * @inheritdoc */ public function isValid($value) { @@ -24,7 +24,7 @@ public function isValid($value) $this->_addMessages( [ sprintf( - $this->context->retrieveMessageTemplate(self::ERROR_INVALID_ATTRIBUTE_TYPE), + (string) $this->context->retrieveMessageTemplate(self::ERROR_INVALID_ATTRIBUTE_TYPE), 'qty', 'decimal' ), diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Weight.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Weight.php index 5cc91d4598701..1e0e074ebf48f 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Weight.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/Validator/Weight.php @@ -10,7 +10,7 @@ class Weight extends AbstractImportValidator implements RowValidatorInterface { /** - * {@inheritdoc} + * @inheritdoc */ public function isValid($value) { @@ -21,7 +21,7 @@ public function isValid($value) $this->_addMessages( [ sprintf( - $this->context->retrieveMessageTemplate(self::ERROR_INVALID_ATTRIBUTE_TYPE), + (string) $this->context->retrieveMessageTemplate(self::ERROR_INVALID_ATTRIBUTE_TYPE), 'weight', 'decimal' ) diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php index 6c2efb6197db0..c29b274f63cfa 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php @@ -12,6 +12,7 @@ use Magento\CatalogImportExport\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product\Validator\Media; use Magento\CatalogImportExport\Model\Import\Product\Validator\Website; +use Magento\Framework\Stdlib\StringUtils; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\ImportExport\Model\Import; use PHPUnit\Framework\MockObject\MockObject; @@ -64,7 +65,10 @@ protected function setUp(): void $this->objectManagerHelper = new ObjectManagerHelper($this); $this->validator = $this->objectManagerHelper->getObject( Validator::class, - ['validators' => $this->validators] + [ + 'validators' => $this->validators, + 'string' => new StringUtils() + ] ); $this->validator->init($this->context); } diff --git a/app/code/Magento/Checkout/Model/DefaultConfigProvider.php b/app/code/Magento/Checkout/Model/DefaultConfigProvider.php index 80748bfa042d7..6a4fbd125a0e8 100644 --- a/app/code/Magento/Checkout/Model/DefaultConfigProvider.php +++ b/app/code/Magento/Checkout/Model/DefaultConfigProvider.php @@ -97,7 +97,7 @@ class DefaultConfigProvider implements ConfigProviderInterface private $configurationPool; /** - * @param QuoteIdMaskFactory + * @var QuoteIdMaskFactory */ protected $quoteIdMaskFactory; @@ -344,7 +344,7 @@ public function getConfig() ScopeInterface::SCOPE_STORE ), 'shippingPolicyContent' => nl2br( - $this->scopeConfig->getValue( + (string) $this->scopeConfig->getValue( 'shipping/shipping_policy/shipping_policy_content', ScopeInterface::SCOPE_STORE ) diff --git a/app/code/Magento/Cms/Model/Wysiwyg/Config.php b/app/code/Magento/Cms/Model/Wysiwyg/Config.php index 95f5971251f1c..cc6187403adeb 100644 --- a/app/code/Magento/Cms/Model/Wysiwyg/Config.php +++ b/app/code/Magento/Cms/Model/Wysiwyg/Config.php @@ -30,7 +30,7 @@ class Config extends \Magento\Framework\DataObject implements ConfigInterface const WYSIWYG_STATUS_CONFIG_PATH = 'cms/wysiwyg/enabled'; /** - * + * Skin image identifier */ const WYSIWYG_SKIN_IMAGE_PLACEHOLDER_ID = 'Magento_Cms::images/wysiwyg_skin_image.png'; @@ -197,7 +197,11 @@ public function getConfig($data = []) ] ); - $config->setData('directives_url_quoted', preg_quote($config->getData('directives_url'))); + $directivesUrl = $config->getData('directives_url'); + $config->setData( + 'directives_url_quoted', + $directivesUrl ? preg_quote($directivesUrl) : '' + ); if (is_array($data)) { $config->addData($data); diff --git a/app/code/Magento/Config/Block/System/Config/Form/Field/Select/Allowspecific.php b/app/code/Magento/Config/Block/System/Config/Form/Field/Select/Allowspecific.php index 9a0bc416d4d46..72fac85d0eeaf 100644 --- a/app/code/Magento/Config/Block/System/Config/Form/Field/Select/Allowspecific.php +++ b/app/code/Magento/Config/Block/System/Config/Form/Field/Select/Allowspecific.php @@ -100,6 +100,7 @@ public function getHtml() */ protected function _getSpecificCountryElementId() { - return substr($this->getId(), 0, strrpos($this->getId(), 'allowspecific')) . 'specificcountry'; + $id = (string) $this->getId(); + return substr($id, 0, strrpos($id, 'allowspecific')) . 'specificcountry'; } } diff --git a/app/code/Magento/Config/Model/Config/Backend/Email/Sender.php b/app/code/Magento/Config/Model/Config/Backend/Email/Sender.php index d9ed5e17f79c9..048eb8cd89475 100644 --- a/app/code/Magento/Config/Model/Config/Backend/Email/Sender.php +++ b/app/code/Magento/Config/Model/Config/Backend/Email/Sender.php @@ -24,7 +24,7 @@ class Sender extends \Magento\Framework\App\Config\Value public function beforeSave() { $value = $this->getValue(); - if (!preg_match("/^[\S ]+$/", $value)) { + if (empty($value) || !preg_match("/^[\S ]+$/", $value)) { throw new \Magento\Framework\Exception\LocalizedException( __('The sender name "%1" is not valid. Please use only visible characters and spaces.', $value) ); diff --git a/app/code/Magento/Contact/Controller/Index/Post.php b/app/code/Magento/Contact/Controller/Index/Post.php index cbe49a767262c..14230e861c5da 100644 --- a/app/code/Magento/Contact/Controller/Index/Post.php +++ b/app/code/Magento/Contact/Controller/Index/Post.php @@ -7,6 +7,7 @@ namespace Magento\Contact\Controller\Index; +use _PHPStan_76800bfb5\Nette\Neon\Exception; use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; use Magento\Contact\Model\ConfigInterface; use Magento\Contact\Model\MailInterface; @@ -91,7 +92,10 @@ public function execute() } /** + * Send contact form data. + * * @param array $post Post data from contact form + * * @return void */ private function sendEmail($post) @@ -103,22 +107,25 @@ private function sendEmail($post) } /** + * Validates parameters from request. + * * @return array * @throws \Exception */ private function validatedParams() { $request = $this->getRequest(); - if (trim($request->getParam('name')) === '') { + if (trim((string) $request->getParam('name')) === '') { throw new LocalizedException(__('Enter the Name and try again.')); } - if (trim($request->getParam('comment')) === '') { + if (trim((string) $request->getParam('comment')) === '') { throw new LocalizedException(__('Enter the comment and try again.')); } - if (false === \strpos($request->getParam('email'), '@')) { + if (false === \strpos((string) $request->getParam('email'), '@')) { throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.')); } - if (trim($request->getParam('hideit')) !== '') { + if (trim((string) $request->getParam('hideit')) !== '') { + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception(); } diff --git a/app/code/Magento/Cron/Model/Schedule.php b/app/code/Magento/Cron/Model/Schedule.php index 136e2ef191084..f8dc133560759 100644 --- a/app/code/Magento/Cron/Model/Schedule.php +++ b/app/code/Magento/Cron/Model/Schedule.php @@ -104,7 +104,8 @@ public function _construct() */ public function setCronExpr($expr) { - $e = preg_split('#\s+#', $expr, null, PREG_SPLIT_NO_EMPTY); + $expr = (string) $expr; + $e = preg_split('#\s+#', $expr, -1, PREG_SPLIT_NO_EMPTY); if (count($e) < 5 || count($e) > 6) { throw new CronException(__('Invalid cron expression: %1', $expr)); } diff --git a/app/code/Magento/Customer/Ui/Component/Listing/Column/AccountLock.php b/app/code/Magento/Customer/Ui/Component/Listing/Column/AccountLock.php index e622edbd29567..7015117c5be60 100644 --- a/app/code/Magento/Customer/Ui/Component/Listing/Column/AccountLock.php +++ b/app/code/Magento/Customer/Ui/Component/Listing/Column/AccountLock.php @@ -9,28 +9,8 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; -/** - * Class AccountLock - */ class AccountLock extends Column { - /** - * Constructor - * - * @param ContextInterface $context - * @param UiComponentFactory $uiComponentFactory - * @param array $components - * @param array $data - */ - public function __construct( - ContextInterface $context, - UiComponentFactory $uiComponentFactory, - array $components = [], - array $data = [] - ) { - parent::__construct($context, $uiComponentFactory, $components, $data); - } - /** * Prepare Data Source * @@ -42,7 +22,7 @@ public function prepareDataSource(array $dataSource) if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (array_key_exists('lock_expires', $item)) { - $lockExpires = new \DateTime($item['lock_expires']); + $lockExpires = new \DateTime($item['lock_expires'] ?? 'now'); if ($lockExpires > new \DateTime()) { $item['lock_expires'] = __('Locked'); } else { diff --git a/app/code/Magento/Developer/Helper/Data.php b/app/code/Magento/Developer/Helper/Data.php index dea6291d5861d..8d24e3b5cf5b1 100644 --- a/app/code/Magento/Developer/Helper/Data.php +++ b/app/code/Magento/Developer/Helper/Data.php @@ -35,7 +35,7 @@ public function isDevAllowed($storeId = null) ); $remoteAddr = $this->_remoteAddress->getRemoteAddress(); if (!empty($allowedIps) && !empty($remoteAddr)) { - $allowedIps = preg_split('#\s*,\s*#', $allowedIps, null, PREG_SPLIT_NO_EMPTY); + $allowedIps = preg_split('#\s*,\s*#', $allowedIps, -1, PREG_SPLIT_NO_EMPTY); if (array_search($remoteAddr, $allowedIps) === false && array_search($this->_httpHeader->getHttpHost(), $allowedIps) === false ) { diff --git a/app/code/Magento/Downloadable/Helper/Catalog/Product/Configuration.php b/app/code/Magento/Downloadable/Helper/Catalog/Product/Configuration.php index a9f5ead86578c..935c75dea17eb 100644 --- a/app/code/Magento/Downloadable/Helper/Catalog/Product/Configuration.php +++ b/app/code/Magento/Downloadable/Helper/Catalog/Product/Configuration.php @@ -63,7 +63,7 @@ public function getLinks(\Magento\Catalog\Model\Product\Configuration\Item\ItemI */ public function getLinksTitle($product) { - $title = $product->getLinksTitle(); + $title = (string) $product->getLinksTitle(); if (strlen($title)) { return $title; } diff --git a/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php b/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php index 05dd8c9d922be..2d181d8ed6060 100644 --- a/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php +++ b/app/code/Magento/Elasticsearch/Model/Adapter/Elasticsearch.php @@ -236,10 +236,10 @@ public function cleanIndex($storeId, $mappedIndexerId) unset($this->preparedIndex[$storeId]); $this->checkIndex($storeId, $mappedIndexerId, true); - $indexName = $this->indexNameResolver->getIndexName($storeId, $mappedIndexerId, $this->preparedIndex); + $indexName = $this->indexNameResolver->getIndexName($storeId, $mappedIndexerId, $this->preparedIndex) ?? ''; // prepare new index name and increase version - $indexPattern = $this->indexNameResolver->getIndexPattern($storeId, $mappedIndexerId); + $indexPattern = $this->indexNameResolver->getIndexPattern($storeId, $mappedIndexerId) ?? ''; $version = (int)(str_replace($indexPattern, '', $indexName)); // compatibility with snapshotting collision diff --git a/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php b/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php index 87b9f7c93a653..fd97dd00e1b5b 100644 --- a/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php +++ b/app/code/Magento/Elasticsearch7/Model/Client/Elasticsearch.php @@ -116,7 +116,7 @@ public function ping(): bool ->ping(['client' => ['timeout' => $this->clientOptions['timeout']]]); } - return $this->pingResult; + return (bool) $this->pingResult; } /** diff --git a/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php b/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php index 5f21228665a0c..1058117a3d48b 100644 --- a/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php +++ b/app/code/Magento/Indexer/Console/Command/IndexerReindexCommand.php @@ -114,8 +114,9 @@ protected function execute(InputInterface $input, OutputInterface $output) } $resultTime = microtime(true) - $startTime; + // cast to (int) added to emulate a behaviour from PHP < 8.1. $output->writeln( - __('has been rebuilt successfully in %time', ['time' => gmdate('H:i:s', $resultTime)]) + __('has been rebuilt successfully in %time', ['time' => gmdate('H:i:s', (int) $resultTime)]) ); } catch (\Throwable $e) { $output->writeln('process error during indexation process:'); diff --git a/app/code/Magento/MediaStorage/App/Media.php b/app/code/Magento/MediaStorage/App/Media.php index 1642b928d5d48..b48000b6085b9 100644 --- a/app/code/Magento/MediaStorage/App/Media.php +++ b/app/code/Magento/MediaStorage/App/Media.php @@ -45,8 +45,6 @@ class Media implements AppInterface private $isAllowed; /** - * Media directory path - * * @var string */ private $mediaDirectoryPath; @@ -184,10 +182,10 @@ public function launch(): ResponseInterface /** @var Config $config */ $config = $this->configFactory->create(['cacheFile' => $this->configCacheFile]); $config->save(); - $this->mediaDirectoryPath = $config->getMediaDirectory(); + $this->mediaDirectoryPath = $config->getMediaDirectory() ?? ''; $allowedResources = $config->getAllowedResources(); $isAllowed = $this->isAllowed; - $fileAbsolutePath = $this->directoryPub->getAbsolutePath($this->relativeFileName); + $fileAbsolutePath = $this->directoryPub->getAbsolutePath($this->relativeFileName) ?? ''; $fileRelativePath = str_replace(rtrim($this->mediaDirectoryPath, '/') . '/', '', $fileAbsolutePath); if (!$isAllowed($fileRelativePath, $allowedResources)) { throw new LogicException('The path is not allowed: ' . $this->relativeFileName); @@ -238,7 +236,8 @@ private function createLocalCopy(): void */ private function checkMediaDirectoryChanged(): bool { - return rtrim($this->mediaDirectoryPath, '/') !== rtrim($this->directoryMedia->getAbsolutePath(), '/'); + $mediaPath = $this->mediaDirectoryPath ? rtrim($this->mediaDirectoryPath, '/') : $this->mediaDirectoryPath; + return $mediaPath !== rtrim($this->directoryMedia->getAbsolutePath(), '/'); } /** diff --git a/app/code/Magento/Quote/Model/QueryResolver.php b/app/code/Magento/Quote/Model/QueryResolver.php index ca616d14956cd..86f7a7ff839dc 100644 --- a/app/code/Magento/Quote/Model/QueryResolver.php +++ b/app/code/Magento/Quote/Model/QueryResolver.php @@ -33,8 +33,6 @@ class QueryResolver private $cacheId; /** - * Cache tags - * * @var array */ private $cacheTags = []; @@ -76,7 +74,8 @@ public function isSingleQuery() } /** - * Initialise data for configuration + * Initialise data for configuration. + * * @return void */ protected function initData() @@ -84,6 +83,7 @@ protected function initData() $data = $this->cache->load($this->cacheId); if (false === $data) { $singleQuery = $this->config->getConnectionName('checkout_setup') == 'default' ? true : false; + $data = []; $data['checkout'] = $singleQuery; $this->cache->save($this->serializer->serialize($data), $this->cacheId, $this->cacheTags); } else { diff --git a/app/code/Magento/ReleaseNotification/Model/Viewer/Log.php b/app/code/Magento/ReleaseNotification/Model/Viewer/Log.php index 2cf3e6770c762..ffa1ad1e35924 100644 --- a/app/code/Magento/ReleaseNotification/Model/Viewer/Log.php +++ b/app/code/Magento/ReleaseNotification/Model/Viewer/Log.php @@ -39,6 +39,6 @@ public function getViewerId() */ public function getLastViewVersion() { - return $this->getData('last_view_version'); + return (string) $this->getData('last_view_version'); } } diff --git a/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php b/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php index fe4c8588728bd..bcbe692ec84d8 100644 --- a/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php +++ b/app/code/Magento/ReleaseNotification/Test/Unit/Model/Condition/CanViewNotificationTest.php @@ -122,7 +122,7 @@ public function isVisibleProvider() return [ [false, '2.2.1-dev', '999.999.999-alpha'], [true, '2.2.1-dev', '2.0.0'], - [true, '2.2.1-dev', null], + [true, '2.2.1-dev', ''], [false, '2.2.1-dev', '2.2.1'], [true, '2.2.1-dev', '2.2.0'], [true, '2.3.0', '2.2.0'], diff --git a/app/code/Magento/Sales/Model/Order.php b/app/code/Magento/Sales/Model/Order.php index f678a0661db2f..a816344e07c77 100644 --- a/app/code/Magento/Sales/Model/Order.php +++ b/app/code/Magento/Sales/Model/Order.php @@ -2037,15 +2037,15 @@ public function getCustomerName() } $customerName = ''; - if ($this->isVisibleCustomerPrefix() && strlen($this->getCustomerPrefix())) { + if ($this->isVisibleCustomerPrefix() && strlen($this->getCustomerPrefix() ?? '')) { $customerName .= $this->getCustomerPrefix() . ' '; } $customerName .= $this->getCustomerFirstname(); - if ($this->isVisibleCustomerMiddlename() && strlen($this->getCustomerMiddlename())) { + if ($this->isVisibleCustomerMiddlename() && strlen($this->getCustomerMiddlename() ?? '')) { $customerName .= ' ' . $this->getCustomerMiddlename(); } $customerName .= ' ' . $this->getCustomerLastname(); - if ($this->isVisibleCustomerSuffix() && strlen($this->getCustomerSuffix())) { + if ($this->isVisibleCustomerSuffix() && strlen($this->getCustomerSuffix() ?? '')) { $customerName .= ' ' . $this->getCustomerSuffix(); } @@ -2074,7 +2074,7 @@ public function addRelatedObject(\Magento\Framework\Model\AbstractModel $object) public function getCreatedAtFormatted($format) { return $this->timezone->formatDateTime( - new \DateTime($this->getCreatedAt()), + new \DateTime($this->getCreatedAt() ?? 'now'), $format, $format, $this->localeResolver->getDefaultLocale(), diff --git a/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php b/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php index 63dff3660a1b5..0712d8bcc9674 100644 --- a/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php +++ b/app/code/Magento/Sales/Model/Order/Pdf/AbstractPdf.php @@ -332,7 +332,7 @@ protected function insertAddress(&$page, $store = null) $top = 815; $values = explode( "\n", - $this->_scopeConfig->getValue( + (string) $this->_scopeConfig->getValue( 'sales/identity/address', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store @@ -476,6 +476,8 @@ protected function insertOrder(&$page, $obj, $putOrderId = true) reset($payment); /* Shipping Address and Method */ + $shippingAddress = []; + $shippingMethod = ''; if (!$order->getIsVirtual()) { /* Shipping Address */ $shippingAddress = $this->_formatAddress( @@ -495,7 +497,7 @@ protected function insertOrder(&$page, $obj, $putOrderId = true) } $addressesHeight = $this->_calcAddressHeight($billingAddress); - if (isset($shippingAddress)) { + if (!empty($shippingAddress)) { $addressesHeight = max($addressesHeight, $this->_calcAddressHeight($shippingAddress)); } diff --git a/app/code/Magento/SalesRule/Model/RulesApplier.php b/app/code/Magento/SalesRule/Model/RulesApplier.php index 3652f22798c14..89689db91dbb7 100644 --- a/app/code/Magento/SalesRule/Model/RulesApplier.php +++ b/app/code/Magento/SalesRule/Model/RulesApplier.php @@ -153,7 +153,7 @@ public function addDiscountDescription($address, $rule) if ($ruleLabel) { $label = $ruleLabel; } else { - if (strlen($address->getCouponCode())) { + if (!empty($address->getCouponCode())) { $label = $address->getCouponCode(); if ($rule->getDescription()) { diff --git a/app/code/Magento/SalesRule/Model/Utility.php b/app/code/Magento/SalesRule/Model/Utility.php index fcf0b098f09cb..38a5841bfaea0 100644 --- a/app/code/Magento/SalesRule/Model/Utility.php +++ b/app/code/Magento/SalesRule/Model/Utility.php @@ -8,11 +8,6 @@ use Magento\Framework\Pricing\PriceCurrencyInterface; -/** - * Class Utility - * - * @package Magento\SalesRule\Model - */ class Utility { /** @@ -91,7 +86,7 @@ public function canProcessRule($rule, $address) */ if ($rule->getCouponType() != \Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON) { $couponCode = $address->getQuote()->getCouponCode(); - if (strlen($couponCode)) { + if ($couponCode !== null && strlen($couponCode)) { /** @var \Magento\SalesRule\Model\Coupon $coupon */ $coupon = $this->couponFactory->create(); $coupon->load($couponCode, 'code'); @@ -153,6 +148,8 @@ public function canProcessRule($rule, $address) } /** + * Set discount amount (found min) + * * @param \Magento\SalesRule\Model\Rule\Action\Discount\Data $discountData * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item * @param float $qty @@ -294,6 +291,8 @@ public function mergeIds($a1, $a2, $asString = true) } /** + * Resets all rounding deltas. + * * @return void */ public function resetRoundingDeltas() diff --git a/app/code/Magento/Shipping/Model/Carrier/AbstractCarrierOnline.php b/app/code/Magento/Shipping/Model/Carrier/AbstractCarrierOnline.php index f88fecf84be6a..da14ec7a691aa 100644 --- a/app/code/Magento/Shipping/Model/Carrier/AbstractCarrierOnline.php +++ b/app/code/Magento/Shipping/Model/Carrier/AbstractCarrierOnline.php @@ -12,6 +12,7 @@ use Magento\Shipping\Model\Shipment\Request; use Magento\Framework\Xml\Security; +// phpcs:disable Magento2.Classes.AbstractApi /** * Abstract online shipping carrier model * @@ -396,7 +397,7 @@ protected function _getQuotesCacheKey($requestParams) ); } - return crc32($requestParams); + return crc32($requestParams ?? ''); } /** @@ -438,6 +439,7 @@ protected function _setCachedQuotes($requestParams, $response) */ protected function _prepareServiceName($name) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $name = html_entity_decode((string)$name); $name = strip_tags(preg_replace('#&\w+;#', '', $name)); diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php index 866b3afd322a0..6152a853918ac 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php @@ -497,6 +497,10 @@ function ($from, $to) { $model = $this->getModelMock(true); + // to avoid issues with null in PHP 8.1 + $model->method('_getBaseDir') + ->willReturn(''); + $this->store->expects($this->atLeastOnce()) ->method('isFrontUrlSecure') ->willReturn(false); diff --git a/app/code/Magento/Store/Model/Store.php b/app/code/Magento/Store/Model/Store.php index f437d9bca0b74..b45d92d934f42 100644 --- a/app/code/Magento/Store/Model/Store.php +++ b/app/code/Magento/Store/Model/Store.php @@ -450,8 +450,10 @@ public function __sleep() public function __wakeup() { parent::__wakeup(); + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->_coreFileStorageDatabase = ObjectManager::getInstance() ->get(\Magento\MediaStorage\Helper\File\Storage\Database::class); + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->_config = ObjectManager::getInstance()->get( \Magento\Framework\App\Config\ReinitableConfigInterface::class ); @@ -666,6 +668,7 @@ public function getBaseUrl($type = UrlInterface::URL_TYPE_LINK, $secure = null) throw new \InvalidArgumentException('Invalid base url type'); } + $url = $url ?? ''; if (false !== strpos($url, self::BASE_URL_PLACEHOLDER)) { $url = str_replace(self::BASE_URL_PLACEHOLDER, $this->_request->getDistroBaseUrl(), $url); } @@ -1427,6 +1430,7 @@ public function setExtensionAttributes( private function getUrlModifier() { if ($this->urlModifier === null) { + // phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor $this->urlModifier = \Magento\Framework\App\ObjectManager::getInstance()->get( \Magento\Framework\Url\ModifierInterface::class ); diff --git a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php index 369f77e527287..a76e12e853145 100644 --- a/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php +++ b/app/code/Magento/Wishlist/Test/Unit/Model/WishlistTest.php @@ -233,7 +233,8 @@ public function testLoadByCustomerId() $this->eventDispatcher->expects($this->any()) ->method('dispatch'); $this->resource->expects($this->any()) - ->method('getCustomerIdFieldName'); + ->method('getCustomerIdFieldName') + ->willReturn($customerIdFieldName); $this->resource->expects($this->once()) ->method('load') ->with($this->logicalOr($this->wishlist, $customerId, $customerIdFieldName));