Skip to content

Instantly share code, notes, and snippets.

@cwhite92
Created December 24, 2015 21:40
Show Gist options
  • Save cwhite92/859cf3fc53bb8fce3bad to your computer and use it in GitHub Desktop.
Save cwhite92/859cf3fc53bb8fce3bad to your computer and use it in GitHub Desktop.
Fractal transformer
<?php
namespace Lykit\Transformers;
use League\Fractal\TransformerAbstract;
use Lykit\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
class UserTransformer extends TransformerAbstract
{
/**
* List of resources that can be included in the response.
*
* @var array
*/
protected $availableIncludes = ['token', 'photo'];
/**
* Transform the User model into an array suitable for output to the API client.
*
* @param User $user
*
* @return array
*/
public function transform(User $user)
{
$object = [
'id' => (int) $user->id,
'name' => $user->name,
'country_iso' => $user->country_iso,
'city' => $user->city,
'dob' => $user->dob,
'sex' => $user->sex,
'total_posts' => (int) $user->total_posts,
'total_friends' => (int) $user->total_friends,
'total_followers' => (int) $user->total_followers,
'total_follows' => (int) $user->total_follows,
'is_my_friend' => (bool) $user->is_my_friend,
'is_following_me' => (bool) $user->is_following_me,
'followed_me_at' => is_null($user->started_following_me_at) ?
$user->started_following_me_at :
$user->started_following_me_at->toIso8601String(),
'am_following' => (bool) $user->am_following,
'is_favourite' => (bool) $user->is_favourite,
'is_blocked' => (bool) $user->is_blocked,
'created_at' => $user->created_at->toIso8601String()
];
// We only want to expose these fields if we're transforming the current user
if (auth()->id() == $user->id) {
$object['email'] = $user->email;
$object['telephone_number'] = $user->telephone_number;
$object['muted_direct_posts'] = (bool) $user->muted_direct_posts;
$object['muted_group_posts'] = (bool) $user->muted_group_posts;
$object['muted_friend_requests'] = (bool) $user->muted_friend_requests;
$object['total_blocks'] = (int) $user->total_blocks;
}
return $object;
}
/**
* Create a new authentication token and include it in the user object.
*
* @param User $user
*
* @return \League\Fractal\Resource\Item
*/
public function includeToken(User $user)
{
// Only allowed to request an include of the token when the user is registering - therefore they are not
// currently logged in.
if (auth()->user()) {
abort(401);
}
$token = JWTAuth::fromUser($user);
return $this->item($token, new TokenTransformer);
}
/**
* Include the user's profile photo in the response.
*
* @param User $user
*
* @return \League\Fractal\Resource\Item
*/
public function includePhoto(User $user)
{
if (!$user->hasMedia()) {
return null;
}
return $this->item($user->getFirstMedia(), new MediaTransformer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment