Skip to content

Commit

Permalink
Fix conversion of Enum::fromKey() to native enum
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed Sep 26, 2023
1 parent cab2e22 commit caa3ebd
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

## 6.6.4

### Fixed

- Fix conversion of `Enum::fromKey()` to native enum

## 6.6.3

### Fixed
Expand Down
10 changes: 8 additions & 2 deletions src/Rector/ToNativeUsagesRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use BenSampo\Enum\Enum;
use BenSampo\Enum\Tests\Enums\UserType;
use Illuminate\Support\Arr;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
Expand Down Expand Up @@ -41,7 +42,6 @@
use PhpParser\Node\Param;
use PhpParser\Node\Scalar\Encapsed;
use PhpParser\Node\Scalar\EncapsedStringPart;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
Expand Down Expand Up @@ -291,7 +291,13 @@ protected function refactorFromKey(StaticCall $call): ?Node
],
);

return new ArrayDimFetch($arrayMatching, new LNumber(0));
return new StaticCall(
new Name(Arr::class),
'first',
[
new Arg($arrayMatching),
],
);
};

if ($call->isFirstClassCallable()) {
Expand Down
4 changes: 2 additions & 2 deletions tests/Rector/Usages/fromKey.php.inc
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ UserType::fromKey(...);

use BenSampo\Enum\Tests\Enums\UserType;

array_filter(UserType::cases(), fn(UserType $userType): bool => $userType->name === 'foo')[0];
static fn(string $key): UserType => array_filter(UserType::cases(), fn(UserType $userType): bool => $userType->name === $key)[0];
Illuminate\Support\Arr::first(array_filter(UserType::cases(), fn(UserType $userType): bool => $userType->name === 'foo'));
static fn(string $key): UserType => Illuminate\Support\Arr::first(array_filter(UserType::cases(), fn(UserType $userType): bool => $userType->name === $key));

0 comments on commit caa3ebd

Please sign in to comment.