rexlabsio / smokescreen-laravel-php

Library for integrating the Smokescreen transformation library with the Laravel framework
MIT License
4 stars 1 forks source link
api eloquent json laravel orm php php-library resource serialization transformer

Laravel Smokescreen

License: MIT Build Status Code Coverage Packagist

Overview

Laravel Smokescreen is a package for transforming your Laravel models, and other entities.

This package tightly integrates the rexlabs/smokescreen (Vanilla PHP) package with the Laravel framework, to provide the convenience and minimal boilerplate when working with Laravel applications.

Usage

<?php
class MyController extends Controller
{
    public function index()
    {
        return Smokescreen::transform(Post::paginate());
    }

     public function show(Post $post)
     {
        return Smokescreen::transform($post);
     }
}

Requirements

Installation

This package is currently hosted on RexSoftware's private packagist repository. First ensure you have configured your composer.json to use this repository.

Install package

composer require rexlabs/laravel-smokescreen

This package will be auto-discovered, and no additional configuration is necessary.

Configuration

To publish the configuration file to your app/config folder, run the following command:

php artisan vendor:publish --provider='Rexlabs\Laravel\Smokescreen\Providers\ServiceProvider --tag=config'

This will create config/smokescreen.php:

<?php
return [
    // Set the default namespace for resolving transformers when
    // they are not explicitly provided.
    'transformer_namespace' => 'App\Transformers',

    // Override the default serializer to be used.
    // If not specified - the Smokescreen DefaultSerializer will be used.
    'default_serializer' => null,

    // Set the default request parameter key which is parsed for
    // the list of includes.
    'include_key' => 'include',
];

API

transform(): Set resource to be transformed

$smokescreen->transform(mixed $resource, mixed $transformer = null);

<?php
$smokescreen->transform(Post::find(1));
$smokescreen->transform(Post::all());
$smokescreen->transform(Post::paginate());
$smokescreen->transform(Post::find(1), new SomeOtherTransformer);

item(): Set single item resource to be transformed

$smokescreen->item(mixed $item, mixed $transformer = null);

<?php
$smokescreen->item(Post::find(1));
$smokescreen->item(Post::find(1), new SomeOtherTransformer);

collection(): Set collection resource to be transformed

$smokescreen->collection(mixed $collection, mixed $transformer = null);

<?php
$smokescreen->collection(Post::all());
$smokescreen->collection(Post::paginate());
$smokescreen->collection(Post::paginate(), new SomeOtherTransformer);

transformWith(): Set the transformer to use on the previously set resource

$smokescreen->transformWith(TransformerInterface|callable $transformer);

<?php
$smokescreen->transform(Post::find(1))
    ->transformWith(new SomeOtherTransformer);

serializeWith(): Override the serializer to be used

<?php
$smokescreen->serializeWith(new MyCustomSerializer);

loadRelationsVia(): Override the default Laravel relations loader

$smokescreen->loadRelationsVia(RelationsLoaderInterface $loader);

<?php
$smokescreen->loadRelationsVia(new MyRelationsLoader);

resolveTransformerVia(): Override the default transformer resolver

$smokescreen->loadTransformersVia(TransformerResolverInterface $loader);

<?php
$smokescreen->loadTransformersVia(new MyTransformerResolver);

response(): Access the generated response object

$response = $smokescreen->response(int $statusCode = 200, array $headers = [], int $options = 0);

<?php
$smokescreen->response()
    ->header('X-Custom-Header', 'boo')
    ->setStatusCode(405);

freshResponse(): Generate a fresh Response object

$response = $smokescreen->freshResponse(int $statusCode = 200, array $headers = [], int $options = 0);

withResponse(): Apply changes to the generated response object

$smokescreen->withResponse(callable $apply);

<?php
$smokescreen->withResponse(function (JsonResponse $response) {
    $response->header('X-Crypto-Alert', 'all your coins are worthless!');
});

clearResponse(): Clear any cached response

$smokescreen->clearResponse();

<?php
$smokescreen->response();       // Data is generated, response object is built and cached
$smokescreen->response(500);    // NOPE - Cached, wont be changed!
$smokescreen->clearResponse();
$smokescreen->response(500);    // Response is re-generated

Transformers

Example Transformer

<?php
class PostTransformer extends AbstractTransformer
{
    protected $includes = [
        'user' => 'default|relation:user|method:includeTheDamnUser',
        'comments' => 'relation',
    ];

    public function transform(Post $post): array
    {
        return [
            'id' => $post->id,
            'user' => $this->when($post->user_id, [
                'id' => $post->user_id,
            ]),
            'title' => $post->title,
            'summary' => $post->summary,
            'body' => $post->body,
            'created_at' => utc_datetime($post->created_at),
            'updated_at' => utc_datetime($post->updated_at),
        ];
    }

    public function includeTheDamnUser(Post $post)
    {
        return $this->item($post->user); // Infer Transformer
    }

    public function includeComments(Post $post)
    {
        return $this->collection($post->comments, new CommentTransformer);
    }
}

Contributing

Pull-requests are welcome. Please ensure code is PSR compliant. Github Repository

About