Completed
Push — master ( 1b73c5...b9dd45 )
by Mahmoud
03:37
created

PortServiceProviderTrait   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 148
Duplicated Lines 8.11 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 4
Bugs 1 Features 1
Metric Value
wmc 19
lcom 1
cbo 3
dl 12
loc 148
rs 10
c 4
b 1
f 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A changeTheDefaultDatabaseModelsFactoriesPath() 0 8 1
A debugDatabaseQueries() 0 18 4
A getMainServiceProviders() 0 13 3
B getAllContainersConsoleCommandsForAutoLoading() 12 18 5
B overrideDefaultFractalSerializer() 0 25 4
A registerAllMiddlewares() 0 16 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
     * By default Laravel takes (server/database/factories) as the
49
     * path to the factories, this function changes the path to load
50
     * the factories from the infrastructure directory.
51
     */
52
    public function changeTheDefaultDatabaseModelsFactoriesPath($customPath)
53
    {
54
        App::singleton(\Illuminate\Database\Eloquent\Factory::class, function ($app) use ($customPath) {
55
            $faker = $app->make(\Faker\Generator::class);
56
57
            return \Illuminate\Database\Eloquent\Factory::construct($faker, base_path() . $customPath);
58
        });
59
    }
60
61
    /**
62
     * Get the containers Service Providers full classes names.
63
     *
64
     * @return  array
65
     */
66
    public function getMainServiceProviders()
67
    {
68
        $containersNamespace = PortButler::getContainersNamespace();
69
70
        $allServiceProviders = [];
71
72
        foreach (PortButler::getContainersNames() as $containerName) {
73
            // append the Module main service provider
74
            $allServiceProviders[] = PortButler::buildMainServiceProvider($containersNamespace, $containerName);
75
        }
76
77
        return array_unique($allServiceProviders) ? : [];
78
    }
79
80
81
    /**
82
     * TODO: needs refactoring, was created in 5 min
83
     *
84
     * @return  array
85
     */
86
    public function getAllContainersConsoleCommandsForAutoLoading()
87
    {
88
        $classes = [];
89 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...
90
            $containerCommandsDirectory = base_path('app/Containers/' . $containerName . '/UI/CLI/Commands/');
91
            if (File::isDirectory($containerCommandsDirectory)) {
92
                $files = \File::allFiles($containerCommandsDirectory);
93
                foreach ($files as $consoleFile) {
94
                    if (\File::isFile($consoleFile)) {
95
                        $pathName = $consoleFile->getPathname();
96
                        $classes[] = PortButler::getClassFullNameFromFile($pathName);
97
                    }
98
                }
99
            }
100
        };
101
102
        return $classes;
103
    }
104
105
106
    /**
107
     * By default the Dingo API package (in the config file) creates an instance of the
108
     * fractal manager which takes the default serializer (specified by the fractal
109
     * package itself, and there's no way to override change it from the configurations of
110
     * the Dingo package).
111
     *
112
     * Here I am replacing the current default serializer (DataArraySerializer) by the
113
     * (JsonApiSerializer).
114
     *
115
     * "Serializers are what build the final response after taking the transformers data".
116
     */
117
    public function overrideDefaultFractalSerializer()
118
    {
119
        $serializerName = Config::get('api.serializer');
120
121
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
122
        if ($serializerName !== 'DataArray') {
123
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
124
                switch ($serializerName) {
125
                    case 'JsonApi':
126
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
127
                        break;
128
                    case 'Array':
129
                        $serializer = new \League\Fractal\Serializer\ArraySerializer(Config::get('api.domain'));
130
                        break;
131
                    default:
132
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
133
                }
134
135
                $fractal = new \League\Fractal\Manager();
136
                $fractal->setSerializer($serializer);
137
138
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
139
            });
140
        }
141
    }
142
143
    /**
144
     * @param array $middlewares
145
     * @param array $middlewareGroups
146
     * @param array $routeMiddlewares
147
     */
148
    public function registerAllMiddlewares(
149
        array $middlewares = [],
150
        array $middlewareGroups = [],
151
        array $routeMiddlewares = []
152
    ) {
153
        // Registering single and grouped middleware's
154
        (App::make(PortKernel::class))
155
            ->registerMiddlewares($middlewares)
156
            ->registerMiddlewareGroups($middlewareGroups);
157
158
        // Registering Route Middleware's
159
        foreach ($routeMiddlewares as $key => $routeMiddleware) {
160
            $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...
161
        }
162
163
    }
164
165
166
}
167