Passed
Push — ft/nomadic ( 8f7952...ec1acc )
by Philippe
50:44 queued 43:40
created

isActiveUrl()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 33
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 17.5839

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 9
nop 2
dl 0
loc 33
ccs 6
cts 15
cp 0.4
crap 17.5839
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Retrieve the logged in admin
5
 */
6
if (!function_exists('chiefAdmin')) {
7
    function chiefAdmin()
8
    {
9 32
        return \Illuminate\Support\Facades\Auth::guard('chief')->user();
10
    }
11
}
12
13
/**
14
 * Retrieve the public asset with a version stamp.
15
 * This allows for browsercache out of the box
16
 */
17
if (!function_exists('chief_cached_asset')) {
18
    function chief_cached_asset($filepath)
19
    {
20 23
        $manifestPath = '/chief-assets/back';
21
22
        // Manifest expects each entry to start with a leading slash - we make sure to deduplicate the manifest path.
23 23
        $entry = str_replace($manifestPath, '', '/'.ltrim($filepath, '/'));
24
25
        try {
26
            // Paths should be given relative to the manifestpath so make sure to remove the basepath
27 23
            return asset(mix($entry, $manifestPath));
28 23
        } catch (\Exception $e) {
29 23
            \Illuminate\Support\Facades\Log::error($e);
30
31 23
            return $manifestPath.$entry;
32
        }
33
    }
34
}
35
36
if (!function_exists('chiefSetting')) {
37
    function chiefSetting($key = null, $locale = null, $default = null)
38
    {
39 46
        $settings = app(\Thinktomorrow\Chief\Settings\Settings::class);
40
41 46
        if (is_null($key)) {
42 2
            return $settings;
43
        }
44
45 46
        return $settings->get($key, $locale, $default);
46
    }
47
}
48
49
if (!function_exists('chiefmenu')) {
50
    function chiefmenu($key = 'main')
51
    {
52
        $menu = \Thinktomorrow\Chief\Menu\Menu::find($key);
53
54
        return $menu ?? new \Thinktomorrow\Chief\Menu\NullMenu();
55
    }
56
}
57
58
if (!function_exists('str_slug_slashed')) {
59
    function str_slug_slashed($title, $separator = '-', $language = 'en')
60
    {
61
        $parts = explode('/', $title);
62
63
        foreach ($parts as $i => $part) {
64
            $parts[$i] = Illuminate\Support\Str::slug($part, $separator, $language);
65
        }
66
67
        return implode('/', $parts);
68
    }
69
}
70
71
if (!function_exists('is_array_empty')) {
72
    function is_array_empty(array $values)
73
    {
74 59
        $empty = true;
75
76 59
        foreach ($values as $value) {
77 59
            if (! $value || !trim($value)) {
78 7
                continue;
79
            }
80 58
            $empty = false;
81
        }
82
83 59
        return $empty;
84
    }
85
}
86
87
if (! function_exists('contract')) {
88
    function contract($instance, $contract)
89
    {
90 126
        return $instance instanceof $contract;
91
    }
92
}
93
94
/**
95
 * --------------------------------------------------------------------------
96
 * Helper: Teaser
97
 * --------------------------------------------------------------------------
98
 */
99
if (!function_exists('teaser')) {
100
    /**
101
     * @param $text
102
     * @param null $max
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $max is correct as it would always require null to be passed?
Loading history...
103
     * @param null $ending
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $ending is correct as it would always require null to be passed?
Loading history...
104
     * @param string $clean - whitelist of html tags: set to null to allow tags
105
     * @return mixed|string
106
     */
107
    function teaser($text, $max = null, $ending = null, $clean = '')
108
    {
109 1
        if (is_null($max) or is_string($max)) {
0 ignored issues
show
introduced by
The condition is_null($max) is always true.
Loading history...
110
            return $text;
111
        }
112 1
        if (!is_null($clean)) {
113 1
            $text = cleanupHTML($text, $clean);
114
        }
115 1
        $teaser = substr($text, 0, $max);
116 1
        return strlen($text) <= $max ? $teaser : $teaser . $ending;
117
    }
118
}
119
120
121
/**
122
 * --------------------------------------------------------------------------
123
 * Helper: cleanupString
124
 * --------------------------------------------------------------------------
125
 *
126
 * Takes an input and cleans up a regular string from unwanted input
127
 *
128
 * @param 	string 	$value
129
 * @return 	string
130
 */
131
if (!function_exists('cleanupString')) {
132
    function cleanupString($value)
133
    {
134
        $value = strip_tags($value);
135
136
        return trim($value);
137
    }
138
}
139
140
/**
141
 * --------------------------------------------------------------------------
142
 * Helper: cleanupHTML
143
 * --------------------------------------------------------------------------
144
 *
145
 * Takes an input and cleans up unwanted / malicious HTML
146
 *
147
 * @param 	string 	$value
148
 * @param 	string 	$whitelist - if false no tagstripping will occur - other than HTMLPurifier
149
 * @return 	string
150
 */
151
if (!function_exists('cleanupHTML')) {
152
    function cleanupHTML($value, $whitelist = null)
153
    {
154 1
        if (is_null($whitelist)) {
155
            $whitelist = '<code><span><div><label><a><br><p><b><i><del><strike><u><img><video><audio><iframe><object><embed><param><blockquote><mark><cite><small><ul><ol><li><hr><dl><dt><dd><sup><sub><big><pre><code><figure><figcaption><strong><em><table><tr><td><th><tbody><thead><tfoot><h1><h2><h3><h4><h5><h6>';
156
        }
157
        // Strip entire blocks of malicious code
158 1
        $value = preg_replace(array(
159 1
            '@<script[^>]*?>.*?</script>@si',
160
            '@onclick=[^ ].*? @si'
161 1
        ), '', $value);
162
        // strip unwanted tags via whitelist...
163 1
        if (false !== $whitelist) {
164 1
            $value = strip_tags($value, $whitelist);
165
        }
166
        // // cleanup HTML and any unwanted attributes
167 1
        $purifier = new HTMLPurifier();
168 1
        $value = $purifier->purify($value);
169
170
        /**
171
         * htmlPurifier converts characters to their encode equivalents. This is something
172
         * that we need to reverse after the htmlPurifier cleanup.
173
         */
174 1
        $value  = str_replace('&amp;', '&', $value);
175
176 1
        return $value;
177
    }
178
}
179
180
/**
181
 * Determine whether current url is the active one
182
 *
183
 * @param string $name routename or path without HOST
184
 * @param array $parameters
185
 * @return bool
186
 */
187
if (!function_exists('isActiveUrl')) {
188
    function isActiveUrl($name, $parameters = [])
189
    {
190 22
        if (\Illuminate\Support\Facades\Route::currentRouteNamed($name)) {
191
            $flag = true;
192
            $current = \Illuminate\Support\Facades\Route::current();
193
194
            /**
195
             * If a single parameter is passed as string, we will convert this to
196
             * the proper array keyed by the first uri parameter
197
             */
198
            if (!is_array($parameters)) {
199
                $names = $current->parameterNames();
200
                $parameters = [reset($names) => $parameters];
201
            }
202
203
            foreach ($parameters as $key => $parameter) {
204
                if ($current->parameter($key, false) != $parameter) {
205
                    $flag = false;
206
                }
207
            }
208
209
            return $flag;
210
        }
211
212 22
        $name = ltrim($name, '/');
213
214 22
        if (false !== strpos($name, '*')) {
215 22
            $pattern = str_replace('\*', '(.*)', preg_quote($name, '#'));
216
217 22
            return !!preg_match("#$pattern#", request()->path());
218
        }
219
220 22
        return ($name == request()->path() || $name == request()->fullUrl());
221
    }
222
}
223
224
/**
225
 * Inject a query parameter into an url
226
 * If the query key already exists, it will be overwritten with the new value
227
 *
228
 * @param $url
229
 * @param array $query_params
230
 * @param array $overrides
231
 * @return string
232
 */
233
if (!function_exists('addQueryToUrl')) {
234
    function addQueryToUrl($url, array $query_params = [], $overrides = [])
235
    {
236 12
        $parsed_url = parse_url($url);
237
238 12
        $parsed_url = array_merge(array_fill_keys([
239 12
            'scheme', 'host', 'port', 'path', 'query', 'fragment'
240 12
        ], null), $parsed_url, $overrides);
241
242 12
        $scheme = $parsed_url['scheme'] ? $parsed_url['scheme'] . '://' : null;
243 12
        $port = $parsed_url['port'] ? ':' . $parsed_url['port'] : null;
244 12
        $fragment = $parsed_url['fragment'] ? '#' . $parsed_url['fragment'] : null;
245
246 12
        $baseurl = $scheme . $parsed_url['host'] . $port . $parsed_url['path'];
247 12
        $current_query = [];
248
249 12
        $_query = explode('&', $parsed_url['query']);
250
251
        array_map(function ($v) use (&$current_query) {
252 12
            if (!$v) {
253 5
                return;
254
            }
255 7
            $split = explode('=', $v);
256 7
            if (count($split) == 2) {
257 7
                $current_query[$split[0]] = $split[1];
258
            }
259 12
        }, $_query);
260
261 12
        foreach ($query_params as $key => $value) {
262 12
            if (isset($current_query[$key])) {
263 12
                unset($current_query[$key]);
264
            }
265
        }
266
267 12
        $query = urldecode(http_build_query(array_merge($current_query, $query_params)));
268
269 12
        return $baseurl . '?' . $query . $fragment;
270
    }
271
}
272
273
if (!function_exists('ddd')) {
274
    function ddd($var, ...$moreVars)
275
    {
276
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
277
        if (php_sapi_name() == 'cli') {
278
            print_r("\e[1;30m dumped at: " . str_replace(base_path(), '', $trace[0]['file']). ", line: " . $trace[0]['line'] . "\e[40m\n");
279
        } else {
280
            print_r("[dumped at: " . str_replace(base_path(), '', $trace[0]['file']). ", line: " . $trace[0]['line'] . "]\n");
281
        }
282
        return dd($var, ...$moreVars);
0 ignored issues
show
Bug introduced by
Are you sure the usage of dd($var, $moreVars) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
283
    }
284
}
285
286
if (!function_exists('chiefMemoize')) {
287
    /**
288
     * Memoize a function
289
     *
290
     * @param $key
291
     * @param Closure $closure
292
     * @param array $parameters
293
     * @return mixed
294
     */
295
    function chiefMemoize($key, \Closure $closure, array $parameters = [])
296
    {
297 79
        return (new \Thinktomorrow\Chief\Common\Helpers\Memoize($key))->run($closure, $parameters);
298
    }
299
}
300