• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

keradus / PHP-CS-Fixer / 19958239208

05 Dec 2025 09:13AM UTC coverage: 93.181% (-1.0%) from 94.158%
19958239208

push

github

keradus
chore: .php-cs-fixer.dist.php - remove no longer needed rule, 'expectedDeprecation' annotation does not exist for long time

28928 of 31045 relevant lines covered (93.18%)

44.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.44
/src/Utils.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <fabien@symfony.com>
9
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14

15
namespace PhpCsFixer;
16

17
use PhpCsFixer\Fixer\FixerInterface;
18
use PhpCsFixer\Tokenizer\Token;
19

20
/**
21
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
22
 * @author Graham Campbell <hello@gjcampbell.co.uk>
23
 * @author Odín del Río <odin.drp@gmail.com>
24
 *
25
 * @internal
26
 *
27
 * @deprecated This is a God Class anti-pattern. Don't expand it. It is fine to use logic that is already here (that's why we don't trigger deprecation warnings), but over time logic should be moved to dedicated, single-responsibility classes.
28
 *
29
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
30
 */
31
final class Utils
32
{
33
    private function __construct()
34
    {
35
        // cannot create instance
36
    }
×
37

38
    /**
39
     * Converts a camel cased string to a snake cased string.
40
     */
41
    public static function camelCaseToUnderscore(string $string): string
42
    {
43
        return mb_strtolower(
13✔
44
            Preg::replace(
13✔
45
                '/(?<!^)(?<!_)((?=[\p{Lu}][^\p{Lu}])|(?<![\p{Lu}])(?=[\p{Lu}]))/',
13✔
46
                '_',
13✔
47
                $string
13✔
48
            )
13✔
49
        );
13✔
50
    }
51

52
    /**
53
     * Calculate the trailing whitespace.
54
     *
55
     * What we're doing here is grabbing everything after the final newline.
56
     */
57
    public static function calculateTrailingWhitespaceIndent(Token $token): string
58
    {
59
        if (!$token->isWhitespace()) {
7✔
60
            throw new \InvalidArgumentException(\sprintf('The given token must be whitespace, got "%s".', $token->getName()));
1✔
61
        }
62

63
        $str = strrchr(
6✔
64
            str_replace(["\r\n", "\r"], "\n", $token->getContent()),
6✔
65
            "\n"
6✔
66
        );
6✔
67

68
        if (false === $str) {
6✔
69
            return '';
1✔
70
        }
71

72
        return ltrim($str, "\n");
5✔
73
    }
74

75
    /**
76
     * Perform stable sorting using provided comparison function.
77
     *
78
     * Stability is ensured by using Schwartzian transform.
79
     *
80
     * @template T
81
     * @template L of list<T>
82
     * @template R
83
     *
84
     * @param L                   $elements
85
     * @param callable(T): R      $getComparedValue a callable that takes a single element and returns the value to compare
86
     * @param callable(R, R): int $compareValues    a callable that compares two values
87
     *
88
     * @return L
89
     */
90
    public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues): array
91
    {
92
        $sortItems = [];
5✔
93
        foreach ($elements as $index => $element) {
5✔
94
            $sortItems[] = [$element, $index, $getComparedValue($element)];
5✔
95
        }
96

97
        usort($sortItems, static function ($a, $b) use ($compareValues): int {
5✔
98
            $comparison = $compareValues($a[2], $b[2]);
5✔
99

100
            if (0 !== $comparison) {
5✔
101
                return $comparison;
3✔
102
            }
103

104
            return $a[1] <=> $b[1];
3✔
105
        });
5✔
106

107
        return array_map(static fn (array $item) => $item[0], $sortItems); // @phpstan-ignore return.type (PHPStan cannot understand that the result will still be L template)
5✔
108
    }
109

110
    /**
111
     * Sort fixers by their priorities.
112
     *
113
     * @template T of list<FixerInterface>
114
     *
115
     * @param T $fixers
116
     *
117
     * @return T
118
     */
119
    public static function sortFixers(array $fixers): array
120
    {
121
        // Schwartzian transform is used to improve the efficiency and avoid
122
        // `usort(): Array was modified by the user comparison function` warning for mocked objects.
123
        return self::stableSort(
1✔
124
            $fixers,
1✔
125
            static fn (FixerInterface $fixer): int => $fixer->getPriority(),
1✔
126
            static fn (int $a, int $b): int => $b <=> $a
1✔
127
        );
1✔
128
    }
129

130
    /**
131
     * Join names in natural language using specified wrapper (double quote by default).
132
     *
133
     * @param list<string> $names
134
     *
135
     * @throws \InvalidArgumentException
136
     */
137
    public static function naturalLanguageJoin(array $names, string $wrapper = '"', string $lastJoin = 'and'): string
138
    {
139
        if (0 === \count($names)) {
24✔
140
            throw new \InvalidArgumentException('Array of names cannot be empty.');
2✔
141
        }
142

143
        if (\strlen($wrapper) > 1) {
22✔
144
            throw new \InvalidArgumentException('Wrapper should be a single-char string or empty.');
1✔
145
        }
146

147
        $names = array_map(static fn (string $name): string => \sprintf('%2$s%1$s%2$s', $name, $wrapper), $names);
21✔
148

149
        $last = array_pop($names);
21✔
150

151
        if (\count($names) > 0) {
21✔
152
            return implode(', ', $names).' '.$lastJoin.' '.$last;
14✔
153
        }
154

155
        return $last;
7✔
156
    }
157

158
    /**
159
     * Join names in natural language wrapped in backticks, e.g. `a`, `b` and `c`.
160
     *
161
     * @param list<string> $names
162
     *
163
     * @throws \InvalidArgumentException
164
     */
165
    public static function naturalLanguageJoinWithBackticks(array $names, string $lastJoin = 'and'): string
166
    {
167
        return self::naturalLanguageJoin($names, '`', $lastJoin);
7✔
168
    }
169

170
    public static function convertArrayTypeToList(string $type): string
171
    {
172
        $parts = explode('[]', $type);
×
173
        $count = \count($parts) - 1;
×
174

175
        return str_repeat('list<', $count).$parts[0].str_repeat('>', $count);
×
176
    }
177

178
    /**
179
     * @param mixed $value
180
     */
181
    public static function toString($value): string
182
    {
183
        return \is_array($value)
11✔
184
            ? self::arrayToString($value)
6✔
185
            : self::scalarToString($value);
11✔
186
    }
187

188
    /**
189
     * @param mixed $value
190
     */
191
    private static function scalarToString($value): string
192
    {
193
        $str = var_export($value, true);
10✔
194

195
        return Preg::replace('/\bNULL\b/', 'null', $str);
10✔
196
    }
197

198
    /**
199
     * @param array<array-key, mixed> $value
200
     */
201
    private static function arrayToString(array $value): string
202
    {
203
        if (0 === \count($value)) {
6✔
204
            return '[]';
1✔
205
        }
206

207
        $isHash = !array_is_list($value);
5✔
208
        $str = '[';
5✔
209

210
        foreach ($value as $k => $v) {
5✔
211
            if ($isHash) {
5✔
212
                $str .= self::scalarToString($k).' => ';
2✔
213
            }
214

215
            $str .= \is_array($v)
5✔
216
                ? self::arrayToString($v).', '
2✔
217
                : self::scalarToString($v).', ';
5✔
218
        }
219

220
        return substr($str, 0, -2).']';
5✔
221
    }
222
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc