Skip to content

Instantly share code, notes, and snippets.

@serefyarar
Created August 2, 2015 16:09
Show Gist options
  • Save serefyarar/fb8a6222b381033fcb46 to your computer and use it in GitHub Desktop.
Save serefyarar/fb8a6222b381033fcb46 to your computer and use it in GitHub Desktop.
My Own Keyless Fractal Serializer
<?php
namespace App\Serializers;
use League\Fractal\Serializer\JsonApiSerializer;
use League\Fractal\Resource\ResourceInterface;
class DataArraySerializer extends JsonApiSerializer
{
/**
* Serialize an item resource
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function collection($resourceKey, array $data)
{
return ($resourceKey && $resourceKey !== 'data') ? array($resourceKey => $data) : $data;
}
public function item($resourceKey, array $data)
{
return ($resourceKey && $resourceKey !== 'data') ? array($resourceKey => $data) : $data;
}
public function includedData(ResourceInterface $resource, array $data)
{
$serializedData = array();
$linkedIds = array();
foreach ($data as $value) {
foreach ($value as $includeKey => $includeValue) {
foreach ($includeValue[$includeKey] as $itemValue) {
if (!array_key_exists('id', $itemValue)) {
$serializedData[$includeKey][] = $itemValue;
continue;
}
$itemId = $itemValue['id'];
if (!empty($linkedIds[$includeKey]) && in_array($itemId, $linkedIds[$includeKey], true)) {
continue;
}
$serializedData[$includeKey][] = $itemValue;
$linkedIds[$includeKey][] = $itemId;
}
}
}
return empty($serializedData) ? array() : $serializedData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment