Skip to content

Commit ebde02c

Browse files
Merge pull request #18 from farbcodegmbh/fix/request-scopes
[Fix]: Per-Request Scoping of Shared States
2 parents 60cc964 + 0c86672 commit ebde02c

3 files changed

Lines changed: 29 additions & 4 deletions

File tree

src/StatefulResourcesServiceProvider.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ public function configurePackage(Package $package): void
2525

2626
public function bootingPackage(): void
2727
{
28-
$states = config()->array('stateful-resources.states');
28+
$states = config()->collection('stateful-resources.states');
2929

3030
$this->app->singleton(StateRegistry::class, function () use ($states) {
3131
$registry = new StateRegistry;
3232

33-
foreach ($states as $state) {
33+
$states->each(function (string|ResourceState $state) use ($registry) {
3434
if ($state instanceof ResourceState) {
3535
$state = $state->value;
3636
}
3737
$registry->register($state);
38-
}
38+
});
3939

4040
return $registry;
4141
});
4242

43-
$this->app->singleton(ActiveState::class, function () {
43+
$this->app->scoped(ActiveState::class, function () {
4444
return new ActiveState;
4545
});
4646
}

tests/Feature/SharedStateTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,16 @@
201201

202202
expect(ActiveState::getShared())->toBe('table');
203203
});
204+
205+
it('resets the active state between requests', function () {
206+
$cat = Cat::factory()->new()->createOne();
207+
208+
CatResource::state('table')->make($cat);
209+
210+
expect(ActiveState::getShared())->toBe('table');
211+
212+
simulateNewOctaneRequest();
213+
214+
expect(ActiveState::getShared())->toBe(app(StateRegistry::class)->getDefaultState());
215+
expect(ActiveState::getForResource(CatResource::class))->toBe(app(StateRegistry::class)->getDefaultState());
216+
});

tests/Pest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
<?php
22

33
use Farbcode\StatefulResources\Tests\TestCase;
4+
use Illuminate\Support\Facades\Facade;
45

56
uses(TestCase::class)->in(__DIR__);
67

8+
/*
9+
|--------------------------------------------------------------------------
10+
| Utility Functions
11+
|--------------------------------------------------------------------------
12+
*/
13+
function simulateNewOctaneRequest(): void
14+
{
15+
app()->forgetScopedInstances();
16+
Facade::clearResolvedInstances();
17+
}
18+
719
/*
820
|--------------------------------------------------------------------------
921
| Expectations

0 commit comments

Comments
 (0)