Passed
Push — main ( 1a8771...d7bb24 )
by Andrey
11:52 queued 10:31
created

Sorter::specialChars()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Helldar\Support\Tools;
4
5
use Helldar\Support\Facades\Helpers\Str;
6
7
final class Sorter
8
{
9
    protected $special_chars = [
10
        ' ',
11
        '*',
12
        '-',
13
        '_',
14
        '=',
15
        '\\',
16
        '/',
17
        '|',
18
        '~',
19
        '`',
20
        '+',
21
        ':',
22
        ';',
23
        '@',
24
        '#',
25
        '$',
26
        '%',
27
        '^',
28
        '&',
29
        '?',
30
        '!',
31
        '(',
32
        ')',
33
        '{',
34
        '}',
35
        '[',
36
        ']',
37
        '§',
38
        '№',
39
        '<',
40
        '>',
41
        '.',
42
        ',',
43
    ];
44
45
    /**
46
     * Gets an array of special characters.
47
     *
48
     * @return string[]
49
     */
50 12
    public function specialChars(): array
51
    {
52 12
        return $this->special_chars;
53
    }
54
55
    /**
56
     * Gets a callback function for sorting.
57
     *
58
     * @return callable
59
     */
60 14
    public function defaultCallback(): callable
61
    {
62 14
        return function ($current, $next) {
63 14
            $current = $this->lower($current);
64 14
            $next    = $this->lower($next);
65
66 14
            if ($current === $next) {
67 2
                return 0;
68
            }
69
70 14
            if (is_string($current) && is_numeric($next)) {
71 8
                return $this->hasSpecialChar($current) ? -1 : 1;
72
            }
73
74 14
            if (is_numeric($current) && is_string($next)) {
75 6
                return $this->hasSpecialChar($next) ? 1 : -1;
76
            }
77
78 14
            return $current < $next ? -1 : 1;
79 14
        };
80
    }
81
82
    /**
83
     * Prepares a value for case-insensitive sorting.
84
     *
85
     * @param $value
86
     *
87
     * @return mixed|string|null
88
     */
89 14
    protected function lower($value)
90
    {
91 14
        return is_string($value) ? Str::lower($value) : $value;
92
    }
93
94
    /**
95
     * Determine if a value is a special character.
96
     *
97
     * @param $value
98
     *
99
     * @return bool
100
     */
101 8
    protected function hasSpecialChar($value): bool
102
    {
103 8
        return in_array($value, $this->specialChars());
104
    }
105
}
106