generated from cerbero90/skeleton
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Cerbero\LazyJsonPages\Sources; | ||
|
||
use Cerbero\JsonParser\Concerns\DetectsEndpoints; | ||
use Cerbero\LazyJsonPages\ValueObjects\Response; | ||
use GuzzleHttp\Client; | ||
use GuzzleHttp\Psr7\Request; | ||
use Psr\Http\Message\RequestInterface; | ||
use Psr\Http\Message\UriInterface; | ||
|
||
/** | ||
* The JSON endpoint source. | ||
* | ||
* @property-read UriInterface|string $source | ||
*/ | ||
class Endpoint extends Source | ||
{ | ||
use DetectsEndpoints; | ||
|
||
/** | ||
* The HTTP request. | ||
*/ | ||
protected RequestInterface $request; | ||
|
||
/** | ||
* The HTTP response value object | ||
*/ | ||
protected Response $response; | ||
|
||
/** | ||
* Determine whether this class can handle the source. | ||
*/ | ||
public function matches(): bool | ||
{ | ||
return $this->source instanceof UriInterface | ||
|| (is_string($this->source) && $this->isEndpoint($this->source)); | ||
} | ||
|
||
/** | ||
* Retrieve the HTTP request. | ||
*/ | ||
public function request(): RequestInterface | ||
{ | ||
return $this->request ??= new Request('GET', $this->source, [ | ||
'Accept' => 'application/json', | ||
'Content-Type' => 'application/json', | ||
]); | ||
} | ||
|
||
/** | ||
* Retrieve the HTTP response or part of it. | ||
* | ||
* @return ($key is string ? mixed : \Cerbero\LazyJsonPages\ValueObjects\Response) | ||
*/ | ||
public function response(?string $key = null): mixed | ||
{ | ||
$this->response ??= (new Client())->send($this->request()); | ||
|
||
return $key === null ? $this->response : $this->response->get($key); | ||
} | ||
} |