Completed
Push — master ( 59f74a...c12486 )
by Mahmoud
03:24
created

getMainServiceProviders()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
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 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
     * Register the Migrations files of all Containers
63
     */
64
    public function publishContainersMigrationsFiles()
65
    {
66
        foreach (PortButler::getContainersNames() as $containerName) {
67
            $this->publishModuleMigrationsFiles($containerName);
68
        }
69
    }
70
71
    /**
72
     * Get the containers Service Providers full classes names.
73
     *
74
     * @return  array
75
     */
76
    public function getMainServiceProviders()
77
    {
78
        $containersNamespace = PortButler::getContainersNamespace();
79
80
        foreach (PortButler::getContainersNames() as $containerName) {
81
            // append the Module main service provider
82
            $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...
83
        }
84
85
        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...
86
    }
87
88
    /**
89
     * Load views from inside the Containers
90
     */
91
    public function autoLoadViewsFromContainers()
92
    {
93
        foreach (PortButler::getContainersNames() as $containerName) {
94
95
            $containerViewDirectory = base_path('app/Containers/' . $containerName . '/UI/WEB/Views/');
96
97
            if (File::isDirectory($containerViewDirectory)) {
98
                View::addLocation($containerViewDirectory);
99
            }
100
        }
101
    }
102
103
    /**
104
     * By default the Dingo API package (in the config file) creates an instance of the
105
     * fractal manager which takes the default serializer (specified by the fractal
106
     * package itself, and there's no way to override change it from the configurations of
107
     * the Dingo package).
108
     *
109
     * Here I am replacing the current default serializer (DataArraySerializer) by the
110
     * (JsonApiSerializer).
111
     *
112
     * "Serializers are what build the final response after taking the transformers data".
113
     */
114
    public function overrideDefaultFractalSerializer()
115
    {
116
        $serializerName = Config::get('api.serializer');
117
118
        // if DataArray `\League\Fractal\Serializer\DataArraySerializer` do noting since it's set by default by the Dingo API
119
        if ($serializerName !== 'DataArray') {
120
            app('Dingo\Api\Transformer\Factory')->setAdapter(function () use ($serializerName) {
121
                switch ($serializerName) {
122
                    case 'JsonApi':
123
                        $serializer = new \League\Fractal\Serializer\JsonApiSerializer(Config::get('api.domain'));
124
                        break;
125
                    case 'Array':
126
                        $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...
127
                        break;
128
                    default:
129
                        throw new UnsupportedFractalSerializerException('Unsupported ' . $serializerName);
130
                }
131
132
                $fractal = new \League\Fractal\Manager();
133
                $fractal->setSerializer($serializer);
134
135
                return new \Dingo\Api\Transformer\Adapter\Fractal($fractal, 'include', ',', false);
136
            });
137
        }
138
    }
139
140
141
    /**
142
     * Register the Migrations files of a Module
143
     *
144
     * This transfers all the Migrations files from the Module directory to the Framework
145
     * Migrations Directory.
146
     *
147
     * @param $directory
148
     */
149
    private function publishModuleMigrationsFiles($containerName)
150
    {
151
        $containerMigrationsDirectory = base_path() . '/app/Containers/' . $containerName . '/Data/Migrations/';
152
153
        if (File::isDirectory($containerMigrationsDirectory)) {
154
            $this->publishes([
0 ignored issues
show
Bug introduced by
It seems like publishes() 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
                $containerMigrationsDirectory => database_path('migrations'),
156
            ], 'migrations');
157
        }
158
    }
159
160
}
161