Test Failed
Push — master ( d27946...98f74e )
by Terzi
08:07
created

translated_values()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 3
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace {
4
    if (!function_exists('array_build')) {
5
        /**
6
         * Build a new array using a callback (Original method was deprecetad since version 5.2).
7
         *
8
         * @param array $array
9
         * @param callable $callback
10
         *
11
         * @return array
12
         */
13
        function array_build($array, callable $callback)
14
        {
15
            $results = [];
16
17
            foreach ($array as $key => $value) {
18
                [$innerKey, $innerValue] = call_user_func($callback, $key, $value);
19
20
                $results[$innerKey] = $innerValue;
21
            }
22
23
            return $results;
24
        }
25
    }
26
27
    if (!function_exists('guarded_auth')) {
28
        /**
29
         * Since version 5.2 Laravel did change the auth model.
30
         * Check if we on the new version.
31
         *
32
         * @return bool
33
         */
34
        function guarded_auth()
35
        {
36
            return version_compare(app()->version(), '5.2') >= 0;
0 ignored issues
show
introduced by
The method version() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

36
            return version_compare(app()->/** @scrutinizer ignore-call */ version(), '5.2') >= 0;
Loading history...
37
        }
38
    }
39
}
40
41
namespace admin\db {
42
43
    use Illuminate\Database\Eloquent\Model;
44
    use Illuminate\Support\Facades\DB;
45
    use Terranet\Translatable\Translatable;
46
47
    if (!function_exists('scheme')) {
48
        function scheme()
49
        {
50
            return app('scaffold.schema');
51
        }
52
    }
53
54
    if (!function_exists('table_columns')) {
55
        function table_columns($model, $withTranslated = true)
56
        {
57
            static $data = [];
58
59
            $table = $model->getTable();
60
61
            if (!array_has($data, $table)) {
62
                $columns = scheme()->columns($table);
63
64
                if ($withTranslated && $model instanceof Translatable && method_exists($model, 'getTranslationModel')) {
65
                    $related = $model->getTranslationModel()->getTable();
66
                    $columns = array_merge(
67
                        $columns,
68
                        array_except(
69
                            scheme()->columns($related),
70
                            array_keys($columns)
71
                        )
72
                    );
73
                }
74
75
                array_set($data, $table, $columns);
76
            }
77
78
            return array_get($data, $table, []);
79
        }
80
    }
81
82
    if (!function_exists('table_indexes')) {
83
        function table_indexes(Model $model, $withTranslated = true)
84
        {
85
            $indexes = scheme()->indexedColumns($model->getTable());
86
87
            if ($withTranslated && $model instanceof Translatable && method_exists($model, 'getTranslationModel')) {
88
                $indexes = array_unique(array_merge(
89
                    $indexes,
90
                    scheme()->indexedColumns($model->getTranslationModel()->getTable())
91
                ));
92
            }
93
94
            return $indexes;
95
        }
96
    }
97
98
    if (!function_exists('connection')) {
99
        /**
100
         * Check if we are on desired connection or get the current connection name.
101
         *
102
         * @param string $name
103
         *
104
         * @return mixed string|boolean
105
         */
106
        function connection($name = null)
107
        {
108
            if (null === $name) {
109
                return DB::connection()->getName();
110
            }
111
112
            return strtolower($name) === strtolower(DB::connection()->getName());
113
        }
114
    }
115
116
    if (!function_exists('enum_values')) {
117
        function enum_values($table, $column)
118
        {
119
            $columns = DB::select("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
120
            $values = [];
121
            if (preg_match('/^enum\((.*)\)$/', $columns[0]->Type, $matches)) {
122
                foreach (explode(',', $matches[1]) as $value) {
123
                    $value = trim($value, "'");
124
                    $values[$value] = title_case($value);
125
                }
126
            }
127
128
            return $values;
129
        }
130
131
        /**
132
         * @param $values
133
         * @param $column
134
         * @return array
135
         */
136
        function translated_values($values, $namespace, $column)
137
        {
138
            $translator = app('translator');
139
140
            foreach ($values as $value => &$label) {
141
                $trKey = "administrator::enums.{$namespace}.{$column}.{$value}";
142
                if ($translator->has($trKey)) {
143
                    $label = $translator->trans($trKey);
144
                } else if ($translator->has($trKey = "administrator::enums.global.{$column}.{$value}")) {
145
                    $label = $translator->trans($trKey);
146
                }
147
            }
148
149
            return $values;
150
        }
151
    }
152
}
153
154
namespace admin\helpers {
155
156
    use Coduo\PHPHumanizer\StringHumanizer;
157
    use Czim\Paperclip\Contracts\AttachableInterface;
158
    use Illuminate\Database\Eloquent\Model;
159
    use Illuminate\Support\Facades\Request;
160
    use Illuminate\Support\Facades\Route;
161
    use Terranet\Administrator\Contracts\Form\HiddenElement;
162
    use Terranet\Administrator\Contracts\Module\Exportable;
163
    use Terranet\Presentable\PresentableInterface;
164
    use Terranet\Translatable\Translatable;
165
166
    if (!function_exists('html_list')) {
167
        /**
168
         * Fetch key => value pairs from an Eloquent model.
169
         *
170
         * @param mixed $model
171
         * @param string $labelAttribute
172
         * @param string $keyAttribute
173
         *
174
         * @return array
175
         */
176
        function html_list($model, $labelAttribute = 'name', $keyAttribute = 'id')
177
        {
178
            if (is_string($model)) {
179
                $model = new $model();
180
            }
181
182
            return $model->pluck($labelAttribute, $keyAttribute)->toArray();
183
        }
184
    }
185
186
    if (!function_exists('qsRoute')) {
187
        /**
188
         * Generate route with query string.
189
         *
190
         * @param       $route
191
         * @param array $params
192
         *
193
         * @return string
194
         */
195
        function qsRoute($route = null, array $params = [])
196
        {
197
            $requestParams = Request::all();
198
199
            if (!$route) {
200
                $current = Route::current();
201
                $requestParams += $current->parameters();
202
                $route = $current->getName();
203
            }
204
205
            $params = array_merge($requestParams, $params);
206
207
            return route($route, $params);
208
        }
209
    }
210
211
    if (!function_exists('html_attributes')) {
212
        function html_attributes(array $attributes = [])
213
        {
214
            $out = [];
215
            foreach ($attributes as $key => $value) {
216
                // transform
217
                if (is_bool($value)) {
218
                    $out[] = "{$key}=\"{$key}\"";
219
                } else {
220
                    if (is_numeric($key)) {
221
                        $out[] = "{$value}=\"{$value}\"";
222
                    } else {
223
                        $value = htmlspecialchars($value);
224
                        $out[] = "{$key}=\"{$value}\"";
225
                    }
226
                }
227
            }
228
229
            return implode(' ', $out);
230
        }
231
    }
232
233
    if (!function_exists('auto_p')) {
234
        function auto_p($value, $lineBreaks = true)
235
        {
236
            if ('' === trim($value)) {
237
                return '';
238
            }
239
240
            $value = $value."\n"; // just to make things a little easier, pad the end
241
            $value = preg_replace('|<br />\s*<br />|', "\n\n", $value);
242
243
            // Space things out a little
244
            $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
245
            $value = preg_replace('!(<'.$allblocks.'[^>]*>)!', "\n$1", $value);
246
            $value = preg_replace('!(</'.$allblocks.'>)!', "$1\n\n", $value);
247
            $value = str_replace(["\r\n", "\r"], "\n", $value); // cross-platform newlines
248
249
            if (false !== strpos($value, '<object')) {
250
                $value = preg_replace('|\s*<param([^>]*)>\s*|', '<param$1>', $value); // no pee inside object/embed
251
                $value = preg_replace('|\s*</embed>\s*|', '</embed>', $value);
252
            }
253
254
            $value = preg_replace("/\n\n+/", "\n\n", $value); // take care of duplicates
255
256
            // make paragraphs, including one at the end
257
            $values = preg_split('/\n\s*\n/', $value, -1, PREG_SPLIT_NO_EMPTY);
258
            $value = '';
259
260
            foreach ($values as $tinkle) {
261
                $value .= '<p>'.trim($tinkle, "\n")."</p>\n";
262
            }
263
264
            // under certain strange conditions it could create a P of entirely whitespace
265
            $value = preg_replace('|<p>\s*</p>|', '', $value);
266
            $value = preg_replace('!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $value);
267
            $value = preg_replace('!<p>\s*(</?'.$allblocks.'[^>]*>)\s*</p>!', '$1', $value); // don't pee all over a tag
268
            $value = preg_replace('|<p>(<li.+?)</p>|', '$1', $value); // problem with nested lists
269
            $value = preg_replace('|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $value);
270
            $value = str_replace('</blockquote></p>', '</p></blockquote>', $value);
271
            $value = preg_replace('!<p>\s*(</?'.$allblocks.'[^>]*>)!', '$1', $value);
272
            $value = preg_replace('!(</?'.$allblocks.'[^>]*>)\s*</p>!', '$1', $value);
273
274
            if ($lineBreaks) {
275
                $value = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '\admin\helpers\autop_newline_preservation_helper', $value);
276
                $value = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $value); // optionally make line breaks
277
                $value = str_replace('<WPPreserveNewline />', "\n", $value);
278
            }
279
280
            $value = preg_replace('!(</?'.$allblocks.'[^>]*>)\s*<br />!', '$1', $value);
281
            $value = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $value);
282
283
            if (false !== strpos($value, '<pre')) {
284
                $value = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', '\admin\helpers\clean_pre', $value);
285
            }
286
            $value = preg_replace("|\n</p>$|", '</p>', $value);
287
288
            return $value;
289
        }
290
291
        /**
292
         * Accepts matches array from preg_replace_callback in wpautop() or a string.
293
         * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
294
         * converted into paragraphs or line-breaks.
295
         *
296
         * @param array|string $matches The array or string
297
         *
298
         * @return string the pre block without paragraph/line-break conversion
299
         */
300
        function clean_pre($matches)
301
        {
302
            if (is_array($matches)) {
303
                $text = $matches[1].$matches[2].'</pre>';
304
            } else {
305
                $text = $matches;
306
            }
307
308
            $text = str_replace(['<br />', '<br/>', '<br>'], ['', '', ''], $text);
309
            $text = str_replace('<p>', "\n", $text);
310
            $text = str_replace('</p>', '', $text);
311
312
            return $text;
313
        }
314
315
        /**
316
         * Newline preservation help function for wpautop.
317
         *
318
         * @since  3.1.0
319
         *
320
         * @param array $matches preg_replace_callback matches array
321
         * @returns string
322
         *
323
         * @return mixed
324
         */
325
        function autop_newline_preservation_helper($matches)
326
        {
327
            return str_replace("\n", '<PreserveNewline />', $matches[0]);
328
        }
329
    }
330
331
    if (!function_exists('hidden_element')) {
332
        function hidden_element($element)
333
        {
334
            return $element instanceof HiddenElement;
335
        }
336
    }
337
338
    if (!function_exists('exportable')) {
339
        function exportable($module)
340
        {
341
            return $module instanceof Exportable;
342
        }
343
    }
344
345
    if (!function_exists('eloquent_attributes')) {
346
        function eloquent_attributes(Model $model)
347
        {
348
            $fillable = $model->getFillable();
349
350
            if (!empty($key = $model->getKeyName())) {
351
                array_unshift($fillable, $key);
352
            }
353
354
            if ($model instanceof Translatable && method_exists($model, 'getTranslatedAttributes')) {
355
                $fillable = array_merge($fillable, $model->getTranslatedAttributes());
0 ignored issues
show
Bug introduced by
It seems like $model->getTranslatedAttributes() can also be of type Illuminate\Database\Eloquent\Builder; however, parameter $array2 of array_merge() does only seem to accept null|array, maybe add an additional type check? ( Ignorable by Annotation )

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

355
                $fillable = array_merge($fillable, /** @scrutinizer ignore-type */ $model->getTranslatedAttributes());
Loading history...
356
            }
357
358
            $fillable = array_merge($fillable, $model->getDates());
359
360
            $fillable = array_filter($fillable, function ($element) use ($model) {
361
                return !in_array($element, $model->getHidden(), true);
362
            });
363
364
            $data = $model->toArray();
365
366
            $out = [];
367
            foreach ($fillable as $column) {
368
                $out[$column] = array_get($data, $column);
369
            }
370
371
            return $out;
372
        }
373
    }
374
375
    if (!function_exists('eloquent_attribute')) {
376
        function eloquent_attribute(Model $object, $key)
377
        {
378
            if ($object instanceof AttachableInterface && array_key_exists($key, $object->getAttachedFiles())) {
0 ignored issues
show
Bug introduced by
It seems like $object->getAttachedFiles() can also be of type Illuminate\Database\Eloquent\Builder and mixed; however, parameter $search of array_key_exists() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

378
            if ($object instanceof AttachableInterface && array_key_exists($key, /** @scrutinizer ignore-type */ $object->getAttachedFiles())) {
Loading history...
379
                return \admin\output\staplerImage($object->getAttribute($key));
380
            }
381
382
            $value = present($object, $key);
383
384
            if (is_array($value)) {
385
                return !empty($value)
386
                    ? highlight_string(json_encode($value, JSON_PRETTY_PRINT))
387
                    : null;
388
            }
389
390
            return $value;
391
        }
392
393
        function present(Model $object, $key, $value = null)
394
        {
395
            $value = $value ?: $object->getAttribute($key);
396
397
            if ($object instanceof PresentableInterface) {
398
                if ($adminKey = has_admin_presenter($object, $key)) {
399
                    return $object->present()->$adminKey($value);
400
                }
401
402
                if ($frontKey = has_presenter($object, $key)) {
403
                    return $object->present()->$frontKey($value);
404
                }
405
            }
406
407
            return $value;
408
        }
409
410
        function has_admin_presenter(PresentableInterface $object, $key)
411
        {
412
            return method_exists($object->present(), $adminKey = camel_case("admin_{$key}"))
413
                ? $adminKey
414
                : null;
415
        }
416
417
        function has_presenter(PresentableInterface $object, $key)
418
        {
419
            return method_exists($object->present(), $frontKey = camel_case($key))
420
                ? $frontKey
421
                : null;
422
        }
423
    }
424
425
    if (!function_exists('str_humanize')) {
426
        function str_humanize($key)
427
        {
428
            return StringHumanizer::humanize($key);
429
        }
430
    }
431
}
432
433
namespace admin\output {
434
435
    use Closure;
436
437
    function boolean($value)
438
    {
439
        return $value ? '<i class="fa fa-fw fa-check"></i>' : '';
440
    }
441
442
    function rank($name, $value, $key)
443
    {
444
        return '<input type="number" style="width: 50px;" value="'.$value.'" name="'.$name.'['.$key.']" />';
445
    }
446
447
    /**
448
     * @param       $image
449
     * @param array $attributes
450
     *
451
     * @return string
452
     */
453
    function image($image, array $attributes = [])
454
    {
455
        $attributes = \admin\helpers\html_attributes($attributes);
456
457
        return $image ? '<img src="'.$image.'" '.$attributes.' />' : '';
458
    }
459
460
    /**
461
     * Output image from Paperclip attachment object.
462
     *
463
     * @param null $attachment
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $attachment is correct as it would always require null to be passed?
Loading history...
464
     * @param null $style
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $style is correct as it would always require null to be passed?
Loading history...
465
     * @param array $attributes
466
     *
467
     * @return null|string
468
     */
469
    function staplerImage($attachment = null, $style = null, $attributes = [])
470
    {
471
        if ($attachment && $attachment->originalFilename()) {
472
            $styles = $attachment->variants();
473
474
            if (count($styles)) {
475
                $firstStyle = $style ?: head($styles);
476
                $origStyle = 'original';
477
478
                // in case then style dimensions are less than predefined, adjust width & height to style's
479
                $aWidth = (int) array_get($attributes, 'width');
480
                $aHeight = (int) array_get($attributes, 'height');
481
482
                if (($aWidth || $aHeight) && $firstStyle) {
483
                    $size = array_filter($styles, function ($style) use ($firstStyle) {
484
                        return $style === $firstStyle;
485
                    });
486
487
                    if (($size = array_shift($size))) {
488
                        $dimensions = array_get($attachment->getConfig(), "variants.{$size}");
489
490
                        if (is_array($dimensions)) {
491
                            $dimensions = array_get($dimensions, 'resize.dimensions');
492
                        }
493
494
                        if ($dimensions && str_contains($dimensions, 'x')) {
495
                            [$width, $height] = explode('x', $dimensions);
496
497
                            if ($aWidth > $width) {
498
                                $attributes['width'] = $width;
499
                            }
500
501
                            if ($aHeight > $height) {
502
                                $attributes['height'] = $height;
503
                            }
504
                        }
505
                    }
506
                }
507
508
                return
509
                    '<a class="fancybox" href="'.url($attachment->url($origStyle)).'">'.
0 ignored issues
show
Bug introduced by
Are you sure url($attachment->url($origStyle)) of type string|Illuminate\Contracts\Routing\UrlGenerator can be used in concatenation? ( Ignorable by Annotation )

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

509
                    '<a class="fancybox" href="'./** @scrutinizer ignore-type */ url($attachment->url($origStyle)).'">'.
Loading history...
510
                    \admin\output\image($attachment->url($firstStyle), $attributes).
511
                    '</a>';
512
            }
513
514
            return link_to($attachment->url(), '<i class="fa fa-cloud-download"></i>', [], false, false);
515
        }
516
517
        return null;
518
    }
519
520
    function _prepare_collection($items, Closure $callback = null)
521
    {
522
        if (is_object($items) && method_exists($items, 'toArray')) {
523
            $items = $items->toArray();
524
        }
525
526
        if (empty($items)) {
527
            return '';
528
        }
529
530
        if ($callback) {
531
            array_walk($items, $callback);
532
        }
533
534
        return $items;
535
    }
536
537
    /**
538
     * @param array $items
539
     * @param null|Closure $callback
540
     * @param array $attributes
541
     *
542
     * @return string
543
     */
544
    function ul($items = [], Closure $callback = null, array $attributes = [])
545
    {
546
        $items = _prepare_collection($items, $callback);
547
548
        return '<ul '.\admin\helpers\html_attributes($attributes).'>'.'<li>'.implode('</li><li>', $items).'</li>'.'</ul>';
0 ignored issues
show
Bug introduced by
It seems like $items can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

548
        return '<ul '.\admin\helpers\html_attributes($attributes).'>'.'<li>'.implode('</li><li>', /** @scrutinizer ignore-type */ $items).'</li>'.'</ul>';
Loading history...
549
    }
550
551
    /**
552
     * @param array $items
553
     * @param null|Closure $callback
554
     * @param array $attributes
555
     *
556
     * @return string
557
     */
558
    function ol($items = [], Closure $callback = null, array $attributes = [])
559
    {
560
        $items = _prepare_collection($items, $callback);
561
562
        return '<ol '.\admin\helpers\html_attributes($attributes).'>'.'<li>'.implode('</li><li>', $items).'</li>'.'</ol>';
0 ignored issues
show
Bug introduced by
It seems like $items can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

562
        return '<ol '.\admin\helpers\html_attributes($attributes).'>'.'<li>'.implode('</li><li>', /** @scrutinizer ignore-type */ $items).'</li>'.'</ol>';
Loading history...
563
    }
564
565
    function label($label = '', $class = 'label-success')
566
    {
567
        return '<span class="label '.$class.'">'.$label.'</span>';
568
    }
569
570
    function badge($label = '', $class = 'bg-green')
571
    {
572
        return '<span class="badge '.$class.'">'.$label.'</span>';
573
    }
574
}
575