Completed
Push — master ( 8b219b...d34292 )
by Mahmoud
04:38
created

changeTheDefaultDatabaseModelsFactoriesPath()   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 DB;
9
use File;
10
use Illuminate\Support\Facades\Config;
11
use Illuminate\Support\Facades\View;
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
        foreach (PortButler::getContainersNames() as $containerName) {
71
            // append the Module main service provider
72
            $allServiceProviders[] = PortButler::buildMainServiceProvider($containersNamespace, $containerName);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$allServiceProviders was never initialized. Although not strictly required by PHP, it is generally a good practice to add $allServiceProviders = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
73
        }
74
75
        return array_unique($allServiceProviders) ? : [];
0 ignored issues
show
Bug introduced by
The variable $allServiceProviders does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
76
    }
77
78
    /**
79
     * Load views from inside the Containers
80
     */
81
    public function autoLoadViewsFromContainers()
82
    {
83
        foreach (PortButler::getContainersNames() as $containerName) {
84
85
            $containerViewDirectory = base_path('app/Containers/' . $containerName . '/UI/WEB/Views/');
86
87
            if (File::isDirectory($containerViewDirectory)) {
88
                View::addLocation($containerViewDirectory);
89
            }
90
        }
91
    }
92
93
    /**
94
     * Load migrations files from Containers to Laravel
95
     */
96
    public function autoMigrationsFromContainers()
97
    {
98
        foreach (PortButler::getContainersNames() as $containerName) {
99
100
            $containerMigrationDirectory = base_path('app/Containers/' . $containerName . '/Data/Migrations');
101
102
            if (File::isDirectory($containerMigrationDirectory)) {
103
104
                App::afterResolving('migrator', function ($migrator) use ($containerMigrationDirectory) {
105
                    foreach ((array)$containerMigrationDirectory as $path) {
106
                        $migrator->path($path);
107
                    }
108
                });
109
            }
110
        }
111
    }
112
113
    /**
114
     * Auto load Containers and Port config files into Laravel
115
     */
116
    public function autoLoadConfigFiles()
117
    {
118
        $this->autoLoadContainersConfigFiles();
119
        $this->autoLoadPortConfigFiles();
120
    }
121
122
    /**
123
     *
124
     */
125
    protected function autoLoadContainersConfigFiles()
126
    {
127
        foreach (PortButler::getContainersNames() as $containerName) {
128
            $this->loadConfigs(base_path('app/Containers/' . $containerName . '/Configs'));
129
        }
130
    }
131
132
    /**
133
     *
134
     */
135
    protected function autoLoadPortConfigFiles()
136
    {
137
        $this->loadConfigs(base_path('app/Port/Configs'));
138
    }
139
140
    /**
141
     * @param $directory
142
     */
143
    private function loadConfigs($directory)
144
    {
145
        if (File::isDirectory($directory)) {
146
147
            $files = File::allFiles($directory);
148
149
            foreach ($files as $file) {
150
                // build the key from the file name (just remove the .php extension from the file name)
151
                $fileNameOnly = str_replace('.php', '', $file->getFilename());
152
153
                // merge the config file
154
                $this->mergeConfigFrom($file->getPathname(), $fileNameOnly);
0 ignored issues
show
Bug introduced by
It seems like mergeConfigFrom() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
155
            }
156
        }
157
    }
158
159
160
    /**
161
     * By default the Dingo API package (in the config file) creates an instance of the
162
     * fractal manager which takes the default serializer (specified by the fractal
163
     * package itself, and there's no way to override change it from the configurations of
164
     * the Dingo package).
165
     *
166
     * Here I am replacing the current default serializer (DataArraySerializer) by the
167
     * (JsonApiSerializer).
168
     *
169
     * "Serializers are what build the final response after taking the transformers data".
170
     */
171
    public function overrideDefaultFractalSerializer()
172
    {
173
        $serializerName = Config::get('api.serializer');
174
175
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
176
        if ($serializerName !== 'DataArray') {
177
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
178
                switch ($serializerName) {
179
                    case 'JsonApi':
180
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
181
                        break;
182
                    case 'Array':
183
                        $serializer = new \League\Fractal\Serializer\ArraySerializer(Config::get('api.domain'));
0 ignored issues
show
Unused Code introduced by
The call to ArraySerializer::__construct() has too many arguments starting with \Illuminate\Support\Faca...nfig::get('api.domain').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
184
                        break;
185
                    default:
186
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
187
                }
188
189
                $fractal = new \League\Fractal\Manager();
190
                $fractal->setSerializer($serializer);
191
192
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
193
            });
194
        }
195
    }
196
}
197