Skip to content

Commit 9514b3d

Browse files
[9.x] Implement Data::find() support for Runway models (#825)
1 parent da0a6d7 commit 9514b3d

3 files changed

Lines changed: 51 additions & 1 deletion

File tree

src/ModelRepository.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,29 @@ class ModelRepository
1010
protected $substitutionsById = [];
1111
protected $substitutionsByUri = [];
1212

13+
public function find(string $reference)
14+
{
15+
$fullReference = "runway::{$reference}";
16+
17+
if ($substitute = Arr::get($this->substitutionsById, $fullReference)) {
18+
return $substitute;
19+
}
20+
21+
if (! str_contains($reference, '::')) {
22+
return null;
23+
}
24+
25+
[$handle, $id] = explode('::', $reference, 2);
26+
27+
$resource = Runway::allResources()->get($handle);
28+
29+
if (! $resource) {
30+
return null;
31+
}
32+
33+
return $resource->model()->find($id);
34+
}
35+
1336
public function findByUri(string $uri)
1437
{
1538
if ($substitute = Arr::get($this->substitutionsByUri, $uri)) {

src/ServiceProvider.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ protected function bootDataRepository(): self
287287
$this->app->singleton(ModelRepository::class);
288288

289289
$this->app->get(\Statamic\Contracts\Data\DataRepository::class)
290-
->setRepository('runway-resources', ModelRepository::class);
290+
->setRepository('runway', ModelRepository::class);
291291

292292
StaticWarm::hook('additional', function ($urls, $next) {
293293
return $next($urls->merge(RunwayUri::select('uri')->pluck('uri')->all()));

tests/ModelRepositoryTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,33 @@
1010

1111
class ModelRepositoryTest extends TestCase
1212
{
13+
#[Test]
14+
public function can_find_by_reference()
15+
{
16+
$post = Post::factory()->create();
17+
18+
$found = Data::find("runway::post::{$post->id}");
19+
20+
$this->assertNotNull($found);
21+
$this->assertEquals($post->id, $found->id);
22+
}
23+
24+
#[Test]
25+
public function cant_find_by_reference_when_model_doesnt_exist()
26+
{
27+
$found = Data::find('runway::post::99999');
28+
29+
$this->assertNull($found);
30+
}
31+
32+
#[Test]
33+
public function cant_find_by_reference_when_resource_doesnt_exist()
34+
{
35+
$found = Data::find('runway::nonexistent::12345');
36+
37+
$this->assertNull($found);
38+
}
39+
1340
#[Test]
1441
public function can_find_by_uri()
1542
{

0 commit comments

Comments
 (0)