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

[2.x] Codebase cleanup #4161

Open
wants to merge 40 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
f24cebc
refactor: replace deprecated constant with suggested enum
xHeaven Jan 17, 2025
b0c5a9c
refactor: replace array access with foreach value
xHeaven Jan 17, 2025
2d0b261
refactor: make classes readonly instead of marking every property
xHeaven Jan 17, 2025
fcf7a7f
refactor: turn complicated foreach into a clean array_map
xHeaven Jan 17, 2025
665261a
refactor: sort arguments
xHeaven Jan 17, 2025
fdf5890
refactor: use PHP ^8.0 str_* methods
xHeaven Jan 17, 2025
372a422
refactor: remove redundant casts
xHeaven Jan 17, 2025
ef7a64e
refactor: remove double-check
xHeaven Jan 17, 2025
63f3a65
refactor: make property readonly
xHeaven Jan 17, 2025
f8cef83
refactor: use nullsafe operator
xHeaven Jan 17, 2025
2454fa0
refactor: flip yoda-style comparison for consistency
xHeaven Jan 17, 2025
12ba0b1
refactor: mark sensitive parameters with SensitiveParameter attribute
xHeaven Jan 17, 2025
5e84a42
refactor: use strict comparison
xHeaven Jan 17, 2025
5405a22
refactor: use first-class-callable
xHeaven Jan 17, 2025
4e16e79
refactor: cleanup redundant PHPDocs
xHeaven Jan 17, 2025
c88c6a5
refactor: use $this instead of parent::
xHeaven Jan 17, 2025
441d7cf
refactor: drop unnecessary null coalescing
xHeaven Jan 17, 2025
faab6de
refactor: merge unset calls
xHeaven Jan 17, 2025
e45718b
refactor: add missing access modifiers
xHeaven Jan 17, 2025
3e4f6d7
refactor: simplify if-else
xHeaven Jan 17, 2025
9ff2253
refactor: merge isset calls
xHeaven Jan 17, 2025
8333bf0
refactor: optimize condition order
xHeaven Jan 17, 2025
25865ea
refactor: cleanup if-else branches
xHeaven Jan 17, 2025
0e00914
refactor: trim first, then convert to lowercase
xHeaven Jan 17, 2025
d6744c9
refactor: use null coalescing operator
xHeaven Jan 17, 2025
ed8cf27
refactor: use short list syntax
xHeaven Jan 17, 2025
85bfc72
refactor: replace in_array() with array_key_exists
xHeaven Jan 17, 2025
984c9ba
refactor: use proper callbacks istead of relying on call_user_func*
xHeaven Jan 17, 2025
99b1b7c
refactor: wrap condition with parentheses to clarify operation order
xHeaven Jan 17, 2025
8b65f1d
refactor: drop property, ExtractsListingParams trait already defines it
xHeaven Jan 17, 2025
ed8d7e4
refactor: remove unused imports
xHeaven Jan 17, 2025
b91eb45
refactor: remove unused variables
xHeaven Jan 17, 2025
efced7b
refactor: remove unused parameters
xHeaven Jan 17, 2025
d37c1f2
refactor: change method call as signature has changed
xHeaven Jan 17, 2025
1331d39
refactor: re-add PHPDoc for phpstan
xHeaven Jan 17, 2025
5319d66
refactor: remove nullable type
xHeaven Jan 17, 2025
7065e50
refactor: add second parameter to json_decode() calls
xHeaven Jan 17, 2025
5600e50
refactor: use strict comparison where possible
xHeaven Jan 17, 2025
2464caf
refactor: add missing property types
xHeaven Jan 17, 2025
a6f313b
style: fix formatting for styleci
xHeaven Jan 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions framework/core/src/Admin/Content/AdminPayload.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ public function __invoke(Document $document, Request $request): void
$document->payload['extensions'] = $this->extensions->getExtensions()->toArray();

$document->payload['displayNameDrivers'] = array_keys($this->container->make('flarum.user.display_name.supported_drivers'));
$document->payload['slugDrivers'] = array_map(function ($resourceDrivers) {
return array_keys($resourceDrivers);
}, $this->container->make('flarum.http.slugDrivers'));
$document->payload['slugDrivers'] = array_map(array_keys(...), $this->container->make('flarum.http.slugDrivers'));
$document->payload['searchDrivers'] = $this->getSearchDrivers();

$document->payload['phpVersion'] = $this->appInfo->identifyPHPVersion();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected function delete(ServerRequestInterface $request): void

$name = Arr::get($request->getQueryParams(), 'name');

if ($this->extensions->getExtension($name) == null) {
if ($this->extensions->getExtension($name) === null) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public function defaultExtracts(Context $context): array
return [
'filter' => RequestUtil::extractFilter($context->request),
'sort' => RequestUtil::extractSort($context->request, $this->defaultSort, $this->getAvailableSorts($context)),
'limit' => $limit = (RequestUtil::extractLimit($context->request, $this->limit, $this->maxLimit) ?? null),
'limit' => $limit = RequestUtil::extractLimit($context->request, $this->limit, $this->maxLimit),
'offset' => RequestUtil::extractOffset($context->request, $limit),
];
}
Expand Down
12 changes: 4 additions & 8 deletions framework/core/src/Api/Endpoint/Concerns/HasEagerLoading.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Flarum\Api\Resource\AbstractDatabaseResource;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str;
use Tobyz\JsonApiServer\Context;

Expand Down Expand Up @@ -147,13 +146,10 @@ protected function compileSimpleEagerLoads(Context $context, array $included): a

protected function compileWhereEagerLoads(Context $context): array
{
$relations = [];

foreach ($this->loadRelationWhere as $name => $callable) {
$relations[$name] = function ($query) use ($callable, $context) {
$callable($query, $context);
};
}
$relations = array_map(
callback: fn ($callable) => fn ($query) => $callable($query, $context),
array: $this->loadRelationWhere
);

return $relations;
}
Expand Down
2 changes: 1 addition & 1 deletion framework/core/src/Api/Endpoint/Create.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function setUp(): void
final protected function fillDefaultValues(Context $context, array &$data): void
{
foreach ($context->fields($context->resource) as $field) {
if (! has_value($data, $field) && ($default = $field->default)) {
if (($default = $field->default) && ! has_value($data, $field)) {
set_value($data, $field, $default($context->withField($field)));
}
}
Expand Down
1 change: 0 additions & 1 deletion framework/core/src/Api/Endpoint/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ class Index extends Endpoint
use HasCustomHooks;

public Closure $paginationResolver;
public ?string $defaultSort = null;
protected ?Closure $query = null;

public function __construct(string $name)
Expand Down
2 changes: 1 addition & 1 deletion framework/core/src/Api/Middleware/FakeHttpMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

class FakeHttpMethods implements Middleware
{
const HEADER_NAME = 'x-http-method-override';
public const HEADER_NAME = 'x-http-method-override';

public function process(Request $request, Handler $handler): Response
{
Expand Down
4 changes: 3 additions & 1 deletion framework/core/src/Api/Middleware/ThrottleApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ public function throttle(Request $request): bool
// Anything else is ignored.
if ($result === false) {
return false;
} elseif ($result === true) {
}

if ($result === true) {
$throttle = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ public function getValue(object $model, Field $field, Context $context): mixed
{
if ($field instanceof Relationship) {
return $this->getRelationshipValue($model, $field, $context);
} else {
return $this->getAttributeValue($model, $field, $context);
}

return $this->getAttributeValue($model, $field, $context);
}

/**
Expand Down
8 changes: 4 additions & 4 deletions framework/core/src/Api/Resource/AccessTokenResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,18 @@ public function fields(): array
{
return [
Schema\Str::make('token')
->visible(function (AccessToken $token, Context $context) {
->visible(function (#[\SensitiveParameter] AccessToken $token, Context $context) {
return $context->getActor()->id === $token->user_id && ! in_array('token', $token->getHidden(), true);
}),
Schema\Integer::make('userId'),
Schema\DateTime::make('createdAt'),
Schema\DateTime::make('lastActivityAt'),
Schema\Boolean::make('isCurrent')
->get(function (AccessToken $token, Context $context) {
->get(function (#[\SensitiveParameter] AccessToken $token, Context $context) {
return $token->token === $context->request->getAttribute('session')->get('access_token');
}),
Schema\Boolean::make('isSessionToken')
->get(function (AccessToken $token) {
->get(function (#[\SensitiveParameter] AccessToken $token) {
return in_array($token->type, [SessionAccessToken::$type, RememberAccessToken::$type], true);
}),
Schema\Str::make('title')
Expand All @@ -99,7 +99,7 @@ public function fields(): array
->maxLength(255),
Schema\Str::make('lastIpAddress'),
Schema\Str::make('device')
->get(function (AccessToken $token) {
->get(function (#[\SensitiveParameter] AccessToken $token) {
$agent = new Agent();
$agent->setUserAgent($token->last_user_agent);

Expand Down
4 changes: 0 additions & 4 deletions framework/core/src/Api/Resource/Contracts/Listable.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,11 @@ interface Listable
{
/**
* Create a query object for the current request.
*
* @param Context $context
*/
public function query(Context $context): object;

/**
* Get results from the given query.
*
* @param Context $context
*/
public function results(object $query, Context $context): iterable;

Expand Down
6 changes: 3 additions & 3 deletions framework/core/src/Api/Resource/UserResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ public function saving(object $model, \Tobyz\JsonApiServer\Context $context): ?o
return $model;
}

private function applyToken(User $user, RegistrationToken $token): void
private function applyToken(User $user, #[\SensitiveParameter] RegistrationToken $token): void
{
foreach ($token->user_attributes as $k => $v) {
if ($k === 'avatar_url') {
Expand Down Expand Up @@ -435,7 +435,7 @@ private function retrieveAvatarFromUrl(string $url): ?string

try {
$response = $client->get($url);
} catch (\Exception $e) {
} catch (\Exception) {
return null;
}

Expand All @@ -446,7 +446,7 @@ private function retrieveAvatarFromUrl(string $url): ?string
return $response->getBody()->getContents();
}

private function fulfillToken(User $user, RegistrationToken $token): void
private function fulfillToken(User $user, #[\SensitiveParameter] RegistrationToken $token): void
{
$token->delete();

Expand Down
4 changes: 2 additions & 2 deletions framework/core/src/Api/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ private function addToMap(Resource $resource, mixed $model, array $include): arr

$this->whenResolved($value, function (mixed $value) use ($key, $field, $context) {
if (
($value = $field->serializeValue($value, $context)) ||
! $field instanceof Relationship
! $field instanceof Relationship ||
($value = $field->serializeValue($value, $context))
) {
set_value($this->map[$key], $field, $value);
}
Expand Down
4 changes: 2 additions & 2 deletions framework/core/src/Console/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;

class Server
readonly class Server
{
public function __construct(
private readonly SiteInterface $site
private SiteInterface $site
) {
}

Expand Down
2 changes: 0 additions & 2 deletions framework/core/src/Database/DatabaseMigrationRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ public function delete(string $file, ?string $extension = null): void

/**
* Create the migration repository data store.
*
* @return void
*/
public function createRepository(): void
{
Expand Down
9 changes: 3 additions & 6 deletions framework/core/src/Database/Migrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function runMigrationList(string $path, array $migrations, ?Extension $ex
// First we will just make sure that there are any migrations to run. If there
// aren't, we will just make a note of it to the developer so they're aware
// that all the migrations have been run against this database system.
if (count($migrations) == 0) {
if (count($migrations) === 0) {
$this->note('<info>Nothing to migrate.</info>');

return;
Expand Down Expand Up @@ -115,7 +115,7 @@ protected function runUp(string $path, string $file, ?Extension $extension = nul
public function reset(string $path, ?Extension $extension = null): int
{
$migrations = array_reverse($this->repository->getRan(
$extension ? $extension->getId() : null
$extension?->getId()
));

$count = count($migrations);
Expand Down Expand Up @@ -176,11 +176,8 @@ protected function resolveAndRunClosureMigration(string $path, string $file, str

/**
* Get all of the migration files in a given path.
*
* @param string $path
* @return array
*/
public function getMigrationFiles($path)
public function getMigrationFiles(string $path): array
{
$files = $this->files->glob($path.'/*_*.php');

Expand Down
2 changes: 0 additions & 2 deletions framework/core/src/Discussion/Discussion.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,6 @@ public function comments(): HasMany
/**
* Query the discussion's participants (a list of unique users who have
* posted in the discussion).
*
* @return Builder
*/
public function participants(): Builder
{
Expand Down
6 changes: 3 additions & 3 deletions framework/core/src/Discussion/DiscussionMetadataUpdater.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function whenPostWasPosted(Posted $event): void
{
$discussion = $event->post->discussion;

if ($discussion && $discussion->exists) {
if ($discussion?->exists) {
$discussion->refreshCommentCount();
$discussion->refreshLastPost();
$discussion->refreshParticipantCount();
Expand Down Expand Up @@ -58,7 +58,7 @@ public function whenPostWasRestored(Restored $event): void
{
$discussion = $event->post->discussion;

if ($discussion && $discussion->exists) {
if ($discussion?->exists) {
$discussion->refreshCommentCount();
$discussion->refreshParticipantCount();
$discussion->refreshLastPost();
Expand All @@ -70,7 +70,7 @@ protected function removePost(Post $post): void
{
$discussion = $post->discussion;

if ($discussion && $discussion->exists) {
if ($discussion?->exists) {
$discussion->refreshCommentCount();
$discussion->refreshParticipantCount();

Expand Down
2 changes: 0 additions & 2 deletions framework/core/src/Discussion/DiscussionRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public function findOrFail(int|string $id, ?User $user = null): Discussion
/**
* Get a query containing the IDs of discussions which a user has read completely.
*
* @param User $user
* @return Builder<Discussion>
*/
public function getReadIdsQuery(User $user): Builder
Expand All @@ -52,7 +51,6 @@ public function getReadIdsQuery(User $user): Builder
* Scope a query to only include records that are visible to a user.
*
* @param Builder<Discussion> $query
* @param User|null $user
* @return Builder<Discussion>
*/
protected function scopeVisibleTo(Builder $query, ?User $user = null): Builder
Expand Down
3 changes: 0 additions & 3 deletions framework/core/src/Discussion/Search/FulltextFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public function search(SearchState $state, string $value): void

protected function sqlite(DatabaseSearchState $state, string $value): void
{
/** @var Builder $query */
$query = $state->getQuery();

$query->where(function (Builder $query) use ($state, $value) {
Expand All @@ -63,7 +62,6 @@ protected function sqlite(DatabaseSearchState $state, string $value): void

protected function mysql(DatabaseSearchState $state, string $value): void
{
/** @var Builder $query */
$query = $state->getQuery();

// Replace all non-word characters with spaces.
Expand Down Expand Up @@ -119,7 +117,6 @@ protected function pgsql(DatabaseSearchState $state, string $value): void
{
$searchConfig = $this->settings->get('pgsql_search_configuration');

/** @var Builder $query */
$query = $state->getQuery();

$grammar = $query->getGrammar();
Expand Down
3 changes: 0 additions & 3 deletions framework/core/src/Extend/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ class Auth implements ExtenderInterface
* password checkers can run.
* - `false` if the given password is invalid, and no other checkers should be considered.
* Evaluation will be immediately halted if any checkers return `false`.
*
* @return self
*/
public function addPasswordChecker(string $identifier, callable|string $callback): self
{
Expand All @@ -49,7 +47,6 @@ public function addPasswordChecker(string $identifier, callable|string $callback
* Remove a password checker.
*
* @param string $identifier: The unique identifier of the password checker to remove.
* @return self
*/
public function removePasswordChecker(string $identifier): self
{
Expand Down
7 changes: 0 additions & 7 deletions framework/core/src/Extend/Conditional.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class Conditional implements ExtenderInterface
*
* @param string $extensionId The ID of the extension.
* @param callable|string $extenders A callable returning an array of extenders, or an invokable class string.
* @return self
*/
public function whenExtensionEnabled(string $extensionId, callable|string $extenders): self
{
Expand All @@ -52,7 +51,6 @@ public function whenExtensionEnabled(string $extensionId, callable|string $exten
*
* @param string $extensionId The ID of the extension.
* @param callable|string $extenders A callable returning an array of extenders, or an invokable class string.
* @return self
*/
public function whenExtensionDisabled(string $extensionId, callable|string $extenders): self
{
Expand All @@ -67,7 +65,6 @@ public function whenExtensionDisabled(string $extensionId, callable|string $exte
* @param bool|callable $condition A boolean or callable that should return a boolean.
* If this evaluates to true, the extenders will be applied.
* @param callable|string $extenders A callable returning an array of extenders, or an invokable class string.
* @return self
*/
public function when(callable|bool $condition, callable|string $extenders): self
{
Expand All @@ -81,10 +78,6 @@ public function when(callable|bool $condition, callable|string $extenders): self

/**
* Iterates over the conditions and applies the associated extenders if the conditions are met.
*
* @param Container $container
* @param Extension|null $extension
* @return void
*/
public function extend(Container $container, ?Extension $extension = null): void
{
Expand Down
2 changes: 0 additions & 2 deletions framework/core/src/Extend/Console.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class Console implements ExtenderInterface
* Add a command to the console.
*
* @param class-string<AbstractCommand|\Illuminate\Console\Command> $command: ::class attribute of command class, which must extend \Flarum\Console\AbstractCommand.
* @return self
*/
public function command(string $command): self
{
Expand All @@ -48,7 +47,6 @@ public function command(string $command): self
* for more information on available methods and what they do.
*
* @param array $args An array of args to call the command with.
* @return self
*/
public function schedule(string $command, callable|string $callback, array $args = []): self
{
Expand Down
3 changes: 0 additions & 3 deletions framework/core/src/Extend/Csrf.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ class Csrf implements ExtenderInterface

/**
* Exempt a named route from CSRF checks.
*
* @param string $routeName
* @return self
*/
public function exemptRoute(string $routeName): self
{
Expand Down
Loading