Lines 100.00% 8 / 8
Methods 100.00% 1 / 1
Classes 100.00% 1 / 1
Covered by tests of size
Name Lines Methods CRAP
 compose 100.00% 8 / 8 100.00% 1 / 1 4
22final class Filename
23{
24    /**
25     * Builds the filename to store for an uploaded attachment.
26     *
27     * When no custom name is given (null or whitespace-only), the original name
28     * is kept unchanged. Otherwise the custom name is reduced to a safe base name
29     * and the original extension is always re-applied so the file ending never
30     * changes.
31     *
32     * Following PHP's pathinfo() semantics, a leading dot in the original name is NOT
33     * treated as solely a name prefix: ".htaccess" yields extension "htaccess", so
34     * a custom name will be returned with that extension appended.
35     */
36    public static function compose(string $originalName, ?string $customName): string
37    {
38        $customName = trim($customName ?? '');
39        if ($customName === '') {
40            return $originalName;
41        }
42
43        $base = pathinfo(basename($customName), PATHINFO_FILENAME);
44        if ($base === '') {
45            return $originalName;
46        }
47
48        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
49
50        return $extension === '' ? $base : $base . '.' . $extension;
51    }
52}