Passed
Pull Request — main (#92)
by Andrey
15:13
created

Sorter::lower()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
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
    public function specialChars(): array
51
    {
52
        return $this->special_chars;
53
    }
54
55
    /**
56
     * Gets a callback function for sorting.
57
     *
58
     * @return callable
59
     */
60
    public function defaultCallback(): callable
61
    {
62
        return function ($current, $next) {
63
            $current = $this->lower($current);
64
            $next    = $this->lower($next);
65
66
            if ($current === $next) {
67
                return 0;
68
            }
69
70
            if (is_string($current) && is_numeric($next)) {
71
                return $this->hasSpecialChar($current) ? -1 : 1;
72
            }
73
74
            if (is_numeric($current) && is_string($next)) {
75
                return $this->hasSpecialChar($next) ? 1 : -1;
76
            }
77
78
            return $current < $next ? -1 : 1;
79
        };
80
    }
81
82
    /**
83
     * Prepares a value for case-insensitive sorting.
84
     *
85
     * @param $value
86
     *
87
     * @return mixed|string|null
88
     */
89
    protected function lower($value)
90
    {
91
        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
    protected function hasSpecialChar($value): bool
102
    {
103
        return in_array($value, $this->specialChars());
104
    }
105
}
106