Skip to content

Commit f2b80ad

Browse files
Merge pull request #242 from MITLibraries/pw-195
Improve error handling and feedback to hours plugin
2 parents f83e12b + 3f4d643 commit f2b80ad

10 files changed

Lines changed: 244 additions & 40 deletions
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# Known improvement areas
2+
3+
This document tracks known issues and improvement opportunities identified
4+
during a modernization review of this plugin. The focus is on error handling,
5+
user feedback, and silent failure modes.
6+
7+
The broader context for this work is a shift toward using the WordPress
8+
Settings Errors API (`add_settings_error()` / `settings_errors()`) to collect
9+
and display status messages after operations complete, rather than scattering
10+
`echo()` calls throughout the business logic.
11+
12+
---
13+
14+
## 1. `set_properties()` does not stop `harvest()` on failure
15+
16+
**File:** `src/class-harvester.php` — `set_properties()` and `harvest()`
17+
18+
There are two silent failure modes in `set_properties()`:
19+
20+
### 1a. `wp_upload_dir()` error is ignored
21+
22+
`wp_upload_dir()` returns an array that includes an `['error']` key, set to a
23+
non-empty string if the upload directory cannot be determined. The current code
24+
reads `['basedir']` unconditionally without checking whether `['error']` is
25+
set. If `wp_upload_dir()` fails, `$this->path` will be set to a wrong or empty
26+
value, and subsequent file writes will fail silently.
27+
28+
**Suggested fix:** Check `wp_upload_dir()['error']` before using `['basedir']`.
29+
If it is non-empty, queue an error via `add_settings_error()` and return
30+
`false` to signal failure to `harvest()`.
31+
32+
### 1b. `wp_mkdir_p()` failure does not propagate to `harvest()`
33+
34+
If the cache directory cannot be created, `set_properties()` queues an error
35+
message but returns nothing, so `harvest()` has no way of knowing that the
36+
directory step failed. Execution continues into the try/catch block, the
37+
Google Sheets API is contacted successfully, and then `write()` silently fails
38+
when it tries to put files into a non-existent directory. The final result
39+
reported to the admin will be `true` (success), which is incorrect.
40+
41+
**Suggested fix:** Have `set_properties()` return a boolean, and have
42+
`harvest()` check that return value before proceeding. If `set_properties()`
43+
returns `false`, `harvest()` should queue an error and return `false` without
44+
contacting the API.
45+
46+
---
47+
48+
## 2. Per-sheet fetch errors are indistinguishable from step-3 errors
49+
50+
**File:** `src/class-harvester.php` — `fetch()`
51+
52+
Inside `fetch()`, `$service->spreadsheets_values->get()` can throw a
53+
`\Google\Service\Exception` — for example if permissions allow reading the
54+
spreadsheet index but not the individual sheet contents, or if a sheet name
55+
is somehow invalid. This is caught by the existing try/catch block in
56+
`harvest()`, but the error message won't identify which sheet caused the
57+
problem, making it harder to diagnose.
58+
59+
**Suggested fix:** This is a lower-priority improvement. Options include
60+
wrapping the inner call in its own try/catch within `fetch()` to capture
61+
per-sheet errors with the sheet name included in the message, or having
62+
`fetch()` return a list of per-sheet results. The current broad catch is
63+
acceptable for now.
64+
65+
---
66+
67+
## 3. `Admin_Widget` never calls the Harvester
68+
69+
**File:** `src/class-admin-widget.php` — `widget()`
70+
71+
The `widget()` method handles a POST action by updating the `cache_timestamp`
72+
option and queuing a message saying "Harvester activated..." — but it never
73+
actually instantiates or calls the `Harvester` class. The timestamp is updated
74+
to the current time without any data being fetched, which means the admin
75+
dashboard widget can display a recent "last updated" timestamp even though the
76+
cache content has not changed.
77+
78+
This appears to be either a stub left over from an earlier design, or an
79+
incomplete implementation of a planned feature to trigger harvesting from the
80+
dashboard widget.
81+
82+
**Suggested fix:** Either complete the implementation by calling
83+
`$harvester->harvest()` (and handling the return value as `Dashboard::update()`
84+
already does), or remove the POST-handling block entirely from `Admin_Widget`
85+
if the intent is that harvesting should only be triggered from the settings
86+
page.
87+
88+
---
89+
90+
## 4. `admin-widget.php` template is fragile with an unset timestamp
91+
92+
**File:** `templates/admin-widget.php`
93+
94+
On a fresh install, or if the `cache_timestamp` option is deleted, `get_option(
95+
'cache_timestamp' )` returns `false`. This is passed to `gmdate()`, which
96+
treats it as `0` (the Unix epoch, January 1 1970), producing a misleading but
97+
non-fatal timestamp display.
98+
99+
Additionally, the `switch` block that calculates the human-readable "X ago"
100+
string compares a `DateInterval` object against boolean expressions in each
101+
`case`. This works due to PHP's type coercion rules in switch statements, but
102+
it is a fragile antipattern that could behave unexpectedly across PHP version
103+
changes.
104+
105+
**Suggested fix:** Guard the timestamp block with a check for a falsy
106+
`cache_timestamp` value, and display a "never harvested" message in that case.
107+
Replace the `switch` on the `DateInterval` object with explicit `if/elseif`
108+
comparisons on its properties (`$ago->y`, `$ago->m`, etc.).
109+
110+
---
111+
112+
## Summary table
113+
114+
| # | File | Issue | Risk |
115+
|---|---|---|---|
116+
| 1a | `class-harvester.php` | `wp_upload_dir()` error key ignored | Wrong path used silently |
117+
| 1b | `class-harvester.php` | `wp_mkdir_p()` failure doesn't stop `harvest()` | False success reported |
118+
| 2 | `class-harvester.php` | Per-sheet errors indistinguishable from index errors | Unhelpful error messages |
119+
| 3 | `class-admin-widget.php` | `Harvester` never called | Timestamp updated, cache stale |
120+
| 4 | `templates/admin-widget.php` | Unguarded timestamp and fragile switch | Misleading display on fresh install |

‎web/app/plugins/mitlib-pull-hours/mitlib-pull-hours.php‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@
2121
}
2222

2323
// Include the necesary classes.
24-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-admin-widget.php' );
25-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-dashboard.php' );
26-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-display-widget.php' );
27-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-display-widget-frontpage.php' );
28-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-display-widget-slim.php' );
29-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-harvester.php' );
30-
require_once( plugin_dir_path( __FILE__ ) . 'src/class-settings.php' );
24+
require_once plugin_dir_path( __FILE__ ) . 'src/class-admin-widget.php';
25+
require_once plugin_dir_path( __FILE__ ) . 'src/class-dashboard.php';
26+
require_once plugin_dir_path( __FILE__ ) . 'src/class-display-widget.php';
27+
require_once plugin_dir_path( __FILE__ ) . 'src/class-display-widget-frontpage.php';
28+
require_once plugin_dir_path( __FILE__ ) . 'src/class-display-widget-slim.php';
29+
require_once plugin_dir_path( __FILE__ ) . 'src/class-harvester.php';
30+
require_once plugin_dir_path( __FILE__ ) . 'src/class-settings.php';
3131

3232
// Register classes with their hooks.
3333
// The settings fields themselves as the admin side initializes...

‎web/app/plugins/mitlib-pull-hours/src/class-admin-widget.php‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,16 @@ public static function widget() {
5858
$cache_timestamp = time();
5959
update_option( 'cache_timestamp', $cache_timestamp );
6060

61-
echo( '<div class="updated"><p>Harvester activated...</p></div>' );
61+
add_settings_error(
62+
'mitlib_pull_hours',
63+
'settings_updated',
64+
'Harvester activated...',
65+
'info'
66+
);
6267

6368
}
6469

6570
// Use the template to render widget output.
66-
require_once( plugin_dir_path( __FILE__ ) . '../templates/admin-widget.php' );
71+
require_once plugin_dir_path( __FILE__ ) . '../templates/admin-widget.php';
6772
}
6873
}

‎web/app/plugins/mitlib-pull-hours/src/class-dashboard.php‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public static function dashboard() {
5858
}
5959

6060
// Otherwise, we render the dashboard page.
61-
require_once( plugin_dir_path( __FILE__ ) . '../templates/dashboard.php' );
61+
require_once plugin_dir_path( __FILE__ ) . '../templates/dashboard.php';
6262
}
6363

6464
/**
@@ -93,11 +93,25 @@ public static function update() {
9393

9494
// Perform the harvesting.
9595
$harvester = new Harvester();
96-
$harvester->harvest();
97-
96+
$result = $harvester->harvest();
97+
98+
if ( $result ) {
99+
// Add the success message.
100+
add_settings_error(
101+
'mitlib_pull_hours',
102+
'harvester_success',
103+
'The library hours settings have been updated. Please <a href="/hours">check the public hours page</a> to verify success.',
104+
'success'
105+
);
106+
} else {
107+
// Add the success message.
108+
add_settings_error(
109+
'mitlib_pull_hours',
110+
'harvester_error',
111+
'Harvesting of library hours failed. Please <a href="/hours">inspect the public hours page closely</a>, and check the application logs for details about what happened.',
112+
'error'
113+
);
114+
}
98115
}
99-
100-
// Add the success message.
101-
echo( '<div class="updated"><p>The library hours settings have been updated. Please <a href="/hours">check the public hours page</a> to verify success.</p></div>' );
102116
}
103117
}

‎web/app/plugins/mitlib-pull-hours/src/class-display-widget-frontpage.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ public function widget( $args, $instance ) {
156156

157157
// Render markup.
158158
echo wp_kses( $args['before_widget'], $allowed );
159-
require( plugin_dir_path( __FILE__ ) . '../templates/display-widget-frontpage.php' );
159+
require plugin_dir_path( __FILE__ ) . '../templates/display-widget-frontpage.php';
160160
echo wp_kses( $args['after_widget'], $allowed );
161161
}
162162
}

‎web/app/plugins/mitlib-pull-hours/src/class-display-widget-slim.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ public function widget( $args, $instance ) {
123123

124124
// Render markup.
125125
echo wp_kses( $args['before_widget'], $allowed );
126-
$template = file_get_contents( dirname( __FILE__ ) . '/../templates/display-widget-slim.html' );
126+
$template = file_get_contents( __DIR__ . '/../templates/display-widget-slim.html' );
127127
echo wp_kses( sprintf( $template, $instance['location_label'], $instance['title'] ), $allowed );
128128
echo wp_kses( $args['after_widget'], $allowed );
129129
}

‎web/app/plugins/mitlib-pull-hours/src/class-display-widget.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ public function widget( $args, $instance ) {
125125
if ( $instance['widget_title'] ) {
126126
echo wp_kses( $args['before_title'], $allowed ) . esc_html( $instance['widget_title'] ) . wp_kses( $args['after_title'], $allowed );
127127
}
128-
require( plugin_dir_path( __FILE__ ) . '../templates/display-widget.php' );
128+
require plugin_dir_path( __FILE__ ) . '../templates/display-widget.php';
129129
echo wp_kses( $args['after_widget'], $allowed );
130130
}
131131

‎web/app/plugins/mitlib-pull-hours/src/class-harvester.php‎

Lines changed: 81 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -81,36 +81,84 @@ public function harvest() {
8181
// - key => filename in cache
8282
// - value => url that will be polled.
8383

84-
// Third, we populate an array of sheet names within our spreadsheet.
85-
// This array will then comprise the "shopping list" of values that
86-
// are harvested to populate the local cache.
87-
$response = $api_service->spreadsheets->get( $this->spreadsheet_key );
88-
$sheet_array = array_map( array( $this, 'pluck_sheet_name' ), $response->sheets );
89-
90-
// Fourth, we iterates over the associative array that was built in the
91-
// last step, reading each URL (in the value) and saving the contents
92-
// to the cache (named in the key).
93-
$this->fetch( $api_service, $sheet_array );
94-
95-
// Finally, we echo an updated message about the number of records
96-
// that were updated.
97-
echo( '<div class="updated"><p>Local hours cache has been harvested with information from ' . esc_html( count( $sheet_array ) ) . ' sheets .</p></div>' );
84+
try {
85+
// Third, we populate an array of sheet names within our spreadsheet.
86+
// This array will then comprise the "shopping list" of values that
87+
// are harvested to populate the local cache.
88+
$response = $api_service->spreadsheets->get( $this->spreadsheet_key ); // Need to catch Google\Service\Exception.
89+
$sheet_array = array_map( array( $this, 'pluck_sheet_name' ), $response->sheets );
90+
91+
// Fourth, we iterates over the associative array that was built in the
92+
// last step, reading each URL (in the value) and saving the contents
93+
// to the cache (named in the key).
94+
$this->fetch( $api_service, $sheet_array );
95+
96+
return true;
97+
98+
} catch ( \Google\Service\Exception $e ) {
99+
error_log( $e->getMessage() );
100+
$raw = json_decode( $e->getMessage(), true );
101+
$code = $raw['error']['code'] ?? 'unknown';
102+
$message = $raw['error']['message'] ?? 'Unknown Google API error - check logs for details.';
103+
add_settings_error(
104+
'mitlib_pull_hours',
105+
'google_api_error',
106+
"Error {$code}: {$message}",
107+
'error'
108+
);
109+
110+
return false;
111+
112+
} catch ( \Exception $e ) {
113+
error_log( $e->getMessage() );
114+
add_settings_error(
115+
'mitlib_pull_hours',
116+
'unexpected_error',
117+
'Something truly unexpected happened. Please check the application logs for details.',
118+
'error'
119+
);
120+
121+
return false;
98122

123+
}
99124
}
100125

101126
/**
102127
* This method iterates over the $array (defined in build_sheet_list) and
103128
* fetches each item (in the $value) and writes it to the filename defined
104129
* by $target (which has been sanitized with dashes).
105130
*
131+
* The method keeps track of how many errors are reported by the write()
132+
* method, and creates a status message based on whether everything succeeds
133+
* or if errors are encountered.
134+
*
106135
* @param Object $service A representation of the Google Sheets API.
107136
* @param Array $array An associative array of filenames and URLs.
108137
*/
109138
private function fetch( $service, $array ) {
139+
$error_count = 0;
140+
$file_count = count( $array );
110141
foreach ( $array as $target ) {
111-
$data = $service->spreadsheets_values->get( $this->spreadsheet_key, $target );
142+
$data = $service->spreadsheets_values->get( $this->spreadsheet_key, $target );
112143
$filename = sanitize_file_name( $target ) . '.json';
113-
$this->write( $filename, json_encode( $data['values'] ) );
144+
if ( ! $this->write( $filename, json_encode( $data['values'] ) ) ) {
145+
$error_count++;
146+
}
147+
}
148+
if ( $error_count > 0 ) {
149+
add_settings_error(
150+
'mitlib_pull_hours',
151+
'fetch_errors',
152+
"Errors encountered while fetching {$error_count} of {$file_count} files.",
153+
'error'
154+
);
155+
} else {
156+
add_settings_error(
157+
'mitlib_pull_hours',
158+
'fetch_success',
159+
"{$file_count} files retrieved successfully.",
160+
'success'
161+
);
114162
}
115163
}
116164

@@ -164,19 +212,33 @@ private function set_properties() {
164212

165213
// Define cache directory, ensure it exists.
166214
$this->path = wp_upload_dir()['basedir'] . '/pull-hours';
215+
add_settings_error(
216+
'mitlib_pull_hours',
217+
'settings_updated',
218+
"Confirming cache directory: _{$this->path}_",
219+
'success'
220+
);
167221
if ( ! wp_mkdir_p( $this->path ) ) {
168-
error_log( 'Failed to create cache directory: ' . $basedir );
222+
error_log( "Failed to create cache directory: {$this->path}" );
223+
add_settings_error(
224+
'mitlib_pull_hours',
225+
'invalid_cache_location',
226+
"Failed to create cache directory: {$this->path}",
227+
'error'
228+
);
169229
}
170230
}
171231

172232
/**
173233
* This method writes a provided piece of data to the specified filename,
174-
* in a directory defined by $this->data_folder.
234+
* in a directory defined by $this->data_folder. It returns a boolean that
235+
* indicates whether the operation succeeded.
175236
*
176237
* @param string $filename The name of the file to be written.
177238
* @param string $data The contents of the file to be written.
239+
* @return boolean
178240
*/
179241
private function write( $filename, $data ) {
180-
file_put_contents( $this->path . '/' . $filename, $data );
242+
return file_put_contents( $this->path . '/' . $filename, $data ) !== false;
181243
}
182244
}

‎web/app/plugins/mitlib-pull-hours/src/class-settings.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,22 +78,22 @@ public static function general() {
7878
*/
7979
public static function google_api_key_callback() {
8080
$google_api_key = get_option( 'google_api_key' );
81-
require_once( plugin_dir_path( __FILE__ ) . '../templates/forms/google-api-key.php' );
81+
require_once plugin_dir_path( __FILE__ ) . '../templates/forms/google-api-key.php';
8282
}
8383

8484
/**
8585
* Field-rendering callback for the Google Spreadsheet key
8686
*/
8787
public static function spreadsheet_callback() {
8888
$spreadsheet_key = get_option( 'spreadsheet_key' );
89-
require_once( plugin_dir_path( __FILE__ ) . '../templates/forms/spreadsheet-key.php' );
89+
require_once plugin_dir_path( __FILE__ ) . '../templates/forms/spreadsheet-key.php';
9090
}
9191

9292
/**
9393
* Field-rendering callback for the Google Spreadsheet key
9494
*/
9595
public static function timestamp_callback() {
9696
$cache_timestamp = get_option( 'cache_timestamp' );
97-
require_once( plugin_dir_path( __FILE__ ) . '../templates/forms/cache-timestamp.php' );
97+
require_once plugin_dir_path( __FILE__ ) . '../templates/forms/cache-timestamp.php';
9898
}
9999
}

0 commit comments

Comments
 (0)