feat: add entries() method (#3)

* feat: add entries() method

* feat(doc): add Enum::entries() to README
This commit is contained in:
Victor Westerlund 2023-10-09 13:32:07 +02:00 committed by GitHub
parent 166f8faf95
commit 99b784841e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 17 deletions

1
.gitignore vendored
View file

@ -5,6 +5,7 @@
/public/storage
/storage/*.key
/vendor
bin
.env
.env.backup
.phpunit.result.cache

View file

@ -22,6 +22,28 @@ HelloWorld::fromName("FOO"); // HelloWorld::FOO
HelloWorld::tryFromName("MOM"); // null
```
# How to use
Requires PHP 8.0 or newer
1. **Install from composer**
```
composer require victorwesterlund/xenum
```
2. **`use` in your project**
```php
use \victorwesterlund\xEnum;
```
3. **`use` with your Enums**
```php
enum HelloWorld {
use xEnum;
}
```
# Methods
All methods implemented by this library
@ -32,6 +54,7 @@ Method
[Enum::tryFromName(int\|string\|null): static\|null](#enumtryfromname)
[Enum::names(): array](#enumnames)
[Enum::values(): array](#enumvalues)
[Enum::entries(): array](#enumentries)
## Enum::fromName()
@ -107,7 +130,7 @@ HelloWorld::names(); // ["FOO", "BAZ"]
Return sequential array of Enum case values
```php
Enum::values(): array
Enum::entries(): array
```
Example:
@ -123,23 +146,23 @@ enum HelloWorld: string {
HelloWorld::values(); // ["BAR", "QUX"]
```
# How to use
## Enum::entries()
Requires PHP 8.0 or newer
Return an associative array of Enum names and values. This method is similar to [JavaScript's Object.entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
1. **Install from composer**
```
composer require victorwesterlund/xenum
```
```php
Enum::entries(): array
```
2. **`use` in your project**
```php
use \victorwesterlund\xEnum;
```
Example:
3. **`use` with your Enums**
```php
enum HelloWorld {
```php
enum HelloWorld: string {
use xEnum;
}
```
case FOO = "BAR";
case BAZ = "QUX";
}
HelloWorld::entries(); // ["FOO" => "BAR", "BAZ" => "QUX"]
```

View file

@ -35,4 +35,9 @@
public static function values(): array {
return array_column(self::cases(), "value");
}
// Return assoc array of enum names and values
public static function entries(): array {
return array_combine(self::names(), self::values());
}
}