
Giorgio Sironi
By: a guest on Sep 30th, 2009 | syntax:
PHP | size: 1.66 KB | hits: 215 | expires: Never
<?php
/**
* For brevity I use public fields instead of getters and setters.
*/
class User
{
public $location;
public $latitude;
public $longitude;
}
class GoogleMaps
{
public function getLatitudeAndLongitude($location)
{
// some obscure network code to contact maps.google.com
// ...
return array('latitude' => $someValue, 'longitude' => $someOtherValue);
}
}
class GeolocationService
{
private $_maps;
public function __construct(GoogleMaps $maps)
{
$this->_maps = $maps;
}
public function locate(User $user)
{
$location = $user->location;
if ($location === null) {
$location = 'Milan';
}
$coordinates = $this->_maps->getLatitudeAndLongitude($location);
$user->latitude = $coordinates['latitude'];
$user->longitude = $coordinates['longitude'];
}
}
class GeolocationServiceTest extends PHPUnit_Framework_TestCase
{
public function testProvidesLatitudeAndLongitudeForAnUser()
{
$coordinates = array('latitude' => '42N', 'longitude' => '12E');
$googleMapsMock = $this->getMock('GoogleMaps', array('getLatitudeAndLongitude'));
$googleMapsMock->expects($this->any())
->method('getLatitudeAndLongitude')
->will($this->returnValue($coordinates));
$service = new GeolocationService($googleMapsMock);
$user = new User;
$user->location = 'Rome';
$service->locate($user);
$this->assertEquals('42N', $user->latitude);
$this->assertEquals('12E', $user->longitude);
}
}