Skip to content

Commit 37b5b0b

Browse files
committed
Fix warnings in search_counter
Right now the website breaks if the .json files are missing, or they contain broken data. Log these cases to see how frequent they are.
1 parent b3be110 commit 37b5b0b

1 file changed

Lines changed: 37 additions & 17 deletions

File tree

app/inc/search_counter.php

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,31 +3,51 @@
33

44
use Json\Json;
55

6-
// Create a JSON file logging locale/number of requests
76
$json_data = new Json;
7+
8+
// Create a JSON file logging locale/number of requests
89
$local_filename = CACHE_PATH . 'stats_locales.json';
9-
$stats = $json_data
10-
->setURI($local_filename)
11-
->fetchContent();
10+
if (file_exists($local_filename)) {
11+
$stats = $json_data
12+
->setURI($local_filename)
13+
->fetchContent();
14+
} else {
15+
$stats = [];
16+
}
17+
18+
// Save JSON only if PHP was able to read the existing stats
19+
if (is_array($stats)) {
20+
$stats[$locale] = array_key_exists($locale, $stats) ? $stats[$locale] += 1 : 1;
21+
$json_data->saveFile($stats, $local_filename);
22+
} else {
23+
$logger->addError('stats_locales.json exists but couldn\'t extract a valid array from JSON');
24+
}
1225

13-
$stats[$locale] = array_key_exists($locale, $stats) ? $stats[$locale] += 1 : 1;
14-
$json_data->saveFile($stats, $local_filename);
1526

1627
// Create a JSON file logging search options to determine if some are unused
1728
$local_filename = CACHE_PATH . 'stats_requests.json';
18-
$stats = $json_data
19-
->setURI($local_filename)
20-
->fetchContent();
29+
if (file_exists($local_filename)) {
30+
$stats = $json_data
31+
->setURI($local_filename)
32+
->fetchContent();
33+
} else {
34+
$stats = [];
35+
}
2136

22-
foreach ($check as $k => $v) {
23-
if (in_array($k, $search->getFormCheckboxes()) && $v == 1) {
24-
$stats[$k] = array_key_exists($k, $stats) ? $stats[$k] += 1 : 1;
25-
}
37+
// Save JSON only if PHP was able to read the existing stats
38+
if (is_array($stats)) {
39+
foreach ($check as $k => $v) {
40+
if (in_array($k, $search->getFormCheckboxes()) && $v == 1) {
41+
$stats[$k] = array_key_exists($k, $stats) ? $stats[$k] += 1 : 1;
42+
}
2643

27-
if (in_array($k, array_diff($search->getFormSearchOptions(), $search->getFormCheckboxes()))) {
28-
$stats[$v] = array_key_exists($v, $stats) ? $stats[$v] += 1 : 1;
29-
}
44+
if (in_array($k, array_diff($search->getFormSearchOptions(), $search->getFormCheckboxes()))) {
45+
$stats[$v] = array_key_exists($v, $stats) ? $stats[$v] += 1 : 1;
46+
}
3047

31-
$json_data->saveFile($stats, $local_filename);
48+
$json_data->saveFile($stats, $local_filename);
49+
}
50+
} else {
51+
$logger->addError('stats_requests.json exists but couldn\'t extract a valid array from JSON');
3252
}
3353
unset($stats);

0 commit comments

Comments
 (0)