somnambulist/fractal-bundle

A port of samj/fractal-bundle for integrating TheLeague Fractal into Symfony

Installs: 11 473

Dependents: 1

Suggesters: 0

Security: 0

Stars: 2

Watchers: 4

Forks: 1

Open Issues: 0

Type:symfony-bundle

2.1.1 2024-12-01 16:00 UTC

This package is auto-updated.

Last update: 2024-12-01 16:01:15 UTC


README

GitHub Actions Build Status Issues License PHP Version Current Version

A fork and re-write of samj/fractal-bundle to provide Fractal integration with the Symfony Framework.

Requirements

  • PHP 8.0+
  • symfony/framework-bundle 6.4+

Installation

Install using composer, or checkout / pull the files from github.com.

  • composer require somnambulist/fractal-bundle

Usage

Add the SomnambulistFractalBundle to your bundles.php list if not registered by Symfony Flex.

Using Transformers as Services

This bundle allows auto-wiring / auto-configuring transformers as services. This allows you to take advantage of Symfonys container to resolve dependencies and reference transformers by class name (or service alias).

So long as the transformer extends from League\Fractal\TransformerAbstract or is tagged with somnambulist.fractal_bundle.transformer, it will be available to the Fractal Manager instance.

services:
    App\Http\Api\Transformers\:
        resource: '%kernel.project_dir%/Http/Api/Transformers/'

If transformers don't extend the TransformerAbstract be sure to tag them:

services:
    App\Http\Api\Transformers\:
        resource: '%kernel.project_dir%/Http/Api/Transformers/'
        tags: ['somnambulist.fractal_bundle.transformer']

Note: if your transformer is not registered as a service or passed as a valid callable or instance of TransformerAbstract, this library will raise an exception.

For example: to add an auth check to a UserTransformer (example from samj readme):

use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    public function __construct(private AuthorizationChecker $authorizationChecker)
    {
    }
    
    public function transform(User $user)
    {
        $data = [
            'id' => $user->id(),
            'name' => $user->name(),
        ];
        
        if ($this->authorizationChecker->isGranted(UserVoter::SEE_EMAIL, $user)) {
            $data['email'] = $user->email();
        }
        
        return $data;
    }
}

Reference the transformer by either a service alias name, or the class name:

$resource = new Collection($users, UserTransformer::class);

This works in includes as well:

public function includeFriends(User $user)
{    
    return $this->collection($user->friends(), UserTransformer::class);
}

Look in the sample application for some further examples.

Tests

PHPUnit 9+ is used for testing. Run tests via vendor/bin/phpunit.