22
33namespace App \Actions ;
44
5+ use Illuminate \Support \Arr ;
56use Illuminate \Support \Facades \Http ;
67use Illuminate \Support \Facades \Log ;
78use Lorisleiva \Actions \Concerns \AsAction ;
@@ -11,7 +12,22 @@ class GetOoklaSpeedtestServers
1112{
1213 use AsAction;
1314
15+ /**
16+ * For UI: return the ID, Sponsor, and Name to start a manual test
17+ */
1418 public function handle (): array
19+ {
20+ return collect (self ::fetch ())->mapWithKeys (function (array $ item ) {
21+ return [
22+ $ item ['id ' ] => ($ item ['sponsor ' ] ?? 'Unknown ' ).' ( ' .($ item ['name ' ] ?? 'Unknown ' ).', ' .$ item ['id ' ].') ' ,
23+ ];
24+ })->toArray ();
25+ }
26+
27+ /**
28+ * Fetch the raw Ookla server array from the Ookla API.
29+ */
30+ public static function fetch (): array
1531 {
1632 $ query = [
1733 'engine ' => 'js ' ,
@@ -23,17 +39,37 @@ public function handle(): array
2339 $ response = Http::retry (3 , 250 )
2440 ->timeout (5 )
2541 ->get (url: 'https://www.speedtest.net/api/js/servers ' , query: $ query );
42+
43+ return $ response ->json ();
2644 } catch (Throwable $ e ) {
2745 Log::error ('Unable to retrieve Ookla servers. ' , [$ e ->getMessage ()]);
2846
2947 return [
3048 '⚠️ Unable to retrieve Ookla servers, check internet connection and see logs. ' ,
3149 ];
3250 }
51+ }
52+
53+ /**
54+ * For API: return array of structured server objects
55+ */
56+ public static function forApi (): array
57+ {
58+ $ servers = self ::fetch ();
59+
60+ // If the first item is not an array, treat as error or empty
61+ if (empty ($ servers ) || ! is_array ($ servers ) || (isset ($ servers [0 ]) && ! is_array ($ servers [0 ]))) {
62+ // Optionally, you could return an error message here, but to match the controller's behavior, return an empty array
63+ return [];
64+ }
3365
34- return $ response -> collect ()->mapWithKeys (function (array $ item, int $ key ) {
66+ return collect ($ servers )->map (function (array $ item ) {
3567 return [
36- $ item ['id ' ] => $ item ['sponsor ' ].' ( ' .$ item ['name ' ].', ' .$ item ['id ' ].') ' ,
68+ 'id ' => $ item ['id ' ],
69+ 'host ' => Arr::get ($ item , 'host ' , 'Unknown ' ),
70+ 'name ' => Arr::get ($ item , 'sponsor ' , 'Unknown ' ),
71+ 'location ' => Arr::get ($ item , 'name ' , 'Unknown ' ),
72+ 'country ' => Arr::get ($ item , 'country ' , 'Unknown ' ),
3773 ];
3874 })->toArray ();
3975 }
0 commit comments