Skip to content

Commit

Permalink
Add a method for getting resources by their URI
Browse files Browse the repository at this point in the history
ref #1
  • Loading branch information
rmasters committed Jan 20, 2015
1 parent f04571f commit 7d3e252
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/SWAPI.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
14 changes: 14 additions & 0 deletions tests/Functional/SWAPITest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace SWAPI\Tests\Functional;

class SWAPITest extends FunctionalBase
{
public function testGetByUri()
{
$vehicle = $this->swapi->getFromUri("http://swapi.co/api/vehicles/4");

$this->assertInstanceOf('SWAPI\Models\Vehicle', $vehicle);
$this->assertEquals("Sand Crawler", $vehicle->name);
}
}

0 comments on commit 7d3e252

Please sign in to comment.