stream icon indicating copy to clipboard operation
stream copied to clipboard

WP-CLI stream query fatal error: array_key_exists() must be of type array

Open dougaxe1 opened this issue 2 years ago • 1 comments

Bug Report

The issue is inside \WP_Stream\CLI->query():

		$records = wp_stream_get_instance()->db->query( $query_args );

		// Make structure Formatter compatible.
		foreach ( (array) $records as $key => $record ) {
			$formatted_records[ $key ] = array();

			// Catch any fields missing in records.
			foreach ( $fields as $field ) {
				if ( ! array_key_exists( $field, $record ) ) {
					$record->$field = null;
				}
			}

wp_stream_get_instance()->db->query() calls \WP_Stream\Query->query():

		/**
		 * QUERY THE DATABASE FOR RESULTS
		 */
		$result = array(
			'items' => $wpdb->get_results( $query ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			'count' => absint( $wpdb->get_var( $count_query ) ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		);

Results from $wpdb->get_results( $query ) default to $output of OBJECT. Line 137 of class-cli.php then calls array_key_exists( $field, $record ) where $record is an object instead of an array.

Possible Fixes

  1. Return the results as an associative array $wpdb->get_results( $query, ARRAY_A ) in \WP_Stream\Query->query()
  2. Use property_exists( $record, $field ) instead of array_key_exists in \WP_Stream\CLI->query()

Expected Behavior

Run the query WP-CLI stream command:

$ wp stream query
+---------------------+-----------+---------+---------------+-------------------------------------------------+
| created             | ip        | user_id | user_role     | summary                                         |
+---------------------+-----------+---------+---------------+-------------------------------------------------+
...
+---------------------+-----------+---------+---------------+-------------------------------------------------+

Actual Behavior

Fatal error: Uncaught TypeError: array_key_exists(): Argument #2 ($array) must be of type array, stdClass given .../wp-content/plugins/stream/classes/class-cli.php(137): array_key_exists()

Steps to Reproduce the Problem

  1. Run wp stream query via WP-CLI
  2. View debug/error

System Information

  • Stream plugin version: 3.9.3
  • WordPress version: 6.1.1/6.2
  • PHP version: 8.0/8.1
  • Browser: CLI
  • Computer operating system: N/A

dougaxe1 avatar Apr 28 '23 13:04 dougaxe1

Seems to be a php 8+ bug

7.4 warnings:

PHP Deprecated:  array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in /Users/jerryprice/Sites/bn/wp-content/plugins/stream/classes/class-cli.php on line 137

jjpmann avatar Apr 28 '23 13:04 jjpmann

This should be fixed by #1437 in the 4.0.1 release.

delawski avatar Jul 30 '24 12:07 delawski