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

Invalid code in DiscussionBestAnswerPage, condition always true #101

Open
clarkwinkelmann opened this issue Nov 7, 2024 · 0 comments · May be fixed by #102
Open

Invalid code in DiscussionBestAnswerPage, condition always true #101

clarkwinkelmann opened this issue Nov 7, 2024 · 0 comments · May be fixed by #102

Comments

@clarkwinkelmann
Copy link

I was looking at the source code after seeing something odd in the screenshot shared by a user on the forum https://discuss.flarum.org/d/18316-flarum-seo/604

"name" => $discussion->user() ? $discussion->user()->first()->getDisplayNameAttribute() : null

$discussion->user() ? $discussion->user()->first()->getDisplayNameAttribute() : null is valid code but doesn't do what is intended. $discussion->user() will always return true because it returns the Eloquent relationship definition object.

There's actually a similar bit of code a few lines below that uses the proper approach:

"name" => $post->user ? $post->user->display_name : null

In the same file I see some more strange code but it shouldn't be causing any logic error by itself:

if ($discussion->tags()->count() >= 1) {
$tags = $discussion->tags()->get()->all();

causes 2 SQL requests to be made, and I don't know where this code is called from, but the relationship might already be loaded, resulting in 3 total requests for this. Using $discussion->tags directly would re-use the already cached results. If it's known that they are not loaded, then there can be an argument for 2 requests if you want to minimize the memory and transfer size but I'm sure response time would still be better with just one request. In any case ->tags()->get() can be replaced with ->tags.

Code can also be inlined ->generateSchemaBreadcrumb($discussion->tags->map(function() {})->all()) 🙉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant