Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
Filename
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
1 / 1
 compose
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3/**
4 * Composes attachment filenames from an original name and an optional custom base name.
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public License,
7 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
8 * obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * @package   phpMyFAQ
11 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
12 * @copyright 2026 phpMyFAQ Team
13 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
14 * @link      https://www.phpmyfaq.de
15 * @since     2026-06-22
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Attachment;
21
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}