From b0c0ca4f5435cd2042ff361abb57b2d42dfbb312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=CC=81=20Pimpa=CC=83o?= Date: Thu, 16 May 2024 13:16:08 +0100 Subject: [PATCH] docs: updated base configuration, resource methods and other improvements --- README.md | 23 +-- docs/01-usage.md | 21 +- docs/02-configuration.md | 248 +++++++---------------- docs/03-supported-endpoints.md | 260 ++++++++++++++++--------- docs/04-error-handling.md | 18 +- docs/{05-objects.md => 05-entities.md} | 0 tests/ApiErrorTest_.php | 96 --------- 7 files changed, 259 insertions(+), 407 deletions(-) rename docs/{05-objects.md => 05-entities.md} (100%) delete mode 100644 tests/ApiErrorTest_.php diff --git a/README.md b/README.md index 146ea1f..24c2192 100644 --- a/README.md +++ b/README.md @@ -19,35 +19,24 @@ You must sign up for a [SportMonks account](https://www.sportmonks.com/football- ## Installation -You can install the library via [Composer](https://getcomposer.org/): +Install the library via [Composer](https://getcomposer.org/): ```bash composer require programmatordev/sportmonksfootball-php-api ``` -To use the library, use Composer's [autoload](https://getcomposer.org/doc/01-basic-usage.md#autoloading): - -```php -require_once 'vendor/autoload.php'; -``` - ## Basic Usage Simple usage looks like: ```php -use ProgrammatorDev\SportMonksFootball\Config; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -// Initialize -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey' - ]) -); +// initialize +$api = new SportMonksFootball('yourapikey'); -// Get all livescores of the current day -$livescores = $sportMonksFootball->livescores()->getAll(); +// get all livescores of the current day +$livescores = $api->livescores()->getAll(); ``` ## Documentation @@ -59,7 +48,7 @@ $livescores = $sportMonksFootball->livescores()->getAll(); - [Odds](docs/03-supported-endpoints.md#odds-endpoints) - [Core](docs/03-supported-endpoints.md#core-endpoints) - [Error Handling](docs/04-error-handling.md) -- [Objects](docs/05-objects.md) +- [Entities](docs/05-entities.md) ## Contributing diff --git a/docs/01-usage.md b/docs/01-usage.md index b936b29..f22bab3 100644 --- a/docs/01-usage.md +++ b/docs/01-usage.md @@ -16,33 +16,22 @@ You must sign up for a [SportMonks account](https://www.sportmonks.com/football- ## Installation -You can install the library via [Composer](https://getcomposer.org/): +Install the library via [Composer](https://getcomposer.org/): ```bash composer require programmatordev/sportmonksfootball-php-api ``` -To use the library, use Composer's [autoload](https://getcomposer.org/doc/01-basic-usage.md#autoloading): - -```php -require_once 'vendor/autoload.php'; -``` - ## Basic Usage Simple usage looks like: ```php -use ProgrammatorDev\SportMonksFootball\Config; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -// Initialize -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey' - ]) -); +// initialize +$api = new SportMonksFootball('yourapikey'); -// Get all livescores of the current day -$livescores = $sportMonksFootball->livescores()->getAll(); +// get all livescores of the current day +$livescores = $api->livescores()->getAll(); ``` diff --git a/docs/02-configuration.md b/docs/02-configuration.md index 14ec153..1eb041b 100644 --- a/docs/02-configuration.md +++ b/docs/02-configuration.md @@ -2,251 +2,151 @@ - [Default Configuration](#default-configuration) - [Options](#options) - - [applicationKey](#applicationkey) - [timezone](#timezone) - [language](#language) - - [httpClientBuilder](#httpclientbuilder) - - [cache](#cache) - - [logger](#logger) -- [Config Object](#config-object) +- [Methods](#methods) + - [setClientBuilder](#setclientbuilder) + - [setCacheBuilder](#setcachebuilder) + - [setLoggerBuilder](#setloggerbuilder) ## Default Configuration -Only the `applicationKey` option is required: +```php +SportMonksFootball(string $apiKey, array $options => []); +``` ```php -use ProgrammatorDev\SportMonksFootball\Config; -use ProgrammatorDev\SportMonksFootball\HttpClient\HttpClientBuilder; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', // required - 'timezone' => 'UTC', - 'language' => 'en', - 'httpClientBuilder' => new HttpClientBuilder(), - 'cache' => null, - 'logger' => null - ]) -); +$api = new SportMonksFootball('yourapikey', [ + 'timezone' => 'UTC', + 'language' => 'en' +]); ``` ## Options -### `applicationKey` - -Required for all requests. Check the [API Key](01-usage.md#api-key) section for more information. - ### `timezone` Timezone used when retrieving data. Check the [official documentation](https://docs.sportmonks.com/football/tutorials-and-guides/tutorials/timezone-parameters-on-different-endpoints) for more information. -List of all supported timezones can be found [here](https://www.php.net/manual/en/timezones.php). - Example: ```php -use ProgrammatorDev\SportMonksFootball\Config; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'timezone' => 'Europe/Lisbon' - ]) -); +$api = new SportMonksFootball('yourapikey', [ + 'timezone' => 'Europe/Lisbon' +]); ``` ### `language` Language used when retrieving data. - List of all available languages can be found [here](https://docs.sportmonks.com/football/api/translations-beta) (still in beta). -[Constants](../src/Language/Language.php) are also available. Example: ```php -use ProgrammatorDev\SportMonksFootball\Config; use ProgrammatorDev\SportMonksFootball\Language\Language; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'language' => Language::JAPANESE - ]) -); +$api = new SportMonksFootball('yourapikey', [ + 'language' => Language::JAPANESE +]); ``` -### `httpClientBuilder` +## Methods -Configure a PSR-18 HTTP client and PSR-17 HTTP factory adapters. +> [!IMPORTANT] +> The [PHP API SDK](https://github.com/programmatordev/php-api-sdk) library was used to create the SportMonksFootball PHP API. +> To get to know about all the available methods, make sure to check the documentation [here](https://github.com/programmatordev/php-api-sdk?tab=readme-ov-file#documentation). -By default, and for convenience, this library makes use of the [HTTPlug's Discovery](https://github.com/php-http/discovery) library. -This means that it will automatically find and install a well-known PSR-18 and PSR-17 implementation for you (if one was not found on your project): -- [List of PSR-18 compatible implementations](https://packagist.org/providers/psr/http-client-implementation) -- [List of PSR-17 compatible implementations](https://packagist.org/providers/psr/http-factory-implementation) +The following sections have examples of some of the most important methods, +particularly related with the configuration of the client, cache and logger. -If you want to manually provide one, it should look like this: +### `setClientBuilder` -```php -use ProgrammatorDev\SportMonksFootball\Config; -use ProgrammatorDev\SportMonksFootball\HttpClient\HttpClientBuilder; -use ProgrammatorDev\SportMonksFootball\SportMonksFootball; +By default, this library makes use of the [HTTPlug's Discovery](https://github.com/php-http/discovery) library. +This means that it will automatically find and install a well-known PSR-18 client and PSR-17 factory implementation for you +(if they were not found on your project): +- [PSR-18 compatible implementations](https://packagist.org/providers/psr/http-client-implementation) +- [PSR-17 compatible implementations](https://packagist.org/providers/psr/http-factory-implementation) -$httpClient = new Symfony\Component\HttpClient\Psr18Client(); -$httpFactory = new Nyholm\Psr7\Factory\Psr17Factory(); - -// HttpClientBuilder( -// ?ClientInterface $client = null, -// ?RequestFactoryInterface $requestFactory = null, -// ?StreamFactoryInterface $streamFactory = null -// ); -$httpClientBuilder = new HttpClientBuilder($httpClient, $httpFactory, $httpFactory); - -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'httpClientBuilder' => $httpClientBuilder - ]) -); -``` - -> **Note** -> All `HttpClientBuilder` parameters are optional. -> If you only pass an HTTP client, an HTTP factory will still be discovered for you. - -#### Plugin System - -[HTTPlug's plugin system](https://docs.php-http.org/en/latest/plugins/index.html) is also implemented to give you full control of what happens during the request/response workflow. - -For example, to attempt to re-send a request in case of failure (service temporarily down because of unreliable connections/servers, etc.), -the [RetryPlugin](https://docs.php-http.org/en/latest/plugins/retry.html) can be added: +If you don't want to rely on the discovery of implementations, you can set the ones you want: ```php -use ProgrammatorDev\SportMonksFootball\Config; -use ProgrammatorDev\SportMonksFootball\HttpClient\HttpClientBuilder; +use Nyholm\Psr7\Factory\Psr17Factory; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; +use Symfony\Component\HttpClient\Psr18Client; -$httpClientBuilder = new HttpClientBuilder(); -$httpClientBuilder->addPlugin( - new \Http\Client\Common\Plugin\RetryPlugin([ - 'retries' => 3 - ]) -); +$api = new SportMonksFootball('yourapikey'); + +$client = new Psr18Client(); +$requestFactory = $streamFactory = new Psr17Factory(); -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'httpClientBuilder' => $httpClientBuilder - ]) +$api->setClientBuilder( + new ClientBuilder( + client: $client, + requestFactory: $requestFactory, + streamFactory: $streamFactory + ) ); ``` -You can check their [plugin list](https://docs.php-http.org/en/latest/plugins/index.html) or [create your own](https://docs.php-http.org/en/latest/plugins/build-your-own.html). - -> **Note** -> This library already uses HTTPlug's `CachePlugin` and `LoggerPlugin`. -> Re-adding those may lead to an unexpected behaviour. - -### `cache` +Check the full documentation [here](https://github.com/programmatordev/php-api-sdk?tab=readme-ov-file#http-client-psr-18-and-http-factories-psr-17). -Configure a PSR-6 cache adapter. +### `setCacheBuilder` -By default, no responses are cached. -To enable cache, you must provide a PSR-6 implementation: -- [List of PSR-6 compatible implementations](https://packagist.org/providers/psr/cache-implementation) +This library allows configuring the cache layer of the client for making API requests. +It uses a standard PSR-6 implementation and provides methods to fine-tune how HTTP caching behaves: +- [PSR-6 compatible implementations](https://packagist.org/providers/psr/cache-implementation) -In the example below, a filesystem-based cache is used: +Example: ```php -use ProgrammatorDev\SportMonksFootball\Config; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; +use Symfony\Component\Cache\Adapter\FilesystemAdapter; + +$api = new SportMonksFootball('yourapikey'); -$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter(); +$pool = new FilesystemAdapter(); -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'cache' => $cache - ]) +// set a file-based cache adapter with a 1-hour default cache lifetime +$api->setCacheBuilder( + new CacheBuilder( + pool: $pool, + ttl: 3600 + ) ); ``` -#### Cache TTL - -When `cache` enabled, all endpoints have a default cache max age that varies according to expected data update interval. -For example, `countries` have a default max age of `1 day` (this is, data will be cached for 1 day, since it is not updated regularly), -while `livescores` have a max age of `1 minute`. -You can check de default cache max age for each endpoint on the [Supported Endpoints](03-supported-endpoints.md) page. - -A few endpoints currently have a forced cache max age. -This is due to them retrieving live data or updates. -This may change in the future. - -To change the default cache max age per endpoint, check the [`withCacheTll`](03-supported-endpoints.md#withcachettl) section. +Check the full documentation [here](https://github.com/programmatordev/php-api-sdk?tab=readme-ov-file#cache-psr-6). -### `logger` +### `setLoggerBuilder` -Configure a PSR-3 logger adapter. +This library allows configuring a logger to save data for making API requests. +It uses a standard PSR-3 implementation and provides methods to fine-tune how logging behaves: +- [PSR-3 compatible implementations](https://packagist.org/providers/psr/log-implementation) -By default, no logs are saved. To enable logs, you must provide a PSR-3 implementation: -- [List of PSR-3 compatible implementations](https://packagist.org/providers/psr/log-implementation) - -In the example below, a file-based logger is used: +Example: ```php -use ProgrammatorDev\SportMonksFootball\Config; +use Monolog\Logger; +use Monolog\Handler\StreamHandler; use ProgrammatorDev\SportMonksFootball\SportMonksFootball; -$logger = new \Monolog\Logger('sportmonksfootball'); -$logger->pushHandler( - new \Monolog\Handler\StreamHandler(__DIR__ . '/logs/sportmonksfootball.log') -); - -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey', - 'logger' => $logger - ]) -); -``` - -> **Note** -> If a `cache` implementation is configured, cache events will also be logged. - -## Config Object +$api = new SportMonksFootball('yourapikey'); -Configuration getters and setters for all options are available to access and change after initialization: - -```php -use ProgrammatorDev\SportMonksFootball\Config; -use ProgrammatorDev\SportMonksFootball\OpenWeatherMap; +$logger = new Logger('api'); +$logger->pushHandler(new StreamHandler('/logs/api.log')); -$sportMonksFootball = new SportMonksFootball( - new Config([ - 'applicationKey' => 'yourappkey' - ]) +$api->setLoggerBuilder( + new LoggerBuilder( + logger: $logger + ) ); - -// Using applicationKey as an example, -// but getters and setters are available for all options -$sportMonksFootball->config()->getApplicationKey(); -$sportMonksFootball->config()->setApplicationKey('newappkey'); ``` -Just take into account that any change will affect any subsequent request globally: - -```php -// Using default 'UTC' timezone -$sportMonksFootball->livescores()->getAll(); - -// Set new timezone -$sportMonksFootball->config()->setTimezone('Europe/Lisbon'); - -// Using 'Europe/Lisbon' timezone -$sportMonksFootball->livescores()->getAll(); -$sportMonksFootball->fixtures()->getAllByDate(new DateTime('today')); -``` \ No newline at end of file +Check the full documentation [here](https://github.com/programmatordev/php-api-sdk?tab=readme-ov-file#logger-psr-3). \ No newline at end of file diff --git a/docs/03-supported-endpoints.md b/docs/03-supported-endpoints.md index 8e61d75..b2ddcba 100644 --- a/docs/03-supported-endpoints.md +++ b/docs/03-supported-endpoints.md @@ -35,10 +35,16 @@ - [Regions](#regions) - [Timezones](#timezones) - [Types](#types) +- [Pagination](#pagination-1) + - [withPage](#withpage) + - [withPerPage](#withperpage) + - [withSortBy](#withsortby) + - [withOrder](#withorder) + - [withPagination](#withpagination) - [Select, Include and Filters](#select-include-and-filters) - [withSelect](#withselect) - [withInclude](#withinclude) - - [withFilters](#withfilters) + - [withFilter](#withfilter) - [Timezone, Language and Cache TTL](#timezone-language-and-cache-ttl) - [withTimezone](#withtimezone) - [withLanguage](#withlanguage) @@ -46,27 +52,27 @@ ## Responses -All successful responses will return an [`Item`](05-objects.md#entityitem) or an [`Collection`](05-objects.md#entitycollection). +All successful responses will return an [`Item`](05-entities.md#entityitem) or an [`Collection`](05-entities.md#entitycollection). -One of the differences between an [`Item`](05-objects.md#entityitem) and an [`Collection`](05-objects.md#entitycollection) -is that the [`Item`](05-objects.md#entityitem) `getData()` method will return a single _Entity_ object, -while the [`Collection`](05-objects.md#entitycollection) `getData()` method will return an array of _Entity_ objects. +One of the differences between an [`Item`](05-entities.md#entityitem) and an [`Collection`](05-entities.md#entitycollection) +is that the [`Item`](05-entities.md#entityitem) `getData()` method will return a single _Entity_ object, +while the [`Collection`](05-entities.md#entitycollection) `getData()` method will return an array of _Entity_ objects. -For example, when requesting a fixture by id, the response will be a `FixtureItem` object and the `getData()` method will return a [`Fixture`](05-objects.md#fixture) object. -The same way that when requesting all fixtures, the response will be a `FixtureCollection` object and the `getData()` method will return an array of [`Fixture`](05-objects.md#fixture) objects. -Check the [responses objects](05-objects.md#response-objects) for more information. +For example, when requesting a fixture by id, the response will be a `FixtureItem` object and the `getData()` method will return a [`Fixture`](05-entities.md#fixture) object. +The same way that when requesting all fixtures, the response will be a `FixtureCollection` object and the `getData()` method will return an array of [`Fixture`](05-entities.md#fixture) objects. +Check the [responses objects](05-entities.md#response-objects) for more information. ```php -// Returns a FixtureItem object -$fixtureItem = $sportMonksFootball->fixtures()->getById(1); -// Returns a Fixture object -$fixture = $fixtureItem->getData(); +// returns a FixtureItem object +$response = $api->fixtures()->getById(1); +// returns a Fixture object +$fixture = $response->getData(); echo $fixture->getName(); -// Returns a FixtureCollection object -$fixtureCollection = $sportMonksFootball->fixtures()->getAll(); -// Returns an array of Fixture objects -$fixtures = $fixtureCollection->getData(); +// returns a FixtureCollection object +$response = $api->fixtures()->getAll(); +// returns an array of Fixture objects +$fixtures = $response->getData(); foreach ($fixtures as $fixture) { echo $fixture->getName(); } @@ -74,24 +80,17 @@ foreach ($fixtures as $fixture) { ### Pagination -[`Collection`](05-objects.md#entitycollection) responses that contain pagination data (not all of them have) +[`Collection`](05-entities.md#entitycollection) responses that contain pagination data (not all of them have) will be accessible through the `getPagination()` method: ```php -$fixtures = $sportMonksFootball->fixtures()->getAll(); - -echo $fixtures->getPagination()->getCount(); -echo $fixtures->getPagination()->getPerPage(); -echo $fixtures->getPagination()->getCurrentPage(); -echo $fixtures->getPagination()->getNextPage(); -echo $fixtures->getPagination()->hasMore(); -``` +$response = $api->fixtures()->getAll(); -Endpoints that support pagination, will always have a `page`, `perPage` and `order` parameters: - -```php -// Returns page 10 with 50 fixtures per page in descending order -$fixtures = $sportMonksFootball->fixtures()->getAll(page: 10, perPage: 50, order: 'desc')->getData(); +echo $response->getPagination()->getCount(); +echo $response->getPagination()->getPerPage(); +echo $response->getPagination()->getCurrentPage(); +echo $response->getPagination()->getNextPage(); +echo $response->getPagination()->hasMore(); ``` ### Rate Limit @@ -100,11 +99,11 @@ All responses include the `getRateLimit()` method with the current quota usage. Check the [official documentation](https://docs.sportmonks.com/football/api/rate-limit) for more information. ```php -$fixture = $sportMonksFootball->fixtures()->getById(1); +$response = $api->fixtures()->getById(1); -echo $fixture->getRateLimit()->getRemainingNumRequests(); -echo $fixture->getRateLimit()->getSecondsToReset(); -echo $fixture->getRateLimit()->getRequestedEntity(); +echo $response->getRateLimit()->getRemainingNumRequests(); +echo $response->getRateLimit()->getSecondsToReset(); +echo $response->getRateLimit()->getRequestedEntity(); ``` ### Timezone @@ -116,9 +115,9 @@ To request data in a different timezone for all requests, check the [configurati For a single endpoint, check the [`withTimezone` section](#withtimezone). ```php -$fixture = $sportMonksFootball->fixtures()->getById(1); +$response = $api->fixtures()->getById(1); -echo $fixture->getTimezone(); // UTC +echo $response->getTimezone(); // UTC ``` ## Football Endpoints @@ -1742,22 +1741,17 @@ foreach ($venues->getData() as $venue) { ### Bookmakers - [Official documentation](https://docs.sportmonks.com/football/endpoints-and-entities/endpoints/bookmakers) -- Cache default max age: `1 day` #### `getAll` ```php -getAll(int $page = 1, int $perPage = 25, string $order = 'asc'): BookmakerCollection +getAll(): BookmakerCollection ``` Get all bookmakers: ```php -$bookmakers = $sportMonksFootball->bookmakers()->getAll(); - -foreach ($bookmakers->getData() as $bookmaker) { - echo $bookmaker->getName(); -} +$response = $api->bookmakers()->getAll(); ``` #### `getById` @@ -1769,40 +1763,31 @@ getById(int $id): BookmakerItem Get bookmaker by id: ```php -$bookmaker = $sportMonksFootball->bookmakers()->getById(1); -echo $bookmaker->getData()->getName(); +$response = $api->bookmakers()->getById(1); ``` #### `getAllByFixtureId` ```php -getAllByFixtureId(int $fixtureId, int $page = 1, int $perPage = 25, string $order = 'asc'): BookmakerCollection +getAllByFixtureId(int $fixtureId): BookmakerCollection ``` Get all bookmakers by fixture id: ```php -$bookmakers = $sportMonksFootball->bookmakers()->getAllByFixtureId(1); - -foreach ($bookmakers->getData() as $bookmaker) { - echo $bookmaker->getName(); -} +$response = $api->bookmakers()->getAllByFixtureId(1); ``` #### `getAllBySearchQuery` ```php -getAllBySearchQuery(string $query, int $page = 1, int $perPage = 25, string $order = 'asc'): BookmakerCollection +getAllBySearchQuery(string $query): BookmakerCollection ``` Get all bookmakers by search query: ```php -$bookmakers = $sportMonksFootball->bookmakers()->getAllBySearchQuery('bet'); - -foreach ($bookmakers->getData() as $bookmaker) { - echo $bookmaker->getName(); -} +$response = $api->bookmakers()->getAllBySearchQuery('bet'); ``` ### Markets @@ -2231,13 +2216,99 @@ foreach ($entities->getData() as $entity) { } ``` +## Pagination + +### `withPage` + +```php +withPage(int $page): self +``` + +Determine the results page number. + +```php +$api->fixtures() + ->withPage(2) + ->getAll(); +``` + +### `withPerPage` + +```php +withPerPage(int $perPage): self +``` + +Determine the number of results per page. +Please note that it only affects the results of the base entity, so includes are not paginated. + +```php +$api->fixtures() + ->withPerPage(50) + ->getAll(); +``` + +### `withSortBy` + +```php +withSortBy(string $sortBy): self +``` + +Specifies the field by which the data will be sorted. Currently supported fields include: +- `starting_at` +- `name` + +```php +$api->fixtures() + ->withSortBy('starting_at') + ->getAll(); +``` + +### `withOrder` + +```php +withOrder(string $order): self +``` + +Determines the order in which the data will be sorted. Users can choose between ascending and descending: +- `asc` +- `desc` + + +```php +$api->fixtures() + ->withOrder('desc') + ->getAll(); +``` + +### withPagination + +```php +withPagination(int $page, int $perPage = 25, ?string $sortBy = null, string $order = 'asc'): self +``` + +Shorthand version of the combined `withPage`, `withPerPage`, `withSortBy` and `withOrder` methods. + +```php +// returns page 5 with 50 fixtures per page sorted by "starting_at" in descending order +$api->fixtures() + ->withPagination(5, 50, 'starting_at', 'desc') + ->getAll(); + +// equivalent to +$api->fixtures() + ->withPage(5) + ->withPerPage(50) + ->withSortBy('starting_at') + ->withOrder('desc') + ->getAll(); +``` + ## Select, Include and Filters #### `withSelect` ```php -/** @param string[] $select **/ -withSelect(array $select): self +withSelect(string $select): self ``` It is possible to request only specific fields on entities and on includes. @@ -2247,17 +2318,16 @@ In addition to reducing response time, the response size is also reduced. For selecting fields on includes, check the [`withInclude`](#withinclude) section. ```php -// Get fixture with fields "name" and "starting_at" only -$fixture = $sportMonksFootball->fixtures() - ->withSelect(['name', 'starting_at']) +// get fixture with fields "name" and "starting_at" only +$api->fixtures() + ->withSelect('name, starting_at') ->getById(1); ``` #### `withInclude` ```php -/** @param string[] $include **/ -withInclude(array $include): self +withInclude(string $include): self ``` Includes allow to enrich the response with relational data. @@ -2265,15 +2335,15 @@ This means that it is possible to request a fixture and have the venue data in t To check what includes ara available per endpoint, check the [official documentation](https://docs.sportmonks.com/football/endpoints-and-entities/endpoints). ```php -// Get fixture with "venue" and "participants" (teams) data -$fixture = $sportMonksFootball->fixtures() - ->withInclude(['venue', 'participants']) +// get fixture with "venue" and "participants" (teams) data +$api->fixtures() + ->withInclude('venue, participants') ->getById(1); -// It is also possible to nest includes -// This will return venue data and country data inside the venue -$fixture = $sportMonksFootball->fixtures() - ->withInclude(['venue.country']) +// it is also possible to get nested includes +// this will return venue data and country data inside the venue +$api->fixtures() + ->withInclude('venue.country') ->getById(1); ``` @@ -2282,26 +2352,25 @@ To better understand how it works, check the [official documentation](https://do To select fields in includes (similar to the [`withSelect`](#withselect)), you can do the following: ```php -// Get fixture with "venue" data with fields "name" and "city_name" only -$fixture = $sportMonksFootball->fixtures() - ->withInclude(['venue:name,city_name']) +// get fixture with "venue" data with fields "name" and "city_name" only +$api->fixtures() + ->withInclude('venue:name,city_name') ->getById(1); ``` -#### `withFilters` +#### `withFilter` ```php -/** @param array $filters **/ -withFilters(array $filters): self +withFilter(string $filter): self ``` Filters are useful to make conditional requests. For example, get fixture events that are only goals: ```php -// Get fixture with "events" that are only goals, own goals or penalties. -$fixture = $sportMonksFootball->fixtures() - ->withInclude(['events']) - ->withFilters(['eventTypes' => '14,15,16']) +// get fixture with "events" that are only goals, own goals or penalties. +$api->fixtures() + ->withInclude('events') + ->withFilter('eventTypes:14,15,16']) ->getById(1); ``` @@ -2317,12 +2386,11 @@ withTimezone(string $timezone): self Makes a request with a different timezone from the one globally defined in the [configuration](02-configuration.md#timezone). -Only available for endpoints that contain Fixtures or Livescores. Check the [official documentation](https://docs.sportmonks.com/football/tutorials-and-guides/tutorials/timezone-parameters-on-different-endpoints) for more information. ```php -// Get all fixtures in the Europe/Lisbon timezone -$fixtures = $sportMonksFootball->fixtures() +// get all fixtures in the Europe/Lisbon timezone +$api->fixtures() ->withTimezone('Europe/Lisbon') ->getAll(); ``` @@ -2335,15 +2403,14 @@ withLanguage(string $language): self Makes a request with a different language from the one globally defined in the [configuration](02-configuration.md#language). -Some endpoints may not support the `withLanguage` method. Check the [official documentation](https://docs.sportmonks.com/football/api/translations-beta) for more information. -> **Note** +> [!NOTE] > This is feature is still in beta and may change in the future. ```php -// Get all fixtures in Japanese -$fixtures = $sportMonksFootball->fixtures() +// get all fixtures in Japanese +$api->fixtures() ->withLanguage(Language::JAPANESE) ->getAll(); ``` @@ -2351,21 +2418,24 @@ $fixtures = $sportMonksFootball->fixtures() #### `withCacheTtl` ```php -withCacheTtl(int $seconds): self +withCacheTtl(?int $ttl): self ``` -Makes a request and saves into cache for the provided duration in seconds. +Makes a request and saves into cache for the provided duration in seconds. -If `0` seconds is provided, the request will not be cached. +Semantics of values: +- `0`, the response will not be cached (if the servers specifies no `max-age`). +- `null`, the response will be cached for as long as it can (forever). -> **Note** -> Setting cache to `0` seconds will **not** invalidate any existing cache. +> [!NOTE] +> Setting cache to `null` or `0` seconds will **not** invalidate any existing cache. -Available for all APIs if `cache` is enabled in the [configuration](02-configuration.md#cache). +Available for all APIs if a cache adapter is set. +Check the following [documentation](02-configuration.md#setcachebuilder) for more information. ```php // Get all fixtures and cache for 1 day -$fixtures = $sportMonksFootball->fixtures() +$api->fixtures() ->withCacheTtl(3600 * 24) ->getAll(); ``` \ No newline at end of file diff --git a/docs/04-error-handling.md b/docs/04-error-handling.md index 452f29c..5e4c44a 100644 --- a/docs/04-error-handling.md +++ b/docs/04-error-handling.md @@ -14,9 +14,9 @@ You can see all available exceptions below: ```php try { - $fixture = $sportMonksFootball->fixtures()->getById(1); + $response = $api->fixtures()->getById(1); } -// When the query did not return any results (for example, the requested id does not exist or is empty) +// when the query did not return any results (for example, the requested id does not exist or is empty) // or there is no access via the current subscription catch (NoResultsFoundException $exception) { echo $exception->getMessage(); @@ -41,19 +41,19 @@ catch (PaginationLimitException $exception) {} catch (RateLimitException $exception) {} catch (InsufficientResourcesException $exception) {} catch (InsufficientIncludesException $exception) {} -// Any other error +// any other error catch (UnexpectedErrorException $exception) {} ``` To catch all API errors with a single exception, `ApiErrorException` is available: ```php -use ProgrammatorDev\OpenWeatherMap\Exception\ApiErrorException; +use ProgrammatorDev\SportMonksFootball\Exception\ApiErrorException; try { - $fixture = $sportMonksFootball->fixtures()->getById(1); + $response = $api->fixtures()->getById(1); } -// Catches all API response errors +// catches all API response errors catch (ApiErrorException $exception) { echo $exception->getCode(); echo $exception->getMessage(); @@ -65,13 +65,13 @@ catch (ApiErrorException $exception) { To catch invalid input data, the `ValidationException` is available: ```php -use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException; +use ProgrammatorDev\Validator\Exception\ValidationException; try { - $fixtures = $sportMonksFootball->fixtures()->getAllBySearchQuery(''); + $response = $api->fixtures()->getAllBySearchQuery(''); } catch (ValidationException $exception) { - // Should print: The query value should not be blank, "" given. + // should print: The query value should not be blank, "" given. echo $exception->getMessage(); } ``` \ No newline at end of file diff --git a/docs/05-objects.md b/docs/05-entities.md similarity index 100% rename from docs/05-objects.md rename to docs/05-entities.md diff --git a/tests/ApiErrorTest_.php b/tests/ApiErrorTest_.php deleted file mode 100644 index 26fdf9c..0000000 --- a/tests/ApiErrorTest_.php +++ /dev/null @@ -1,96 +0,0 @@ -mockClient->addResponse( - new Response( - status: 200, - body: MockResponse::ERROR_NO_RESULTS - ) - ); - - $this->expectException(NoResultsFoundException::class); - $this->givenApi()->continents()->getById(1); - } - - #[DataProvider('provideApiErrorPropertyCodeData')] - public function testApiErrorPropertyCode(int $code, string $expectedException) - { - $this->mockClient->addResponse( - new Response( - status: 422, - body: MockResponse::buildResponse(MockResponse::ERROR_PROPERTY_CODE, [ - 'code' => $code - ]) - ) - ); - - $this->expectException($expectedException); - $this->givenApi()->continents()->getById(1); - } - - public static function provideApiErrorPropertyCodeData(): \Generator - { - yield 'include not allowed exception' => [5000, IncludeNotAllowedException::class]; - yield 'include not found exception' => [5001, IncludeNotFoundException::class]; - yield 'insufficient includes exception' => [5002, InsufficientIncludesException::class]; - yield 'pagination limit exception' => [5003, PaginationLimitException::class]; - yield 'query complexity exception' => [5004, QueryComplexityException::class]; - yield 'rate limit exception' => [5005, RateLimitException::class]; - yield 'invalid query parameter exception' => [5006, InvalidQueryParameterException::class]; - yield 'insufficient resources exception' => [5007, InsufficientResourcesException::class]; - yield 'include depth exception' => [5008, IncludeDepthException::class]; - yield 'filter not applicable exception' => [5010, FilterNotApplicableException::class]; - yield 'include not available exception' => [5013, IncludeNotAvailableException::class]; - yield 'unexpected error exception' => [9999, UnexpectedErrorException::class]; - } - - #[DataProvider('provideApiErrorStatusCodeData')] - public function testApiErrorStatusCode(int $statusCode, string $expectedException) - { - $this->mockClient->addResponse( - new Response( - status: $statusCode, - body: MockResponse::ERROR_STATUS_CODE - ) - ); - - $this->expectException($expectedException); - $this->givenApi()->continents()->getById(1); - } - - public static function provideApiErrorStatusCodeData(): \Generator - { - yield 'bad request exception' => [400, BadRequestException::class]; - yield 'unauthorized exception' => [401, UnauthorizedException::class]; - yield 'forbidden exception' => [403, ForbiddenException::class]; - yield 'not found exception' => [404, NotFoundException::class]; - yield 'too many requests exception' => [429, TooManyRequestsException::class]; - yield 'unexpected error exception' => [500, UnexpectedErrorException::class]; - } -} \ No newline at end of file