Created
August 2, 2015 16:09
-
-
Save serefyarar/fb8a6222b381033fcb46 to your computer and use it in GitHub Desktop.
My Own Keyless Fractal Serializer
This file contains 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 | |
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