Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
4.76% covered (danger)
4.76%
4 / 84
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
MapController
4.76% covered (danger)
4.76%
4 / 84
25.00% covered (danger)
25.00%
1 / 4
609.95
0.00% covered (danger)
0.00%
0 / 1
 index
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 testMapCaches
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 getLocationsFromAPCu
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 getLocations
0.00% covered (danger)
0.00%
0 / 61
0.00% covered (danger)
0.00%
0 / 1
342
1<?php
2
3namespace App\Http\Controllers;
4
5use Illuminate\Http\Request;
6use Illuminate\Http\JsonResponse;
7use Illuminate\Support\Facades\DB;
8use Illuminate\Support\Facades\Redis;
9
10class MapController extends Controller
11{
12    public function index(Request $request): JsonResponse
13    {
14        $user = $request->user();
15        return response()->json([
16            'result' => compact('user')
17        ]);
18    }
19
20    public function testMapCaches(Request $request): JsonResponse
21    {
22        $user = ['user' => ['role' => null]];
23        $locations = ['locations' => null];
24
25        if ($request->has('level')) {
26            $level = $request->get('level');
27            $code = $request->has('options')
28                ? $request->get('options') : null;
29
30            $locations = $this->getLocations($level, $code);
31        }
32
33        return response()->json([
34            'result' => array_merge($locations, $user)
35        ]);
36    }
37
38
39    private function getLocationsFromAPCu($level, $code)
40    {
41        $result = array();
42        try {
43
44            if ($level == "districts") {
45                $codeForApcu = "district";
46
47            } else {
48
49                $codeForApcu = "{$level}_{$code}";
50            }
51
52
53            foreach (new \APCUIterator("/^location_pt_$codeForApcu/") as $counter) {
54                $results = $counter['value'];
55            }
56
57            return $result;
58
59        } catch (\Exception $e) {
60            echo 'Erro ao iterar sobre os contadores APCu: ' . $e->getMessage(); die;
61        }
62
63    }
64
65
66
67
68    private function getLocations(string $level, string $code = null) : array
69    {
70
71        // Validate levels
72        if ($level != "districts" && $level != "municipality" && $level != "parish")
73        {
74            die("invalid level");
75        }
76
77        $results = [];
78
79        try {
80
81            if ($level == "districts")
82            {
83                $codeForApcu = "district" ;
84
85            } else {
86
87                $codeForApcu = "{$level}_{$code}";
88            }
89
90
91            foreach (new \APCUIterator("/^location_pt_$codeForApcu/") as $counter) {
92                 $results['locations'][] = $counter['value'];
93            }
94        } catch (\Exception $e) {
95            echo 'Erro ao iterar sobre os contadores APCu: ' . $e->getMessage();
96        }
97
98        // Verificar se há resultados antes de retornar
99        if (!empty($results['locations'])) {
100            $results['source'] = 'APCu';
101             return $results;
102        }
103
104
105       // var_dump($results); die;
106
107
108        // Go to Redis. Case exists save in APCu and return.
109        Redis::select(2);
110         $redis = Redis::connection();
111        if ($redis->ping()) {
112            // Conexão bem-sucedida
113           //  $code = ($code != "%") ? $code : "";
114
115            $level_aux = $level;
116            if ($level == "districts")
117            {
118                $code = "";
119                $level_aux = "district";
120            }
121
122
123            $pattern = "location_pt_{$level_aux}_{$code}*";
124            $keys = $redis->keys($pattern);
125
126            foreach ($keys as $key)
127            {
128                $value = Redis::get($key);
129                $results['locations'][] = $value;
130
131                // Save in APCu
132                 apcu_store($key, $value);
133            }
134
135        } else {
136            // Conexão falhou
137            echo "Não foi possível estabelecer conexão com o Redis.";
138        }
139
140        if (!empty($results))
141        {
142            sort($results['locations']);
143            $results['source'] = 'Redis';
144            return $results;
145        }
146
147
148
149
150        $level_aux = "";
151        $level_aux2 = $level;
152        if ($level == "districts")
153        {
154            $level_aux = "district";
155            $level_aux2 = "district";
156        }
157
158        if ($level == "municipality")
159        {
160            $level_aux = "district";
161        }
162
163        if ($level == "parish")
164        {
165            $level_aux = "municipality";
166        }
167
168        // Go to DB. Case exists save in Redis and APCu.
169        {
170            $dbResult = DB::table('locations_pt')
171                ->select("{$level_aux2}_name", "{$level_aux2}_code")
172                ->distinct();
173                if ($level != "districts"){
174                    $dbResult = $dbResult->where("{$level_aux}_code", '=', $code);
175                }
176                $dbResult->orderBy("{$level_aux2}_name");
177                $dbResult = $dbResult->get()
178                ->toArray();
179        }
180
181        // Save caches
182        foreach ($dbResult as $value)
183        {
184            $level_aux = $level;
185            if ($level == "districts")
186            {
187                $level_aux = "district";
188            }
189
190
191
192            $propertyValue = $results['locations'][] = json_encode($value);
193            $propertyKey   = "{$level_aux}_code";
194
195
196           // var_dump($value); die;
197
198            // Save in Redis
199            Redis::set("location_pt_{$level_aux}_{$value->$propertyKey}", $propertyValue);
200
201            // Save in APCu
202            apcu_store("location_pt_{$level_aux}_{$value->$propertyKey}", $propertyValue);
203        }
204
205        $results['source'] = 'Database';
206        return $results;
207    }
208
209}