Skip to content

Internals Installer Package PackageInstaller

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

installer\package\PackageInstaller

Framework Internals · Subsystem overview · Developer guide

Source: awt_src/classes/installer/package/PackageInstaller.php · Snapshot 8411f4287706.

Installation validates archives and manifests, moves files, persists metadata, copies data into storage, invokes an optional hook and emits an event. These operations do not form one atomic transaction.

Imports and dependencies

use installer\events\PackageInstalledEvent;
use installer\interfaces\package\IExtractor;
use installer\interfaces\package\IPackageInstaller;
use installer\interfaces\package\IPackageMover;
use installer\interfaces\package\IPackageStorageTreeGenerator;
use package\manifest\exceptions\ManifestReaderException;
use package\manifest\reader\ManifestReader;
use package\model\repository\interfaces\IPackageRepository;
use RuntimeException;

PackageInstaller

Declaration and architectural role

readonly class PackageInstaller implements IPackageInstaller

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
Constructor-promoted private IExtractor $extractor Initialized from the constructor argument; default expression is evaluated when the argument is omitted.
Constructor-promoted private IPackageMover $mover Initialized from the constructor argument; default expression is evaluated when the argument is omitted.
Constructor-promoted private IPackageStorageTreeGenerator $storageGenerator Initialized from the constructor argument; default expression is evaluated when the argument is omitted.
Constructor-promoted private IPackageRepository $packageRepository Initialized from the constructor argument; default expression is evaluated when the argument is omitted.
Constructor-promoted private PackageAssetLinks $assetLinks = new PackageAssetLinks() Initialized from the constructor argument; default expression is evaluated when the argument is omitted.

Method index

Method Signature
__construct public function __construct( private IExtractor $extractor, private IPackageMover $mover, private IPackageStorageTreeGenerator $storageGenerator, private IPackageRepository $packageRepository, private PackageAssetLinks $assetLinks = new PackageAssetLinks(), )
install public function install(): bool
update public function update(): bool
apply private function apply(bool $updating): bool
applyExtracted private function applyExtracted(string $extractedBase, bool $updating): bool
execute public function execute(): bool
findPackageDir private function findPackageDir(string $extractedBase): string
cleanup private function cleanup(string $dir): void

__construct

Source line 17

public function __construct(
        private IExtractor                   $extractor,
        private IPackageMover                $mover,
        private IPackageStorageTreeGenerator $storageGenerator,
        private IPackageRepository           $packageRepository,
        private PackageAssetLinks            $assetLinks = new PackageAssetLinks(),
    );

Parameters

Parameter Type, modifiers and default Purpose
$extractor private IExtractor $extractor Operation input; the exact use, validation and propagation are shown in the implementation trace.
$mover private IPackageMover $mover Operation input; the exact use, validation and propagation are shown in the implementation trace.
$storageGenerator private IPackageStorageTreeGenerator $storageGenerator Operation input; the exact use, validation and propagation are shown in the implementation trace.
$packageRepository private IPackageRepository $packageRepository Operation input; the exact use, validation and propagation are shown in the implementation trace.
$assetLinks private PackageAssetLinks $assetLinks = new PackageAssetLinks() Operation input; the exact use, validation and propagation are shown in the implementation trace.

Concrete no-op/default hook: this method performs no work. Override it where the lifecycle or extension contract calls for behavior.

install

Source line 30

public function install(): bool

@throws ManifestReaderException @throws \JsonException

Return expressions (including local callbacks): $this->apply(false).

Implementation, validation guards and interaction order
/**
     * @inheritDoc
     * @throws ManifestReaderException
     * @throws \JsonException
     */
    public function install(): bool { return $this->apply(false); }

update

Source line 31

public function update(): bool

Return expressions (including local callbacks): $this->apply(true).

Implementation, validation guards and interaction order
public function update(): bool { return $this->apply(true); }

apply

Source line 33

private function apply(bool $updating): bool

Parameters

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

Return expressions (including local callbacks): $this->applyExtracted($extractedBase, $updating).

Implementation, validation guards and interaction order
private function apply(bool $updating): bool
    {
        $this->extractor->extract();
        $extractedBase = $this->extractor->getDestination();
        try {
            return $this->applyExtracted($extractedBase, $updating);
        } finally {
            $this->cleanup($extractedBase);
        }
    }

applyExtracted

Source line 44

private function applyExtracted(string $extractedBase, bool $updating): bool

Parameters

Parameter Type, modifiers and default Purpose
$extractedBase string $extractedBase Operation input; the exact use, validation and propagation are shown in the implementation trace.
$updating bool $updating Operation input; the exact use, validation and propagation are shown in the implementation trace.

Return expressions (including local callbacks): false; true.

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

External effects include mkdir.

Implementation, validation guards and interaction order
private function applyExtracted(string $extractedBase, bool $updating): bool
    {
        global $eventDispatcher;
        $packageDir = is_file($extractedBase . DIRECTORY_SEPARATOR . 'manifest.json')
            ? $extractedBase : $this->findPackageDir($extractedBase);

        $manifestPath = $packageDir . DIRECTORY_SEPARATOR . 'manifest.json';

        $manifest = ManifestReader::readFile($manifestPath);
        if (defined('AWT_VERSION') && (version_compare(AWT_VERSION, $manifest['minimum_awt_version'], '<')
            || (!empty($manifest['maximum_awt_version']) && version_compare(AWT_VERSION, $manifest['maximum_awt_version'], '>')))) {
            throw new RuntimeException('Package is incompatible with this AWT version.');
        }
        $installedPackage = $this->packageRepository->getPackage($manifest['name']);
        if ($updating && $installedPackage === null) {
            throw new RuntimeException("Package is not installed: {$manifest['name']}.");
        }
        if (!$updating && $installedPackage !== null) {
            throw new RuntimeException("Package is already installed: {$manifest['name']}. Use the update workflow.");
        }
        foreach ($manifest['dependencies'] as $data) {
            $dependency = \package\dependency\Dependency::fromArray($data);
            $installed = $this->packageRepository->getPackage($dependency->name);
            if ($installed === null || !\package\dependency\Dependency::matchesVersion($installed['version'], $dependency->version)) {
                throw new RuntimeException("Required dependency is missing or incompatible: {$dependency->name} {$dependency->version}");
            }
        }

        $verifyManifest  = new VerifyManifest($manifest);
        $verifyStructure = new VerifyStructure($packageDir);
        $preparer        = new PrepareInstallation($verifyManifest, $verifyStructure);

        if (!$preparer->prepare()->verify()) {
            return false;
        }

        $packageName = $manifest['name'];
        $destination = rtrim(PACKAGES, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . str_replace(' ', '', $packageName);

        if (!is_dir($destination) && !mkdir($destination, 0755, true) && !is_dir($destination)) {
            throw new RuntimeException("Failed to create package directory: {$destination}");
        }

        $this->mover->setSource($packageDir);
        $this->mover->setDestination($destination);
        $this->mover->move();

        $manifestReader = new ManifestReader($packageName);
        $forDb = $manifestReader->getManifest();
        // Dependencies are persisted; startup never needs to reread the manifest.
        if ($updating) {
            $packageId = (int) $installedPackage['id'];
            // Optional metadata omitted from an update keeps its installed value.
            $forDb = array_merge($installedPackage, $forDb);
            if (!$this->packageRepository->updatePackage($packageId, $forDb)) {
                throw new RuntimeException("Failed to update package '{$packageName}'.");
            }
        } else {
            $packageId = $this->packageRepository->newPackage($forDb);
        }

        if ($packageId === null) {
            throw new RuntimeException("Failed to register package '{$packageName}' in the database.");
        }

        $dataDir = $destination . DIRECTORY_SEPARATOR . 'data';
        if (is_dir($dataDir)) {
            $this->storageGenerator->setSource($dataDir);
            $this->storageGenerator->setDestination(
                PACKAGE_STORAGE . $packageName
            );
            $this->storageGenerator->setBaseUrl('/packages/' . $packageName);
            $this->storageGenerator->setPackageId($packageId);
            $this->storageGenerator->buildStorageTree()->generate();
            $this->storageGenerator->registerItems();
            $this->assetLinks->register($packageId, PACKAGE_STORAGE . $packageName, $manifest);
        }

        $hookFile = $destination . DIRECTORY_SEPARATOR . ($updating ? 'update.php' : 'install.php');
        if (is_file($hookFile)) {
            $hook = \object\ObjectHandler::createObjectFromFile($hookFile);
            if ($updating && $hook instanceof \package\install\interfaces\IPackageUpdate) {
                if (!$hook->update($packageId, $packageName)) throw new RuntimeException('Package update hook failed.');
            } elseif (!$updating && $hook instanceof \package\install\interfaces\IPackageInstall) {
                if (!$hook->postInstall($packageId, $packageName)) throw new RuntimeException('Package post-install hook failed.');
            } elseif ($updating && $hook instanceof \installer\interfaces\package\actions\IPostUpdate) {
                $hook->postUpdate($packageId);
            } elseif (!$updating && $hook instanceof \installer\interfaces\package\actions\IPostInstall) {
                $hook->postInstall($packageId);
            } else {
                throw new RuntimeException('Package hook does not implement the required install/update contract.');
            }
        }
        $e = $updating ? new \installer\events\PackageUpdatedEvent() : new PackageInstalledEvent();
        $e->setId($packageId);
        $e->setManifest($manifest);
        if ($eventDispatcher instanceof \event\EventDispatcher) $eventDispatcher->dispatch($e);

        return true;
    }

execute

Source line 148

public function execute(): bool

Return expressions (including local callbacks): true.

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

Implementation, validation guards and interaction order
/**
     * @inheritDoc
     */
    public function execute(): bool
    {
        if (!$this->install()) {
            throw new RuntimeException("Package installation failed.");
        }

        return true;
    }

findPackageDir

Source line 157

private function findPackageDir(string $extractedBase): string

Parameters

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

Return expressions (including local callbacks): $fullPath; $extractedBase.

Implementation, validation guards and interaction order
private function findPackageDir(string $extractedBase): string
    {
        $scan = scandir($extractedBase);
        foreach ($scan as $entry) {
            if ($entry === '.' || $entry === '..') {
                continue;
            }
            $fullPath = $extractedBase . DIRECTORY_SEPARATOR . $entry;
            if (is_dir($fullPath) && is_file($fullPath . DIRECTORY_SEPARATOR . 'manifest.json')) {
                return $fullPath;
            }
        }

        return $extractedBase;
    }

cleanup

Source line 173

private function cleanup(string $dir): void

Parameters

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

External effects include unlink, rmdir.

Implementation, validation guards and interaction order
private function cleanup(string $dir): void
    {
        if (!is_dir($dir) || is_link($dir)) {
            return;
        }

        $scan = scandir($dir);
        foreach ($scan as $entry) {
            if ($entry === '.' || $entry === '..') {
                continue;
            }
            $path = $dir . DIRECTORY_SEPARATOR . $entry;
            is_dir($path) && !is_link($path) ? $this->cleanup($path) : unlink($path);
        }

        rmdir($dir);
    }

Related types

Clone this wiki locally