Skip to content

Commit

Permalink
Merge pull request #103 from macbookandrew/feature/livewire-wirable
Browse files Browse the repository at this point in the history
add optional wirable support to enums
  • Loading branch information
freekmurze authored Jun 12, 2024
2 parents 8e328b6 + 75d2d2d commit 848d8ab
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,41 @@ The static `register()` method is only a little helper - you can for sure regist

The faker methods itself are inherited from the base packages [Faker Provider](https://github.com/spatie/enum#faker-provider).

### Livewire

You can use an enum as a property on a Livewire component like this:

```php
class ShowCustomer extends Component
{
public StatusEnum $statusEnum;

public function mount($id)
{
$customer = Customer::find($id);
$this->statusEnum = $customer->status;
}

public function render()
{
return view('livewire.customer');
}
}
```

Just one thing is required to make this work: implement `\Livewire\Wireable` on all the enums you’ll be using with Livewire::

```php
use Livewire\Wireable;

/**
* @method static self pending()
* @method static self active()
*/
final class StatusEnum implements Wireable
{}
```

## Testing

```bash
Expand Down
17 changes: 17 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ public static function toRule(): EnumRule
return new EnumRule(static::class);
}

public static function fromLivewire($enum): self
{
if (is_a($enum, self::class)) {
return $enum;
}

return self::from($enum['value']);
}

public function toLivewire(): mixed

Check failure on line 38 in src/Enum.php

View workflow job for this annotation

GitHub Actions / psalm

ReservedWord

src/Enum.php:38:35: ReservedWord: mixed is a reserved word (see https://psalm.dev/095)
{
return [
'value' => $this->value,
'label' => $this->label,
];
}

public function toJson($options = 0): string
{
return json_encode($this->jsonSerialize(), $options);
Expand Down
18 changes: 18 additions & 0 deletions tests/WireableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Spatie\Enum\Laravel\Tests;

use Spatie\Enum\Laravel\Tests\Extra\StatusEnum;

final class WireableTest extends TestCase
{
/** @test */
public function it_can_be_cast_to_and_from_livewire()
{
$enum = StatusEnum::draft();

$castEnum = StatusEnum::fromLivewire($enum->toLivewire());

$this->assertTrue($castEnum->equals($enum));
}
}

0 comments on commit 848d8ab

Please sign in to comment.