Skip to content

Commit

Permalink
fix phpstan errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jrmajor committed Apr 2, 2024
1 parent 11b76af commit 501eee8
Show file tree
Hide file tree
Showing 20 changed files with 78 additions and 38 deletions.
11 changes: 4 additions & 7 deletions dev/Currencies/CurrenciesFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ final class CurrenciesFactory
*/
public static function make(string $locale): array
{
/** @var array<string, array<string, string>> $data */
$data = H\CldrData::get('numbers', $locale, 'currencies.*.*.numbers.*');

return Dict\map_with_key(
/** @var array<string, array<string, string>> */
H\CldrData::get('numbers', $locale, 'currencies.*.*.numbers.*'),
$data,
fn ($code, $data) => self::makeCurrency($locale, $code, $data),
);
}

/**
* @param array<string, string> $data
*/
private static function makeCurrency(string $locale, string $code, array $data): Currency
{
$name = $data['displayName'] ?? null;
Expand All @@ -40,8 +39,6 @@ private static function makeCurrency(string $locale, string $code, array $data):
}

/**
* @param array<string, string> $data
*
* @return ?non-empty-array<string, string>
*/
private static function makePlurals(array $data, string $exceptionsFor): ?array
Expand Down
17 changes: 13 additions & 4 deletions dev/Helpers/CldrData.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ public static function regions(string $package): array
return $regions;
}

/**
* @return array<mixed>
*/
public static function get(string $package, string $locale, string $key): array
public static function get(string $package, string $locale, string $key): mixed
{
if (! str_contains($key, '.')) {
throw new InvalidArgumentException('Key should be in a dot notation.');
Expand All @@ -59,8 +56,20 @@ public static function get(string $package, string $locale, string $key): array

$data = Json\decode(File\read($path));

$path = '';

foreach (Str\Byte\split($keys, '.') as $key) {
$path = $path == '' ? $key : "{$path}.{$key}";

if (! is_array($data)) {
throw new InvalidArgumentException(sprintf('Can not acces key "%s" on a %s.', $key, gettype($data)));
}

if ($key !== '*') {
if (! array_key_exists($key, $data)) {
throw new InvalidArgumentException(sprintf('There is nothing at path %s.', $path));
}

$data = $data[$key];

continue;
Expand Down
3 changes: 3 additions & 0 deletions dev/Locales/LocalesFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ final class LocalesFactory
{
public static function make(string $locale): Locale
{
/** @var array<string, mixed> */
$data = H\CldrData::get('numbers', $locale, 'numbers.*.*.numbers');

$system = self::system($data);
Expand Down Expand Up @@ -87,6 +88,8 @@ private static function unitPatterns(array $data, string $system): array
return [];
}

$data = Type\dict(Type\string(), Type\string())->coerce($data);

return Dict\map_keys($data, function ($key) {
return Str\strip_prefix($key, 'unitPattern-count-');
});
Expand Down
8 changes: 4 additions & 4 deletions dev/Units/UnitsFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Psl\Dict;
use Psl\Iter;
use Psl\Str;
use Psl\Type;

final class UnitsFactory
{
Expand Down Expand Up @@ -69,6 +70,7 @@ final class UnitsFactory
*/
public static function make(string $locale): array
{
/** @var array<string, mixed> */
$data = H\CldrData::get('units', $locale, 'units.*.*.units');

return Dict\map(self::Units, fn ($unit) => new Unit(
Expand All @@ -79,8 +81,6 @@ public static function make(string $locale): array
}

/**
* @param array<string, mixed> $data
*
* @return array<string, string>
*/
private static function makeStyle(
Expand All @@ -94,12 +94,12 @@ private static function makeStyle(
$styleData = $data[$style][$unit]
?? throw new Exception("No data {$exceptionsFor}.");

$styleData = Type\dict(Type\string(), Type\string())->coerce($styleData);

return self::makePlurals($styleData, $exceptionsFor);
}

/**
* @param array<string, string> $data
*
* @return array<string, string>
*/
private static function makePlurals(array $data, string $exceptionsFor): array
Expand Down
9 changes: 9 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ parameters:
- dev
- src
- tests
ignoreErrors:
- '#^Method .*::patternType\(\) never returns .* so it can be removed from the return type\.$#'
- '#^Parameter \#1 \$file of function Psl\\File\\read expects non-empty-string, string given\.$#'
-
message: '#^Generator expects value type .*$#'
path: tests/Formatters/Number
-
message: '#^Method .* has parameter \$data with no value type specified in iterable type array\.$#'
path: dev/**/*Factory.php

tmpDir: .cache/phpstan

Expand Down
6 changes: 6 additions & 0 deletions src/Bundle/FluentBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ public function reportError(ResolverException $error): void

/**
* @return list<ResolverException>
*
* @phpstan-impure
*/
public function popErrors(): array
{
Expand Down Expand Up @@ -169,6 +171,9 @@ public function message(string $message, array $arguments = []): ?string
return $this->resolvePattern($pattern, $arguments);
}

/**
* @param array<string, mixed> $arguments
*/
private function resolvePattern(?Pattern $pattern, array $arguments): string
{
$resolver = new PatternResolver($this, $arguments);
Expand Down Expand Up @@ -224,6 +229,7 @@ private function numberFunction(
$number = new FluentNumber($number);
}

/** @phpstan-ignore-next-line */
return $number->setLocale($this->locale)->setOptions($options);
}

Expand Down
1 change: 1 addition & 0 deletions src/Bundle/Types/FluentNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public function original(): string
public function __toString(): string
{
return (new NumberFormatter($this->locale))->format(
/** @phpstan-ignore-next-line */
$this->value, new Options(...$this->options),
);
}
Expand Down
1 change: 1 addition & 0 deletions src/Exceptions/ParserException.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public function __construct(
'E0027' => 'Unbalanced closing brace in TextElement',
'E0028' => 'Expected an inline expression',
'E0029' => 'Expected simple expression as selector',
default => 'Unknown error',
};

if ($source !== null) {
Expand Down
14 changes: 9 additions & 5 deletions src/Formatters/LocaleData.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Major\Fluent\Formatters\Number\Locale\Currency;
use Major\Fluent\Formatters\Number\Locale\Locale;
use Major\Fluent\Formatters\Number\Locale\Unit;

/**
* @internal
Expand Down Expand Up @@ -35,6 +36,9 @@ public static function loadCurrencies(string $locale): array
);
}

/**
* @return array<string, Unit>
*/
public static function loadUnits(string $locale): array
{
[$language, $region] = self::getLangAndRegionPaths('units', $locale);
Expand Down Expand Up @@ -90,7 +94,7 @@ private static function splitLocale(string $locale): array
*/
private static function getFiles(string $type, string $language): array
{
/** @var list<non-empty-string> $files */
/** @phpstan-ignore-next-line */
return glob(self::Path . "{$type}/{$language}*.php");
}

Expand All @@ -113,9 +117,9 @@ private static function fileLocale(string $path): string
*/
public static function all(): array
{
return array_map(
fn (string $f): Locale => require $f,
glob(self::Path . 'numbers/*.php'),
);
$files = glob(self::Path . 'numbers/*.php');
assert($files !== false);

return array_map(fn (string $f): Locale => require $f, $files);
}
}
1 change: 1 addition & 0 deletions src/Formatters/Number/NumberFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ private function insertCurrencySymbol(Options $o, string $formatted): string
'symbol' => $currency->symbol,
'narrowSymbol' => $currency->narrow,
'code' => $currency->code,
default => throw new ShouldNotHappen(),
};

$prefix = '';
Expand Down
4 changes: 4 additions & 0 deletions src/Formatters/Number/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ public function __construct(
public ?int $minimumSignificantDigits = null,
public ?int $maximumSignificantDigits = null,
public ?string $currency = null,
/** @var 'symbol'|'narrowSymbol'|'code'|'name' */
public string $currencyDisplay = 'symbol',
public ?string $unit = null,
/** @var 'long'|'short'|'narrow' */
public string $unitDisplay = 'short',
) {
/** @psalm-suppress DocblockTypeContradiction */
Expand Down Expand Up @@ -94,11 +96,13 @@ private function fillForOther(?Currency $currency): void

$this->minimumFractionDigits ??= match ($this->style) {
'decimal', 'percent', 'unit' => 0,
/** @phpstan-ignore-next-line */
'currency' => $currency->minorUnits,
};

$this->maximumFractionDigits ??= match ($this->style) {
'decimal', 'unit' => max($this->minimumFractionDigits, 3),
/** @phpstan-ignore-next-line */
'currency' => max($this->minimumFractionDigits, $currency->minorUnits),
'percent' => max($this->minimumFractionDigits, 0),
};
Expand Down
3 changes: 3 additions & 0 deletions src/Parser/Cursor.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ private function charFromIndex(int $offset = 0): ?string
return $char;
}

/**
* @phpstan-impure
*/
public function currentChar(): ?string
{
return $this->charFromIndex();
Expand Down
2 changes: 2 additions & 0 deletions src/Resolver/PatternResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Major\Fluent\Bundle\Types\FluentNone;
use Major\Fluent\Bundle\Types\FluentNumber;
use Major\Fluent\Exceptions\Resolver as Err;
use Major\Fluent\Exceptions\ShouldNotHappen;
use Major\Fluent\Node\Syntax\CallArguments;
use Major\Fluent\Node\Syntax\Expressions as Expr;
use Major\Fluent\Node\Syntax\Expressions\Expression;
Expand Down Expand Up @@ -98,6 +99,7 @@ private function resolveExpression(Expr\Expression $e): string|Stringable
$e instanceof Expr\MessageReference => $this->resolveMessageReference($e),
$e instanceof Expr\TermReference => $this->resolveTermReference($e),
$e instanceof Expr\VariableReference => $this->resolveVariableReference($e),
default => throw new ShouldNotHappen(),
};
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Formatters/Number/LocaleDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public function testLoadNumbers(string $locale, Locale $expected): void
PU::assertTrue($actual->isIdentical($expected));
}

/**
* @return list<array{string, Locale}>
*/
public static function provideLoadNumbersCases(): array
{
return [
Expand Down Expand Up @@ -56,6 +59,9 @@ public function testLoadCurrencies(string $locale, Currency $expected): void
PU::assertTrue($actual[$expected->code]->isIdentical($expected));
}

/**
* @return list<array{string, Currency}>
*/
public static function provideLoadCurrenciesCases(): array
{
$polishPlurals = [
Expand Down Expand Up @@ -90,6 +96,9 @@ public function testLoadUnits(string $locale, Unit $expected): void
PU::assertTrue($actual['stone']->isIdentical($expected));
}

/**
* @return list<array{string, Unit}>
*/
public static function provideLoadUnitsCases(): array
{
return [
Expand Down
14 changes: 0 additions & 14 deletions tests/Formatters/Number/LocaleKnownValuesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
use Major\Fluent\Tests\Helpers as H;
use Major\Fluent\Tests\TestCase;
use PHPUnit\Framework\Attributes\TestDox;
use Psl\Iter;
use Psl\Vec;
use ReflectionClass;
use ReflectionParameter;

final class LocaleKnownValuesTest extends TestCase
{
Expand Down Expand Up @@ -113,17 +110,6 @@ public function testSymbols(): void
], H\count_values($values));
}

/**
* @psalm-suppress PossiblyNullReference
*/
private function getDefaultValueFor(string $property): mixed
{
return Iter\search(
(new ReflectionClass(Locale::class))->getConstructor()->getParameters(),
fn (ReflectionParameter $p): bool => $p->getName() === $property,
)->getDefaultValue();
}

/**
* @param list<array{value: string, ...}> $expected
* @param list<array{value: string, ...}> $actual
Expand Down
5 changes: 4 additions & 1 deletion tests/Formatters/Number/NodeVersionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Major\Fluent\Tests\Helpers\Node;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psl\Type;

final class NodeVersionTest extends TestCase
{
Expand All @@ -22,6 +23,8 @@ public function testCldr(): void

private function versionOf(string $library): string
{
return Node::instance()->freshOutput("process.versions.{$library}");
$v = Node::instance()->freshOutput("process.versions.{$library}");

return Type\string()->coerce($v);
}
}
3 changes: 2 additions & 1 deletion tests/Helpers/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static function instance(): self
return self::$instance ??= new self();
}

public function cachedOutput(string $command): string
public function cachedOutput(string $command): mixed
{
$hash = Hash\hash($command, Hash\Algorithm::SHA1);

Expand All @@ -60,6 +60,7 @@ private function loadCache(): void
File\write($this->path, '{}');
}

/** @phpstan-ignore-next-line */
$this->cache = Json\decode(File\read($this->path));
}

Expand Down
1 change: 1 addition & 0 deletions tests/Helpers/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function count_values(array $values): array
$primary = $b['count'] <=> $a['count'];
$secondary = $a['value'] <=> $b['value'];

/** @phpstan-ignore-next-line */
return $primary ?: $secondary;

Check failure on line 37 in tests/Helpers/helpers.php

View workflow job for this annotation

GitHub Actions / Types / PHP 8.2

No error to ignore is reported on line 37.
});
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Parser/Literals/NumberLiteralTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private static function assertValueAndPrecision(
): void {
$ast = (new FluentParser(true))->parseEntry($ftl);

/** @psalm-suppress UndefinedPropertyFetch */
/** @phpstan-ignore-next-line */
$expr = $ast->value->elements[0]->expression;

$parsed = Type\instance_of(NumberLiteralValue::class)->coerce($expr->parse());
Expand Down
2 changes: 1 addition & 1 deletion tests/Parser/Literals/StringLiteralTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private static function assertValue(string $value, string $ftl): void
{
$ast = (new FluentParser(true))->parseEntry($ftl);

/** @psalm-suppress UndefinedPropertyFetch */
/** @phpstan-ignore-next-line */
$expr = $ast->value->elements[0]->expression;

$parsed = Type\instance_of(StringLiteralValue::class)->coerce($expr->parse());
Expand Down

0 comments on commit 501eee8

Please sign in to comment.