Get Tournament History
The get tournament history method retrieves a player's complete tournament participation history, including tournaments they've joined, scores submitted, and rewards claimed.
Overview
The getTournamentHistory method:
- Retrieves player's tournament participation history
- Includes tournament metadata and player performance
- Shows completed and ongoing tournaments
- Returns historical data for analysis
Method Signature
public function getTournamentHistory(string $gameID): array
Parameters
Required Parameters
gameID(String) - The Game ID to retrieve tournament history for
Return Value
Returns an array containing:
- Tournament history - List of tournaments player participated in
- Performance data - Scores, rankings, and achievements
- Reward information - Prizes won and claimed status
- Participation dates - When player joined and completed tournaments
Basic Usage
Get Player Tournament History
use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;
$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);
try {
$history = $moitribe->tournRequestsHandler->getTournamentHistory('your-game-id');
echo "Tournament History:\n";
echo "Total tournaments: " . count($history) . "\n\n";
foreach ($history as $tournament) {
echo "Tournament: " . $tournament->getName() . "\n";
echo "ID: " . $tournament->getId() . "\n";
echo "Status: " . $tournament->getStatus() . "\n";
echo "Joined: " . $tournament->getJoinDate() . "\n";
echo "Score: " . $tournament->getPlayerScore() . "\n";
echo "Rank: " . $tournament->getPlayerRank() . "\n";
if ($tournament->getPrize()) {
echo "Prize: " . $tournament->getPrize() . "\n";
echo "Claimed: " . ($tournament->isPrizeClaimed() ? 'Yes' : 'No') . "\n";
}
echo "---\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Filter Tournament History
function getFilteredTournamentHistory($gameId, $filters = []) {
global $moitribe;
try {
$history = $moitribe->tournRequestsHandler->getTournamentHistory($gameId);
$filteredHistory = $history;
// Filter by status
if (isset($filters['status'])) {
$filteredHistory = array_filter($filteredHistory, function($tournament) use ($filters) {
return $tournament->getStatus() === $filters['status'];
});
}
// Filter by date range
if (isset($filters['start_date']) && isset($filters['end_date'])) {
$filteredHistory = array_filter($filteredHistory, function($tournament) use ($filters) {
$joinDate = strtotime($tournament->getJoinDate());
return $joinDate >= strtotime($filters['start_date']) &&
$joinDate <= strtotime($filters['end_date']);
});
}
// Filter by prize won
if (isset($filters['prize_won'])) {
$filteredHistory = array_filter($filteredHistory, function($tournament) use ($filters) {
$hasPrize = !empty($tournament->getPrize());
return $filters['prize_won'] ? $hasPrize : !$hasPrize;
});
}
// Sort by date (newest first)
usort($filteredHistory, function($a, $b) {
return strtotime($b->getJoinDate()) - strtotime($a->getJoinDate());
});
return array_values($filteredHistory);
} catch (Exception $e) {
error_log("Error getting tournament history: " . $e->getMessage());
return [];
}
}
// Usage examples
$allHistory = getFilteredTournamentHistory('your-game-id');
$activeTournaments = getFilteredTournamentHistory('your-game-id', [
'status' => 'active'
]);
$recentHistory = getFilteredTournamentHistory('your-game-id', [
'start_date' => '2024-01-01',
'end_date' => '2024-12-31'
]);
$winningHistory = getFilteredTournamentHistory('your-game-id', [
'prize_won' => true
]);
Integration Examples
Player Statistics Dashboard
class TournamentHistoryAnalyzer {
private $moitribe;
private $gameId;
public function __construct($moitribe, $gameId) {
$this->moitribe = $moitribe;
$this->gameId = $gameId;
}
public function getPlayerStatistics($playerId) {
try {
$history = $this->moitribe->tournRequestsHandler->getTournamentHistory($this->gameId);
$stats = [
'total_tournaments' => count($history),
'active_tournaments' => 0,
'completed_tournaments' => 0,
'total_winnings' => 0,
'best_score' => 0,
'average_score' => 0,
'best_rank' => PHP_INT_MAX,
'prizes_won' => 0,
'prizes_claimed' => 0,
'recent_activity' => []
];
$totalScore = 0;
$scoreCount = 0;
foreach ($history as $tournament) {
// Count by status
if ($tournament->getStatus() === 'active') {
$stats['active_tournaments']++;
} elseif ($tournament->getStatus() === 'ended') {
$stats['completed_tournaments']++;
}
// Score statistics
$playerScore = $tournament->getPlayerScore();
if ($playerScore > 0) {
$totalScore += $playerScore;
$scoreCount++;
$stats['best_score'] = max($stats['best_score'], $playerScore);
}
// Rank statistics
$playerRank = $tournament->getPlayerRank();
if ($playerRank > 0) {
$stats['best_rank'] = min($stats['best_rank'], $playerRank);
}
// Prize statistics
$prize = $tournament->getPrize();
if ($prize) {
$stats['prizes_won']++;
$stats['total_winnings'] += $this->parsePrizeValue($prize);
if ($tournament->isPrizeClaimed()) {
$stats['prizes_claimed']++;
}
}
// Recent activity (last 5 tournaments)
if (count($stats['recent_activity']) < 5) {
$stats['recent_activity'][] = [
'tournament_name' => $tournament->getName(),
'date' => $tournament->getJoinDate(),
'score' => $playerScore,
'rank' => $playerRank,
'prize' => $prize
];
}
}
// Calculate averages
if ($scoreCount > 0) {
$stats['average_score'] = round($totalScore / $scoreCount, 2);
}
return $stats;
} catch (Exception $e) {
error_log("Error analyzing tournament history: " . $e->getMessage());
return null;
}
}
public function getPerformanceTrends($playerId, $months = 6) {
try {
$history = $this->moitribe->tournRequestsHandler->getTournamentHistory($this->gameId);
$trends = [];
$cutoffDate = strtotime("-$months months");
foreach ($history as $tournament) {
$joinDate = strtotime($tournament->getJoinDate());
if ($joinDate < $cutoffDate) {
continue; // Skip old tournaments
}
$monthKey = date('Y-m', $joinDate);
if (!isset($trends[$monthKey])) {
$trends[$monthKey] = [
'tournaments_played' => 0,
'total_score' => 0,
'best_score' => 0,
'average_rank' => 0,
'prizes_won' => 0
];
}
$trends[$monthKey]['tournaments_played']++;
$trends[$monthKey]['total_score'] += $tournament->getPlayerScore();
$trends[$monthKey]['best_score'] = max(
$trends[$monthKey]['best_score'],
$tournament->getPlayerScore()
);
if ($tournament->getPlayerRank() > 0) {
$trends[$monthKey]['average_rank'] += $tournament->getPlayerRank();
}
if ($tournament->getPrize()) {
$trends[$monthKey]['prizes_won']++;
}
}
// Calculate monthly averages
foreach ($trends as $month => &$data) {
if ($data['tournaments_played'] > 0) {
$data['average_score'] = round($data['total_score'] / $data['tournaments_played'], 2);
$data['average_rank'] = round($data['average_rank'] / $data['tournaments_played'], 1);
}
}
return $trends;
} catch (Exception $e) {
error_log("Error getting performance trends: " . $e->getMessage());
return [];
}
}
private function parsePrizeValue($prize) {
// Simple prize value parsing - implement based on your prize system
if (is_numeric($prize)) {
return (float)$prize;
}
// For non-numeric prizes, return a default value
return 0;
}
}
// Usage
$analyzer = new TournamentHistoryAnalyzer($moitribe, 'your-game-id');
$stats = $analyzer->getPlayerStatistics('player-123');
echo "Player Statistics:\n";
echo "Total Tournaments: " . $stats['total_tournaments'] . "\n";
echo "Completed: " . $stats['completed_tournaments'] . "\n";
echo "Best Score: " . $stats['best_score'] . "\n";
echo "Average Score: " . $stats['average_score'] . "\n";
echo "Best Rank: " . ($stats['best_rank'] === PHP_INT_MAX ? 'N/A' : $stats['best_rank']) . "\n";
echo "Prizes Won: " . $stats['prizes_won'] . "\n";
echo "Total Winnings: " . $stats['total_winnings'] . "\n";
$trends = $analyzer->getPerformanceTrends('player-123', 3);
echo "\nRecent Performance Trends:\n";
foreach ($trends as $month => $data) {
echo "$month: {$data['tournaments_played']} tournaments, ";
echo "Avg Score: {$data['average_score']}, ";
echo "Avg Rank: {$data['average_rank']}\n";
}
Tournament History API Endpoint
function getTournamentHistoryAPI() {
global $moitribe;
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}
$playerId = $_GET['player_id'] ?? '';
$gameId = $_GET['game_id'] ?? 'your-game-id';
$filters = [
'status' => $_GET['status'] ?? null,
'limit' => (int)($_GET['limit'] ?? 50),
'offset' => (int)($_GET['offset'] ?? 0)
];
try {
if (empty($playerId)) {
throw new InvalidArgumentException('Player ID is required');
}
$history = $moitribe->tournRequestsHandler->getTournamentHistory($gameId);
// Apply filters
$filteredHistory = $history;
if ($filters['status']) {
$filteredHistory = array_filter($filteredHistory, function($tournament) use ($filters) {
return $tournament->getStatus() === $filters['status'];
});
}
// Apply pagination
$total = count($filteredHistory);
$filteredHistory = array_slice($filteredHistory, $filters['offset'], $filters['limit']);
// Format response
$formattedHistory = array_map(function($tournament) {
return [
'tournament_id' => $tournament->getId(),
'tournament_name' => $tournament->getName(),
'status' => $tournament->getStatus(),
'join_date' => $tournament->getJoinDate(),
'player_score' => $tournament->getPlayerScore(),
'player_rank' => $tournament->getPlayerRank(),
'prize' => $tournament->getPrize(),
'prize_claimed' => $tournament->isPrizeClaimed(),
'end_date' => $tournament->getEndDate()
];
}, $filteredHistory);
http_response_code(200);
echo json_encode([
'success' => true,
'data' => $formattedHistory,
'pagination' => [
'total' => $total,
'limit' => $filters['limit'],
'offset' => $filters['offset'],
'has_more' => ($filters['offset'] + $filters['limit']) < $total
]
]);
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Server error occurred']);
error_log("Tournament history API error: " . $e->getMessage());
}
}
// Route handler
if (strpos($_SERVER['REQUEST_URI'], '/api/tournament/history') !== false) {
getTournamentHistoryAPI();
}
Error Handling
Common Error Scenarios
- Invalid game ID - Game doesn't exist
- Player not found - Player ID doesn't exist
- Access denied - No permission to view history
- Network issues - API communication problems
Error Handling Example
function safeGetTournamentHistory($gameId) {
global $moitribe;
try {
if (empty($gameId)) {
throw new InvalidArgumentException("Game ID is required");
}
$history = $moitribe->tournRequestsHandler->getTournamentHistory($gameId);
return [
'success' => true,
'data' => $history,
'count' => count($history)
];
} catch (InvalidArgumentException $e) {
return [
'success' => false,
'error' => 'Invalid input: ' . $e->getMessage()
];
} catch (Exception $e) {
error_log("Tournament history error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve tournament history'
];
}
}
Best Practices
-
Implement Pagination
- History can become very large over time
- Use reasonable page sizes (20-50 items)
- Provide filtering options
-
Cache History Data
- Tournament history doesn't change frequently
- Cache for longer periods (10-30 minutes)
- Invalidate when new tournaments are completed
-
Provide Analytics
- Calculate performance trends
- Show statistics and achievements
- Display progress over time
-
Protect Privacy
- Only show history to authenticated players
- Consider privacy settings
- Limit sensitive information exposure
Related Methods
- List Tournaments - Find new tournaments to join
- Join Tournament - Participate in tournaments
- Submit Tournament Score - Submit scores during tournaments
- Claim Tournament Rewards - Claim prizes from completed tournaments