Passed
Push — 0.3 ( 9403ca...4e3904 )
by Philippe
43:02
created

chief_cached_asset()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 14
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * Retrieve the logged in admin
5
 */
6
if (!function_exists('chiefAdmin')) {
7
    function chiefAdmin()
8
    {
9 26
        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 37
        $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 37
        $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 37
            return asset(mix($entry, $manifestPath));
28 37
        } catch (\Exception $e) {
29 37
            \Illuminate\Support\Facades\Log::error($e);
30
31 37
            return $manifestPath.$entry;
32
        }
33
    }
34
}
35
36
if (!function_exists('chiefSetting')) {
37
    function chiefSetting($key = null, $default = null)
38
    {
39 8
        $manager = app(\Thinktomorrow\Chief\Settings\SettingsManager::class);
40
41 8
        if (is_null($key)) {
42 2
            return $manager;
43
        }
44
        
45 8
        return $manager->get($key, $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] = str_slug($part, $separator, $language);
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated: Str::slug() should be used directly instead. Will be removed in Laravel 5.9. ( Ignorable by Annotation )

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

64
            $parts[$i] = /** @scrutinizer ignore-deprecated */ str_slug($part, $separator, $language);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
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 53
        $empty = true;
75
76 53
        foreach ($values as $value) {
77 53
            if (! $value || !trim($value)) {
78 7
                continue;
79
            }
80 52
            $empty = false;
81
        }
82
83 53
        return $empty;
84
    }
85
}
86
87
if (! function_exists('contract')) {
88
    function contract($instance, $contract)
89
    {
90 103
        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 htmLawed
149
 * @return 	string
150
 */
151
if (!function_exists('cleanupHTML')) {
152
    function cleanupHTML($value, $whitelist = null)
153
    {
154 1
        if (!function_exists('cleanupHTML')) {
155
            require_once __DIR__ . '/vendors/htmlLawed.php';
156
        }
157 1
        if (is_null($whitelist)) {
158
            $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>';
159
        }
160
        // Strip entire blocks of malicious code
161 1
        $value = preg_replace(array(
162 1
            '@<script[^>]*?>.*?</script>@si',
163
            '@onclick=[^ ].*? @si'
164 1
        ), '', $value);
165
        // strip unwanted tags via whitelist...
166 1
        if (false !== $whitelist) {
167 1
            $value = strip_tags($value, $whitelist);
168
        }
169
        // cleanup HTML and any unwanted attributes
170 1
        $value = htmLawed($value);
171
172
        // Undo the encoding performed by htmlLawed.
173 1
        $value = str_replace('&amp;', '&', $value);
174
175 1
        return $value;
176
    }
177
}
178
179
/**
180
 * Determine whether current url is the active one
181
 *
182
 * @param string $name routename or path without HOST
183
 * @param array $parameters
184
 * @return bool
185
 */
186
if (!function_exists('isActiveUrl')) {
187
    function isActiveUrl($name, $parameters = [])
188
    {
189 16
        if (\Illuminate\Support\Facades\Route::currentRouteNamed($name)) {
190
            $flag = true;
191
            $current = \Illuminate\Support\Facades\Route::current();
192
193
            /**
194
             * If a single parameter is passed as string, we will convert this to
195
             * the proper array keyed by the first uri parameter
196
             */
197
            if (!is_array($parameters)) {
198
                $names = $current->parameterNames();
199
                $parameters = [reset($names) => $parameters];
200
            }
201
202
            foreach ($parameters as $key => $parameter) {
203
                if ($current->parameter($key, false) != $parameter) {
204
                    $flag = false;
205
                }
206
            }
207
208
            return $flag;
209
        }
210
211 16
        $name = ltrim($name, '/');
212
213 16
        if (false !== strpos($name, '*')) {
214 16
            $pattern = str_replace('\*', '(.*)', preg_quote($name, '#'));
215
216 16
            return !!preg_match("#$pattern#", request()->path());
217
        }
218
219 16
        return ($name == request()->path());
220
    }
221
}
222
223
/**
224
 * Inject a query parameter into an url
225
 * If the query key already exists, it will be overwritten with the new value
226
 *
227
 * @param $url
228
 * @param array $query_params
229
 * @param array $overrides
230
 * @return string
231
 */
232
if (!function_exists('addQueryToUrl')) {
233
    function addQueryToUrl($url, array $query_params = [], $overrides = [])
234
    {
235 12
        $parsed_url = parse_url($url);
236
237 12
        $parsed_url = array_merge(array_fill_keys([
238 12
            'scheme', 'host', 'port', 'path', 'query', 'fragment'
239 12
        ], null), $parsed_url, $overrides);
240
241 12
        $scheme = $parsed_url['scheme'] ? $parsed_url['scheme'] . '://' : null;
242 12
        $port = $parsed_url['port'] ? ':' . $parsed_url['port'] : null;
243 12
        $fragment = $parsed_url['fragment'] ? '#' . $parsed_url['fragment'] : null;
244
245 12
        $baseurl = $scheme . $parsed_url['host'] . $port . $parsed_url['path'];
246 12
        $current_query = [];
247
248 12
        $_query = explode('&', $parsed_url['query']);
249
250
        array_map(function ($v) use (&$current_query) {
251 12
            if (!$v) {
252 5
                return;
253
            }
254 7
            $split = explode('=', $v);
255 7
            if (count($split) == 2) {
256 7
                $current_query[$split[0]] = $split[1];
257
            }
258 12
        }, $_query);
259
260 12
        foreach ($query_params as $key => $value) {
261 12
            if (isset($current_query[$key])) {
262 12
                unset($current_query[$key]);
263
            }
264
        }
265
266 12
        $query = urldecode(http_build_query(array_merge($current_query, $query_params)));
267
268 12
        return $baseurl . '?' . $query . $fragment;
269
    }
270
}
271
272
if (!function_exists('ddd')) {
273
    function ddd($var, ...$moreVars)
274
    {
275
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
276
        if (php_sapi_name() == 'cli') {
277
            print_r("\e[1;30m dumped at: " . str_replace(base_path(), '', $trace[0]['file']). ", line: " . $trace[0]['line'] . "\e[40m\n");
278
        } else {
279
            print_r("[dumped at: " . str_replace(base_path(), '', $trace[0]['file']). ", line: " . $trace[0]['line'] . "]\n");
280
        }
281
        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...
282
    }
283
}
284
285
if (!function_exists('chiefMemoize')) {
286
    /**
287
     * Memoize a function
288
     *
289
     * @param $key
290
     * @param Closure $closure
291
     * @param array $parameters
292
     * @return mixed
293
     */
294
    function chiefMemoize($key, \Closure $closure, array $parameters = [])
295
    {
296 87
        return (new \Thinktomorrow\Chief\Common\Helpers\Memoize($key))->run($closure, $parameters);
297
    }
298
}
299