Completed
Push — master ( dc322e...438d0e )
by Mahmoud
03:27
created

FractalTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 41
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B overrideDefaultFractalSerializer() 0 25 4
1
<?php
2
3
namespace App\Ship\Engine\Traits;
4
5
use App\Ship\Features\Exceptions\UnsupportedFractalSerializerException;
6
use Illuminate\Support\Facades\Config;
7
8
/**
9
 * Class FractalTrait.
10
 *
11
 * @author  Mahmoud Zalt <[email protected]>
12
 */
13
trait FractalTrait
14
{
15
16
    /**
17
     * By default the Dingo API package (in the config file) creates an instance of the
18
     * fractal manager which takes the default serializer (specified by the fractal
19
     * package itself, and there's no way to override change it from the configurations of
20
     * the Dingo package).
21
     *
22
     * Here I am replacing the current default serializer (DataArraySerializer) by the
23
     * (JsonApiSerializer).
24
     *
25
     * "Serializers are what build the final response after taking the transformers data".
26
     */
27
    public function overrideDefaultFractalSerializer()
28
    {
29
        $serializerName = Config::get('hello.api.serializer');
30
31
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
32
        if ($serializerName !== 'DataArray') {
33
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
34
                switch ($serializerName) {
35
                    case 'JsonApi':
36
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
37
                        break;
38
                    case 'Array':
39
                        $serializer = new \League\Fractal\Serializer\ArraySerializer(Config::get('api.domain'));
40
                        break;
41
                    default:
42
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
43
                }
44
45
                $fractal = new \League\Fractal\Manager();
46
                $fractal->setSerializer($serializer);
47
48
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
49
            });
50
        }
51
    }
52
53
}
54