Untitled

mail@pastecode.io avatar
unknown
php
a year ago
1.1 kB
10
Indexable
Never
<?php

class ApiUserRepository implements UserRepositoryInterface
{

    public function __construct(
        readonly HttpClientInterface $httpClient,
        readonly string $baseApiUrl
    )
    {
    }

    /**
     * @throws Exception
     */
    public function getUserById(int $id): User
    {
        $response = $this->httpClient->get($this->baseApiUrl . "/users/{$id}");
        if(!$response->isOk()) {
            throw new Exception('API error OR the user not found');
        }

        return $this->apiUserToUser(
            $response->json()
        );
    }

    /**
     * @throws Exception
     */
    public function getUsers(): array
    {
        $response = $this->httpClient->get($this->baseApiUrl . "/users");

        if(!$response->isOk()) {
            throw new Exception('API error');
        }

        return array_map(
            fn ($apiUser): User => $this->apiUserToUser($apiUser),
            $response->json()
        );
    }

    private function apiUserToUser(array $user): User
    {
        return new User(
          $user['id'],
          $user['name'],
          $user['surname'],
        );
    }
}