Completed
Push — master ( b9dd45...d03d4d )
by Mahmoud
03:06
created

getMainServiceProviders()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 13
rs 9.4285
cc 3
eloc 6
nc 4
nop 0
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
    /**
63
     * TODO: needs refactoring, was created in 5 min
64
     *
65
     * @return  array
66
     */
67
    public function getAllContainersConsoleCommandsForAutoLoading()
68
    {
69
        $classes = [];
70 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...
71
            $containerCommandsDirectory = base_path('app/Containers/' . $containerName . '/UI/CLI/Commands/');
72
            if (File::isDirectory($containerCommandsDirectory)) {
73
                $files = \File::allFiles($containerCommandsDirectory);
74
                foreach ($files as $consoleFile) {
75
                    if (\File::isFile($consoleFile)) {
76
                        $pathName = $consoleFile->getPathname();
77
                        $classes[] = PortButler::getClassFullNameFromFile($pathName);
78
                    }
79
                }
80
            }
81
        };
82
83
        return $classes;
84
    }
85
86
87
    /**
88
     * By default the Dingo API package (in the config file) creates an instance of the
89
     * fractal manager which takes the default serializer (specified by the fractal
90
     * package itself, and there's no way to override change it from the configurations of
91
     * the Dingo package).
92
     *
93
     * Here I am replacing the current default serializer (DataArraySerializer) by the
94
     * (JsonApiSerializer).
95
     *
96
     * "Serializers are what build the final response after taking the transformers data".
97
     */
98
    public function overrideDefaultFractalSerializer()
99
    {
100
        $serializerName = Config::get('api.serializer');
101
102
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
103
        if ($serializerName !== 'DataArray') {
104
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
105
                switch ($serializerName) {
106
                    case 'JsonApi':
107
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
108
                        break;
109
                    case 'Array':
110
                        $serializer = new \League\Fractal\Serializer\ArraySerializer(Config::get('api.domain'));
111
                        break;
112
                    default:
113
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
114
                }
115
116
                $fractal = new \League\Fractal\Manager();
117
                $fractal->setSerializer($serializer);
118
119
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
120
            });
121
        }
122
    }
123
124
    /**
125
     * @param array $middlewares
126
     * @param array $middlewareGroups
127
     * @param array $routeMiddlewares
128
     */
129
    public function registerAllMiddlewares(
130
        array $middlewares = [],
131
        array $middlewareGroups = [],
132
        array $routeMiddlewares = []
133
    ) {
134
        // Registering single and grouped middleware's
135
        (App::make(PortKernel::class))
136
            ->registerMiddlewares($middlewares)
137
            ->registerMiddlewareGroups($middlewareGroups);
138
139
        // Registering Route Middleware's
140
        foreach ($routeMiddlewares as $key => $routeMiddleware) {
141
            $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...
142
        }
143
144
    }
145
146
147
}
148