Skip to content

Instantly share code, notes, and snippets.

@ProcessEight
Last active May 3, 2024 20:34
Show Gist options
  • Save ProcessEight/6238fcc9810565957184862e40d0172a to your computer and use it in GitHub Desktop.
Save ProcessEight/6238fcc9810565957184862e40d0172a to your computer and use it in GitHub Desktop.
Discussion of automated refactoring processes to bring legacy codebases up to date

Automated Refactoring

Table of Contents

Created by gh-md-toc

Phase 1: Manually re-factoring modules

Phase 1 is a exploration/discovery/proof-of-concept stage to test the concepts, tools and workflow.

Desired

Suggested workflow:

  • Check out a module
  • Create feature branch for PHP8.1 refactoring
  • Configure Rector
  • Run Rector on it
  • Commit and PR
  • Update Repman (by tagging the commit and pushing tags)

Check out a module

https://bitbucket.org/elementarydigital/magento2-module-product-label/src/master/

Create feature branch for PHP8.1 refactoring

Check out a new feature branch in the module directory:

git checkout -b php81-refactoring HEAD --

Configure Rector

The tool we'll use is called Rector. It's a static analysis tool, which means it doesn't actually run the code being analysed. Unlike most static analysis tools, Rector can also be used to refactor code, e.g. To bring make it compatible with a newer PHP version or to comply with a given coding standard.

I recommend installing Rector globally, so you can always keep it up to date and run it using the latest version of PHP.

  • Install Rector
    • Add it as a composer require --dev dependency to the project (or install it globally)
  • Configure Rector for PHP and Magento 2
    • Create a rector,php file in the root of the module/project directory
    • Magento 2 specific rectors can be found in the Magento coding standard repository (magento/magento-coding-standard)
    • Project-specific rector.php config files can be passed to the global Rector. You don't need to use the same PHP version as the project.
  • Consider configuring Rector for other things e.g. Re-factoring PHPUnit tests!

Run Rector

php /var/www/html/rector/vendor/bin/rector process \
--config /var/www/html/wearemagneto/projects/hstv/html/rector.php \
--autoload-file /var/www/html/wearemagneto/projects/hstv/html/vendor/autoload.php \ 
/var/www/html/wearemagneto/projects/hstv/html/app/code/Mapp/Connect/Test/Unit/Setup/Patch/Data/DisableForSilverSurfersStoreTest.php
  • --config The path to the rector.php config file to use
  • --autoload-file The path to the autoloader for the project. Not required, but it does help Rector make better judgments about the structure of the code and what rectors (refactorings) can be applied
  • /var/www/html/... An absolute path to a file or folder containing code to analyse and possibly refactor.

Commit and PR changes (if any)

  • Commit to the feature branch, push and create a new PR in Bitbucket.
    • It may be better to break up the PRs to prevent producing a huge PR
      • The larger the PR, the less time developers will spend reviewing it and the less in-depth the review
      • Bitbucket doesn't like big PRs!
  • Tag in other developers for visibility and to solicit feedback.
  • Once the PR has been approved, merge to master and tag the commit with an update release version number. Repman will then automatically update the package and make the new version available in composer.

Phase 2: Automation

  • Build a workflow to automate these steps, possibly using Deployer

Notes

  • I prefer to have automated tests covering the code before and after to ensure correctness and validity and to make sure no bugs were introduced. Perhaps we should wait until we have basic test coverage before starting on wholesale automated refactoring of modules.
  • Can we pass the output of Rector to AI and use it to generate a summary of the changes made as a message added to the PR?

Appendix A: Output of running Rector on internal module (wearemagneto/magento2-product-label)

$ php /var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/html/vendor/bin/rector process --config /var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/html/rector.php /var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/
 56/56 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
29 files with changes
=====================

1) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/ViewModel/Labels.php:45

    ---------- begin diff ----------
@@ @@
             $block->setProduct($product);

             return $block->toHtml();
-        } catch (\Exception $e) {
+        } catch (\Exception) {
             return '';
         }
     }
    ----------- end diff -----------

Applied rules:
 * RemoveUnusedVariableInCatchRector (https://wiki.php.net/rfc/non-capturing_catches)
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)


2) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Ui/Component/Listing/Column/Stores.php:42

    ---------- begin diff ----------
@@ @@
      * @param LabelFactory         $labelFactory
      * @param Escaper              $escaper
      * @param Store                $systemStore
-     * @param array                $components
-     * @param array                $data
      */
     public function __construct(
         ContextInterface     $context,
@@ @@
     /**
      * This method will set the data for the store view column
      *
-     * @param array $dataSource
      *
      * @return array
      */
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector


3) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Ui/Component/Listing/Column/Preview.php:47

    ---------- begin diff ----------
@@ @@
      * @param UrlInterface         $url
      * @param Repository           $assetRepository
      * @param LabelFactory         $labelFactory,
-     * @param array                $components
-     * @param array                $data
      */
     public function __construct(
         ContextInterface     $context,
@@ @@
     /**
      * This method will set the data for the image column
      *
-     * @param array $dataSource
      *
      * @return array
      */
@@ @@
      * Get Image Preview
      *
      * @param Label $label
-     *
-     * @return string
      */
     protected function _getImagePreview($label): string
     {
@@ @@
      * Get Text Preview
      *
      * @param Label $label
-     *
-     * @return string
      */
     protected function _getTextPreview($label): string
     {
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector


4) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Ui/Component/Listing/Column/CustomerGroups.php:49

    ---------- begin diff ----------
@@ @@
      * @param LabelFactory         $labelFactory
      * @param Escaper              $escaper
      * @param CollectionFactory    $groupCollectionFactory
-     * @param array                $components
-     * @param array                $data
      */
     public function __construct(
         ContextInterface     $context,
@@ @@
     /**
      * This method will set the data for the customer group column
      *
-     * @param array $dataSource
      *
      * @return array
      */
@@ @@

     /**
      * Get Customer Groups
-     *
-     * @return array
      */
     protected function _getGroups(): array
     {
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector


5) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Ui/Component/Listing/Column/Actions.php:26

    ---------- begin diff ----------
@@ @@
      * @param ContextInterface   $context
      * @param UiComponentFactory $uiComponentFactory
      * @param UrlInterface       $url
-     * @param array              $components
-     * @param array              $data
      */
     public function __construct(
         ContextInterface   $context,
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector


6) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Service/Labels.php:113

    ---------- begin diff ----------
@@ @@
      *
      * @return Collection|Label[]
      */
-    protected function _getLabels()
+    protected function _getLabels(): \WeAreMagneto\ProductLabel\Model\ResourceModel\Label\Collection|array
     {
         /** @var Collection $labels */
         $labels = $this->_labelCollectionFactory->create();
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * UnionTypesRector


7) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Observer/SaveProductObserver.php:21

    ---------- begin diff ----------
@@ @@

     /**
      * SaveProductObserver constructor
-     *
-     * @param Labels $labelService
      */
     public function __construct(
         Labels $labelService
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector


8) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Observer/SaveLabelObserver.php:21

    ---------- begin diff ----------
@@ @@

     /**
      * SaveLabelObserver constructor
-     *
-     * @param Labels $labelService
      */
     public function __construct(
         Labels $labelService
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector


9) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/Source/Positions.php:11

    ---------- begin diff ----------
@@ @@
  */
 class Positions implements OptionSourceInterface
 {
-    const TOP_LEFT = 'top_left';
+    final public const TOP_LEFT = 'top_left';

-    const TOP_MIDDLE = 'top_middle';
+    final public const TOP_MIDDLE = 'top_middle';

-    const TOP_RIGHT = 'top_right';
+    final public const TOP_RIGHT = 'top_right';

-    const MIDDLE_LEFT = 'middle_left';
+    final public const MIDDLE_LEFT = 'middle_left';

-    const MIDDLE_RIGHT = 'middle_right';
+    final public const MIDDLE_RIGHT = 'middle_right';

-    const BOTTOM_LEFT = 'bottom_left';
+    final public const BOTTOM_LEFT = 'bottom_left';

-    const BOTTOM_MIDDLE = 'bottom_middle';
+    final public const BOTTOM_MIDDLE = 'bottom_middle';

-    const BOTTOM_RIGHT = 'bottom_right';
+    final public const BOTTOM_RIGHT = 'bottom_right';

     /**
      * Label Positions
    ----------- end diff -----------

Applied rules:
 * PublicConstantVisibilityRector (https://wiki.php.net/rfc/class_const_visibility)
 * FinalizePublicClassConstantRector (https://php.watch/versions/8.1/final-class-const)


10) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/ResourceModel/Label/Grid/Collection.php:47

    ---------- begin diff ----------
@@ @@
         $connection = null,
         $resource = null
     ) {
-        parent::__construct(
-            $entityFactory,
-            $logger,
-            $fetchStrategy,
-            $eventManager,
-            $connection,
-            $resource
-        );
         $this->_eventPrefix = 'product_label_grid_collection';
         $this->_eventObject = 'product_label_collection';
         $this->_init($model, Label::class);
    ----------- end diff -----------

Applied rules:
 * RemoveParentCallWithoutParentRector


11) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/ResourceModel/Label/Collection.php:28

    ---------- begin diff ----------
@@ @@
     /**
      * Filter collection by specified date. Filter collection to only active rules.
      *
-     * @param string|null $now
      *
      * @return $this
      */
-    public function setValidationFilter($now = null)
+    public function setValidationFilter(?string $now = null)
     {
         if (!$this->getFlag('validation_filter')) {
             $this->addDateFilter($now);
@@ @@
     /**
      * From date or to date filter
      *
-     * @param string|null $now
      *
-     * @return $this
      */
-    public function addDateFilter($now = ''): Collection
+    public function addDateFilter(?string $now = ''): Collection
     {
         if (!$now) {
             $now = (new \DateTime())->format('Y-m-d H:i:s');
@@ @@
     /**
      * Add Store filter
      *
-     * @param int $storeId
      *
-     * @return $this
      */
     public function addStoreFilter(int $storeId): Collection
     {
@@ @@
     /**
      * Add Customer Group filter
      *
-     * @param int $customerGroupId
      *
-     * @return $this
      */
     public function addCustomerGroupFilter(int $customerGroupId): Collection
     {
    ----------- end diff -----------

Applied rules:
 * UnionTypesRector


12) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/ResourceModel/Label.php:31

    ---------- begin diff ----------
@@ @@
      *
      * @param Context      $context
      * @param UrlInterface $url
-     * @param Logger       $labelLogger
      * @param null         $connectionName
      */
     public function __construct(
@@ @@
             return '';
         }

-        $mediaUrl = rtrim($this->_url->getBaseUrl([
+        $mediaUrl = rtrim((string) $this->_url->getBaseUrl([
             '_type' => UrlInterface::URL_TYPE_MEDIA
         ]), '/');

@@ @@
             ->where('label_id=:label_id');

         $groupResults = $connection->fetchAll($customerGroupSelect, $bind);
-        if (count($groupResults)) {
+        if (is_countable($groupResults) ? count($groupResults) : 0) {
             foreach ($groupResults as $groupResult) {
                 $groupIds[] = (int) $groupResult['customer_group_id'];
             }
@@ @@
             ->where('label_id=:label_id');

         $storeResults = $connection->fetchAll($storeSelect, $bind);
-        if (count($storeResults)) {
+        if (is_countable($storeResults) ? count($storeResults) : 0) {
             foreach ($storeResults as $storeResult) {
                 $storeIds[] = (int) $storeResult['store_id'];
             }
    ----------- end diff -----------

Applied rules:
 * CountOnNullRector (https://3v4l.org/Bndc9)
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector
 * NullToStrictStringFuncCallArgRector


13) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/Resolver/Product/Labels.php:34

    ---------- begin diff ----------
@@ @@
     /**
      * Get labels for product
      *
-     * @param array $labelIds
-     * @param int   $groupId
-     * @param int   $storeId
      *
-     * @return array
      */
     protected function _getLabels(array $labelIds, int $groupId, int $storeId): array
     {
    ----------- end diff -----------

Applied rules:
 * UnionTypesRector


14) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/Resolver/Labels.php:46

    ---------- begin diff ----------
@@ @@
      *
      * @param array|null $args
      *
-     * @return void
      *
      * @throws GraphQlInputException
      */
@@ @@
     /**
      * Get labels for product
      *
-     * @param array $labelIds
-     * @param int   $groupId
-     * @param int   $storeId
      *
-     * @return array
      */
     protected function _getLabels(array $labelIds, int $groupId, int $storeId): array
     {
    ----------- end diff -----------

Applied rules:
 * UnionTypesRector


15) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/Resolver/AbstractLabels.php:26

    ---------- begin diff ----------
@@ @@
     protected $_labelCollectionFactory;

     /**
-     * @param LabelRepositoryInterface $labelRepository
      * @param CollectionFactory        $labelCollectionFactory
      */
     public function __construct(
@@ @@
     /**
      * Get label by its id and format
      *
-     * @param int $labelId
-     * @param int $groupId
-     * @param int $storeId
      *
      * @return array
      */
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector


16) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/LabelRepository.php:46

    ---------- begin diff ----------
@@ @@
     /**
      * Get Label Ids From Product Ids
      *
-     * @param array $productIds
      *
-     * @return array
      */
     protected function _getLabelIdsByProducts(array $productIds): array
     {
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * UnionTypesRector


17) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Model/Label.php:29

    ---------- begin diff ----------
@@ @@
     /**
      * Cache tag
      */
-    const CACHE = 'wam_product_label';
+    final public const CACHE = 'wam_product_label';

     /**
      * Images Location
      */
-    const IMAGE_PATH = 'product_labels/uploads';
+    final public const IMAGE_PATH = 'product_labels/uploads';

     /**
      * {@inheritdoc}
@@ @@
      * @param Registry                  $registry
      * @param FormFactory               $formFactory
      * @param TimezoneInterface         $localeDate
-     * @param CatalogRuleCombineFactory $catalogRuleCombineFactory
-     * @param ProductCollectionFactory  $productCollectionFactory
      * @param ProductFactory            $productFactory
      * @param Iterator                  $iterator
      * @param StoreManagerInterface     $storeManager
      * @param AbstractResource|null     $resource
      * @param AbstractDb|null           $resourceCollection
-     * @param array                     $data
      */
     public function __construct(
         Context                   $context,
@@ @@
         $this->getConditions()->collectValidatedAttributes($productCollection);

         $this->_iterator->walk($productCollection->getSelect(), [
-            [
-                $this,
-                'callbackValidateProductCondition'
-            ]
+            $this->callbackValidateProductCondition(...)
         ], [
             'attributes' => $this->getCollectedAttributes(),
             'product' => $this->_productFactory->create(),
    ----------- end diff -----------

Applied rules:
 * PublicConstantVisibilityRector (https://wiki.php.net/rfc/class_const_visibility)
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * FirstClassCallableRector (https://php.watch/versions/8.1/first-class-callable-syntax)
 * FinalizePublicClassConstantRector (https://php.watch/versions/8.1/final-class-const)


18) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Helper/Config.php:13

    ---------- begin diff ----------
@@ @@
 {
     /**
      * Check if labels can be shown
-     *
-     * @return bool
      */
     public function isEnabled(): bool
     {
@@ @@

     /**
      * Get Max Height
-     *
-     * @return int
      */
     public function getMaxHeight(): int
     {
@@ @@

     /**
      * Get Max Width
-     *
-     * @return int
      */
     public function getMaxWidth(): int
     {
@@ @@

     /**
      * Get Label Limit
-     *
-     * @return int
      */
     public function getLimit(): int
     {
    ----------- end diff -----------

Applied rules:
 * UnionTypesRector


19) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Controller/Adminhtml/Labels/Save.php:135

    ---------- begin diff ----------
@@ @@
     /**
      * Check Image is uploaded
      *
-     * @param string $inputName
      *
-     * @return bool
      */
     protected function _isImageAttached(string $inputName): bool
     {
@@ @@
     /**
      * Upload Image
      *
-     * @param string $inputName
-     * @param string $path
      *
-     * @return string
      *
      * @throws \Exception
      */
@@ @@
      */
     public function validateDimensions($filePath)
     {
-        list(
-            $width,
-            $height
-        ) = getimagesize($filePath);
+        [$width, $height] = getimagesize($filePath);

         $maxWidth = $this->_config->getMaxWidth();
         $maxHeight = $this->_config->getMaxHeight();
    ----------- end diff -----------

Applied rules:
 * LongArrayToShortArrayRector
 * ListToArrayDestructRector (https://wiki.php.net/rfc/short_list_syntax https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring)
 * UnionTypesRector


20) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Controller/Adminhtml/Labels/NewConditionHtml.php:22

    ---------- begin diff ----------
@@ @@
     public function execute()
     {
         $id = $this->getRequest()->getParam('id');
-        $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
+        $typeArr = explode('|', str_replace('-', '/', (string) $this->getRequest()->getParam('type')));
         $type = $typeArr[0];

         $model = $this->_objectManager->create(
    ----------- end diff -----------

Applied rules:
 * NullToStrictStringFuncCallArgRector


21) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Controller/Adminhtml/AbstractAction.php:21

    ---------- begin diff ----------
@@ @@
  */
 abstract class AbstractAction extends Action
 {
-    const ACL_RESOURCE = 'WeAreMagneto_ProductLabel::labels';
+    final public const ACL_RESOURCE = 'WeAreMagneto_ProductLabel::labels';

-    const ADMIN_RESOURCE = 'WeAreMagneto_ProductLabel::labels';
+    final public const ADMIN_RESOURCE = 'WeAreMagneto_ProductLabel::labels';

     /**
      * @var ForwardFactory
@@ @@
      * @param Filesystem      $filesystem
      * @param UploaderFactory $uploaderFactory
      * @param Date            $dateFilter
-     * @param Config          $config
      */
     public function __construct(
         Context         $context,
    ----------- end diff -----------

Applied rules:
 * PublicConstantVisibilityRector (https://wiki.php.net/rfc/class_const_visibility)
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * FinalizePublicClassConstantRector (https://php.watch/versions/8.1/final-class-const)


22) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Console/ProductLabelCommand.php:40

    ---------- begin diff ----------
@@ @@
      *
      * @param State             $state
      * @param CollectionFactory $collectionFactory
-     * @param Labels            $labelService
      * @param string|null       $name
      */
     public function __construct(
@@ @@
         try {
             $this->_state->emulateAreaCode(
                 Area::AREA_ADMINHTML,
-                [$this, 'processProductLabels'],
+                $this->processProductLabels(...),
                 [$input, $output]
             );
             $output->writeln(PHP_EOL . '<info>Label Indexer Finished</info>');
@@ @@
     /**
      * Add Index for Labels
      *
-     * @param Label $label
      *
      * @return void
      */
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector
 * FirstClassCallableRector (https://php.watch/versions/8.1/first-class-callable-syntax)


23) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Block/Labels.php:72

    ---------- begin diff ----------
@@ @@
      *
      * @param Template\Context         $context
      * @param CollectionFactory        $labelCollectionFactory
-     * @param LabelRepositoryInterface $labelRepository
      * @param SessionFactory           $sessionFactory
-     * @param Config                   $config
      * @param Registry                 $registry
-     * @param array                    $data
      */
     public function __construct(
         Template\Context         $context,
@@ @@
      *
      * @return Label[]|Collection
      */
-    public function getLabels()
+    public function getLabels(): array|\WeAreMagneto\ProductLabel\Model\ResourceModel\Label\Collection
     {
         if (!$this->_labels) {
             $product = $this->getProduct();
@@ @@
      * Get Position Styles
      *
      * @param Label $label
-     *
-     * @return string
      */
     public function getPositionStyles($label): string
     {
-        switch ($label->getPosition()) {
-            case Positions::TOP_LEFT:
-                $style = 'position:absolute; top:0; left:0; z-index:1;';
-                break;
-            case Positions::TOP_MIDDLE:
-                $style = 'position:absolute; top:0; left:50%; transform:translateX(-50%); z-index:1;';
-                break;
-            case Positions::TOP_RIGHT:
-                $style = 'position:absolute; top:0; right:0; z-index:1;';
-                break;
-            case Positions::MIDDLE_LEFT:
-                $style = 'position:absolute; top:50%; left:0; transform:translateY(-50%); z-index:1;';
-                break;
-            case Positions::MIDDLE_RIGHT:
-                $style = 'position:absolute; top:50%; right:0; transform:translateY(-50%); z-index:1;';
-                break;
-            case Positions::BOTTOM_LEFT:
-                $style = 'position:absolute; bottom:0; left:0; z-index:1;';
-                break;
-            case Positions::BOTTOM_MIDDLE:
-                $style = 'position:absolute; bottom:0; left:50%; transform:translateX(-50%); z-index:1;';
-                break;
-            case Positions::BOTTOM_RIGHT:
-                $style = 'position:absolute; bottom:0; right:0; z-index:1;';
-                break;
-            default:
-                $style = '';
-        }
+        $style = match ($label->getPosition()) {
+            Positions::TOP_LEFT => 'position:absolute; top:0; left:0; z-index:1;',
+            Positions::TOP_MIDDLE => 'position:absolute; top:0; left:50%; transform:translateX(-50%); z-index:1;',
+            Positions::TOP_RIGHT => 'position:absolute; top:0; right:0; z-index:1;',
+            Positions::MIDDLE_LEFT => 'position:absolute; top:50%; left:0; transform:translateY(-50%); z-index:1;',
+            Positions::MIDDLE_RIGHT => 'position:absolute; top:50%; right:0; transform:translateY(-50%); z-index:1;',
+            Positions::BOTTOM_LEFT => 'position:absolute; bottom:0; left:0; z-index:1;',
+            Positions::BOTTOM_MIDDLE => 'position:absolute; bottom:0; left:50%; transform:translateX(-50%); z-index:1;',
+            Positions::BOTTOM_RIGHT => 'position:absolute; bottom:0; right:0; z-index:1;',
+            default => '',
+        };

         return $style;
     }
@@ @@

     /**
      * Get Customer Group Id
-     *
-     * @return int
      */
     protected function _getGroupId(): int
     {
@@ @@
                 /** @var Session $session */
                 $session = $this->_sessionFactory->create();
                 $this->_groupId = (int)$session->getCustomerGroupId();
-            } catch (\Exception $e) {
+            } catch (\Exception) {
                 $this->_groupId = 0;
             }
         }
@@ @@

     /**
      * Check if the customer is on the product page
-     *
-     * @return bool
      */
     protected function _isProductPage(): bool
     {
    ----------- end diff -----------

Applied rules:
 * RemoveUnusedVariableInCatchRector (https://wiki.php.net/rfc/non-capturing_catches)
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector
 * ChangeSwitchToMatchRector (https://wiki.php.net/rfc/match_expression_v2)


24) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Block/Adminhtml/Labels/Field/Position.php:99

    ---------- begin diff ----------
@@ @@
      * Get Position Element
      *
      * @param string $position
-     *
-     * @return string
      */
     protected function _getPositionElement($position): string
     {
    ----------- end diff -----------

Applied rules:
 * UnionTypesRector


25) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Block/Adminhtml/Labels/Edit/Tab/Main.php:65

    ---------- begin diff ----------
@@ @@
      * @param Registry          $registry
      * @param FormFactory       $formFactory
      * @param Store             $storeSource
-     * @param Source\Status     $statusSource
-     * @param Source\Type       $typeSource
-     * @param Source\Positions  $positionsSource
      * @param CollectionFactory $groupCollectionFactory
-     * @param Config            $config
-     * @param array             $data
      */
     public function __construct(
         Context            $context,
@@ @@

     /**
      * Get Customer Group Options
-     *
-     * @return array
      */
     protected function _getCustomerGroupOptions(): array
     {
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector


26) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Block/Adminhtml/Labels/Edit/Tab/Conditions.php:35

    ---------- begin diff ----------
@@ @@
      * @param Context        $context
      * @param Registry       $registry
      * @param FormFactory    $formFactory
-     * @param RuleConditions $conditions
      * @param Fieldset       $rendererFieldset
-     * @param array          $data
      */
     public function __construct(
         Context        $context,
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector


27) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Block/Adminhtml/Labels/Edit.php:24

    ---------- begin diff ----------
@@ @@
      *
      * @param Context  $context
      * @param Registry $registry
-     * @param array    $data
      */
     public function __construct(
         Context  $context,
@@ @@
     /**
      * Check permissions
      *
-     * @param string $resourceId
      *
-     * @return bool
      */
     protected function _isAllowedAction(string $resourceId): bool
     {
    ----------- end diff -----------

Applied rules:
 * ClassPropertyAssignToConstructorPromotionRector (https://wiki.php.net/rfc/constructor_promotion https://github.com/php/php-src/pull/5291)
 * MixedTypeRector
 * UnionTypesRector


28) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Api/LabelRepositoryInterface.php:21

    ---------- begin diff ----------
@@ @@
     /**
      * Get the Label Ids by the product ids
      *
-     * @param array $productIds
      *
      * @return array
      */
    ----------- end diff -----------

Applied rules:
 * MixedTypeRector


29) ../../var/www/html/wearemagneto/research-and-development/wamid-23-automated-refactoring/modules/magento2-module-product-label/Api/Data/LabelInterface.php:9

    ---------- begin diff ----------
@@ @@
  */
 interface LabelInterface
 {
-    const TABLE = 'wam_product_label';
+    public const TABLE = 'wam_product_label';

-    const STORE_TABLE = 'wam_product_label_store';
+    public const STORE_TABLE = 'wam_product_label_store';

-    const CUSTOMER_GROUP_TABLE = 'wam_product_label_customer_group';
+    public const CUSTOMER_GROUP_TABLE = 'wam_product_label_customer_group';

-    const INDEX_TABLE = 'wam_product_label_index';
+    public const INDEX_TABLE = 'wam_product_label_index';

-    const LABEL_ID = 'label_id';
+    public const LABEL_ID = 'label_id';

-    const NAME = 'name';
+    public const NAME = 'name';

-    const CONDITION_SERIALIZED = 'conditions_serialized';
+    public const CONDITION_SERIALIZED = 'conditions_serialized';

-    const LABEL_TYPE = 'label_type';
+    public const LABEL_TYPE = 'label_type';

-    const LABEL_IMAGE_CATEGORY = 'label_image_category';
+    public const LABEL_IMAGE_CATEGORY = 'label_image_category';

-    const LABEL_IMAGE_PRODUCT = 'label_image_product';
+    public const LABEL_IMAGE_PRODUCT = 'label_image_product';

-    const LABEL_TEXT = 'label_text';
+    public const LABEL_TEXT = 'label_text';

-    const LABEL_CSS = 'label_css';
+    public const LABEL_CSS = 'label_css';

-    const LABEL_URL = 'label_url';
+    public const LABEL_URL = 'label_url';

-    const POSITION = 'position';
+    public const POSITION = 'position';

-    const STATUS = 'status';
+    public const STATUS = 'status';

-    const SORT_ORDER = 'sort_order';
+    public const SORT_ORDER = 'sort_order';

-    const FROM_DATE = 'from_date';
+    public const FROM_DATE = 'from_date';

-    const TO_DATE = 'to_date';
+    public const TO_DATE = 'to_date';

-    const CREATED_AT = 'created_at';
+    public const CREATED_AT = 'created_at';

-    const UPDATED_AT = 'updated_at';
+    public const UPDATED_AT = 'updated_at';

-    const TYPE_IMAGE = 0;
+    public const TYPE_IMAGE = 0;

-    const TYPE_TEXT = 1;
+    public const TYPE_TEXT = 1;

-    const STATUS_DISABLED = 0;
+    public const STATUS_DISABLED = 0;

-    const STATUS_ENABLED = 1;
+    public const STATUS_ENABLED = 1;

     /**
      * Get Name
@@ @@
     /**
      * Set an extension attributes object.
      *
-     * @param \WeAreMagneto\ProductLabel\Api\Data\LabelExtensionInterface $extensionAttributes
      *
      * @return $this
      */
    ----------- end diff -----------

Applied rules:
 * PublicConstantVisibilityRector (https://wiki.php.net/rfc/class_const_visibility)
 * MixedTypeRector


                                                                                                                        
 [OK] 29 files have been changed by Rector                                                                              
@MagePsycho
Copy link

Do you mind sharing the rector.php file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment