Last active
August 4, 2021 00:25
-
-
Save benglass/e7b2af60451d2a46182b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
class TransformerAbstract | |
{ | |
private $fields; | |
private $allowedFields = array('id', 'name', 'phone', 'email', 'bio', 'num_friends'); | |
private $partialFields = array( | |
'id' => array('id', 'name'), | |
'info' => array('name', 'phone', 'email', 'bio'), | |
'bio' => array('bio') | |
); | |
private $partials; | |
private $defaultPartials = array('id'); | |
public function setPartials(array $partials) | |
{ | |
$this->partials = $partials; | |
} | |
public function transform($object) | |
{ | |
$data = // do normal transform | |
// Extract only the requested fields, do this before embedding. This is somewhat wasteful but simplifies the code since we just use string keys for fields | |
if ($this->partials) { | |
$killKeys = array_diff( | |
array_keys($data), | |
$this->getFieldsForPartials($this->partials) | |
); | |
foreach ($killKey as $killKeys) { | |
unset($data[$killKey]); | |
} | |
} | |
// Do embedding | |
return $data; | |
} | |
protected function getFieldsForPartials(array $partials) | |
{ | |
$partialFields = $this->partialFields; | |
return array_reduce( | |
$partials, | |
function ($carry, $partial) use ($partialFields) { | |
return array_merge($carry, $partialFields[$partial]); | |
}, | |
array() | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment