Skip to content

Commit

Permalink
Increase PHPStan rule level to 7
Browse files Browse the repository at this point in the history
  • Loading branch information
theimbender committed Sep 17, 2023
1 parent 6e7160f commit 7bad8ea
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 41 deletions.
2 changes: 1 addition & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ includes:
- phpstan-baseline.neon

parameters:
level: 6
level: 7
tmpDir: .
phpVersion: 80204

Expand Down
9 changes: 6 additions & 3 deletions src/Builder/ArchiveBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ public function dump(array $packages): void
$distUrl = sprintf('%s/%s/%s/%s', $endpoint, $this->config['archive']['directory'], $intermediatePath, $archive);
$package->setDistType($archiveFormat);
$package->setDistUrl($distUrl);
$package->setDistSha1Checksum($includeArchiveChecksum ? hash_file('sha1', $path) : null);
$hasedPath = $includeArchiveChecksum ? hash_file('sha1', $path) : false;
$package->setDistSha1Checksum(false !== $hasedPath ? $hasedPath : null);
$package->setDistReference($package->getSourceReference());

if ($renderProgress) {
Expand Down Expand Up @@ -171,7 +172,7 @@ private function archive(DownloadManager $downloadManager, ArchiveManager $archi

$filesystem = new Filesystem();
$filesystem->ensureDirectoryExists($targetDir);
$targetDir = realpath($targetDir);
$targetDir = (string) realpath($targetDir);

if ($overrideDistType) {
$originalDistType = $package->getDistType();
Expand Down Expand Up @@ -203,7 +204,9 @@ private function archive(DownloadManager $downloadManager, ArchiveManager $archi
$downloadPromise = $downloader->download($package, $downloadDir);
$downloadPromise->then(function ($filename) use ($path, $filesystem) {
$filesystem->ensureDirectoryExists(dirname($path));
$filesystem->rename($filename, $path);
if (is_string($filename)) {
$filesystem->rename($filename, $path);
}
});
SyncHelper::await($this->composer->getLoop(), $downloadPromise);
$filesystem->removeDirectory($downloadDir);
Expand Down
2 changes: 1 addition & 1 deletion src/Builder/ArchiveBuilderHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ protected function isOneOfNamesInList(array $names, array $list): bool
protected function doesNameMatchOneOfPatterns(string $name, array $patterns): bool
{
foreach ($patterns as $pattern) {
if (preg_match($pattern, $name)) {
if (1 === preg_match($pattern, $name)) {
return true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Builder/PackagesBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ private function pruneIncludeDirectories(): void
foreach (new \DirectoryIterator($dirname) as $file) {
foreach ($entries as $entry) {
list($pattern, $hash) = $entry;
if (preg_match($pattern, $file->getFilename(), $matches) && $matches[1] !== $hash) {
if (1 === preg_match($pattern, $file->getFilename(), $matches) && $matches[1] !== $hash) {
$group = sprintf(
'%s/%s',
basename($dirname),
Expand Down
4 changes: 2 additions & 2 deletions src/Builder/WebBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,12 @@ private function getTwigEnvironment(): Environment
$twigTemplate = $this->config['twig-template'] ?? null;
$templateDir = !is_null($twigTemplate) ? pathinfo($twigTemplate, PATHINFO_DIRNAME) : __DIR__ . '/../../views';
$loader = new FilesystemLoader($templateDir);
$options = getenv('SATIS_TWIG_DEBUG') ? ['debug' => true] : [];
$options = false !== getenv('SATIS_TWIG_DEBUG') ? ['debug' => true] : [];

$this->twig = new Environment($loader, $options);
$this->twig->addExtension(new HtmlExtension());

if (getenv('SATIS_TWIG_DEBUG')) {
if (false !== getenv('SATIS_TWIG_DEBUG')) {
$this->twig->addExtension(new DebugExtension());
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Console/Command/AddCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$vcsDriver = $input->getOption('type');
$repositoryName = $input->getOption('name');

if (preg_match('{^https?://}i', $configFile)) {
if (1 === preg_match('{^https?://}i', $configFile)) {
$output->writeln('<error>Unable to write to remote file ' . $configFile . '</error>');

return 2;
Expand Down
37 changes: 25 additions & 12 deletions src/Console/Command/BuildCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,17 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// load auth.json authentication information and pass it to the io interface
$io = $this->getIO();
$io->loadConfiguration($this->getConfiguration());
$config = [];

if (preg_match('{^https?://}i', $configFile)) {
if (1 === preg_match('{^https?://}i', $configFile)) {
$rfs = new RemoteFilesystem($io, $this->getConfiguration());
$contents = $rfs->getContents(parse_url($configFile, PHP_URL_HOST), $configFile, false);
$config = JsonFile::parseJson($contents, $configFile);
$host = parse_url($configFile, PHP_URL_HOST);
if (is_string($host)) {
$contents = $rfs->getContents($host, $configFile, false);
if (is_string($contents)) {
$config = JsonFile::parseJson($contents, $configFile);
}
}
} else {
$file = new JsonFile($configFile);
if (!$file->exists()) {
Expand Down Expand Up @@ -179,7 +185,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int
throw new \InvalidArgumentException('The output dir must be specified as second argument or be configured inside ' . $input->getArgument('file'));
}

if ($homepage = getenv('SATIS_HOMEPAGE')) {
$homepage = getenv('SATIS_HOMEPAGE');
if (false !== $homepage) {
$config['homepage'] = $homepage;
$output->writeln(sprintf('<notice>Homepage config used from env SATIS_HOMEPAGE: %s</notice>', $homepage));
}
Expand Down Expand Up @@ -277,17 +284,19 @@ private function getConfiguration(): Config
private function getComposerHome(): string
{
$home = getenv('COMPOSER_HOME');
if (!$home) {
if (false === $home) {
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!getenv('APPDATA')) {
$appData = getenv('APPDATA');
if (false === $appData) {
throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
$home = strtr(getenv('APPDATA'), '\\', '/') . '/Composer';
$home = strtr($appData, '\\', '/') . '/Composer';
} else {
if (!getenv('HOME')) {
$homeEnv = getenv('HOME');
if (false === $homeEnv) {
throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
$home = rtrim(getenv('HOME'), '/') . '/.composer';
$home = rtrim($homeEnv, '/') . '/.composer';
}
}

Expand All @@ -304,16 +313,20 @@ private function check(string $configFile): bool
$content = file_get_contents($configFile);

$parser = new JsonParser();
$result = $parser->lint($content);
$result = is_string($content) ? $parser->lint($content) : new ParsingException('Could not read file contents from "' . $configFile . '"');
if (null === $result) {
if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) {
throw new \UnexpectedValueException('"' . $configFile . '" is not UTF-8, could not parse as JSON');
}

$data = json_decode($content);
$data = json_decode((string) $content);

$schemaFile = __DIR__ . '/../../../res/satis-schema.json';
$schema = json_decode(file_get_contents($schemaFile));
$schemaFileContents = file_get_contents($schemaFile);
if (false === $schemaFileContents) {
throw new ParsingException('Could not read file contents from "' . $schemaFile . '"');
}
$schema = json_decode($schemaFileContents);
$validator = new Validator();
$validator->check($data, $schema);

Expand Down
4 changes: 2 additions & 2 deletions src/Console/Command/InitCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

$configFile = $input->getArgument('file');

if (preg_match('{^https?://}i', $configFile)) {
if (1 === preg_match('{^https?://}i', $configFile)) {
$output->writeln('<error>Unable to write to remote file ' . $configFile . '</error>');

return 2;
Expand Down Expand Up @@ -117,7 +117,7 @@ protected function interact(InputInterface $input, OutputInterface $output): voi
});

$this->prompt($input, $output, 'Home page', 'homepage', function ($value) {
if (!preg_match('/https?:\/\/.+/', $value)) {
if (1 !== preg_match('/https?:\/\/.+/', $value)) {
throw new \InvalidArgumentException('Enter a valid URL it will be used for building your repository');
}

Expand Down
45 changes: 29 additions & 16 deletions src/PackageSelection/PackageSelection.php
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,14 @@ public function select(PartialComposer $composer, bool $verbose): array
$this->addRepositories($repositorySet, $repos);
// dependencies of required packages might have changed and be part of filtered repos
if ($this->hasRepositoriesFilter() && true !== $this->repositoryFilterDep) {
$this->addRepositories($repositorySet, \array_udiff($initialRepos, $repos, fn ($a, $b) => $a->getRepoName() <=> $b->getRepoName()));
$this->addRepositories(
$repositorySet,
\array_udiff(
$initialRepos,
$repos,
fn ($a, $b) => (method_exists($a, 'getRepoName') ? $a->getRepoName() : '') <=> (method_exists($b, 'getRepoName') ? $b->getRepoName() : '')
)
);
}

// additional repositories for dependencies
Expand Down Expand Up @@ -293,7 +300,7 @@ public function load(): array
$baseUrlLength = strlen($baseUrl);

foreach ($rootConfig['providers'] as $package => $provider) {
$file = str_replace(['%package%', '%hash%'], [$package, $provider['sha256']], $rootConfig['providers-url']);
$file = (string) str_replace(['%package%', '%hash%'], [$package, $provider['sha256']], $rootConfig['providers-url']);

if ($baseUrl && substr($file, 0, $baseUrlLength) === $baseUrl) {
$file = substr($file, $baseUrlLength);
Expand Down Expand Up @@ -506,10 +513,10 @@ private function matchStripHostsPatterns(string $url): bool
}

$sshRegex = '#^[^@:\/]+@([^\/:]+)#ui';
if (preg_match($sshRegex, $url, $matches)) {
if (1 === preg_match($sshRegex, $url, $matches)) {
$url = $matches[1];
} else {
$url = trim(parse_url($url, PHP_URL_HOST), '[]');
$url = trim((string) parse_url($url, PHP_URL_HOST), '[]');
}

if (false !== filter_var($url, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
Expand All @@ -522,7 +529,7 @@ private function matchStripHostsPatterns(string $url): bool

$urlunpack = null;
if ('ipv4' === $urltype || 'ipv6' === $urltype) {
$urlunpack = unpack('N*', @inet_pton($url));
$urlunpack = (array) unpack('N*', (string) @inet_pton($url));
}

foreach ($this->stripHosts as $pattern) {
Expand All @@ -546,7 +553,7 @@ private function matchStripHostsPatterns(string $url): bool
return true;
}
} elseif ('name' === $type) {
if ('name' === $urltype && preg_match($host, $url)) {
if ('name' === $urltype && 1 === preg_match($host, $url)) {
return true;
}
}
Expand Down Expand Up @@ -577,15 +584,17 @@ private function matchAddr($addr1, $addr2, $len = 0, $chunklen = 32): bool
}

/**
* @param RepositoryInterface[] $repositories
* @param array<RepositoryInterface|ConfigurableRepositoryInterface> $repositories
*
* @throws \Exception
*/
private function addRepositories(RepositorySet $repositorySet, array $repositories): void
{
foreach ($repositories as $repository) {
try {
$repositorySet->addRepository($repository);
if ($repository instanceof RepositoryInterface) {
$repositorySet->addRepository($repository);
}
} catch (\Exception $exception) {
if (!$this->skipErrors) {
throw $exception;
Expand Down Expand Up @@ -697,7 +706,7 @@ function (Link $link) use ($packagesFilter) {
}

/**
* @param RepositoryInterface[] $repositories
* @param array<RepositoryInterface|ConfigurableRepositoryInterface> $repositories
*
* @return Link[]|PackageInterface[]
*/
Expand All @@ -714,7 +723,11 @@ private function getAllLinks(array $repositories, string $minimumStability, bool
}

try {
$packages = $this->getPackages($repository);
if ($repository instanceof RepositoryInterface) {
$packages = $this->getPackages($repository);
} else {
continue;
}
} catch (\Exception $exception) {
if (!$this->skipErrors) {
throw $exception;
Expand Down Expand Up @@ -745,9 +758,9 @@ private function getAllLinks(array $repositories, string $minimumStability, bool
}

/**
* @param Link[]|PackageInterface[] $links
* @param array<Link|PackageInterface> $links
*
* @return Link[]
* @return array<Link|PackageInterface>
*/
private function selectLinks(RepositorySet $repositorySet, array $links, bool $isRoot, bool $verbose): array
{
Expand All @@ -758,14 +771,14 @@ private function selectLinks(RepositorySet $repositorySet, array $links, bool $i
while (null !== key($links)) {
$link = current($links);
$matches = [];
if (is_a($link, PackageInterface::class)) {
if (false !== $link && is_a($link, PackageInterface::class)) {
$matches = [$link];
} elseif (is_a($link, Link::class)) {
} elseif (false !== $link && is_a($link, Link::class)) {
$name = $link->getTarget();
if (!$isRoot && $this->onlyBestCandidates) {
$selector = new VersionSelector($repositorySet);
$match = $selector->findBestCandidate($name, $link->getConstraint()->getPrettyString());
$matches = $match ? [$match] : [];
$matches = false !== $match ? [$match] : [];
} elseif (PlatformRepository::isPlatformPackage($name)) {
} else {
$matches = $repositorySet->createPoolForPackage($link->getTarget())->whatProvides($name, $link->getConstraint());
Expand Down Expand Up @@ -795,7 +808,7 @@ private function selectLinks(RepositorySet $repositorySet, array $links, bool $i
// otherwise metadata will stripped as usual
if (1 === substr_count($prettyVersion, '+')) {
// re-inject metadata because it has been stripped by the VersionParser
if (preg_match('/.+(\+[0-9A-Za-z-]*)$/', $prettyVersion, $match)) {
if (1 === preg_match('/.+(\+[0-9A-Za-z-]*)$/', $prettyVersion, $match)) {
$uniqueName .= $match[1];
}
}
Expand Down
11 changes: 9 additions & 2 deletions tests/Builder/PackagesBuilderDumpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ public function testNominalCase(bool $providers = false): void
$includeJson = end($includes);
}

// Skip if there is no valid json file
if (!is_string($includeJson)) {
continue;
}

$includeJsonFile = 'build/' . $includeJson;
$this->assertTrue(is_file(vfsStream::url($includeJsonFile)));

Expand All @@ -96,7 +101,7 @@ public function testNominalCase(bool $providers = false): void
$packagesIncludeJson = JsonFile::parseJson($file->getContent());
$this->assertEquals($arrayPackages, $packagesIncludeJson['packages']);

if ($lastIncludedJsonFile && $lastIncludedJsonFile !== $includeJsonFile) {
if (!is_null($lastIncludedJsonFile) && $lastIncludedJsonFile !== $includeJsonFile) {
$this->assertFalse(is_file(vfsStream::url($lastIncludedJsonFile)), 'Previous files not pruned');
}

Expand Down Expand Up @@ -210,7 +215,9 @@ public function testPrettyPrintOption(int $jsonOptions, bool $shouldPrettyPrint
$file = $this->root->getChild('build/out.json');
$content = $file->getContent();

self::assertEquals(trim(json_encode($expected, $jsonOptions)), trim($content));
$jsonEncodedObject = json_encode($expected, $jsonOptions);
self::assertIsString($jsonEncodedObject);
self::assertEquals(trim($jsonEncodedObject), trim($content));
}

public function testComposer2MinifiedProvider(): void
Expand Down

0 comments on commit 7bad8ea

Please sign in to comment.