Skip to content

Instantly share code, notes, and snippets.

@nebkam nebkam/api_client.php
Last active Nov 1, 2019

Embed
What would you like to do?
<?php
class ApiClient
{
/**
* @return Project[]
*/
public function getProjects(): array
{
$projects = [];
$response = $this->client->get('https://some-awesome.api/projects');
$data = json_decode($response->getBody()->getContents(), true);
// Some associative array property guessing...
if (!empty($data['Result']))
{
foreach ($data['Result'] as $projectData)
{
if ($projectData['SaleStatus'] === 'InActiveSale')
{
$projects[] = Project::fromApiResponse($projectData);
}
}
}
return $projects;
}
public function addNewProject(Project $project)
{
$this->client->post('https://some-awesome.api/projects', ['body' => $project->toApiRequestPayload() ]);
}
}
<?php
class Project
{
public static function fromApiResponse(array $data): self
{
$project = new Project();
// Manual mapping of arrays to object properties..
$project->setInternalId( (string) $data['Id']);
$project->setTitle($data['Name']);
$project->setQuality((int)$data['Quality']);
// ...
return $project;
}
public function toApiRequestPayload(): array
{
$data = [];
// Manual mapping of object properties to arrays..
$data['Id'] = (int) $this->getInternalId();
$data['Name'] = $this->getTitle();
$data['Quality'] = (float) $this->getQuality();
// ...
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.