Skip to content

Commit f8b91c9

Browse files
committed
chore: optional setBaseUrl
1 parent 8cbfc0a commit f8b91c9

File tree

11 files changed

+82
-143
lines changed

11 files changed

+82
-143
lines changed

README.md

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class YourApi extends Api
4040
{
4141
parent::__construct();
4242

43-
// minimum required config
43+
// recommended config
4444
$this->setBaseUrl('https://api.example.com/v1');
4545
}
4646

@@ -77,11 +77,11 @@ Getter and setter for the base URL.
7777
Base URL is the common part of the API URL and will be used in all requests.
7878

7979
```php
80-
$this->setBaseUrl(string $baseUrl): self
80+
$this->setBaseUrl(?string $baseUrl): self
8181
```
8282

8383
```php
84-
$this->getBaseUrl(): string
84+
$this->getBaseUrl(): ?string
8585
```
8686

8787
### Requests
@@ -99,16 +99,12 @@ use Psr\Http\Message\StreamInterface;
9999
$this->request(
100100
string $method,
101101
string $path,
102-
array $query [],
102+
array $query = [],
103103
array $headers = [],
104104
StreamInterface|string $body = null
105105
): mixed
106106
```
107107

108-
> [!NOTE]
109-
> A `ConfigException` will be thrown if a base URL is not set (this is, if it is empty).
110-
> Check the [`setBaseUrl`](#base-url) method for more information.
111-
112108
> [!NOTE]
113109
> A `ClientException` will be thrown if there is an error while processing the request.
114110
@@ -123,7 +119,7 @@ class YourApi extends Api
123119
{
124120
parent::__construct();
125121

126-
// minimum required config
122+
// recommended config
127123
$this->setBaseUrl('https://api.example.com/v1');
128124
}
129125

@@ -165,6 +161,7 @@ class YourApi extends Api
165161
{
166162
parent::__construct();
167163

164+
// recommended config
168165
$this->setBaseUrl('https://api.example.com/v1');
169166
}
170167

@@ -316,18 +313,11 @@ use Http\Message\Authentication;
316313
$this->getAuthentication(): ?Authentication;
317314
```
318315

319-
Available authentication methods:
320-
- [`BasicAuth`](https://docs.php-http.org/en/latest/message/authentication.html#id1) Username and password
321-
- [`Bearer`](https://docs.php-http.org/en/latest/message/authentication.html#bearer) Token
322-
- [`Wsse`](https://docs.php-http.org/en/latest/message/authentication.html#id2) Username and password
323-
- [`QueryParam`](https://docs.php-http.org/en/latest/message/authentication.html#query-params) Array of query parameter values
324-
- [`Header`](https://docs.php-http.org/en/latest/message/authentication.html#header) Header name and value
325-
- [`Chain`](https://docs.php-http.org/en/latest/message/authentication.html#chain) Array of authentication instances
326-
- `RequestConditional` A request matcher and authentication instances
316+
Check all available authentication methods in the [PHP HTTP documentation](https://docs.php-http.org/en/latest/message/authentication.html#authentication-methods).
327317

328318
You can also [implement your own](https://docs.php-http.org/en/latest/message/authentication.html#implement-your-own) authentication method.
329319

330-
For example, if you have an API that is authenticated with a query parameter:
320+
For example, if you have an API authenticated with a query parameter:
331321

332322
```php
333323
use ProgrammatorDev\Api\Api;
@@ -367,7 +357,7 @@ class YourApi extends Api
367357

368358
#### `addPreRequestListener`
369359

370-
The `addPreRequestListener` method is used to add a function that is called before a request has been made.
360+
The `addPreRequestListener` method is used to add a function called before a request has been made.
371361
This event listener will be applied to every API request.
372362

373363
```php
@@ -413,7 +403,7 @@ $this->addPreRequestListener(function(PreRequestEvent $event) {
413403

414404
#### `addPostRequestListener`
415405

416-
The `addPostRequestListener` method is used to add a function that is called after a request has been made.
406+
The `addPostRequestListener` method is used to add a function called after a request has been made.
417407
This function can be used to inspect the request and response data that was sent to, and received from, the API.
418408
This event listener will be applied to every API request.
419409

@@ -468,7 +458,7 @@ $this->addPostRequestListener(function(PostRequestEvent $event) {
468458

469459
#### `addResponseContentsListener`
470460

471-
The `addResponseContentsListener` method is used to manipulate the response that was received from the API.
461+
The `addResponseContentsListener` method is used to manipulate the response received from the API.
472462
This event listener will be applied to every API request.
473463

474464
```php
@@ -648,7 +638,7 @@ class YourApi extends Api
648638
This library enables attaching plugins to the HTTP client.
649639
A plugin modifies the behavior of the client by intercepting the request and response flow.
650640

651-
Since plugin order matters, a plugin is added with a priority level, and are executed in descending order from highest to lowest.
641+
Since plugin order matters, a plugin is added with a priority level and is executed in descending order from highest to lowest.
652642

653643
Check all the [available plugins](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).
654644

@@ -673,7 +663,7 @@ The following list has all the implemented plugins with the respective priority
673663
| [`LoggerPlugin`](https://docs.php-http.org/en/latest/plugins/logger.html) | 8 | only if logger is enabled |
674664

675665
For example, if you wanted the client to automatically attempt to re-send a request that failed
676-
(due to unreliable connections and servers, for example) you can add the [RetryPlugin](https://docs.php-http.org/en/latest/plugins/retry.html):
666+
(due to unreliable connections and servers, for example), you can add the [RetryPlugin](https://docs.php-http.org/en/latest/plugins/retry.html):
677667

678668
```php
679669
use ProgrammatorDev\Api\Api;
@@ -686,7 +676,7 @@ class YourApi extends Api
686676
// ...
687677

688678
// if a request fails, it will retry at least 3 times
689-
// priority is 20 to execute before the cache plugin
679+
// the priority is 20 to execute before the cache plugin
690680
// (check the above plugin order list for more information)
691681
$this->getClientBuilder()->addPlugin(
692682
plugin: new RetryPlugin(['retries' => 3]),
@@ -709,12 +699,11 @@ use Psr\Cache\CacheItemPoolInterface;
709699
new CacheBuilder(
710700
// a PSR-6 cache adapter
711701
CacheItemPoolInterface $pool,
712-
// default lifetime (in seconds) of cache items
702+
// default lifetime (in seconds) of cached items
713703
?int $ttl = 60,
714704
// An array of HTTP methods for which caching should be applied
715705
$methods = ['GET', 'HEAD'],
716-
// An array of cache directives to be compared with the headers of the HTTP response,
717-
// in order to determine cacheability
706+
// An array of cache directives to be compared with the headers of the HTTP response to determine cacheability
718707
$responseCacheDirectives = ['max-age']
719708
);
720709
```
@@ -854,7 +843,7 @@ class YourApi extends Api
854843

855844
private function configureOptions(array $options): array
856845
{
857-
// set defaults values, if none were provided
846+
// set defaults values if none were provided
858847
$this->optionsResolver->setDefault('timezone', 'UTC');
859848
$this->optionsResolver->setDefault('language', 'en');
860849

@@ -872,7 +861,7 @@ class YourApi extends Api
872861

873862
private function configureApi(): void
874863
{
875-
// set required base url
864+
// set the base url
876865
$this->setBaseUrl('https://api.example.com/v1');
877866

878867
// set options as query defaults (will be included in all requests)

src/Api.php

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515
use ProgrammatorDev\Api\Event\PostRequestEvent;
1616
use ProgrammatorDev\Api\Event\PreRequestEvent;
1717
use ProgrammatorDev\Api\Event\ResponseContentsEvent;
18-
use ProgrammatorDev\Api\Exception\ConfigException;
19-
use ProgrammatorDev\Api\Helper\StringHelperTrait;
18+
use ProgrammatorDev\Api\Helper\StringHelper;
2019
use Psr\Http\Client\ClientExceptionInterface as ClientException;
2120
use Psr\Http\Message\RequestInterface;
2221
use Psr\Http\Message\StreamInterface;
@@ -25,8 +24,6 @@
2524

2625
class Api
2726
{
28-
use StringHelperTrait;
29-
3027
private ?string $baseUrl = null;
3128

3229
private array $queryDefaults = [];
@@ -53,7 +50,6 @@ public function __construct()
5350
}
5451

5552
/**
56-
* @throws ConfigException If a base URL has not been set.
5753
* @throws ClientException
5854
*/
5955
public function request(
@@ -64,18 +60,14 @@ public function request(
6460
string|StreamInterface $body = null
6561
): mixed
6662
{
67-
if (!$this->baseUrl) {
68-
throw new ConfigException('A base URL must be set.');
69-
}
70-
7163
$this->configurePlugins();
7264

7365
if (!empty($this->queryDefaults)) {
74-
$query = \array_merge($this->queryDefaults, $query);
66+
$query = array_merge($this->queryDefaults, $query);
7567
}
7668

7769
if (!empty($this->headerDefaults)) {
78-
$headers = \array_merge($this->headerDefaults, $headers);
70+
$headers = array_merge($this->headerDefaults, $headers);
7971
}
8072

8173
$uri = $this->buildUri($path, $query);
@@ -161,7 +153,7 @@ public function getBaseUrl(): ?string
161153
return $this->baseUrl;
162154
}
163155

164-
public function setBaseUrl(string $baseUrl): self
156+
public function setBaseUrl(?string $baseUrl): self
165157
{
166158
$this->baseUrl = $baseUrl;
167159

@@ -278,8 +270,8 @@ public function addResponseContentsListener(callable $listener, int $priority =
278270
public function buildPath(string $path, array $parameters): string
279271
{
280272
foreach ($parameters as $parameter => $value) {
281-
$path = \str_replace(
282-
\sprintf('{%s}', $parameter),
273+
$path = str_replace(
274+
sprintf('{%s}', $parameter),
283275
$value,
284276
$path
285277
);
@@ -290,10 +282,10 @@ public function buildPath(string $path, array $parameters): string
290282

291283
private function buildUri(string $path, array $query = []): string
292284
{
293-
$uri = $this->reduceDuplicateSlashes($this->baseUrl . $path);
285+
$uri = StringHelper::reduceDuplicateSlashes($this->baseUrl . $path);
294286

295287
if (!empty($query)) {
296-
$uri = \sprintf('%s?%s', $uri, \http_build_query($query));
288+
$uri = sprintf('%s?%s', $uri, http_build_query($query));
297289
}
298290

299291
return $uri;
@@ -314,7 +306,7 @@ private function createRequest(
314306

315307
if ($body !== null && $body !== '') {
316308
$request = $request->withBody(
317-
\is_string($body) ? $this->clientBuilder->getStreamFactory()->createStream($body) : $body
309+
is_string($body) ? $this->clientBuilder->getStreamFactory()->createStream($body) : $body
318310
);
319311
}
320312

src/Builder/ClientBuilder.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,13 @@ public function addPlugin(Plugin $plugin, int $priority): self
7575
{
7676
if (isset($this->plugins[$priority])) {
7777
throw new PluginException(
78-
\sprintf('A plugin with priority %d already exists.', $priority)
78+
sprintf('A plugin with priority %d already exists.', $priority)
7979
);
8080
}
8181

8282
$this->plugins[$priority] = $plugin;
8383
// sort plugins by priority (key) in descending order
84-
\krsort($this->plugins);
84+
krsort($this->plugins);
8585

8686
return $this;
8787
}

src/Builder/Listener/CacheLoggerListener.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function onCacheResponse(
2626
if ($fromCache) {
2727
/** @var $cacheItem CacheItemInterface */
2828
$logger->info(
29-
\sprintf("Cache hit:\n%s", $formatter->formatRequest($request)),
29+
sprintf("Cache hit:\n%s", $formatter->formatRequest($request)),
3030
[
3131
'expires' => $cacheItem->get()['expiresAt'],
3232
'key' => $cacheItem->getKey()
@@ -36,12 +36,12 @@ public function onCacheResponse(
3636
// if response is a cache miss (and was cached)
3737
else if ($cacheItem instanceof CacheItemInterface) {
3838
// handle future deprecation
39-
$formattedResponse = \method_exists($formatter, 'formatResponseForRequest')
39+
$formattedResponse = method_exists($formatter, 'formatResponseForRequest')
4040
? $formatter->formatResponseForRequest($response, $request)
4141
: $formatter->formatResponse($response);
4242

4343
$logger->info(
44-
\sprintf("Cached response:\n%s", $formattedResponse),
44+
sprintf("Cached response:\n%s", $formattedResponse),
4545
[
4646
'expires' => $cacheItem->get()['expiresAt'],
4747
'key' => $cacheItem->getKey()

src/Exception/ConfigException.php

Lines changed: 0 additions & 5 deletions
This file was deleted.

src/Helper/StringHelper.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace ProgrammatorDev\Api\Helper;
4+
5+
class StringHelper
6+
{
7+
public static function reduceDuplicateSlashes(string $string): string
8+
{
9+
return preg_replace('#(^|[^:])//+#', '\\1/', $string);
10+
}
11+
}

src/Helper/StringHelperTrait.php

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)