Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
ProvidedDocumentDownload
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
3
100.00% covered (success)
100.00%
1 / 1
 respond
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 sanitiseAttachmentFilename
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace App\Support;
6
7use App\Domain\Document\Provided\Data\ProvidedDocumentData;
8use Psr\Http\Message\ResponseInterface;
9use Psr\Http\Message\StreamInterface;
10
11/**
12 * Shared response builder for streaming an admin-provided document back to the
13 * client as an attachment. Used by both the admin and investor download
14 * actions so the security headers stay identical.
15 *
16 * Files live outside the webroot; Content-Disposition is forced to attachment
17 * and X-Content-Type-Options to nosniff so nothing renders inline.
18 */
19final class ProvidedDocumentDownload
20{
21    public static function respond(
22        ResponseInterface $response,
23        ProvidedDocumentData $document,
24        StreamInterface $stream,
25    ): ResponseInterface {
26        $filename = self::sanitiseAttachmentFilename($document->originalFilename);
27
28        return $response
29            ->withHeader('Content-Type', $document->mimeType)
30            ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
31            ->withHeader('Cache-Control', 'private, no-store')
32            ->withHeader('X-Content-Type-Options', 'nosniff')
33            ->withBody($stream);
34    }
35
36    private static function sanitiseAttachmentFilename(string $name): string
37    {
38        $clean = preg_replace('/[^A-Za-z0-9 ._\-]/', '_', $name) ?? 'document';
39        $clean = trim($clean);
40
41        return $clean === '' ? 'document' : $clean;
42    }
43}