fix(posts): return empty Eloquent collection for posts without category - #2
Open
Guajir0-code wants to merge 2 commits into
Open
fix(posts): return empty Eloquent collection for posts without category#2Guajir0-code wants to merge 2 commits into
Guajir0-code wants to merge 2 commits into
Conversation
getRelatedPosts() declares Eloquent\Collection but returned collect(), which builds a Support\Collection. Support\Collection is not a subclass of Eloquent\Collection, so any post whose category lookup comes back empty raises a TypeError and the post page answers 500. Return an empty Eloquent\Collection instead. Covered by a regression test that reproduces the TypeError against the previous code. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Same data condition as the server-side fix: PostCard and PostContentCover indexed categories[0] unconditionally, so a post with an empty categories array threw at render time on the client. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problema
Um post cuja busca de categoria não retorna nada derruba a própria página com HTTP 500. Não é degradação — a página não abre.
Evidência
Reproduzido localmente com o teste incluído neste PR, rodando contra o código atual:
O
PostController::show()chamagetRelatedPosts()no caminho de render da página do post, então o erro sobe direto para a resposta.Causa
app/Services/WpPostService.php:111declara o retorno comoEloquent\Collection(ouseno topo do arquivo aponta paraIlluminate\Database\Eloquent\Collection):Mas o caminho de saída antecipada devolve outra coisa:
O helper
collect()constrói umSupport\Collection. A hierarquia éEloquent\Collection extends Support\Collection— nunca o contrário. Então o valor devolvido não satisfaz o tipo declarado e o PHP lançaTypeError.Quando isso acontece na prática
$categorySlugvem de:Fica nulo sempre que o post não tem nenhum termo da taxonomia
category. O WordPress normalmente atribui "Sem categoria" por padrão, o que torna o caso raro — mas ele aparece em posts importados de outra instalação, migrados entre taxonomias, ou que tiveram a categoria removida direto no banco. E quando aparece, o resultado é a página inteira fora do ar.Solução
Collectionaqui já é oEloquent\Collectionimportado no topo do arquivo — nenhumusenovo foi necessário. O comentário fica no código porquecollect()é o reflexo natural de quem estiver editando esse trecho depois.Como validar
Verificado nos dois sentidos — contra o código anterior, o primeiro teste falha exatamente com o
TypeErrordescrito acima:O segundo teste existe para garantir que o caminho normal (post com categoria) continua devolvendo os posts relacionados e excluindo o próprio post da lista — ou seja, que a correção não trocou um bug por outro.
Impacto
Nota sobre
phpunit.xmlContém a mesma alteração de duas linhas do PR #1 (fixar
sqlite/:memory:), porque sem ela a suíte não inicia e o teste deste PR não roda:As duas branches saíram de
main, então a mudança aparece nos dois PRs. Se o PR #1 for mesclado primeiro, esta parte vira no-op — o conteúdo é idêntico, então não deve gerar conflito.A outra metade: o mesmo dado quebra o front
O segundo commit blinda a mesma condição no cliente.
PostCard.vueePostContentCover.vueindexavamcategories[0]sem verificar se o array tem elementos:<Link + v-if="post.categories?.length" :href="'/category/' + post.categories[0].slug"Sem isso, corrigir só o servidor trocaria um 500 por um erro de render no navegador para exatamente os mesmos posts. O selo de categoria simplesmente não aparece quando não há categoria.
Fora de escopo
getRelatedPostsroda duas queries por post sem cache quente e a relaçãotermsnão é eager-loaded em lugar nenhum. É problema de performance, tratado no PR dedicado a N+1.beforeEachsão o recorte mínimo do schema que este método toca. Um conjunto reutilizável vem no PR de infraestrutura de testes.