Completed
Push — master ( 9527ea...3aab7f )
by Mahmoud
03:10
created

  A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace App\Port\Provider\Traits;
4
5
use App;
6
use App\Port\Butler\Portals\Facade\PortButler;
7
use App\Port\Exception\Exceptions\UnsupportedFractalSerializerException;
8
use App\Port\Middleware\PortKernel;
9
use DB;
10
use File;
11
use Illuminate\Support\Facades\Config;
12
use Log;
13
14
/**
15
 * Class PortServiceProviderTrait.
16
 *
17
 * @author  Mahmoud Zalt <[email protected]>
18
 */
19
trait PortServiceProviderTrait
20
{
21
22
    /**
23
     * Write the DB queries in the Log and Display them in the
24
     * terminal (in case you want to see them while executing the tests).
25
     *
26
     * @param bool|false $terminal
27
     */
28
    public function debugDatabaseQueries($log = true, $terminal = false)
29
    {
30
        if (Config::get('database.query_debugging')) {
31
            DB::listen(function ($event) use ($terminal, $log) {
32
                $fullQuery = vsprintf(str_replace(['%', '?'], ['%%', '%s'], $event->sql), $event->bindings);
33
34
                $text = $event->connectionName . ' (' . $event->time . '): ' . $fullQuery;
35
36
                if ($terminal) {
37
                    dump($text);
38
                }
39
40
                if ($log) {
41
                    Log::info($text);
42
                }
43
            });
44
        }
45
    }
46
47
    /**
48
     * TODO: needs refactoring, was created in 5 min
49
     *
50
     * @return  array
51
     */
52
    public function getAllContainersConsoleCommandsForAutoLoading()
53
    {
54
        $classes = [];
55 View Code Duplication
        foreach (PortButler::getContainersNames() as $containerName) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
            $containerCommandsDirectory = base_path('app/Containers/' . $containerName . '/UI/CLI/Commands/');
57
            if (File::isDirectory($containerCommandsDirectory)) {
58
                $files = \File::allFiles($containerCommandsDirectory);
59
                foreach ($files as $consoleFile) {
60
                    if (\File::isFile($consoleFile)) {
61
                        $pathName = $consoleFile->getPathname();
62
                        $classes[] = PortButler::getClassFullNameFromFile($pathName);
63
                    }
64
                }
65
            }
66
        };
67
68
        return $classes;
69
    }
70
71
72
    /**
73
     * By default the Dingo API package (in the config file) creates an instance of the
74
     * fractal manager which takes the default serializer (specified by the fractal
75
     * package itself, and there's no way to override change it from the configurations of
76
     * the Dingo package).
77
     *
78
     * Here I am replacing the current default serializer (DataArraySerializer) by the
79
     * (JsonApiSerializer).
80
     *
81
     * "Serializers are what build the final response after taking the transformers data".
82
     */
83
    public function overrideDefaultFractalSerializer()
84
    {
85
        $serializerName = Config::get('api.serializer');
86
87
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
88
        if ($serializerName !== 'DataArray') {
89
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
90
                switch ($serializerName) {
91
                    case 'JsonApi':
92
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
93
                        break;
94
                    case 'Array':
95
                        $serializer = new \League\Fractal\Serializer\ArraySerializer(Config::get('api.domain'));
96
                        break;
97
                    default:
98
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
99
                }
100
101
                $fractal = new \League\Fractal\Manager();
102
                $fractal->setSerializer($serializer);
103
104
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
105
            });
106
        }
107
    }
108
109
    /**
110
     * @param array $middlewares
111
     * @param array $middlewareGroups
112
     * @param array $routeMiddlewares
113
     */
114
    public function registerAllMiddlewares(
115
        array $middlewares = [],
116
        array $middlewareGroups = [],
117
        array $routeMiddlewares = []
118
    ) {
119
        // Registering single and grouped middleware's
120
        (App::make(PortKernel::class))
121
            ->registerMiddlewares($middlewares)
122
            ->registerMiddlewareGroups($middlewareGroups);
123
124
        // Registering Route Middleware's
125
        foreach ($routeMiddlewares as $key => $routeMiddleware) {
126
            $this->app['router']->middleware($key, $routeMiddleware);
0 ignored issues
show
Bug introduced by
The property app does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
127
        }
128
129
    }
130
131
132
}
133