Lines 93.75% 15 / 16
Functions and Methods 83.33% 5 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Identifier 93.75% 15 / 16 83.33% 5 / 6 12.04 0.00% 0 / 1
 __construct 0.00% 0 / 1 0.00% 0 / 1 2
 convertToCamelCase 100.00% 6 / 6 100.00% 1 / 1 3
 startsWithLetter 100.00% 2 / 2 100.00% 1 / 1 2
 convertToPascalCase 100.00% 4 / 4 100.00% 1 / 1 3
 splitIntoAsciiWords 100.00% 2 / 2 100.00% 1 / 1 2
 capitalizeWord 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Codegen\Php;
6
7use function Symfony\Component\String\u;
8
9final class Identifier
10{
11    private function __construct() {}
12
13    public static function convertToCamelCase(string $raw): string
14    {
15        $words = self::splitIntoAsciiWords($raw);
16
17        if ($words === []) {
18            return '_';
19        }
20
21        $first = array_shift($words);
22        $name = strtolower($first) . implode('', array_map(self::capitalizeWord(...), $words));
23
24        return ctype_digit($name[0]) ? '_' . $name : $name;
25    }
26
27    public static function startsWithLetter(string $raw): bool
28    {
29        $words = self::splitIntoAsciiWords($raw);
30
31        return $words !== [] && ctype_alpha($words[0][0]);
32    }
33
34    public static function convertToPascalCase(string $raw): string
35    {
36        $name = implode('', array_map(self::capitalizeWord(...), self::splitIntoAsciiWords($raw)));
37
38        if ($name === '') {
39            return '_';
40        }
41
42        return ctype_digit($name[0]) ? '_' . $name : $name;
43    }
44
45    /** @return list<string> */
46    private static function splitIntoAsciiWords(string $raw): array
47    {
48        $split = preg_split('/[^A-Za-z0-9]+/', u($raw)->ascii()->toString(), -1, \PREG_SPLIT_NO_EMPTY);
49
50        return $split === false ? [] : $split;
51    }
52
53    private static function capitalizeWord(string $word): string
54    {
55        return ucfirst(strtolower($word));
56    }
57}