1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zmaglica\RickAndMortyApiWrapper\Model; |
4
|
|
|
|
5
|
|
View Code Duplication |
class Location extends AbstractModel |
|
|
|
|
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Get all location residents without running API call. Useful if you want to perform additional filtering. |
9
|
|
|
* @param bool $removeDuplicates |
10
|
|
|
* @return \Zmaglica\RickAndMortyApiWrapper\Api\AbstractApi |
11
|
|
|
*/ |
12
|
|
|
public function residents($removeDuplicates = false) |
13
|
|
|
{ |
14
|
|
|
$ids = $this->extractIdsFromResponseBasedOnKey('residents', $removeDuplicates); |
15
|
|
|
|
16
|
|
|
return $this->api->character()->whereId($ids); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Get all location residents |
21
|
|
|
* @param bool $removeDuplicates |
22
|
|
|
* @return mixed |
23
|
|
|
*/ |
24
|
|
|
public function getResidents($removeDuplicates = false) |
25
|
|
|
{ |
26
|
|
|
return $this->residents($removeDuplicates)->get(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* This helper function will extract all URL ids by key. Key can be location, residence or episode |
31
|
|
|
* @param $key |
32
|
|
|
* @param $removeDuplicates |
33
|
|
|
* @return array |
34
|
|
|
*/ |
35
|
|
|
private function extractIdsFromResponseBasedOnKey($key, $removeDuplicates) |
36
|
|
|
{ |
37
|
|
|
$ids = []; |
38
|
|
|
if ($this->info) { |
39
|
|
|
$urls = array_column($this->data['results'], $key); |
40
|
|
|
// flatten array to single one because there can be multiple residents per location |
41
|
|
|
$urls = array_merge(...$urls); |
42
|
|
|
} elseif (isset($this->data[0])) { |
43
|
|
|
$urls = array_column($this->data, $key); |
44
|
|
|
// flatten array to single one because there can be multiple residents per location |
45
|
|
|
$urls = array_merge(...$urls); |
46
|
|
|
} else { |
47
|
|
|
$urls = $this->data[$key]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if ($removeDuplicates) { |
51
|
|
|
$urls = array_unique($urls); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
foreach ($urls as $url) { |
55
|
|
|
$ids[] = substr(strrchr($url, '/'), 1); |
56
|
|
|
; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $ids; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.