Skip to content

Commit

Permalink
Better migration for new verbs_snapshot table (#153)
Browse files Browse the repository at this point in the history
* Better migration for new verbs_snapshot table

* Fix styling
  • Loading branch information
inxilpro authored Jul 24, 2024
1 parent 3a83969 commit fe50ea4
Show file tree
Hide file tree
Showing 30 changed files with 126 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public function up()
{
// If they've already migrated under the previous migration name, just skip
if (Schema::hasTable($this->tableName())) {
throw new RuntimeException('The create_verbs_* migrations have been renamed. See <https://verbs.thunk.dev/docs/reference/upgrading>');
return;
}

Schema::create($this->tableName(), function (Blueprint $table) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
<?php

use Glhd\Bits\Contracts\MakesSnowflakes;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Thunk\Verbs\Facades\Id;

return new class extends Migration
{
public function up()
{
// If they've already migrated under the previous migration name, just skip
if (Schema::hasTable($this->tableName())) {
throw new RuntimeException('The create_verbs_* migrations have been renamed. See <https://verbs.thunk.dev/docs/reference/upgrading>');
// If we migrated before Verbs 0.5.0 we need to do a little extra work
$migrating = Schema::hasTable($this->tableName());

return;
if ($migrating) {
Schema::rename($this->tableName(), '__verbs_snapshots_pre_050');
}

Schema::create($this->tableName(), function (Blueprint $table) {
Expand All @@ -33,11 +37,37 @@ public function up()

$table->index(['state_id', 'type']);
});

if ($migrating) {
DB::table('__verbs_snapshots_pre_050')
->select('*')
->chunkById(100, $this->migrateChunk(...));
}
}

public function down()
{
Schema::dropIfExists($this->tableName());

if (Schema::hasTable('__verbs_snapshots_pre_050')) {
Schema::rename('__verbs_snapshots_pre_050', $this->tableName());
}
}

protected function migrateChunk(Collection $chunk): void
{
$rows = $chunk->map(fn ($row) => [
'id' => app(MakesSnowflakes::class)->makeFromTimestamp(Date::parse($row->created_at))->id(),
'type' => $row->type,
'state_id' => $row->id,
'data' => $row->data,
'last_event_id' => $row->last_event_id,
'expires_at' => null,
'created_at' => $row->created_at,
'updated_at' => $row->updated_at,
]);

DB::table($this->tableName())->insert($rows->toArray());
}

protected function tableName(): string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public function up()
{
// If they've already migrated under the previous migration name, just skip
if (Schema::hasTable($this->tableName())) {
throw new RuntimeException('The create_verbs_* migrations have been renamed. See <https://verbs.thunk.dev/docs/reference/upgrading>');
return;
}

Schema::create($this->tableName(), function (Blueprint $table) {
Expand Down
4 changes: 2 additions & 2 deletions examples/Monopoly/src/Events/Setup/GameStarted.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function applyToGame(GameState $game)
$game->started = true;
$game->started_at = now()->toImmutable();
$game->player_ids = [];
$game->board = new Board();
$game->bank = new Bank();
$game->board = new Board;
$game->bank = new Bank;
}
}
2 changes: 1 addition & 1 deletion examples/Monopoly/src/Game/Spaces/Space.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ abstract class Space implements SerializedByVerbs

public static function instance(): static
{
return self::$instances[static::class] ?? new static();
return self::$instances[static::class] ?? new static;
}

public function __construct()
Expand Down
2 changes: 1 addition & 1 deletion examples/Monopoly/tests/MonopolyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
$player1_id = snowflake_id();
$player2_id = snowflake_id();

$game_state = verb(new GameStarted())->state(GameState::class);
$game_state = verb(new GameStarted)->state(GameState::class);

expect($game_state->started)->toBeTrue()
->and($game_state->board->spaces->count())->toBe(40)
Expand Down
2 changes: 1 addition & 1 deletion src/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function states(): StateCollection
{
// TODO: This is a bit hacky, but is probably OK right now

static $map = new WeakMap();
static $map = new WeakMap;

return $map[$this] ??= app(EventStateRegistry::class)->getStates($this);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Lifecycle/EventStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ protected function readEvents(
/** @param Event[] $events */
protected function guardAgainstConcurrentWrites(array $events): void
{
$max_event_ids = new Collection();
$max_event_ids = new Collection;

$query = VerbStateEvent::query()->toBase();

Expand Down
4 changes: 2 additions & 2 deletions src/Lifecycle/Guards.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ public function authorize(): static
$this->event->failedAuthorization($this->state);
}

throw new AuthorizationException();
throw new AuthorizationException;
}

public function validate(): static
{
$exception = new EventNotValidForCurrentState();
$exception = new EventNotValidForCurrentState;

try {
if ($this->passesValidation()) {
Expand Down
2 changes: 1 addition & 1 deletion src/Lifecycle/Hook.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function __construct(
public Closure $callback,
public array $events = [],
public array $states = [],
public SplObjectStorage $phases = new SplObjectStorage(),
public SplObjectStorage $phases = new SplObjectStorage,
public ?string $name = null,
) {}

Expand Down
10 changes: 5 additions & 5 deletions src/Lifecycle/MetadataManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ class MetadataManager

public function __construct()
{
$this->ephemeral = new WeakMap();
$this->persistent = new WeakMap();
$this->ephemeral = new WeakMap;
$this->persistent = new WeakMap;
}

public function createMetadataUsing(?callable $callback = null): void
Expand All @@ -41,12 +41,12 @@ public function setLastResults(Event $event, Collection $results): static

public function getLastResults(Event $event): Collection
{
return $this->getEphemeral($event, '_last_results', new Collection());
return $this->getEphemeral($event, '_last_results', new Collection);
}

public function getEphemeral(Event|State $target, ?string $key = null, mixed $default = null): mixed
{
$ephemeral = data_get($this->ephemeral[$target] ?? [], $key, $not_found = new stdClass());
$ephemeral = data_get($this->ephemeral[$target] ?? [], $key, $not_found = new stdClass);

if ($ephemeral === $not_found) {
$this->setEphemeral($target, $key, $default);
Expand Down Expand Up @@ -88,7 +88,7 @@ public function initialize(Event $event): Metadata

protected function makeMetadata(Event $event): Metadata
{
$metadata = new Metadata();
$metadata = new Metadata;

foreach ($this->callbacks as $callback) {
$result = $callback($metadata, $event);
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Metadata implements ArrayAccess

public function __construct(array $data = [])
{
$this->extra = new Collection();
$this->extra = new Collection;

$this->merge($data);
}
Expand Down
8 changes: 4 additions & 4 deletions src/StateFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@ public static function new(string $state_class, array $data = []): static
/** @param class-string<TStateType> $state_class */
public function __construct(
protected string $state_class,
protected Collection $transformations = new Collection(),
protected Collection $transformations = new Collection,
protected ?int $count = null,
protected int|string|null $id = null,
protected bool $singleton = false,
protected ?Generator $faker = null,
protected Collection $makeCallbacks = new Collection(),
protected Collection $createCallbacks = new Collection(),
protected Collection $makeCallbacks = new Collection,
protected Collection $createCallbacks = new Collection,
) {}

public function definition(): array
Expand Down Expand Up @@ -114,7 +114,7 @@ public function create(array $data = [], Bits|UuidInterface|AbstractUid|int|stri
}

if ($this->count < 1) {
return new StateCollection();
return new StateCollection;
}

if ($this->count === 1) {
Expand Down
4 changes: 2 additions & 2 deletions src/Support/EventStateRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ public function __construct(

public function getStates(Event $event): StateCollection
{
$discovered = new StateCollection();
$deferred = new StateCollection();
$discovered = new StateCollection;
$deferred = new StateCollection;

foreach ($this->getAttributes($event) as $attribute) {
// If there are state dependencies that the attribute relies on that we haven't already
Expand Down
6 changes: 3 additions & 3 deletions src/Support/Normalization/CollectionNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a
$isAssoc = data_get($data, 'associative', false);

if ($items === []) {
return new $fqcn();
return new $fqcn;
}

$subtype = data_get($data, 'type');
Expand Down Expand Up @@ -100,7 +100,7 @@ class_basename($collection),
protected function getCollectionMetadata(Collection $collection): array
{
$only_objects = true;
$types = new Collection();
$types = new Collection;

foreach ($collection as $value) {
$only_objects = $only_objects && is_object($value);
Expand All @@ -121,6 +121,6 @@ protected function getSharedAncestorTypes(Collection $types)
->unique();

return $common->isEmpty() ? $parents : $parents->intersect($common);
}, new Collection());
}, new Collection);
}
}
2 changes: 1 addition & 1 deletion src/Support/Reflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public static function getParametersOfType(string $type, ReflectionFunctionAbstr
$method = static::reflectFunction($method);

if (empty($parameters = $method->getParameters())) {
return new Collection();
return new Collection;
}

return collect($parameters)
Expand Down
4 changes: 2 additions & 2 deletions src/Support/Wormhole.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ public function realNow(): CarbonInterface

public function realMutableNow(): Carbon
{
return $this->mutable_now?->copy() ?? Carbon::instance(new DateTime());
return $this->mutable_now?->copy() ?? Carbon::instance(new DateTime);
}

public function realImmutableNow(): CarbonImmutable
{
return $this->immutable_now ?? CarbonImmutable::instance(new DateTime());
return $this->immutable_now ?? CarbonImmutable::instance(new DateTime);
}

public function warp(Event $event, Closure $callback)
Expand Down
6 changes: 3 additions & 3 deletions src/Testing/EventStoreFake.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class EventStoreFake implements StoresEvents
public function __construct(
protected MetadataManager $metadata,
) {
$this->events = new Collection();
$this->events = new Collection;
}

public function read(
Expand All @@ -50,7 +50,7 @@ public function read(
public function write(array $events): bool
{
foreach ($events as $event) {
$this->events[$event::class] ??= new Collection();
$this->events[$event::class] ??= new Collection;
$this->events[$event::class]->push($event);
}

Expand All @@ -61,7 +61,7 @@ public function write(array $events): bool
public function committed(string $class_name, ?Closure $filter = null): Collection
{
if (! $this->hasCommitted($class_name)) {
return new Collection();
return new Collection;
}

return $this->events[$class_name]
Expand Down
8 changes: 4 additions & 4 deletions src/Testing/SnapshotStoreFake.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ class SnapshotStoreFake implements StoresSnapshots

public function __construct()
{
$this->states = new Collection();
$this->states = new Collection;
}

public function write(array $states): bool
{
foreach ($states as $state) {
$this->states[$state::class] ??= new Collection();
$this->states[$state::class] ??= new Collection;
$this->states[$state::class]->put(Id::from($state->id), $state);
}

Expand All @@ -48,7 +48,7 @@ public function loadSingleton(string $type): ?State

public function reset(): bool
{
$this->states = new Collection();
$this->states = new Collection;

return true;
}
Expand Down Expand Up @@ -88,7 +88,7 @@ protected function assertWrittenTimes(string $class_name, int $times = 1): stati
public function written(string $class_name, ?Closure $filter = null): Collection
{
if (! $this->hasWritten($class_name)) {
return new Collection();
return new Collection;
}

return $this->states[$class_name]
Expand Down
8 changes: 4 additions & 4 deletions src/VerbsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ public function packageRegistered()

$this->app->singleton(PropertyNormalizer::class, function () {
$loader = class_exists(AttributeLoader::class)
? new AttributeLoader()
: new AnnotationLoader();
? new AttributeLoader
: new AnnotationLoader;

return new PropertyNormalizer(
propertyTypeExtractor: new ReflectionExtractor(),
propertyTypeExtractor: new ReflectionExtractor,
classDiscriminatorResolver: new ClassDiscriminatorFromClassMetadata(new ClassMetadataFactory($loader)),
);
});
Expand All @@ -120,7 +120,7 @@ classDiscriminatorResolver: new ClassDiscriminatorFromClassMetadata(new ClassMet
->map(fn ($class_name) => app($class_name))
->values()
->all(),
encoders: [new JsonEncoder()],
encoders: [new JsonEncoder],
);
});

Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/SerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@
it('allows us to store a serializable class as a property', function () {
expect(function () {
EventWithDto::fire(
dto: new DTO()
dto: new DTO
);
})->not->toThrow(TypeError::class);
});

it('honors configured context', function () {
$target = new class()
$target = new class
{
public $is_public = 'public';

Expand Down
Loading

0 comments on commit fe50ea4

Please sign in to comment.