[php-src] Issue #12863: BackedEnum::from() and BackedEnum::tryFrom() incorrect param typing
| From: | jack-worman | Date: | Sun, 03 Dec 2023 23:02:19 +0000 |
| Subject: | [php-src] Issue #12863: BackedEnum::from() and BackedEnum::tryFrom() incorrect param typing | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-245970@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/12863
Author: jack-worman
### Description
The following code (https://3v4l.org/o5uHL#v8.3.0):
```php
<?php
declare(strict_types=1);
enum IntBacked: int {
case One = 1;
}
var_export(IntBacked::tryFrom('bogus'));
```
Resulted in this output:
```
Fatal error: Uncaught TypeError: IntBacked::tryFrom(): Argument #1 ($value) must be of type int,
string given in /in/XN86X:9
Stack trace:
#0 /in/XN86X(9): IntBacked::tryFrom('bogus')
#1 {main}
thrown in /in/XN86X on line 9
Process exited with code 255.
```
But I expected this output instead:
```
NULL
```
# Explanation:
The typing for BackedEnum is declared as:
```php
interface BackedEnum extends UnitEnum
{
public static function from(int|string $value): static;
public static function tryFrom(int|string $value): ?static;
}
```
but this is clearly wrong because int backed enums only allow int
$value's and
string backed enums only allow string $value's.
I think the real typing should match BackedEnum exactly. I don't see the downside
in doing this.
Example expected behavior:
```php
<?php
declare(strict_types=1);
enum IntBacked: int {
case One = 1;
}
enum StringBacked: string {
case One = 'one';
}
var_export(IntBacked::from(1)); // IntBacked::One
var_export(IntBacked::from('1')); // Fatal error: Uncaught ValueError: "1" is
not a valid backing value for enum "IntBacked"
var_export(IntBacked::from('bogus')); // Fatal error: Uncaught ValueError:
"bogus" is not a valid backing value for enum "IntBacked"
var_export(IntBacked::tryFrom(1)); // IntBacked::One
var_export(IntBacked::tryFrom('1')); // NULL
var_export(IntBacked::tryFrom('bogus')); // NULL
```
### PHP Version
>= 8.1.0
### Operating System
_No response_