Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
6 | class IpLocationProvider implements ILocationProvider |
||
7 | { |
||
8 | private $apikey; |
||
9 | private $database; |
||
10 | |||
11 | public function __construct(PdoDatabase $database, $apikey) |
||
12 | { |
||
13 | $this->database = $database; |
||
14 | $this->apikey = $apikey; |
||
15 | } |
||
16 | |||
17 | public function getIpLocation($address) |
||
18 | { |
||
19 | $address = trim($address); |
||
20 | |||
21 | // lets look in our database first. |
||
22 | $location = GeoLocation::getByAddress($address, $this->database, true); |
||
23 | |||
24 | if ($location != null) { |
||
25 | // touch cache timer |
||
26 | $location->save(); |
||
27 | |||
28 | return $location->getData(); |
||
29 | } |
||
30 | |||
31 | // OK, it's not there, let's do an IP2Location lookup. |
||
32 | $result = $this->getResult($address); |
||
33 | |||
34 | if ($result != null) { |
||
35 | $location = new GeoLocation(); |
||
36 | $location->setDatabase($this->database); |
||
37 | $location->setAddress($address); |
||
38 | $location->setData($result); |
||
39 | $location->save(); |
||
40 | |||
41 | return $result; |
||
42 | } |
||
43 | |||
44 | return null; |
||
45 | } |
||
46 | |||
47 | // adapted from http://www.ipinfodb.com/ip_location_api.php |
||
48 | |||
49 | /** |
||
50 | * @param string $ip |
||
51 | * @return array|null |
||
52 | */ |
||
53 | private function getResult($ip) |
||
78 | } |
||
79 | |||
80 | protected function getApiBase() |
||
83 | } |
||
84 | } |
||
85 |