Skip to content

Internals Vfs Storage Storage

Stefan Crkvenjakov edited this page Oct 7, 2026 · 1 revision

vfs\storage\Storage

Framework Internals · Subsystem overview · Developer guide

Source: awt_src/classes/vfs/storage/Storage.php · Snapshot 8411f4287706.

VFS includes package resource lookup, database-backed file metadata, filesystem collaborators, transient pools and persistent PHP-array caches.

Imports and dependencies

use vfs\storage\enums\EOwnerType;
use vfs\storage\interfaces\IFileSystemService;
use vfs\storage\interfaces\IStorageFacade;
use vfs\storage\interfaces\IStorageManager;
use vfs\storage\services\LocalFileSystemService;
use vfs\storage\strategies\PackageOwnerStorageStrategy;

Storage

Declaration and architectural role

class Storage implements IStorageFacade

Source description (behavioral corrections are recorded in Known discrepancies):

Class Storage

Self-wiring facade for all storage operations (upload, multi-upload, download).

By default the class builds and wires its own dependency graph, so callers need only supply a base path:

$storage = new Storage('/var/www/storage/'); $storage->upload($_FILES['file'], EOwnerType::PACKAGE, ownerId: 1);

Every dependency can be overridden via constructor parameters for testing or alternative implementations — no manual wiring required in production.

Constants, enum cases, traits and properties

Declarations below preserve visibility, type, default and modifiers exactly. A typed property without an initializer remains uninitialized until its constructor or another method assigns it. Mutable fields belong to this instance unless marked static; readonly fields can be initialized once. Constructor-promoted properties are also listed below.

Member Declaration Purpose or source contract
const STAGING_DIR private const STAGING_DIR = 'staging' . DIRECTORY_SEPARATOR; State or definition consumed by the methods below; reads and writes are preserved in their implementation traces.
$manager private IStorageManager $manager; Used by __construct(), upload(), download().
$fileSystem private IFileSystemService $fileSystem; Used by __construct(), upload(), download(), buildDefaultManager(), stageUploadedFile(), buildEntry(), sendDownloadHeaders().
Constructor-promoted private readonly string $basePath = DATA . 'storage' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR Initialized from the constructor argument; default expression is evaluated when the argument is omitted.

Method index

Method Signature
__construct public function __construct( private readonly string $basePath = DATA . 'storage' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR, ?IStorageManager $manager = null, ?IFileSystemService $fileSystem = null )
upload public function upload( array $file, EOwnerType $ownerType, ?int $ownerId = null, ?string $ownerName = null, ?string $middleware = null ): StorageEntry
uploadMultiple public function uploadMultiple( array $files, EOwnerType $ownerType, ?int $ownerId = null, ?string $ownerName = null, ?string $middleware = null ): array
download public function download(int $id, string $disposition = 'attachment'): void
normaliseMultiFileArray public function normaliseMultiFileArray(array $filesEntry): array
buildDefaultManager private function buildDefaultManager(): StorageManager
assertValidFileArray private function assertValidFileArray(array $file): void
stageUploadedFile private function stageUploadedFile(array $file): string
buildEntry private function buildEntry( string $originalName, string $stagedPath, EOwnerType $ownerType, ?int $ownerId, ?string $middleware ): StorageEntry
sendDownloadHeaders private function sendDownloadHeaders(StorageEntry $entry, string $disposition): void

__construct

Source line 38

public function __construct(
        private readonly string $basePath    = DATA . 'storage' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR,
        ?IStorageManager        $manager     = null,
        ?IFileSystemService     $fileSystem  = null
    )

Parameters

Parameter Type, modifiers and default Purpose
$basePath private readonly string $basePath = DATA . 'storage' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR Absolute path to the storage root.
$manager ?IStorageManager $manager = null Override for testing / custom implementations.
$fileSystem ?IFileSystemService $fileSystem = null Override for testing / custom implementations.

@param string $basePath Absolute path to the storage root. @param IStorageManager|null $manager Override for testing / custom implementations. @param IFileSystemService|null $fileSystem Override for testing / custom implementations.

State writes: $this->fileSystem, $this->manager.

Implementation, validation guards and interaction order
/**
     * @param string                  $basePath    Absolute path to the storage root.
     * @param IStorageManager|null    $manager     Override for testing / custom implementations.
     * @param IFileSystemService|null $fileSystem  Override for testing / custom implementations.
     */
    public function __construct(
        private readonly string $basePath    = DATA . 'storage' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR,
        ?IStorageManager        $manager     = null,
        ?IFileSystemService     $fileSystem  = null
    ) {
        $this->fileSystem = $fileSystem ?? new LocalFileSystemService();
        $this->manager    = $manager    ?? $this->buildDefaultManager();
    }

upload

Source line 51

public function upload(
        array      $file,
        EOwnerType $ownerType,
        ?int       $ownerId    = null,
        ?string    $ownerName  = null,
        ?string    $middleware = null
    ): StorageEntry

Parameters

Parameter Type, modifiers and default Purpose
$file array $file Uploaded file array, file object or path according to the declared contract.
$ownerType EOwnerType $ownerType Storage owner category; a matching registered strategy is required for registration.
$ownerId ?int $ownerId = null Owning record ID or null.
$ownerName ?string $ownerName = null Operation input; the exact use, validation and propagation are shown in the implementation trace.
$middleware ?string $middleware = null Middleware object or class name according to the component; route and storage return handling differ.

Return expressions (including local callbacks): $entry.

Explicit exceptions: \RuntimeException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Failure handling catches \Throwable.

Implementation, validation guards and interaction order
// ----------------------------------------------------------------
    // IStorageFacade implementation
    // ----------------------------------------------------------------

    public function upload(
        array      $file,
        EOwnerType $ownerType,
        ?int       $ownerId    = null,
        ?string    $ownerName  = null,
        ?string    $middleware = null
    ): StorageEntry {
        $this->assertValidFileArray($file);

        $stagingPath = $this->stageUploadedFile($file);

        try {
            $entry = $this->buildEntry($file['name'], $stagingPath, $ownerType, $ownerId, $middleware);
            if (!$this->manager->registerLocal($entry, $ownerName)) throw new \RuntimeException('Failed to register uploaded file.');
            return $entry;
        } catch (\Throwable $e) {
            if ($this->fileSystem->exists($stagingPath) && !$this->fileSystem->delete($stagingPath)) {
                throw new \RuntimeException("Could not clean up staged upload: {$stagingPath}", previous: $e);
            }
            throw $e;
        }
    }

uploadMultiple

Source line 74

public function uploadMultiple(
        array      $files,
        EOwnerType $ownerType,
        ?int       $ownerId    = null,
        ?string    $ownerName  = null,
        ?string    $middleware = null
    ): array

Parameters

Parameter Type, modifiers and default Purpose
$files array $files Operation input; the exact use, validation and propagation are shown in the implementation trace.
$ownerType EOwnerType $ownerType Storage owner category; a matching registered strategy is required for registration.
$ownerId ?int $ownerId = null Owning record ID or null.
$ownerName ?string $ownerName = null Operation input; the exact use, validation and propagation are shown in the implementation trace.
$middleware ?string $middleware = null Middleware object or class name according to the component; route and storage return handling differ.

Return expressions (including local callbacks): $entries.

Explicit exceptions: \RuntimeException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Failure handling catches \Throwable.

Implementation, validation guards and interaction order
public function uploadMultiple(
        array      $files,
        EOwnerType $ownerType,
        ?int       $ownerId    = null,
        ?string    $ownerName  = null,
        ?string    $middleware = null
    ): array {
        $entries = [];

        foreach ($files as $index => $file) {
            try {
                $entries[] = $this->upload($file, $ownerType, $ownerId, $ownerName, $middleware);
            } catch (\Throwable $e) {
                $name = is_array($file) && is_string($file['name'] ?? null) ? $file['name'] : 'unknown';
                throw new \RuntimeException(
                    "Failed to upload file at index {$index} ('{$name}'): " . $e->getMessage(),
                    previous: $e
                );
            }
        }

        return $entries;
    }

download

Source line 98

public function download(int $id, string $disposition = 'attachment'): void

Parameters

Parameter Type, modifiers and default Purpose
$id int $id Record or runtime identifier selected by this operation.
$disposition string $disposition = 'attachment' Operation input; the exact use, validation and propagation are shown in the implementation trace.

Explicit exceptions: \RuntimeException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

External effects include readfile, exit.

Implementation, validation guards and interaction order
public function download(int $id, string $disposition = 'attachment'): void
    {
        $entry = $this->manager->get($id);
        StorageAccess::authorize($entry);
        $path  = $entry->getPath();

        if (!$this->fileSystem->exists($path)) {
            throw new \RuntimeException(
                "File not found on disk for storage entry {$id}: {$path}"
            );
        }

        $this->sendDownloadHeaders($entry, $disposition);

        readfile($path);
        exit;
    }

normaliseMultiFileArray

Source line 116

public function normaliseMultiFileArray(array $filesEntry): array

Parameters

Parameter Type, modifiers and default Purpose
$filesEntry array $filesEntry Operation input; the exact use, validation and propagation are shown in the implementation trace.

Return expressions (including local callbacks): $result.

Implementation, validation guards and interaction order
public function normaliseMultiFileArray(array $filesEntry): array
    {
        $keys   = ['name', 'tmp_name', 'error', 'size', 'type'];
        $count  = count($filesEntry['name'] ?? []);
        $result = [];

        for ($i = 0; $i < $count; $i++) {
            $single = [];
            foreach ($keys as $key) {
                $single[$key] = $filesEntry[$key][$i] ?? null;
            }
            $result[] = $single;
        }

        return $result;
    }

buildDefaultManager

Source line 141

private function buildDefaultManager(): StorageManager

Build the default StorageManager with all known strategies pre-registered. Adding a new EOwnerType strategy only requires registering it here (OCP).

Return expressions (including local callbacks): new StorageManager($repository, $this->fileSystem, $strategies).

Implementation, validation guards and interaction order
// ----------------------------------------------------------------
    // Private — dependency construction
    // ----------------------------------------------------------------

    /**
     * Build the default StorageManager with all known strategies pre-registered.
     * Adding a new EOwnerType strategy only requires registering it here (OCP).
     */
    private function buildDefaultManager(): StorageManager
    {
        $repository = new StorageRepository();

        $strategies = [
            new PackageOwnerStorageStrategy($this->fileSystem, $repository, $this->basePath),
            // Register additional strategies here as new EOwnerTypes are introduced:
            // new UserOwnerStorageStrategy($this->fileSystem, $repository, $this->basePath),
            // new SystemOwnerStorageStrategy($this->fileSystem, $repository, $this->basePath),
        ];

        return new StorageManager($repository, $this->fileSystem, $strategies);
    }

assertValidFileArray

Source line 162

private function assertValidFileArray(array $file): void

Parameters

Parameter Type, modifiers and default Purpose
$file array $file Uploaded file array, file object or path according to the declared contract.

@throws \InvalidArgumentException

Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

Implementation, validation guards and interaction order
// ----------------------------------------------------------------
    // Private — upload helpers
    // ----------------------------------------------------------------

    /**
     * @throws \InvalidArgumentException
     */
    private function assertValidFileArray(array $file): void
    {
        foreach (['name', 'tmp_name', 'error', 'size'] as $key) {
            if (!array_key_exists($key, $file)) {
                throw new \InvalidArgumentException("Missing key '{$key}' in file array.");
            }
        }

        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new \InvalidArgumentException(
                "Upload failed for '{$file['name']}' with PHP error code {$file['error']}."
            );
        }

        if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            throw new \InvalidArgumentException(
                "Invalid or missing temp file for '{$file['name']}'."
            );
        }
    }

stageUploadedFile

Source line 188

private function stageUploadedFile(array $file): string

Parameters

Parameter Type, modifiers and default Purpose
$file array $file Uploaded file array, file object or path according to the declared contract.

Move the uploaded temp file to staging and return its new path.

@throws \RuntimeException

Return expressions (including local callbacks): $destination.

Explicit exceptions: \RuntimeException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.

External effects include move_uploaded_file.

Implementation, validation guards and interaction order
/**
     * Move the uploaded temp file to staging and return its new path.
     *
     * @throws \RuntimeException
     */
    private function stageUploadedFile(array $file): string
    {
        $stagingDir = rtrim($this->basePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . self::STAGING_DIR;

        if (!$this->fileSystem->makeDirectory($stagingDir)) throw new \RuntimeException('Could not create upload staging directory.');

        $destination = FileName::unique($stagingDir, $file['name']);

        if (!move_uploaded_file($file['tmp_name'], $destination)) {
            throw new \RuntimeException(
                "Could not move uploaded file '{$file['name']}' to staging directory."
            );
        }

        return $destination;
    }

buildEntry

Source line 205

private function buildEntry(
        string     $originalName,
        string     $stagedPath,
        EOwnerType $ownerType,
        ?int       $ownerId,
        ?string    $middleware
    ): StorageEntry

Parameters

Parameter Type, modifiers and default Purpose
$originalName string $originalName Operation input; the exact use, validation and propagation are shown in the implementation trace.
$stagedPath string $stagedPath Operation input; the exact use, validation and propagation are shown in the implementation trace.
$ownerType EOwnerType $ownerType Storage owner category; a matching registered strategy is required for registration.
$ownerId ?int $ownerId Owning record ID or null.
$middleware ?string $middleware Middleware object or class name according to the component; route and storage return handling differ.

Return expressions (including local callbacks): $entry.

Implementation, validation guards and interaction order
private function buildEntry(
        string     $originalName,
        string     $stagedPath,
        EOwnerType $ownerType,
        ?int       $ownerId,
        ?string    $middleware
    ): StorageEntry {
        $entry = new StorageEntry();

        $entry->setName($originalName)
            ->setPath($stagedPath)
            ->setSize($this->fileSystem->fileSize($stagedPath))
            ->setLastModified($this->fileSystem->lastModified($stagedPath))
            ->setOwnerType($ownerType)
            ->setOwnerId($ownerId)
            ->setMiddleware($middleware);

        return $entry;
    }

sendDownloadHeaders

Source line 229

private function sendDownloadHeaders(StorageEntry $entry, string $disposition): void

Parameters

Parameter Type, modifiers and default Purpose
$entry StorageEntry $entry Operation input; the exact use, validation and propagation are shown in the implementation trace.
$disposition string $disposition Operation input; the exact use, validation and propagation are shown in the implementation trace.

External effects include header.

Implementation, validation guards and interaction order
// ----------------------------------------------------------------
    // Private — download helpers
    // ----------------------------------------------------------------

    private function sendDownloadHeaders(StorageEntry $entry, string $disposition): void
    {
        if (!in_array($disposition, ['attachment', 'inline'], true)) {
            $disposition = 'attachment';
        }

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: ' . $disposition . '; filename="' . addcslashes(str_replace(["\r", "\n"], '', basename($entry->getName())), '"\\') . '"');
        header('Content-Length: ' . $this->fileSystem->fileSize($entry->getPath()));
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
    }

Related types

Clone this wiki locally