Completed
Push — master ( 270485...f89d9f )
by Mahmoud
03:15
created

FractalTrait::overrideDefaultFractalSerializer()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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