### Usage Examples with SofaScore Facade (Laravel) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Demonstrates how to use the SofaScore SDK within a Laravel application using the provided facade. Examples include fetching event details, team players, searching for teams, getting live events, and retrieving tournament standings. ```php use DevSmith88\SofaScore\Facades\SofaScore; // Get event details $event = SofaScore::events()->getDetails(12345); // Get team players $players = SofaScore::teams()->getPlayers(67890); // Search for teams $results = SofaScore::search()->searchTeams('Manchester'); // Get live football events $liveEvents = SofaScore::sports()->getLiveEvents('football'); // Get tournament standings $standings = SofaScore::tournaments()->getStandings(17, 52186, 'total'); ``` -------------------------------- ### Usage Example with Dependency Injection (Laravel) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Illustrates how to inject the SofaScore client into a Laravel controller using dependency injection. This allows for cleaner code and easier testing by injecting the SDK instance directly into the controller's constructor. ```php use DevSmith88\SofaScore\SofaScore; class MatchController extends Controller { public function __construct( protected SofaScore $sofascore ) {} public function show(int $matchId) { $event = $this->sofascore->events()->getDetails($matchId); $lineups = $this->sofascore->events()->getLineups($matchId); return view('match.show', compact('event', 'lineups')); } } ``` -------------------------------- ### Install SofaScore PHP SDK via Composer Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md This command installs the SofaScore PHP SDK using Composer, the dependency manager for PHP. Ensure Composer is installed globally on your system. ```bash composer require devsmith88/sofascore-php-sdk ``` -------------------------------- ### Implement Custom HTTP Client in PHP Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt This PHP code snippet shows how to implement a custom HTTP client by extending the `HttpClientInterface`. It includes examples of adding logging, caching responses, and making custom requests. This allows for advanced control over HTTP interactions with the SofaScore API. ```php info("API Request: GET {$endpoint}", $query); // Implement caching logic $cacheKey = md5($endpoint . serialize($query)); if ($cached = cache()->get($cacheKey)) { return $cached; } // Make actual request (implement your logic) $response = $this->makeRequest('GET', $endpoint, $query); // Cache for 5 minutes cache()->put($cacheKey, $response, 300); return $response; } public function post(string $endpoint, array $data = []): ?array { logger()->info("API Request: POST {$endpoint}", $data); return $this->makeRequest('POST', $endpoint, $data); } public function getRaw(string $endpoint): ?string { // Return raw binary data return $this->makeRawRequest($endpoint); } private function makeRequest(string $method, string $endpoint, array $data): ?array { // Your custom HTTP implementation } private function makeRawRequest(string $endpoint): ?string { // Your custom raw HTTP implementation } } // Use custom client $customClient = new CustomHttpClient(); $sofascore = SofaScore::withClient($customClient); $event = $sofascore->events()->getDetails(12345); ``` -------------------------------- ### Get Event Details, Lineups, Stats, H2H, Incidents, Heatmap, and Commentary (PHP) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Retrieve detailed information about a specific sports event, including lineups, statistics, head-to-head data, incidents, player heatmaps, and commentary. Requires a valid event ID and optionally a player ID and language code. ```php // Get event details $event = SofaScore::events()->getDetails(12345); // Get lineups $lineups = SofaScore::events()->getLineups(12345); // Returns: ['home' => [...], 'away' => [...]] // Get match statistics $stats = SofaScore::events()->getStatistics(12345); // Get head-to-head $h2h = SofaScore::events()->getH2H(12345); // Get incidents (goals, cards, etc.) $incidents = SofaScore::events()->getIncidents(12345); // Get player heatmap for event $heatmap = SofaScore::events()->getPlayerHeatmap(12345, 789); // Get commentary $commentary = SofaScore::events()->getCommentary(12345, 'en'); ``` -------------------------------- ### Get Player Details, Transfer History, Characteristics, Heatmap, and Ratings (PHP) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Fetch detailed information for a specific player, including their profile, past transfers, key characteristics, seasonal heatmap, and performance ratings. Requires player ID and season-specific parameters. ```php // Get player details $player = SofaScore::players()->getDetails(12345); // Get transfer history $transfers = SofaScore::players()->getTransferHistory(12345); // Get player characteristics $characteristics = SofaScore::players()->getCharacteristics(12345); // Get season heatmap $heatmap = SofaScore::players()->getSeasonHeatmap(12345, 17, 52186, 'overall'); // Get season ratings $ratings = SofaScore::players()->getSeasonRatings(12345, 17, 52186, 'overall'); ``` -------------------------------- ### Retrieve Tournament Data with SofaScore PHP SDK Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt This PHP code snippet demonstrates how to use the SofaScore PHP SDK to fetch various tournament-related data. It covers fetching league details, seasons, standings, teams, rounds, groups, event information, rankings, and media. Ensure the SofaScore SDK is installed and configured. ```php getDetails($leagueId); // Get all available seasons $seasons = SofaScore::tournaments()->getSeasons($leagueId); // Get league standings (total, home, away) $standingsTotal = SofaScore::tournaments()->getStandings($leagueId, $seasonId, 'total'); $standingsHome = SofaScore::tournaments()->getStandings($leagueId, $seasonId, 'home'); $standingsAway = SofaScore::tournaments()->getStandings($leagueId, $seasonId, 'away'); // Get all teams in a season $teams = SofaScore::tournaments()->getTeams($leagueId, $seasonId); // Get rounds/matchdays $rounds = SofaScore::tournaments()->getRounds($leagueId, $seasonId); // Get groups (for group stage tournaments like Champions League) $groups = SofaScore::tournaments()->getGroups($leagueId, $seasonId); // Get season info and venues $seasonInfo = SofaScore::tournaments()->getSeasonInfo($leagueId, $seasonId); $venues = SofaScore::tournaments()->getVenues($leagueId, $seasonId); // Get cup/bracket structure $cuptrees = SofaScore::tournaments()->getCuptrees($leagueId, $seasonId); // Get past and upcoming events with pagination $lastEvents = SofaScore::tournaments()->getLastEvents($leagueId, $seasonId, 0); // page 0 $nextEvents = SofaScore::tournaments()->getNextEvents($leagueId, $seasonId, 0); // Get events by specific round $roundEvents = SofaScore::tournaments()->getEventsByRound($leagueId, $seasonId, 38); // Get events by round with pagination $paginatedEvents = SofaScore::tournaments()->getEventsByRoundPaginated( $leagueId, $seasonId, 38, 'last', 1 ); // Get top teams and players $topTeams = SofaScore::tournaments()->getTopTeams($leagueId, $seasonId); $topPlayers = SofaScore::tournaments()->getTopPlayers($leagueId, $seasonId); $topPlayersPerGame = SofaScore::tournaments()->getTopPlayersPerGame($leagueId, $seasonId); // Get top players by position $topGoalkeepers = SofaScore::tournaments()->getTopPlayersByPosition($leagueId, $seasonId, 'goalkeeper'); $topDefenders = SofaScore::tournaments()->getTopPlayersByPosition($leagueId, $seasonId, 'defender'); // Get team of the week $totwRounds = SofaScore::tournaments()->getTeamOfTheWeekRounds($leagueId, $seasonId); $totw = SofaScore::tournaments()->getTeamOfTheWeek($leagueId, $seasonId, 38); // Get power rankings $powerRankingRounds = SofaScore::tournaments()->getPowerRankingRounds($leagueId, $seasonId); $powerRankings = SofaScore::tournaments()->getPowerRankings($leagueId, $seasonId, 38); // Get team events within tournament $teamId = 33; // Manchester United $teamEvents = SofaScore::tournaments()->getTeamEvents($leagueId, $seasonId, $teamId, 'last', 0); $teamPerformance = SofaScore::tournaments()->getTeamPerformanceGraph($leagueId, $seasonId, $teamId); // Get top ratings for a specific team $topRatings = SofaScore::tournaments()->getTopRatingsForTeam($leagueId, $seasonId, $teamId); // Get shot action areas $shotActions = SofaScore::tournaments()->getShotActionAreas($leagueId, $seasonId, 'overall'); // Get tournament media and main events $media = SofaScore::tournaments()->getMedia($leagueId); $mainEvents = SofaScore::tournaments()->getMainEvents($leagueId, 'last', 0); // MMA-specific events $mmaEvents = SofaScore::tournaments()->getMmaEvents($leagueId, 'main', 'last', 0); ``` -------------------------------- ### Get Team Details, Players, Transfers, Next Events, and Statistics (PHP) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Retrieve information about a specific sports team, including its general details, roster of players, transfer history, upcoming matches, and season-specific statistics. Requires team ID and season-related parameters. ```php // Get team details $team = SofaScore::teams()->getDetails(67890); // Get team players $players = SofaScore::teams()->getPlayers(67890); // Get team transfers $transfers = SofaScore::teams()->getTransfers(67890); // Get team's next events $nextEvents = SofaScore::teams()->getNextEvents(67890, 0); // Get team statistics for a season $stats = SofaScore::teams()->getStatistics(67890, 17, 52186, 'overall'); ``` -------------------------------- ### Get Tournament Details, Seasons, Standings, Top Players, Team of the Week, and Past Events (PHP) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Fetch comprehensive data for a specific tournament, including its details, available seasons, league standings, top-performing players, team of the week, and past events. Requires tournament ID, season ID, and optionally a category or type. ```php // Get tournament details $tournament = SofaScore::tournaments()->getDetails(17); // Get all seasons $seasons = SofaScore::tournaments()->getSeasons(17); // Get standings $standings = SofaScore::tournaments()->getStandings(17, 52186, 'total'); // Get top players $topPlayers = SofaScore::tournaments()->getTopPlayers(17, 52186); // Get team of the week $totw = SofaScore::tournaments()->getTeamOfTheWeek(17, 52186, 38); // Get past events $events = SofaScore::tournaments()->getLastEvents(17, 52186, 0); ``` -------------------------------- ### Configure SofaScore PHP SDK Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Demonstrates how to configure the SofaScore PHP SDK. Configuration can be done using environment variables or by directly instantiating the SofaScore client with custom parameters. Laravel-specific configuration steps are also outlined. ```php [ DevSmith88\SofaScore\SofaScoreServiceProvider::class, ], 'aliases' => [ 'SofaScore' => DevSmith88\SofaScore\Facades\SofaScore::class, ], ``` -------------------------------- ### Retrieve TV Channels and Media Content - PHP Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Access information about TV broadcasting channels for events and retrieve media content. This includes getting available channels for an event in a specific country and fetching raw image data. ```php getCountryChannels($eventId); // Returns channels available in different countries // Get channel votes for an event in specific country $channelVotes = SofaScore::media()->getChannelVotes($countryId, $eventId); // Get raw image content $image = SofaScore::media()->getImage('/image/path/logo.png'); // Returns raw binary image data ?> ``` -------------------------------- ### Initialize SofaScore Client in PHP and Laravel Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Illustrates different ways to initialize the SofaScore client. This includes standalone PHP usage, Laravel Facade pattern, dependency injection within Laravel controllers, and creating an instance from a configuration array. ```php events()->getDetails(12345); $team = $sofascore->teams()->getDetails(67890); // Laravel Facade usage $event = SofaScoreFacade::events()->getDetails(12345); $players = SofaScoreFacade::teams()->getPlayers(67890); // Laravel Dependency Injection class MatchController extends Controller { public function __construct( protected SofaScore $sofascore ) {} public function show(int $matchId) { $event = $this->sofascore->events()->getDetails($matchId); $lineups = $this->sofascore->events()->getLineups($matchId); $stats = $this->sofascore->events()->getStatistics($matchId); return view('match.show', compact('event', 'lineups', 'stats')); } } // Create instance from config array $sofascore = SofaScore::fromConfig([ 'base_url' => 'https://api.sofascore.com/api/v1', 'timeout' => 30, 'connect_timeout' => 10, 'user_agent' => 'CustomApp/2.0' ]); ``` -------------------------------- ### Get Referee Details, Statistics, and Events - PHP Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Retrieve comprehensive information about a referee, including their personal details, performance statistics (like cards and penalties awarded), and a history of their past events. This functionality requires a valid referee ID. ```php getDetails($refereeId); // Returns: ['referee' => ['id' => 12345, 'name' => 'Referee Name', 'country' => [...], ...]] // Get referee statistics (cards given, penalties awarded, etc.) $statistics = SofaScore::referees()->getStatistics($refereeId); // Get referee's past events with pagination $lastEvents = SofaScore::referees()->getLastEvents($refereeId, 0); $moreEvents = SofaScore::referees()->getLastEvents($refereeId, 1); // page 1 ?> ``` -------------------------------- ### ConfigService - Configuration and Utilities Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Access global configuration, rankings, managers, and transfers using the ConfigService. ```APIDOC ## ConfigService - Configuration and Utilities ### Description Access global configuration, rankings, managers, and transfers. ### Method GET ### Endpoint `/config/country` (for country config) `/config/rankings/{path}` (for rankings) `/config/manager/{id}` (for manager data) `/config/transfers` (for transfers) `/config/content/{path}` (for generic content) ### Parameters #### Path Parameters - **path** (string) - Required - The path for retrieving rankings or content. - **id** (string) - Required - The ID of the manager. #### Query Parameters - **sport** (string) - Optional - Filter transfers by sport. - **page** (integer) - Optional - The page number for retrieving transfers. ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; // Get country sport priorities configuration $countryConfig = SofaScore::config()->getCountryConfig(); // Get rankings by path $rankings = SofaScore::config()->getRankings('football/fifa'); // Get manager data by path $manager = SofaScore::config()->getManager('123'); // Get transfers with query parameters $transfers = SofaScore::config()->getTransfers([ 'sport' => 'football', 'page' => 0, ]); // Get generic content by path $content = SofaScore::config()->getContent('some/path'); ``` ### Response #### Success Response (200) - **countryConfig** (object) - Contains country sport priorities. - **rankings** (object) - Contains ranking data. - **manager** (object) - Contains manager data. - **transfers** (array) - Contains transfer information. - **content** (object) - Contains generic content. #### Response Example ```json { "countryConfig": { ... } } ``` ``` -------------------------------- ### Standalone PHP Usage (Without Laravel) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Shows how to instantiate and use the SofaScore SDK in a standalone PHP environment without a framework. You can create a client with default settings or provide custom configuration parameters like base URL and timeouts. ```php use DevSmith88\SofaScore\SofaScore; // Create client with default settings $sofascore = new SofaScore(); // Or with custom configuration $sofascore = new SofaScore( baseUrl: 'https://api.sofascore.com/api/v1', timeout: 30, connectTimeout: 10, userAgent: 'MyApp/1.0' ); // Use the client $event = $sofascore->events()->getDetails(12345); $team = $sofascore->teams()->getDetails(67890); ``` -------------------------------- ### Access Configuration, Rankings, Managers, and Transfers - PHP Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Utilize the ConfigService to access global settings, sports rankings, manager data, and transfer information. This service allows fetching data based on specific paths and query parameters. ```php getCountryConfig(); // Get rankings by path $rankings = SofaScore::config()->getRankings('football/fifa'); // Get manager data by path $manager = SofaScore::config()->getManager('123'); // manager ID // Get transfers with query parameters $transfers = SofaScore::config()->getTransfers([ 'sport' => 'football', 'page' => 0, ]); // Get generic content by path $content = SofaScore::config()->getContent('some/path'); ?> ``` -------------------------------- ### Get Sport Categories, Scheduled Events, Live Events, and Active Tournaments (PHP) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Retrieve data related to sports, including categories for a given sport, events scheduled for a specific date, currently live events, and active tournaments. Requires sport name and date parameters. ```php // Get all categories for a sport $categories = SofaScore::sports()->getCategories('football'); // Get scheduled events for a date $events = SofaScore::sports()->getScheduledEvents('football', '2024-01-15'); // Get live events $liveEvents = SofaScore::sports()->getLiveEvents('football'); // Get active tournaments $tournaments = SofaScore::sports()->getActiveTournaments('football', '2024-01-15'); ``` -------------------------------- ### Publish SofaScore Configuration (Laravel) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md This Artisan command publishes the SofaScore SDK's configuration file to your Laravel application. This allows for customization of settings like base URL, timeouts, and user agent. ```bash php artisan vendor:publish --tag=sofascore-config ``` -------------------------------- ### PlayerService API Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Endpoints for accessing player details, transfer history, performance metrics, and season-specific statistics. ```APIDOC ## PlayerService - Player Data and Career Statistics ### Description Access player details, transfer history, performance metrics, and season-specific statistics. ### Method Various (e.g., GET) ### Endpoints - `/players/getDetails/{playerId}` - `/players/getTransferHistory/{playerId}` - `/players/getPenaltyHistory/{playerId}` - `/players/getNearEvents/{playerId}` - `/players/getStatisticsSeasons/{playerId}` - `/players/getLastYearSummary/{playerId}` - `/players/getCharacteristics/{playerId}` - `/players/getAttributeOverviews/{playerId}` - `/players/getNationalTeamStatistics/{playerId}` - `/players/getUniqueTournamentSeasonTeams/{playerId}` - `/players/getMedia/{playerId}` - `/players/getSeoContent/{playerId}/{language}` - `/players/getLastEvents/{playerId}/{page}` - `/players/getTournamentEvents/{playerId}/{tournamentId}/{page}` - `/players/getSeasonRatings/{playerId}/{tournamentId}/{seasonId}/{filter}` - `/players/getSeasonShotActions/{playerId}/{tournamentId}/{seasonId}/{filter}` - `/players/getSeasonHeatmap/{playerId}/{tournamentId}/{seasonId}/{filter}` - `/players/getSeasonPenaltyHistory/{playerId}/{tournamentId}/{seasonId}` ### Parameters #### Path Parameters - **playerId** (integer) - Required - The ID of the player. - **tournamentId** (integer) - Required - The ID of the tournament. - **seasonId** (integer) - Required - The ID of the season. - **language** (string) - Required - The language code for SEO content (e.g., 'en'). - **page** (integer) - Required - The page number for pagination. - **filter** (string) - Optional - Filter for statistics (e.g., 'overall'). ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; $playerId = 12345; $tournamentId = 17; $seasonId = 52186; // Get player details $player = SofaScore::players()->getDetails($playerId); ``` ### Response #### Success Response (200) - **player** (object) - Details of the player. - **transfers** (array) - Transfer history of the player. - **penalties** (array) - Penalty history of the player. - **nearEvents** (array) - Upcoming events for the player. - **statsSeasons** (array) - Statistics seasons available for the player. - **yearSummary** (object) - Last year performance summary. - **characteristics** (object) - Player characteristics (attributes, strengths). - **attributes** (object) - Player attribute overviews. - **nationalStats** (object) - National team statistics for the player. - **tournamentTeams** (array) - Unique tournament season teams the player has played for. - **media** (array) - Media associated with the player. - **seoContent** (object) - SEO content for the player page. - **events** (array) - List of player events. - **tournamentEvents** (array) - Player events in a specific tournament. - **seasonRatings** (object) - Season ratings for the player. - **shotActions** (object) - Season shot actions for the player. - **heatmap** (object) - Heatmap data for a season. - **seasonPenalties** (array) - Penalty history for a specific season. #### Response Example ```json { "player": { "id": 12345, "name": "Player Name", "position": "F" } } ``` ``` -------------------------------- ### Register SofaScore Service Provider and Facade (Laravel Manual) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/README.md Optional manual registration for the SofaScore SDK's service provider and facade in a Laravel application. This is typically handled automatically by Laravel's auto-discovery feature. ```php /* config/app.php */ 'providers' => [ // ... DevSmith88\SofaScore\SofaScoreServiceProvider::class, ], 'aliases' => [ // ... 'SofaScore' => DevSmith88\SofaScore\Facades\SofaScore::class, ] ``` -------------------------------- ### Retrieve Team Data using SofaScore PHP SDK Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt This snippet demonstrates how to fetch various details about a team using the TeamService of the SofaScore PHP SDK. It covers retrieving team information, player rosters, transfer history, rankings, performance metrics, season statistics, and media. Ensure the SofaScore facade is correctly imported. ```php getDetails($teamId); // Returns: ['team' => ['id' => 67890, 'name' => 'Team Name', 'country' => [...], ...]] // Get current squad/players $players = SofaScore::teams()->getPlayers($teamId); // Get transfer history $transfers = SofaScore::teams()->getTransfers($teamId); // Get team rankings $rankings = SofaScore::teams()->getRankings($teamId); // Get team performance metrics $performance = SofaScore::teams()->getPerformance($teamId); // Get unique tournaments team participates in $tournaments = SofaScore::teams()->getUniqueTournaments($teamId); // Get standings and statistics seasons $standingsSeasons = SofaScore::teams()->getStandingsSeasons($teamId); $statsSeasons = SofaScore::teams()->getStatisticsSeasons($teamId); // Get career statistics $careerStats = SofaScore::teams()->getCareerStatistics($teamId); // Get team media $media = SofaScore::teams()->getMedia($teamId); // Get SEO content for team page $seoContent = SofaScore::teams()->getSeoContent($teamId, 'en'); // Get team events with pagination $lastEvents = SofaScore::teams()->getLastEvents($teamId, 0); $allLastEvents = SofaScore::teams()->getAllLastEvents($teamId, 0); $nextEvents = SofaScore::teams()->getNextEvents($teamId, 0); // Get top players for team in specific season $topPlayers = SofaScore::teams()->getTopPlayers($teamId, $tournamentId, $seasonId, 'overall'); // Get team season statistics $statistics = SofaScore::teams()->getStatistics($teamId, $tournamentId, $seasonId, 'overall'); // Get team ranks in season $ranks = SofaScore::teams()->getRanks($teamId, $tournamentId, $seasonId, 'overall'); // Get team heatmap for season $heatmap = SofaScore::teams()->getHeatmap($teamId, $tournamentId, $seasonId, 'overall'); // Get goal distributions $goalDistributions = SofaScore::teams()->getGoalDistributions($teamId, $tournamentId, $seasonId); // Motorsport-specific endpoints $driverHistory = SofaScore::teams()->getDriverCareerHistory($teamId); $lastRaces = SofaScore::teams()->getLastRaces($teamId, 0); // Get stage seasons $stageSeasons = SofaScore::teams()->getStageSeasons($teamId); ``` -------------------------------- ### Error Handling Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Details on how to handle API errors gracefully using specific exception types provided by the SDK. ```APIDOC ## Error Handling ### Description Handle API errors gracefully with specific exception types that provide detailed error context. ### Exception Types - **ApiException**: For API-specific errors with detailed context (status code, endpoint, response body). - **SofaScoreException**: For general SDK errors. ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; use DevSmith88\SofaScore\Exceptions\ApiException; use DevSmith88\SofaScore\Exceptions\SofaScoreException; try { $event = SofaScore::events()->getDetails(12345); // Process event data } catch (ApiException $e) { // Handle API-specific errors echo "API Error: " . $e->getMessage() . "\n"; echo "Status Code: " . $e->getStatusCode() . "\n"; echo "Endpoint: " . $e->getEndpoint() . "\n"; echo "Response Body: " . $e->getResponseBody() . "\n"; if ($e->getStatusCode() === 404) { echo "Event not found"; } elseif ($e->getStatusCode() === 429) { echo "Rate limit exceeded"; } } catch (SofaScoreException $e) { // Handle general SDK errors echo "SDK Error: " . $e->getMessage(); } // Example: Retry logic for rate limiting function fetchWithRetry(callable $callback, int $maxRetries = 3): mixed { $attempts = 0; while ($attempts < $maxRetries) { try { return $callback(); } catch (ApiException $e) { if ($e->getStatusCode() === 429) { $attempts++; sleep(pow(2, $attempts)); // Exponential backoff continue; } throw $e; } } throw new SofaScoreException("Max retries exceeded"); } $event = fetchWithRetry(fn() => SofaScore::events()->getDetails(12345)); ``` ### Response #### Error Response Examples - **404 Not Found**: Indicates that the requested resource was not found. - **429 Too Many Requests**: Indicates that the rate limit has been exceeded. #### Exception Details - **ApiException**: Provides `getMessage()`, `getStatusCode()`, `getEndpoint()`, and `getResponseBody()` methods. - **SofaScoreException**: Provides `getMessage()` method. ``` -------------------------------- ### MediaService - TV Channels and Media Content Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Access TV broadcasting information and media content using the MediaService. ```APIDOC ## MediaService - TV Channels and Media Content ### Description Access TV broadcasting information and media content. ### Method GET ### Endpoint `/media/event/{eventId}/channels` (for country channels) `/media/country/{countryId}/event/{eventId}/channels` (for channel votes) `/media/image/{imagePath}` (for image content) ### Parameters #### Path Parameters - **eventId** (integer) - Required - The unique identifier for the event. - **countryId** (integer) - Required - The unique identifier for the country. - **imagePath** (string) - Required - The path to the image file. ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; $eventId = 12345; $countryId = 1; // Get available TV channels for an event by country $countryChannels = SofaScore::media()->getCountryChannels($eventId); // Get channel votes for an event in specific country $channelVotes = SofaScore::media()->getChannelVotes($countryId, $eventId); // Get raw image content $image = SofaScore::media()->getImage('/image/path/logo.png'); ``` ### Response #### Success Response (200) - **countryChannels** (object) - Contains TV channel information for different countries. - **channelVotes** (object) - Contains channel vote data for a specific event and country. - **image** (binary) - Raw binary image data. #### Response Example ```json { "countryChannels": { ... } } ``` ``` -------------------------------- ### Add New Endpoint to README.md (Markdown) Source: https://github.com/devsmith88/sofascore-php-sdk/blob/main/CONTRIBUTING.md This snippet shows the markdown table format required for adding new API endpoints to the README.md file. It includes the HTTP method, the endpoint path with parameters, and a description. ```markdown | GET | `/endpoint/{param}` | Description of what it does | ``` -------------------------------- ### Retrieve Match Details and Statistics with SofaScore PHP SDK Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt This snippet demonstrates how to use the SofaScore PHP SDK's EventService to fetch various types of match-related data. It covers retrieving complete event details, lineups, statistics, incidents, head-to-head history, momentum graphs, commentary, highlights, manager information, fan votes, pre-game form, team streaks, featured players, AI insights, player-specific data (heatmap, shotmap, stats), team-specific data (heatmap, shotmap), tennis-specific data (point-by-point, power), betting odds, and media. ```php getDetails($matchId); // Returns: ['event' => ['id' => 12345, 'homeTeam' => [...], 'awayTeam' => [...], 'status' => [...], ...]] // Get team lineups (formations, starting XI, substitutes) $lineups = SofaScore::events()->getLineups($matchId); // Returns: ['home' => ['players' => [...], 'formation' => '4-3-3'], 'away' => [...]] // Get match statistics (possession, shots, passes, etc.) $stats = SofaScore::events()->getStatistics($matchId); // Get match incidents (goals, cards, substitutions) $incidents = SofaScore::events()->getIncidents($matchId); // Get head-to-head history between teams $h2h = SofaScore::events()->getH2H($matchId); // Get momentum graph data for live visualization $graph = SofaScore::events()->getGraph($matchId); // Get match commentary in specific language $commentary = SofaScore::events()->getCommentary($matchId, 'en'); // Get match highlights $highlights = SofaScore::events()->getHighlights($matchId); // Get team managers info $managers = SofaScore::events()->getManagers($matchId); // Get fan voting results $votes = SofaScore::events()->getVotes($matchId); // Get pre-game form analysis $pregameForm = SofaScore::events()->getPregameForm($matchId); // Get team streaks (winning/losing streaks) $streaks = SofaScore::events()->getTeamStreaks($matchId); // Get featured/best players $featuredPlayers = SofaScore::events()->getFeaturedPlayers($matchId); $bestPlayers = SofaScore::events()->getBestPlayers($matchId); // Get AI-generated post-match insights $aiInsights = SofaScore::events()->getAiInsights($matchId, 'en'); // Get player-specific data for a match $playerId = 789; $playerHeatmap = SofaScore::events()->getPlayerHeatmap($matchId, $playerId); $playerShotmap = SofaScore::events()->getPlayerShotmap($matchId, $playerId); $playerStats = SofaScore::events()->getPlayerStatistics($matchId, $playerId); // Get team-specific data for a match $teamId = 456; $teamHeatmap = SofaScore::events()->getTeamHeatmap($matchId, $teamId); $teamShotmap = SofaScore::events()->getTeamShotmap($matchId, $teamId); // Tennis-specific endpoints $pointByPoint = SofaScore::events()->getTennisPointByPoint($matchId); $tennisPower = SofaScore::events()->getTennisPower($matchId); // Get betting odds for an event $odds = SofaScore::events()->getOdds($matchId, 1, 'all'); // providerId=1, type='all' // Get event media (images, videos) $media = SofaScore::events()->getMedia($matchId); ``` -------------------------------- ### TeamService API Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Endpoints for retrieving team information, player rosters, transfers, events, and season statistics. ```APIDOC ## TeamService - Team Information and Statistics ### Description Retrieve team details, player rosters, transfers, events, and season statistics. ### Method Various (e.g., GET) ### Endpoints - `/teams/getDetails/{teamId}` - `/teams/getPlayers/{teamId}` - `/teams/getTransfers/{teamId}` - `/teams/getRankings/{teamId}` - `/teams/getPerformance/{teamId}` - `/teams/getUniqueTournaments/{teamId}` - `/teams/getStandingsSeasons/{teamId}` - `/teams/getStatisticsSeasons/{teamId}` - `/teams/getCareerStatistics/{teamId}` - `/teams/getMedia/{teamId}` - `/teams/getSeoContent/{teamId}/{language}` - `/teams/getLastEvents/{teamId}/{page}` - `/teams/getAllLastEvents/{teamId}/{page}` - `/teams/getNextEvents/{teamId}/{page}` - `/teams/getTopPlayers/{teamId}/{tournamentId}/{seasonId}/{filter}` - `/teams/getStatistics/{teamId}/{tournamentId}/{seasonId}/{filter}` - `/teams/getRanks/{teamId}/{tournamentId}/{seasonId}/{filter}` - `/teams/getHeatmap/{teamId}/{tournamentId}/{seasonId}/{filter}` - `/teams/getGoalDistributions/{teamId}/{tournamentId}/{seasonId}` - `/teams/getDriverCareerHistory/{teamId}` - `/teams/getLastRaces/{teamId}/{page}` - `/teams/getStageSeasons/{teamId}` ### Parameters #### Path Parameters - **teamId** (integer) - Required - The ID of the team. - **tournamentId** (integer) - Required - The ID of the tournament. - **seasonId** (integer) - Required - The ID of the season. - **language** (string) - Required - The language code for SEO content (e.g., 'en'). - **page** (integer) - Required - The page number for pagination. - **filter** (string) - Optional - Filter for statistics (e.g., 'overall'). ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; $teamId = 67890; $tournamentId = 17; $seasonId = 52186; // Get team details $team = SofaScore::teams()->getDetails($teamId); ``` ### Response #### Success Response (200) - **team** (object) - Details of the team. - **players** (array) - List of players in the team. - **transfers** (array) - Transfer history of the team. - **rankings** (array) - Rankings of the team. - **performance** (object) - Performance metrics of the team. - **tournaments** (array) - Unique tournaments the team participates in. - **standingsSeasons** (array) - Standings for different seasons. - **statsSeasons** (array) - Statistics seasons for the team. - **careerStats** (object) - Career statistics of the team. - **media** (array) - Media associated with the team. - **seoContent** (object) - SEO content for the team page. - **events** (array) - List of team events. - **topPlayers** (array) - Top players in a specific season. - **statistics** (object) - Season statistics for the team. - **ranks** (object) - Ranks in a specific season. - **heatmap** (object) - Heatmap data for a season. - **goalDistributions** (object) - Goal distributions for a season. - **driverHistory** (object) - Driver career history (Motorsport). - **lastRaces** (array) - Last races participated in (Motorsport). - **stageSeasons** (array) - Stage seasons for the team. #### Response Example ```json { "team": { "id": 67890, "name": "Team Name", "country": {"code": "US", "name": "United States"} } } ``` ``` -------------------------------- ### Retrieve Player Data using SofaScore PHP SDK Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt This snippet illustrates how to access player information using the PlayerService of the SofaScore PHP SDK. It covers fetching player details, transfer and penalty history, upcoming events, performance metrics, characteristics, and season-specific statistics. Ensure the SofaScore facade is correctly imported. ```php getDetails($playerId); // Returns: ['player' => ['id' => 12345, 'name' => 'Player Name', 'position' => 'F', ...]] // Get transfer history $transfers = SofaScore::players()->getTransferHistory($playerId); // Get penalty history $penalties = SofaScore::players()->getPenaltyHistory($playerId); // Get near/upcoming events $nearEvents = SofaScore::players()->getNearEvents($playerId); // Get available statistics seasons $statsSeasons = SofaScore::players()->getStatisticsSeasons($playerId); // Get last year performance summary $yearSummary = SofaScore::players()->getLastYearSummary($playerId); // Get player characteristics (attributes, strengths) $characteristics = SofaScore::players()->getCharacteristics($playerId); // Get attribute overviews $attributes = SofaScore::players()->getAttributeOverviews($playerId); // Get national team statistics $nationalStats = SofaScore::players()->getNationalTeamStatistics($playerId); // Get unique tournament season teams $tournamentTeams = SofaScore::players()->getUniqueTournamentSeasonTeams($playerId); // Get player media $media = SofaScore::players()->getMedia($playerId); // Get SEO content $seoContent = SofaScore::players()->getSeoContent($playerId, 'en'); // Get player events with pagination $lastEvents = SofaScore::players()->getLastEvents($playerId, 0); // Get player events in specific tournament $tournamentEvents = SofaScore::players()->getTournamentEvents($playerId, $tournamentId, 0); // Get season-specific ratings $seasonRatings = SofaScore::players()->getSeasonRatings($playerId, $tournamentId, $seasonId, 'overall'); // Get season shot actions $shotActions = SofaScore::players()->getSeasonShotActions($playerId, $tournamentId, $seasonId, 'overall'); // Get season heatmap $heatmap = SofaScore::players()->getSeasonHeatmap($playerId, $tournamentId, $seasonId, 'overall'); // Get penalty history for specific season $seasonPenalties = SofaScore::players()->getSeasonPenaltyHistory($playerId, $tournamentId, $seasonId); ``` -------------------------------- ### RefereeService - Referee Information Source: https://context7.com/devsmith88/sofascore-php-sdk/llms.txt Access referee details, statistics, and event history using the RefereeService. ```APIDOC ## RefereeService - Referee Information ### Description Access referee details, statistics, and event history. ### Method GET ### Endpoint `/referees/{refereeId}` (for details and statistics) `/referees/{refereeId}/events` (for last events) ### Parameters #### Path Parameters - **refereeId** (integer) - Required - The unique identifier for the referee. #### Query Parameters - **page** (integer) - Optional - The page number for retrieving past events (defaults to 0). ### Request Example ```php use DevSmith88\SofaScore\Facades\SofaScore; $refereeId = 12345; // Get referee details $referee = SofaScore::referees()->getDetails($refereeId); // Get referee statistics $statistics = SofaScore::referees()->getStatistics($refereeId); // Get referee's past events (page 0) $lastEvents = SofaScore::referees()->getLastEvents($refereeId, 0); ``` ### Response #### Success Response (200) - **referee** (object) - Contains referee details (id, name, country, etc.). - **statistics** (object) - Contains referee statistics (cards given, penalties awarded, etc.). - **events** (array) - Contains a list of past events associated with the referee. #### Response Example ```json { "referee": { "id": 12345, "name": "Referee Name", "country": { ... } } } ``` ```