Passed
Push — main ( 35cea8...263c2f )
by Andrey
21:51 queued 20:06
created

Sorter::default()   B

Complexity

Conditions 9
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 11
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 9
rs 8.0555
1
<?php
2
3
namespace Helldar\Support\Callbacks;
4
5
use Helldar\Support\Facades\Helpers\Str;
6
7
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
    /**
47
     * Gets an array of special characters.
48
     *
49
     * @return string[]
50
     */
51 16
    public function specialChars(): array
52
    {
53 16
        return $this->special_chars;
54
    }
55
56
    /**
57
     * Gets a callback function for sorting.
58
     *
59
     * @return callable
60
     */
61 18
    public function default(): callable
62
    {
63 18
        return function ($current, $next) {
64 18
            $current = $this->lower($current);
65 18
            $next    = $this->lower($next);
66
67 18
            if ($current === $next) {
68 2
                return 0;
69
            }
70
71 18
            if (is_string($current) && is_numeric($next)) {
72 12
                return $this->hasSpecialChar($current) ? -1 : 1;
73
            }
74
75 18
            if (is_numeric($current) && is_string($next)) {
76 12
                return $this->hasSpecialChar($next) ? 1 : -1;
77
            }
78
79 18
            return $current < $next ? -1 : 1;
80 18
        };
81
    }
82
83
    /**
84
     * Prepares a value for case-insensitive sorting.
85
     *
86
     * @param $value
87
     *
88
     * @return mixed|string|null
89
     */
90 18
    protected function lower($value)
91
    {
92 18
        return is_string($value) ? Str::lower($value) : $value;
93
    }
94
95
    /**
96
     * Determine if a value is a special character.
97
     *
98
     * @param $value
99
     *
100
     * @return bool
101
     */
102 12
    protected function hasSpecialChar($value): bool
103
    {
104 12
        return in_array($value, $this->specialChars());
105
    }
106
}
107