Skip to content

Instantly share code, notes, and snippets.

@benglass
Last active August 4, 2021 00:25
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benglass/e7b2af60451d2a46182b to your computer and use it in GitHub Desktop.
Save benglass/e7b2af60451d2a46182b to your computer and use it in GitHub Desktop.
<?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