Skip to content

Commit 7d3e252

Browse files
committed
Add a method for getting resources by their URI
ref #1
1 parent f04571f commit 7d3e252

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/SWAPI.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,31 @@ public function vehicles($fresh = false)
127127
}
128128
return $this->vehicles;
129129
}
130+
131+
/**
132+
* @param string $url
133+
* @return object SWAPI Model
134+
* @throws \UnexpectedValueException When given an unrecognised URI
135+
*/
136+
public function getFromUri($uri)
137+
{
138+
if (preg_match("/\/api\/(\w+)\/(\d+)(\/|$)/", $uri, $matches) !== false) {
139+
switch (strtolower($matches[1])) {
140+
case "characters":
141+
return $this->characters()->get($matches[2]);
142+
case "films":
143+
return $this->films()->get($matches[2]);
144+
case "planets":
145+
return $this->planets()->get($matches[2]);
146+
case "species":
147+
return $this->species()->get($matches[2]);
148+
case "starships":
149+
return $this->starships()->get($matches[2]);
150+
case "vehicles":
151+
return $this->vehicles()->get($matches[2]);
152+
}
153+
}
154+
155+
throw new \UnexpectedValueException(sprintf("Could not match a URI to an endpoint handler for %s", $uri));
156+
}
130157
}

tests/Functional/SWAPITest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace SWAPI\Tests\Functional;
4+
5+
class SWAPITest extends FunctionalBase
6+
{
7+
public function testGetByUri()
8+
{
9+
$vehicle = $this->swapi->getFromUri("http://swapi.co/api/vehicles/4");
10+
11+
$this->assertInstanceOf('SWAPI\Models\Vehicle', $vehicle);
12+
$this->assertEquals("Sand Crawler", $vehicle->name);
13+
}
14+
}

0 commit comments

Comments
 (0)