Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate and extend rector config for better code quality #921

Merged
merged 9 commits into from
Aug 19, 2024
Merged
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,16 @@
"cd docs && make html"
],
"pre-push": [
"@cs",
"@rector-fix",
"@test",
"@test-bc"
],
"rector": [
"vendor/bin/rector --dry-run"
],
"rector-fix": [
"vendor/bin/rector"
"vendor/bin/rector",
"@cs"
],
"reset-project": [
"tests/bin/reset-project"
Expand Down
40 changes: 14 additions & 26 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,20 @@
declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector;
use Rector\PHPUnit\Set\PHPUnitSetList;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
return RectorConfig::configure()
->withPaths([
__DIR__.'/src',
__DIR__.'/tests',
]);

$rectorConfig->cacheDirectory(__DIR__.'/.build/rector');

$rectorConfig->importNames();

// register a single rule
// $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);

// define sets of rules
$rectorConfig->sets([
SetList::EARLY_RETURN,
LevelSetList::UP_TO_PHP_81,
PHPUnitSetList::PHPUNIT_100,
]);

$rectorConfig->skip([
AddLiteralSeparatorToNumberRector::class,
]);
};
])
->withPhpSets()
->withPreparedSets(
deadCode: true,
typeDeclarations: true,
privatization: true,
earlyReturn: true,
phpunitCodeQuality: true,
phpunit: true,
)
->withImportNames(removeUnusedImports: true)
;
2 changes: 0 additions & 2 deletions src/Firebase/AppCheck/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ public function exchangeCustomToken(string $appId, string $customToken): array

/**
* @param non-empty-string $method
* @param string|UriInterface $uri
* @param array<string, mixed>|null $options
*
* @throws AppCheckException
*/
private function requestApi(string $method, string|UriInterface $uri, ?array $options = null): ResponseInterface
Expand Down
4 changes: 2 additions & 2 deletions src/Firebase/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function getUser(Stringable|string $uid): UserRecord

public function getUsers(array $uids): array
{
$uids = array_map(static fn($uid) => Uid::fromString($uid)->value, $uids);
$uids = array_map(static fn($uid): string => Uid::fromString($uid)->value, $uids);

$users = array_fill_keys($uids, null);

Expand Down Expand Up @@ -490,7 +490,7 @@ public function unlinkProvider($uid, $provider): UserRecord
$provider = array_values(
array_filter(
array_map('strval', (array) $provider),
static fn(string $value) => $value !== '',
static fn(string $value): bool => $value !== '',
),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static function fromArray(array $settings): self
{
$instance = new self();

$settings = array_filter($settings, static fn($value) => $value !== null);
$settings = array_filter($settings, static fn($value): bool => $value !== null);

foreach ($settings as $key => $value) {
switch (mb_strtolower($key)) {
Expand Down Expand Up @@ -116,6 +116,6 @@ public function toArray(): array
'androidMinimumVersion' => $this->androidMinimumVersion,
'androidInstallApp' => $this->androidInstallApp,
'iOSBundleId' => $this->iOSBundleId,
], static fn($value) => is_bool($value) || (is_string($value) && $value !== ''));
], static fn($value): bool => is_bool($value) || (is_string($value) && $value !== ''));
}
}
6 changes: 3 additions & 3 deletions src/Firebase/Auth/SignInResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,10 @@ public function asTokenResponse(): array
{
return [
'token_type' => 'Bearer',
'access_token' => $this->accessToken(),
'access_token' => $this->accessToken,
'id_token' => $this->idToken,
'refresh_token' => $this->refreshToken(),
'expires_in' => $this->ttl(),
'refresh_token' => $this->refreshToken,
'expires_in' => $this->ttl,
];
}
}
2 changes: 1 addition & 1 deletion src/Firebase/Auth/UserRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private static function mfaInfoFromResponseData(array $data): ?MfaInfo
private static function userInfoFromResponseData(array $data): array
{
return array_map(
static fn(array $userInfoData) => UserInfo::fromResponseData($userInfoData),
static fn(array $userInfoData): UserInfo => UserInfo::fromResponseData($userInfoData),
$data['providerUserInfo'],
);
}
Expand Down
9 changes: 6 additions & 3 deletions src/Firebase/Contract/AppCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
use Kreait\Firebase\AppCheck\AppCheckTokenOptions;
use Kreait\Firebase\AppCheck\VerifyAppCheckTokenResponse;
use Kreait\Firebase\Exception;
use Kreait\Firebase\Exception\AppCheck\FailedToVerifyAppCheckToken;
use Kreait\Firebase\Exception\AppCheck\InvalidAppCheckToken;
use Kreait\Firebase\Exception\AppCheck\InvalidAppCheckTokenOptions;

/**
* @phpstan-import-type AppCheckTokenOptionsShape from AppCheckTokenOptions
Expand All @@ -18,7 +21,7 @@ interface AppCheck
* @param non-empty-string $appId
* @param AppCheckTokenOptions|AppCheckTokenOptionsShape|null $options
*
* @throws Exception\AppCheck\InvalidAppCheckTokenOptions
* @throws InvalidAppCheckTokenOptions
* @throws Exception\AppCheckException
* @throws Exception\FirebaseException
*/
Expand All @@ -27,8 +30,8 @@ public function createToken(string $appId, $options = null): AppCheckToken;
/**
* @param non-empty-string $appCheckToken
*
* @throws Exception\AppCheck\InvalidAppCheckToken
* @throws Exception\AppCheck\FailedToVerifyAppCheckToken
* @throws InvalidAppCheckToken
* @throws FailedToVerifyAppCheckToken
* @throws Exception\AppCheckException
* @throws Exception\FirebaseException
*/
Expand Down
4 changes: 1 addition & 3 deletions src/Firebase/Database/Query/Modifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ public function modifyUri(UriInterface $uri): UriInterface;

/**
* Modifies the given value and returns it.
*
* @param mixed $value
*/
public function modifyValue($value): mixed;
public function modifyValue(mixed $value): mixed;
}
2 changes: 1 addition & 1 deletion src/Firebase/Database/Query/ModifierTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
*/
trait ModifierTrait
{
public function modifyValue($value): mixed
public function modifyValue(mixed $value): mixed
{
return $value;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Firebase/Database/Query/Sorter/OrderByChild.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ public function modifyUri(UriInterface $uri): UriInterface
return $this->appendQueryParam($uri, 'orderBy', sprintf('"%s"', $this->childKey));
}

public function modifyValue($value): mixed
public function modifyValue(mixed $value): mixed
{
if (!is_array($value)) {
return $value;
}

$expression = str_replace('/', '.', $this->childKey);

uasort($value, static fn($a, $b) => search($expression, $a) <=> search($expression, $b));
uasort($value, static fn($a, $b): int => search($expression, $a) <=> search($expression, $b));

return $value;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Firebase/Database/Query/Sorter/OrderByKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function modifyUri(UriInterface $uri): UriInterface
return $this->appendQueryParam($uri, 'orderBy', '"$key"');
}

public function modifyValue($value): mixed
public function modifyValue(mixed $value): mixed
{
if (!is_array($value)) {
return $value;
Expand Down
2 changes: 1 addition & 1 deletion src/Firebase/Database/Query/Sorter/OrderByValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function modifyUri(UriInterface $uri): UriInterface
return $this->appendQueryParam($uri, 'orderBy', '"$value"');
}

public function modifyValue($value): mixed
public function modifyValue(mixed $value): mixed
{
if (!is_array($value)) {
return $value;
Expand Down
1 change: 0 additions & 1 deletion src/Firebase/Database/UrlBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Kreait\Firebase\Exception\InvalidArgumentException;
use Kreait\Firebase\Util;

use function assert;
use function http_build_query;
use function in_array;
use function preg_match;
Expand Down
4 changes: 2 additions & 2 deletions src/Firebase/DynamicLink/EventStatistics.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,12 @@ public function appReOpens(): self

public function filterByType(string $type): self
{
return $this->filter(static fn(array $event) => ($event['event'] ?? null) === $type);
return $this->filter(static fn(array $event): bool => ($event['event'] ?? null) === $type);
}

public function filterByPlatform(string $platform): self
{
return $this->filter(static fn(array $event) => ($event['platform'] ?? null) === $platform);
return $this->filter(static fn(array $event): bool => ($event['platform'] ?? null) === $platform);
}

public function filter(callable $filter): self
Expand Down
3 changes: 2 additions & 1 deletion src/Firebase/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use Kreait\Firebase\JWT\IdTokenVerifier;
use Kreait\Firebase\JWT\SessionCookieVerifier;
use Kreait\Firebase\Messaging\AppInstanceApiClient;
use Kreait\Firebase\Messaging\RequestFactory;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;
use Psr\Http\Message\UriInterface;
Expand Down Expand Up @@ -406,7 +407,7 @@ public function createMessaging(): Contract\Messaging
$projectId = $this->getProjectId();

$errorHandler = new MessagingApiExceptionConverter($this->clock);
$requestFactory = new Messaging\RequestFactory(
$requestFactory = new RequestFactory(
requestFactory: $this->httpFactory,
streamFactory: $this->httpFactory,
);
Expand Down
12 changes: 7 additions & 5 deletions src/Firebase/Http/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
namespace Kreait\Firebase\Http;

use Beste\Json;
use Closure;
use Exception;
use Fig\Http\Message\StatusCodeInterface as StatusCode;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Query;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
Expand All @@ -29,7 +31,7 @@ final class Middleware
*/
public static function ensureJsonSuffix(): callable
{
return static fn(callable $handler) => static function (RequestInterface $request, ?array $options = null) use ($handler) {
return static fn(callable $handler): Closure => static function (RequestInterface $request, ?array $options = null) use ($handler) {
$uri = $request->getUri();
$path = '/'.ltrim($uri->getPath(), '/');

Expand All @@ -47,7 +49,7 @@ public static function ensureJsonSuffix(): callable
*/
public static function addDatabaseAuthVariableOverride(?array $override): callable
{
return static fn(callable $handler) => static function (RequestInterface $request, ?array $options = null) use ($handler, $override) {
return static fn(callable $handler): Closure => static function (RequestInterface $request, ?array $options = null) use ($handler, $override) {
$uri = $request->getUri();

$uri = $uri->withQuery(Query::build(
Expand All @@ -60,16 +62,16 @@ public static function addDatabaseAuthVariableOverride(?array $override): callab

public static function log(LoggerInterface $logger, MessageFormatter $formatter, string $logLevel, string $errorLogLevel): callable
{
return static fn(callable $handler) => static fn($request, array $options) => $handler($request, $options)->then(
static function (ResponseInterface $response) use ($logger, $request, $formatter, $logLevel, $errorLogLevel) {
return static fn(callable $handler): Closure => static fn($request, array $options) => $handler($request, $options)->then(
static function (ResponseInterface $response) use ($logger, $request, $formatter, $logLevel, $errorLogLevel): ResponseInterface {
$message = $formatter->format($request, $response);
$messageLogLevel = $response->getStatusCode() >= StatusCode::STATUS_BAD_REQUEST ? $errorLogLevel : $logLevel;

$logger->log($messageLogLevel, $message);

return $response;
},
static function (Exception $reason) use ($logger, $request, $formatter, $errorLogLevel) {
static function (Exception $reason) use ($logger, $request, $formatter, $errorLogLevel): PromiseInterface {
$response = $reason instanceof RequestException ? $reason->getResponse() : null;
$message = $formatter->format($request, $response, $reason);

Expand Down
10 changes: 5 additions & 5 deletions src/Firebase/Messaging.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@ public function sendAll($messages, bool $validateOnly = false): MulticastSendRep
$sendReports = array_fill(0, count($messages), null);

$config = [
'fulfilled' => function (ResponseInterface $response, int $index) use ($messages, &$sendReports) {
'fulfilled' => function (ResponseInterface $response, int $index) use ($messages, &$sendReports): void {
$message = $messages[$index];

$json = Json::decode((string) $response->getBody(), true);

$sendReports[$index] = SendReport::success($message->target(), $json, $message);
},
'rejected' => function (Throwable $reason, int $index) use ($messages, &$sendReports) {
'rejected' => function (Throwable $reason, int $index) use ($messages, &$sendReports): void {
$message = $messages[$index];

$error = $this->exceptionConverter->convertException($reason);
Expand Down Expand Up @@ -159,7 +159,7 @@ public function unsubscribeFromTopic(string|Topic $topic, RegistrationTokens|Reg
public function unsubscribeFromTopics(array $topics, RegistrationTokens|RegistrationToken|array|string $registrationTokenOrTokens): array
{
$topics = array_map(
static fn($topic) => $topic instanceof Topic ? $topic : Topic::fromValue($topic),
static fn($topic): Topic => $topic instanceof Topic ? $topic : Topic::fromValue($topic),
$topics,
);

Expand All @@ -177,7 +177,7 @@ public function unsubscribeFromAllTopics($registrationTokenOrTokens): array
foreach ($tokens as $token) {
$promises[$token->value()] = $this->appInstanceApi
->getAppInstanceAsync($token)
->then(function (AppInstance $appInstance) use ($token) {
->then(function (AppInstance $appInstance) use ($token): array {
$topics = [];

foreach ($appInstance->topicSubscriptions() as $subscription) {
Expand All @@ -186,7 +186,7 @@ public function unsubscribeFromAllTopics($registrationTokenOrTokens): array

return array_keys($this->unsubscribeFromTopics($topics, $token));
})
->otherwise(static fn(Throwable $e) => $e->getMessage())
->otherwise(static fn(Throwable $e): string => $e->getMessage())
;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Firebase/Messaging/AndroidConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ public function withNotificationVisibility(string $notificationVisibility): self

public function jsonSerialize(): array
{
return array_filter($this->config, static fn($value) => $value !== null && $value !== []);
return array_filter($this->config, static fn($value): bool => $value !== null && $value !== []);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Firebase/Messaging/AppInstance.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function isSubscribedToTopic(Topic|string $topic): bool
$topic = $topic instanceof Topic ? $topic : Topic::fromValue($topic);

return $this->topicSubscriptions
->filter(static fn(TopicSubscription $subscription) => $topic->value() === $subscription->topic()->value())
->filter(static fn(TopicSubscription $subscription): bool => $topic->value() === $subscription->topic()->value())
->count() > 0
;
}
Expand Down
Loading