diff --git a/src/SWAPI.php b/src/SWAPI.php index 9bd566e..a62518c 100644 --- a/src/SWAPI.php +++ b/src/SWAPI.php @@ -127,4 +127,31 @@ public function vehicles($fresh = false) } return $this->vehicles; } + + /** + * @param string $url + * @return object SWAPI Model + * @throws \UnexpectedValueException When given an unrecognised URI + */ + public function getFromUri($uri) + { + if (preg_match("/\/api\/(\w+)\/(\d+)(\/|$)/", $uri, $matches) !== false) { + switch (strtolower($matches[1])) { + case "characters": + return $this->characters()->get($matches[2]); + case "films": + return $this->films()->get($matches[2]); + case "planets": + return $this->planets()->get($matches[2]); + case "species": + return $this->species()->get($matches[2]); + case "starships": + return $this->starships()->get($matches[2]); + case "vehicles": + return $this->vehicles()->get($matches[2]); + } + } + + throw new \UnexpectedValueException(sprintf("Could not match a URI to an endpoint handler for %s", $uri)); + } } diff --git a/tests/Functional/SWAPITest.php b/tests/Functional/SWAPITest.php new file mode 100644 index 0000000..cbcbe46 --- /dev/null +++ b/tests/Functional/SWAPITest.php @@ -0,0 +1,14 @@ +swapi->getFromUri("http://swapi.co/api/vehicles/4"); + + $this->assertInstanceOf('SWAPI\Models\Vehicle', $vehicle); + $this->assertEquals("Sand Crawler", $vehicle->name); + } +}