Skip to content

[4.x] Rector Updates #3900

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
uses: craftcms/.github/.github/workflows/ci.yml@v3
with:
craft_version: '4'
jobs: '["ecs", "phpstan", "prettier", "tests"]'
jobs: '["ecs", "phpstan", "prettier", "tests", "rector"]'
notify_slack: true
slack_subteam: <!subteam^S01CWPYH9D5>
secrets:
Expand Down
29 changes: 15 additions & 14 deletions rector.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
<?php
// rector.php
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function(ContainerConfigurator $containerConfigurator): void {
// $containerConfigurator->import(SetList::CODE_QUALITY);
declare(strict_types=1);

// register single rule
$services = $containerConfigurator->services();
// $containerConfigurator->import(SetList::PHP_80);
$services->set(\Rector\Php80\Rector\FunctionLike\UnionTypesRector::class);
$services->set(\Rector\Php80\Rector\NotIdentical\StrContainsRector::class);
$services->set(\Rector\Php80\Rector\Identical\StrStartsWithRector::class);
$services->set(\Rector\Php80\Rector\Identical\StrEndsWithRector::class);
$services->set(\Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector::class);
};
use Rector\Config\RectorConfig;

return RectorConfig::configure()
->withPaths([
__DIR__ . '/src',
__DIR__ . '/tests/unit',
])
->withSkip([
Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector::class => [
__DIR__ . '/src/console/controllers/GatewaysController.php',
],
Rector\Php80\Rector\Class_\StringableForToStringRector::class,
])
->withPhpSets(php80: true);
4 changes: 1 addition & 3 deletions src/base/Stat.php
Original file line number Diff line number Diff line change
Expand Up @@ -428,9 +428,7 @@ public function getOrderStatuses(): ?array
continue;
}

$orderStatus = ArrayHelper::firstWhere($allOrderStatuses, function(OrderStatus $os) use ($orderStatus) {
return $orderStatus === $os->handle || $orderStatus === $os->uid;
});
$orderStatus = ArrayHelper::firstWhere($allOrderStatuses, fn(OrderStatus $os) => $orderStatus === $os->handle || $orderStatus === $os->uid);
if (!$orderStatus) {
unset($this->_orderStatuses[$key]);
continue;
Expand Down
2 changes: 1 addition & 1 deletion src/base/Zone.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ abstract class Zone extends BaseModel implements ZoneInterface
/**
* @var ?ZoneAddressCondition
*/
private ?ZoneAddressCondition $_condition;
private ?ZoneAddressCondition $_condition = null;

abstract public function getCpEditUrl(): string;

Expand Down
16 changes: 7 additions & 9 deletions src/console/controllers/UpgradeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,12 @@ public function actionRun(): int
->all();

// Filter out the address columns we don't need to migrate to custom fields
$this->neededCustomAddressFields = array_filter($this->neededCustomAddressFields, static function($fieldHandle) {
return (new Query())
->select($fieldHandle)
->where(['not', [$fieldHandle => null]])
->andWhere(['not', [$fieldHandle => '']])
->from(['{{%commerce_addresses}}'])
->exists();
}, ARRAY_FILTER_USE_KEY);
$this->neededCustomAddressFields = array_filter($this->neededCustomAddressFields, static fn($fieldHandle) => (new Query())
->select($fieldHandle)
->where(['not', [$fieldHandle => null]])
->andWhere(['not', [$fieldHandle => '']])
->from(['{{%commerce_addresses}}'])
->exists(), ARRAY_FILTER_USE_KEY);

$startTime = DateTimeHelper::currentUTCDateTime();

Expand Down Expand Up @@ -395,7 +393,7 @@ private function _migrateAddressCustomFields(): void
$firstTab = $this->_addressFieldLayout->getTabs()[0];
$layoutElements = $firstTab->getElements();

$list = implode(array_map(fn($label) => " - $label\n", $this->neededCustomAddressFields));
$list = implode('', array_map(fn($label) => " - $label\n", $this->neededCustomAddressFields));
$this->stdout(<<<EOL
Customer and order addresses will be migrated to native Craft address elements.
Some of the existing addresses contain data that will need to be stored in custom fields:
Expand Down
21 changes: 7 additions & 14 deletions src/controllers/DiscountsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
use yii\web\HttpException;
use yii\web\Response;
use function explode;
use function get_class;

/**
* Class Discounts Controller
Expand Down Expand Up @@ -459,17 +458,11 @@ public function actionClearDiscountUses(): Response
return $this->asFailure(Craft::t('commerce', 'Type not in allowed options.'));
}

switch ($type) {
case self::DISCOUNT_COUNTER_TYPE_EMAIL:
Plugin::getInstance()->getDiscounts()->clearEmailUsageHistoryById($id);
break;
case self::DISCOUNT_COUNTER_TYPE_CUSTOMER:
Plugin::getInstance()->getDiscounts()->clearCustomerUsageHistoryById($id);
break;
case self::DISCOUNT_COUNTER_TYPE_TOTAL:
Plugin::getInstance()->getDiscounts()->clearDiscountUsesById($id);
break;
}
match ($type) {
self::DISCOUNT_COUNTER_TYPE_EMAIL => Plugin::getInstance()->getDiscounts()->clearEmailUsageHistoryById($id),
self::DISCOUNT_COUNTER_TYPE_CUSTOMER => Plugin::getInstance()->getDiscounts()->clearCustomerUsageHistoryById($id),
self::DISCOUNT_COUNTER_TYPE_TOTAL => Plugin::getInstance()->getDiscounts()->clearDiscountUsesById($id),
};

return $this->asSuccess();
}
Expand Down Expand Up @@ -678,8 +671,8 @@ private function _populateVariables(array &$variables): void
foreach ($purchasableIds as $purchasableId) {
$purchasable = Craft::$app->getElements()->getElementById((int)$purchasableId);
if ($purchasable instanceof PurchasableInterface) {
$class = get_class($purchasable);
$purchasables[$class] = $purchasables[$class] ?? [];
$class = $purchasable::class;
$purchasables[$class] ??= [];
$purchasables[$class][] = $purchasable;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/controllers/GatewaysController.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,15 @@ public function actionEdit(int $id = null, ?GatewayInterface $gateway = null): R
$allGatewayTypes = $gatewayService->getAllGatewayTypes();

// Make sure the selected gateway class is in there
if ($gateway && !in_array(get_class($gateway), $allGatewayTypes, true)) {
$allGatewayTypes[] = get_class($gateway);
if ($gateway && !in_array($gateway::class, $allGatewayTypes, true)) {
$allGatewayTypes[] = $gateway::class;
}

$gatewayInstances = [];
$gatewayOptions = [];

foreach ($allGatewayTypes as $class) {
if (($gateway && $class === get_class($gateway)) || $class::isSelectable()) {
if (($gateway && $class === $gateway::class) || $class::isSelectable()) {
$gatewayInstances[$class] = $gatewayService->createGateway($class);

$gatewayOptions[] = [
Expand Down
16 changes: 5 additions & 11 deletions src/controllers/OrdersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -613,9 +613,7 @@ public function actionCustomerSearch(): Response
$userQuery->search(urldecode($query));
}

$customers = $userQuery->collect()->map(function(User $user) {
return $this->_customerToArray($user);
});
$customers = $userQuery->collect()->map(fn(User $user) => $this->_customerToArray($user));

return $this->asSuccess(data: compact('customers'));
}
Expand Down Expand Up @@ -648,11 +646,9 @@ public function actionGetCustomerAddresses(): Response

$total = $addressElements->count();

$addresses = $addressElements->map(function(Address $address) {
return $address->toArray() + [
'html' => Cp::addressCardHtml(address: $address),
];
});
$addresses = $addressElements->map(fn(Address $address) => $address->toArray() + [
'html' => Cp::addressCardHtml(address: $address),
]);

return $this->asSuccess(data: compact('addresses', 'total'));
}
Expand Down Expand Up @@ -849,9 +845,7 @@ public function actionGetIndexSourcesBadgeCounts(): Response

$counts = Plugin::getInstance()->getOrderStatuses()->getOrderCountByStatus();

$total = array_reduce($counts, static function($sum, $thing) {
return $sum + (int)$thing['orderCount'];
}, 0);
$total = array_reduce($counts, static fn($sum, $thing) => $sum + (int)$thing['orderCount'], 0);

return $this->asSuccess(data: compact('counts', 'total'));
}
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/PaymentsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ public function actionPay(): ?Response

// Last line of try block we have a successful payment source creation
$sourceCreated = true;
} catch (PaymentSourceCreatedLaterException $exception) {
} catch (PaymentSourceCreatedLaterException) {
if (property_exists($paymentForm, 'paymentSource')) {
$paymentForm->savePaymentSource = true;
}
Expand Down
5 changes: 2 additions & 3 deletions src/controllers/SalesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
use yii\web\HttpException;
use yii\web\Response;
use function explode;
use function get_class;

/**
* Class Sales Controller
Expand Down Expand Up @@ -525,8 +524,8 @@ private function _populateVariables(&$variables): void
foreach ($purchasableIds as $purchasableId) {
$purchasable = Craft::$app->getElements()->getElementById((int)$purchasableId);
if ($purchasable instanceof PurchasableInterface) {
$class = get_class($purchasable);
$purchasables[$class] = $purchasables[$class] ?? [];
$class = $purchasable::class;
$purchasables[$class] ??= [];
$purchasables[$class][] = $purchasable;
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/controllers/ShippingCategoriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ public function actionEdit(int $id = null, ShippingCategory $shippingCategory =

$variables['productTypesOptions'] = [];
if (!empty($variables['productTypes'])) {
$variables['productTypesOptions'] = ArrayHelper::map($variables['productTypes'], 'id', function($row) {
return ['label' => $row->name, 'value' => $row->id];
});
$variables['productTypesOptions'] = ArrayHelper::map($variables['productTypes'], 'id', fn($row) => ['label' => $row->name, 'value' => $row->id]);
}

$allShippingCategoryIds = ArrayHelper::getColumn(Plugin::getInstance()->getShippingCategories()->getAllShippingCategories(), 'id');
Expand Down
4 changes: 1 addition & 3 deletions src/controllers/TaxCategoriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ public function actionEdit(int $id = null, TaxCategory $taxCategory = null): Res

$variables['productTypesOptions'] = [];
if (!empty($variables['productTypes'])) {
$variables['productTypesOptions'] = ArrayHelper::map($variables['productTypes'], 'id', function($row) {
return ['label' => $row->name, 'value' => $row->id];
});
$variables['productTypesOptions'] = ArrayHelper::map($variables['productTypes'], 'id', fn($row) => ['label' => $row->name, 'value' => $row->id]);
}

$allTaxCategoryIds = array_keys(Plugin::getInstance()->getTaxCategories()->getAllTaxCategories());
Expand Down
4 changes: 1 addition & 3 deletions src/controllers/TaxRatesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,7 @@ public function actionEdit(int $id = null, TaxRate $taxRate = null): Response
$productTypes = Plugin::getInstance()->getProductTypes()->getAllProductTypes();
$productTypesOptions = [];
if (!empty($productTypes)) {
$productTypesOptions = ArrayHelper::map($productTypes, 'id', function(ProductType $row) {
return ['label' => $row->name, 'value' => $row->id];
});
$productTypesOptions = ArrayHelper::map($productTypes, 'id', fn(ProductType $row) => ['label' => $row->name, 'value' => $row->id]);
}
$variables['newTaxCategoryFields'] = $view->namespaceInputs(
$view->renderTemplate('commerce/tax/taxcategories/_fields', compact('productTypes', 'productTypesOptions'))
Expand Down
5 changes: 2 additions & 3 deletions src/elements/Donation.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ protected function defineRules(): array

$rules[] = [['sku'], 'trim'];
$rules[] = [
['sku'], 'required', 'when' => function($model) {
['sku'], 'required', 'when' => fn($model) =>
/** @var self $model */
return $model->availableForPurchase && $model->enabled;
},
$model->availableForPurchase && $model->enabled,
];

return $rules;
Expand Down
22 changes: 7 additions & 15 deletions src/elements/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -1475,10 +1475,9 @@ protected function defineRules(): array
// Are the addresses both being set to each other.
[
['billingAddress', 'shippingAddress'], 'validateAddressReuse',
'when' => function($model) {
'when' => fn($model) =>
/** @var Order $model */
return !$model->isCompleted;
},
!$model->isCompleted,
],

// Line items are valid?
Expand Down Expand Up @@ -2583,13 +2582,9 @@ public function getTotalPaid(): float
$this->_transactions = Plugin::getInstance()->getTransactions()->getAllTransactionsByOrderId($this->id);
}

$paidTransactions = ArrayHelper::where($this->_transactions, static function(Transaction $transaction) {
return $transaction->status == TransactionRecord::STATUS_SUCCESS && ($transaction->type == TransactionRecord::TYPE_PURCHASE || $transaction->type == TransactionRecord::TYPE_CAPTURE);
});
$paidTransactions = ArrayHelper::where($this->_transactions, static fn(Transaction $transaction) => $transaction->status == TransactionRecord::STATUS_SUCCESS && ($transaction->type == TransactionRecord::TYPE_PURCHASE || $transaction->type == TransactionRecord::TYPE_CAPTURE));

$refundedTransactions = ArrayHelper::where($this->_transactions, static function(Transaction $transaction) {
return $transaction->status == TransactionRecord::STATUS_SUCCESS && $transaction->type == TransactionRecord::TYPE_REFUND;
});
$refundedTransactions = ArrayHelper::where($this->_transactions, static fn(Transaction $transaction) => $transaction->status == TransactionRecord::STATUS_SUCCESS && $transaction->type == TransactionRecord::TYPE_REFUND);

$paid = array_sum(ArrayHelper::getColumn($paidTransactions, 'amount', false));
$refunded = array_sum(ArrayHelper::getColumn($refundedTransactions, 'amount', false));
Expand Down Expand Up @@ -3063,10 +3058,9 @@ public function removeBillingAddress(): void
public function hasMatchingAddresses(?array $attributes = null): bool
{
$addressAttributes = (new ReflectionClass(AddressInterface::class))->getMethods();
$addressAttributes = array_map(static function(ReflectionMethod $method) {
$addressAttributes = array_map(static fn(ReflectionMethod $method) =>
// Remove `get` and lower case first character
return lcfirst(substr($method->name, 3));
}, $addressAttributes);
lcfirst(substr($method->name, 3)), $addressAttributes);

$relationCustomFieldHandles = [];
$customFieldHandles = array_map(static function(FieldInterface $field) use (&$relationCustomFieldHandles) {
Expand All @@ -3077,9 +3071,7 @@ public function hasMatchingAddresses(?array $attributes = null): bool
return $field->handle;
}, (new AddressElement())->getFieldLayout()->getCustomFields());

$nameTraitProperties = array_map(static function(ReflectionProperty $property) {
return $property->name;
}, (new ReflectionClass(NameTrait::class))->getProperties());
$nameTraitProperties = array_map(static fn(ReflectionProperty $property) => $property->name, (new ReflectionClass(NameTrait::class))->getProperties());

$toArrayHandles = [...$nameTraitProperties, ...$addressAttributes, ...$customFieldHandles];

Expand Down
15 changes: 5 additions & 10 deletions src/elements/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -745,15 +745,10 @@ protected static function defineSortOptions(): array
*/
protected static function prepElementQueryForTableAttribute(ElementQueryInterface $elementQuery, string $attribute): void
{
switch ($attribute) {
case 'subscriber':
$elementQuery->andWith('subscriber');
break;
case 'orderLink':
$elementQuery->andWith('order');
break;
default:
parent::prepElementQueryForTableAttribute($elementQuery, $attribute);
}
match ($attribute) {
'subscriber' => $elementQuery->andWith('subscriber'),
'orderLink' => $elementQuery->andWith('order'),
default => parent::prepElementQueryForTableAttribute($elementQuery, $attribute),
};
}
}
5 changes: 2 additions & 3 deletions src/elements/Variant.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,10 +367,9 @@ protected function defineRules(): array
[
['stock'],
'required',
'when' => static function($model) {
'when' => static fn($model) =>
/** @var Variant $model */
return !$model->hasUnlimitedStock;
},
!$model->hasUnlimitedStock,
'on' => self::SCENARIO_LIVE,
],
[['stock'], 'number'],
Expand Down
4 changes: 1 addition & 3 deletions src/elements/conditions/orders/OrderStatusConditionRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ public function modifyQuery(ElementQueryInterface $query): void
$orderStatuses = Plugin::getInstance()->getOrderStatuses()->getAllOrderStatuses();

/** @var OrderQuery $query */
$query->orderStatus($this->paramValue(function(string $value) use ($orderStatuses) {
return ArrayHelper::firstWhere($orderStatuses, 'uid', $value)?->handle;
}));
$query->orderStatus($this->paramValue(fn(string $value) => ArrayHelper::firstWhere($orderStatuses, 'uid', $value)?->handle));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ public function modifyQuery(ElementQueryInterface $query): void
$productTypes = Plugin::getInstance()->getProductTypes()->getAllProductTypes();

/** @var string[] $value */
$value = $this->paramValue(function(string $value) use ($productTypes) {
return ArrayHelper::firstWhere($productTypes, 'uid', $value)?->handle;
});
$value = $this->paramValue(fn(string $value) => ArrayHelper::firstWhere($productTypes, 'uid', $value)?->handle);

/** @var ProductQuery $query */
$query->type($value);
Expand Down
Loading
Loading