Skip to content

Commit

Permalink
Adding some query methods for the custom tables
Browse files Browse the repository at this point in the history
  • Loading branch information
dpanta94 committed Jan 30, 2025
1 parent 67ca706 commit 39157a4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Common/Integrations/Custom_Table_Abstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@
abstract class Custom_Table_Abstract extends Table {
use Traits\Custom_Table_Query_Methods;

/**
* An array of all the columns in the table.
*
* @since TBD
*
* @var string[]
*/
abstract public static function get_columns(): array;

/**
* Helper method to check and add an index to a table.
*
Expand Down
55 changes: 55 additions & 0 deletions src/Common/Integrations/Traits/Custom_Table_Query_Methods.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,59 @@ public static function fetch_first_where( string $where_clause, string $output =
$output
);
}

/**
* Method used to paginate the results of a query.
*
* @since TBD
*
* @param array $args The query arguments.
* @param int $per_page The number of items to display per page.
* @param int $page The current page number.
* @param string $output The output type of the query, one of OBJECT, ARRAY_A, or ARRAY_N.
*
* @return array The items.
*/
public static function paginate( array $args, int $per_page, int $page, string $output = OBJECT ): array {
$offset = ( $page - 1 ) * $per_page;

$orderby = $args['orderby'] ?? self::uid_column();
$order = strtoupper( $args['order'] ) ?? 'ASC';

if ( ! in_array( $orderby, static::get_columns(), true ) ) {
$orderby = self::uid_column();
}

if ( ! in_array( $order, [ 'ASC', 'DESC' ], true ) ) {
$order = 'ASC';
}

return DB::get_results(
DB::prepare(
"SELECT * FROM %i ORDER BY {$orderby} {$order} LIMIT %d, %d",
static::table_name( true ),
$offset,
$per_page
),
$output
);
}

/**
* Gets the total number of items in the table.
*
* @since TBD
*
* @param array $args The query arguments.
*
* @return int The total number of items in the table.
*/
public static function get_total_items( array $args = [] ): int {
return (int) DB::get_var(
DB::prepare(
'SELECT COUNT(*) FROM %i',
static::table_name( true )
)
);
}
}

0 comments on commit 39157a4

Please sign in to comment.