|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace NuonicPluginInstaller\Service; |
| 6 | + |
| 7 | +use League\Flysystem\FilesystemException; |
| 8 | +use League\Flysystem\FilesystemOperator; |
| 9 | +use NuonicPluginInstaller\Exception\MalformedIndexException; |
| 10 | +use NuonicPluginInstaller\Struct\PackageIndexEntry; |
| 11 | + |
| 12 | +class IndexFileService implements IndexFileServiceInterface |
| 13 | +{ |
| 14 | + public const FILE_NAME = 'shopware-extension-index.json'; |
| 15 | + |
| 16 | + /** @var array<string, PackageIndexEntry> */ |
| 17 | + private array $packageInformation = []; |
| 18 | + |
| 19 | + public function __construct( |
| 20 | + private readonly FilesystemOperator $filesystem, |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + public function getPackageInformation(string $packageName): ?PackageIndexEntry |
| 25 | + { |
| 26 | + if (!isset($this->packageInformation[$packageName])) { |
| 27 | + $this->loadPluginInformationFromFile(); |
| 28 | + } |
| 29 | + |
| 30 | + return $this->packageInformation[$packageName]; |
| 31 | + } |
| 32 | + |
| 33 | + public function listPackages(): array |
| 34 | + { |
| 35 | + if (empty($this->packageInformation)) { |
| 36 | + $this->loadPluginInformationFromFile(); |
| 37 | + } |
| 38 | + |
| 39 | + return $this->packageInformation; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @return void |
| 44 | + * @throws MalformedIndexException |
| 45 | + */ |
| 46 | + private function loadPluginInformationFromFile(): void |
| 47 | + { |
| 48 | + try { |
| 49 | + $jsonData = $this->filesystem->read(self::FILE_NAME); |
| 50 | + $data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR); |
| 51 | + } catch (FilesystemException $e) { |
| 52 | + // if the file does not exist, do not build an index |
| 53 | + return; |
| 54 | + } catch (\JsonException $e) { |
| 55 | + throw new MalformedIndexException(sprintf('JSON decoding failed: %s', $e->getMessage()), $e->getCode(), $e); |
| 56 | + } |
| 57 | + |
| 58 | + foreach ($data as $package => $packageInfo) { |
| 59 | + if (!isset($packageInfo['repositoryUrl'], $packageInfo['ref'])) { |
| 60 | + throw new MalformedIndexException(sprintf('Package information is missing required fields for package: %s', $package)); |
| 61 | + } |
| 62 | + |
| 63 | + $this->packageInformation[$package] = new PackageIndexEntry( |
| 64 | + repositoryUrl: $packageInfo['repositoryUrl'], |
| 65 | + ref: $packageInfo['ref'], |
| 66 | + ); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments