Skip to content

Commit

Permalink
Add synthesizer for Livewire (#7)
Browse files Browse the repository at this point in the history
* Add synthesizer for Livewire

* Convert to string instead of an integer

* Change namespace and add generic synth

* Code style

---------

Co-authored-by: Chris Morrell <[email protected]>
  • Loading branch information
gehrisandro and inxilpro authored Jul 10, 2024
1 parent dbe3b4a commit 7380ab2
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,34 @@ $example->id instanceof Snowflake; // true
echo $example->id; // 65898467809951744
```

### Usage with Livewire

If you're using Livewire, you can use the `SnowflakeSynth` synthesizer to
make Snowflakes usable in your components.

All you need to do is to register the synthesizer in your `AppServiceProvider`:

```php
use Glhd\Bits\Support\Livewire\SnowflakeSynth;
use Glhd\Bits\Support\Livewire\BitsSynth;

class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// If only using Snowflakes:
Livewire::propertySynthesizer(SnowflakeSynth::class);

// If using Sonyflakes or a custom Bits variant:
Livewire::propertySynthesizer(BitsSynth::class);
}
}
```

If you're using a non-Snowflake variant of Bits, you can use the `BitsSynth`
instead, which supports any version of Bits at the cost of storing a little
more data.

## About 64-bit Unique IDs

### Snowflake format
Expand Down
31 changes: 31 additions & 0 deletions src/Support/Livewire/BitsSynth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Glhd\Bits\Support\Livewire;

use Glhd\Bits\Bits;
use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;

class BitsSynth extends Synth
{
public static string $key = 'bits';

public static function match($target)
{
return $target instanceof Bits;
}

/** @var Bits $target */
public function dehydrate($target)
{
return [$target->jsonSerialize(), ['class' => $target::class]];
}

/**
* @param string $value
* @param array{ class: class-string<Bits> } $meta
*/
public function hydrate($value, $meta)
{
return $meta['class']::fromId($value);
}
}
27 changes: 27 additions & 0 deletions src/Support/Livewire/SnowflakeSynth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Glhd\Bits\Support\Livewire;

use Glhd\Bits\Snowflake;
use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;

class SnowflakeSynth extends Synth
{
public static string $key = 'snowflake';

public static function match($target)
{
return $target instanceof Snowflake;
}

/** @var Snowflake $target */
public function dehydrate($target)
{
return [$target->jsonSerialize(), []];
}

public function hydrate($value)
{
return Snowflake::fromId($value);
}
}

0 comments on commit 7380ab2

Please sign in to comment.