Skip to content

Instantly share code, notes, and snippets.

@nebkam
Last active November 1, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebkam/e56d33f2f0a1ece651285b9b27052ab8 to your computer and use it in GitHub Desktop.
Save nebkam/e56d33f2f0a1ece651285b9b27052ab8 to your computer and use it in GitHub Desktop.
<?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