Passed
Pull Request — 2.x (#1446)
by Harings
08:51
created

capsule_namespace_to_path()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
use A17\Twill\Facades\TwillCapsules;
4
use A17\Twill\Services\Blocks\BlockCollection;
5
use Illuminate\Events\Dispatcher;
6
use Illuminate\Filesystem\Filesystem;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Filesystem. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Facades\Event;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Event. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
use Illuminate\Support\Str;
10
11
if (!function_exists('dumpUsableSqlQuery')) {
12
    function dumpUsableSqlQuery($query)
13
    {
14
        dd(vsprintf(str_replace('?', '%s', $query->toSql()), array_map(function ($binding) {
15
            return is_numeric($binding) ? $binding : "'{$binding}'";
16
        }, $query->getBindings())));
17
    }
18
}
19
20
if (!function_exists('classUsesDeep')) {
21
    /**
22
     * @param mixed $class
23
     * @param bool $autoload
24
     * @return array
25
     */
26 36
    function classUsesDeep($class, $autoload = true)
27
    {
28
        $traits = [];
29
30 36
        // Get traits of all parent classes
31 36
        do {
32
            $traits = array_merge(class_uses($class, $autoload), $traits);
33
        } while ($class = get_parent_class($class));
34 36
35 36
        // Get traits of all parent traits
36 36
        $traitsToSearch = $traits;
37 36
        while (!empty($traitsToSearch)) {
38 36
            $newTraits = class_uses(array_pop($traitsToSearch), $autoload);
39
            $traits = array_merge($newTraits, $traits);
40
            $traitsToSearch = array_merge($newTraits, $traitsToSearch);
41 36
        }
42 36
43
        foreach ($traits as $trait => $same) {
44
            $traits = array_merge(class_uses($trait, $autoload), $traits);
45 36
        }
46
47
        return array_unique($traits);
48
    }
49
}
50
51
if (!function_exists('classHasTrait')) {
52
    /**
53
     * @param mixed $class
54
     * @param string $trait
55
     * @return bool
56
     */
57 36
    function classHasTrait($class, $trait)
58
    {
59 36
        $traits = classUsesDeep($class);
60 33
61
        if (in_array($trait, array_keys($traits))) {
62
            return true;
63 3
        }
64
65
        return false;
66
    }
67
}
68
69
if (!function_exists('getFormFieldsValue')) {
70
    /**
71
     * @param array $formFields
72
     * @param string $name
73
     * @param mixed $default
74
     * @return mixed
75 2
     */
76
    function getFormFieldsValue($formFields, $name, $default = null)
77
    {
78
        return Arr::get($formFields, str_replace(']', '', str_replace('[', '.', $name)), $default ?? '') ?? $default;
79
    }
80
}
81
82
if (!function_exists('fireCmsEvent')) {
83
    /**
84
     * @param string $eventName
85
     * @param array $input
86
     * @return void
87 25
     */
88 25
    function fireCmsEvent($eventName, $input = [])
89 25
    {
90
        $method = method_exists(Dispatcher::class, 'dispatch') ? 'dispatch' : 'fire';
91
        Event::$method($eventName, [$eventName, $input]);
92
    }
93
}
94
95
if (!function_exists('twill_path')) {
96
    /**
97
     * @param string $path
98
     * @return string
99
     */
100 69
    function twill_path($path = '')
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
101 1
    {
102
        // Is it a full application path?
103
        if (Str::startsWith($path, base_path())) {
104
            return $path;
105 69
        }
106
107 69
        // Split to separate root namespace
108
        preg_match('/(\w*)\W?(.*)/', config('twill.namespace'), $namespaceParts);
109 69
110
        $twillBase = app_path(
111 69
            fix_directory_separator(
112
                $namespaceParts[1] == 'App' ? $namespaceParts[2] : $namespaceParts[0]
113
            )
114 69
        ) . '/';
115
116
        // Remove base path from path
117
        if (Str::startsWith($path, $twillBase)) {
118
            $path = Str::after($path, $twillBase);
119 69
        }
120 69
121
        // Namespace App is unchanged in config?
122
        if ($namespaceParts[0] === 'App') {
123
            return app_path($path);
124
        }
125
126
        // If it it still starts with App, use the left part, otherwise use the whole namespace
127
        // This can be a problem for those using a completely different app path for the application
128
        $left = ($namespaceParts[1] === 'App' ? $namespaceParts[2] : $namespaceParts[0]);
129
130
        // Join, fix slashes for the current operating system, and return path
131
        return app_path(fix_directory_separator(
132
            $left . (filled($path) ? '\\' . $path : '')
133
        ));
134
    }
135
}
136
137
if (!function_exists('make_twill_directory')) {
138
    /**
139
     * @param string $path
140
     * @param bool $recursive
141
     * @param \Illuminate\Filesystem\Filesystem|null $fs
142 1
     */
143
    function make_twill_directory($path, $recursive = true, $fs = null)
144 1
    {
145
        $fs = filled($fs)
146 1
        ? $fs
147
        : app(Filesystem::class);
148 1
149 1
        $path = twill_path($path);
150
151 1
        if (!$fs->isDirectory($path)) {
0 ignored issues
show
Bug introduced by
The method isDirectory() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

151
        if (!$fs->/** @scrutinizer ignore-call */ isDirectory($path)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
152
            $fs->makeDirectory($path, 0755, $recursive);
153
        }
154
    }
155
}
156
157
if (!function_exists('twill_put_stub')) {
158
    /**
159
     * @param string $path
160
     * @param bool $recursive
161
     * @param \Illuminate\Filesystem\Filesystem|null $fs
162 1
     */
163
    function twill_put_stub($path, $stub, $fs = null)
164 1
    {
165
        $fs = filled($fs)
166 1
        ? $fs
167 1
        : app(Filesystem::class);
168 1
169 1
        $stub = str_replace(
170
            'namespace App\\',
171
            sprintf('namespace %s\\', config('twill.namespace')),
172 1
            $stub
173 1
        );
174
175 1
        if (!$fs->exists($path)) {
176
            $fs->put($path, $stub);
177
        }
178
    }
179
}
180
181
if (!function_exists('fix_directory_separator')) {
182
    /**
183
     * @param string $path
184
     * @param bool $recursive
185
     * @param int $mode
186 69
     */
187 69
    function fix_directory_separator($path)
188 69
    {
189 69
        return str_replace(
190
            '\\',
191
            DIRECTORY_SEPARATOR,
192
            $path
193
        );
194
    }
195
}
196
197
if (!function_exists('generate_list_of_allowed_blocks')) {
198
    /**
199
     * @param array $blocks
200
     * @param array $groups
201
     * @return array
202 4
     */
203
    function generate_list_of_available_blocks($blocks, $groups)
204 4
    {
205 4
        $blockList = app(BlockCollection::class)->getBlockList();
206 4
207
        $appBlocksList = $blockList->filter(function ($block) {
208 4
            return $block['source'] !== A17\Twill\Services\Blocks\Block::SOURCE_TWILL;
209 4
        });
210 4
211 4
        $finalBlockList = $blockList->filter(
212 4
            function ($block) use ($blocks, $groups, $appBlocksList) {
213 4
                if ($block['group'] === A17\Twill\Services\Blocks\Block::SOURCE_TWILL) {
214 4
                    if (!collect(
215
                        config('twill.block_editor.use_twill_blocks')
216
                    )->contains($block['name'])) {
217
                        return false;
218
                    }
219
220
                    if (count($appBlocksList) > 0 && $appBlocksList->contains(
221
                        function ($appBlock) use ($block) {
222
                            return $appBlock['name'] === $block['name'];
223
                        })
224
                    ) {
225
                        return false;
226
                    }
227
                }
228 4
229 4
                return (filled($blocks) ? collect($blocks)->contains($block['name']) : true)
230
                    && (filled($groups) ? collect($groups)->contains($block['group']) : true);
231
            }
232
        );
233
234
        // Sort them by the original definition
235
        $sorted = $finalBlockList->sortBy(function($b) use ($blocks) {
236
            return collect($blocks)->search(function($id, $key) use ($b) {
237
                return $id == $b['name'];
238
            });
239
        })->values()->toArray();
240
241
        return $sorted;
242
    }
243
}
244
245
if (!function_exists('capsule_namespace')) {
246
    /**
247
     * @deprecated use TwillCapsules::capsuleNamespace instead
248
     */
249
    function capsule_namespace($capsuleName, $type = null) {
250
        return TwillCapsules::capsuleNamespace($capsuleName, $type);
251
    }
252
}
253
254
if (!function_exists('capsule_namespace_to_path')) {
255
    /**
256
     * @deprecated use TwillCapsules::capsuleNamespaceToPath instead
257
     */
258
    function capsule_namespace_to_path($namespace, $capsuleNamespace, $rootPath) {
259
        return TwillCapsules::capsuleNamespaceToPath($namespace, $capsuleNamespace, $rootPath);
260
    }
261
}
262