Favoriterepository
**Site relevance:** Spiralist.org
**Memory type:** plugin source memory
**Source path:** Spiralist/wp-content/plugins/spiralist-workspace/includes/Domain/FavoriteRepository.php
**Size:** 2 KB
Summary
namespace SpiralistWorkspace\Domain;
Source Preview
This source file is short enough to preview directly on its source-memory page.
<?php
namespace SpiralistWorkspace\Domain;
use SpiralistWorkspace\Installer;
if (!defined('ABSPATH')) {
exit;
}
/**
* Stores member favorites.
*/
class FavoriteRepository
{
/**
* Marks a prompt as a favorite.
*/
public function add(int $prompt_id, int $user_id): bool
{
global $wpdb;
$result = $wpdb->replace(
Installer::table('favorites'),
[
'prompt_post_id' => $prompt_id,
'user_id' => $user_id,
'created_utc' => gmdate('Y-m-d H:i:s'),
],
['%d', '%d', '%s']
);
return (bool) $result;
}
/**
* Removes a favorite.
*/
public function remove(int $prompt_id, int $user_id): bool
{
global $wpdb;
return (bool) $wpdb->delete(
Installer::table('favorites'),
[
'prompt_post_id' => $prompt_id,
'user_id' => $user_id,
],
['%d', '%d']
);
}
/**
* Returns favorite prompt IDs for a user.
*/
public function list_prompt_ids_for_user(int $user_id): array
{
global $wpdb;
$sql = $wpdb->prepare(
'SELECT prompt_post_id FROM ' . Installer::table('favorites') . ' WHERE user_id = %d ORDER BY created_utc DESC',
$user_id
);
$ids = $wpdb->get_col($sql);
return array_values(array_map('intval', is_array($ids) ? $ids : []));
}
/**
* Returns whether the prompt is already favorited.
*/
public function is_favorite(int $prompt_id, int $user_id): bool
{
global $wpdb;
$sql = $wpdb->prepare(
'SELECT COUNT(*) FROM ' . Installer::table('favorites') . ' WHERE prompt_post_id = %d AND user_id = %d',
$prompt_id,
$user_id
);
return (int) $wpdb->get_var($sql) > 0;
}
}