diff --git a/app/Http/Controllers/PostController.php b/app/Http/Controllers/PostController.php
index 022665d..625f10b 100644
--- a/app/Http/Controllers/PostController.php
+++ b/app/Http/Controllers/PostController.php
@@ -19,7 +19,11 @@ class PostController extends Controller
public function homePosts(Request $request)
{
$page = $request->integer('page', 1);
- $searchTerm = $request->get('s');
+
+ // Normalised here rather than inside the service so the value used for
+ // the query is the same one echoed back to the page.
+ $searchTerm = WpPostService::normaliseSearchTerm($request->get('s'));
+
$posts = WpPostService::getHomePosts($page, $searchTerm);
$highlightedPosts = WpPostService::getHighlightedPosts();
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 452e6b6..e23bb7b 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -2,6 +2,9 @@
namespace App\Providers;
+use Illuminate\Cache\RateLimiting\Limit;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
@@ -19,6 +22,12 @@ public function register(): void
*/
public function boot(): void
{
- //
+ // Only requests carrying ?s= are limited. Ordinary home page traffic,
+ // including pagination, is left alone.
+ RateLimiter::for('search', function (Request $request) {
+ return $request->filled('s')
+ ? Limit::perMinute(20)->by($request->ip())
+ : Limit::none();
+ });
}
}
diff --git a/app/Services/WpPostService.php b/app/Services/WpPostService.php
index 6e463f1..bc64c14 100644
--- a/app/Services/WpPostService.php
+++ b/app/Services/WpPostService.php
@@ -12,6 +12,33 @@ class WpPostService
public const DEFAULT_PER_PAGE_ON_LISTS = 10;
+ /**
+ * Shorter than this and a LIKE '%..%' scan matches most of the table while
+ * returning nothing useful.
+ */
+ public const MIN_SEARCH_LENGTH = 3;
+
+ public const MAX_SEARCH_LENGTH = 60;
+
+ /**
+ * Collapses a raw ?s= value into the form used both for querying and for
+ * the cache key, or null when it is not worth searching for.
+ *
+ * Without this, "Games", "games" and " games " are three cache entries for
+ * one result set, and every distinct string a crawler invents becomes a
+ * day-long entry of its own.
+ */
+ public static function normaliseSearchTerm(?string $term): ?string
+ {
+ $term = trim(preg_replace('/\s+/u', ' ', (string) $term));
+
+ if (mb_strlen($term) < self::MIN_SEARCH_LENGTH) {
+ return null;
+ }
+
+ return mb_strtolower(mb_substr($term, 0, self::MAX_SEARCH_LENGTH));
+ }
+
public static function getHighlightedPosts(): Collection
{
$cacheKey = 'highlighted_posts';
@@ -28,9 +55,15 @@ public static function getHighlightedPosts(): Collection
public static function getHomePosts(int $page, ?string $searchTerm = null): LengthAwarePaginator
{
+ $searchTerm = self::normaliseSearchTerm($searchTerm);
+
$searchTermHash = $searchTerm ? md5($searchTerm) : null;
$cacheKey = $searchTerm ? "search_{$searchTermHash}_posts_page_{$page}" : "home_posts_page_{$page}";
- $cacheTTL = now()->addDay();
+
+ // Search results are keyed by arbitrary visitor input, so they are kept
+ // for minutes rather than a day: the entries are unbounded in number
+ // and each one is only ever useful to whoever typed that exact term.
+ $cacheTTL = $searchTerm ? now()->addMinutes(5) : now()->addDay();
return cache()->remember($cacheKey, $cacheTTL, function () use ($searchTerm) {
return WpPost::query()
diff --git a/phpunit.xml b/phpunit.xml
index c09b5bc..61c031c 100644
--- a/phpunit.xml
+++ b/phpunit.xml
@@ -22,7 +22,8 @@
-
+
+
diff --git a/routes/web.php b/routes/web.php
index bb65cc6..45efab9 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -3,7 +3,9 @@
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
-Route::get('/', [PostController::class, 'homePosts'])->name('home.posts');
+Route::get('/', [PostController::class, 'homePosts'])
+ ->middleware('throttle:search')
+ ->name('home.posts');
Route::get('/politica-de-privacidade', [PostController::class, 'privacyPolicy'])->name('page.privacy-policy');
Route::get('/author/{author}', [PostController::class, 'authorPosts'])->name('author.posts');
Route::get('/category/{category}', [PostController::class, 'categoryPosts'])->name('category.posts');
diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php
deleted file mode 100644
index 1e2a000..0000000
--- a/tests/Feature/ExampleTest.php
+++ /dev/null
@@ -1,7 +0,0 @@
-get('/');
-
- $response->assertStatus(200);
-});
diff --git a/tests/Feature/RoutesTest.php b/tests/Feature/RoutesTest.php
new file mode 100644
index 0000000..a8c6210
--- /dev/null
+++ b/tests/Feature/RoutesTest.php
@@ -0,0 +1,140 @@
+author = Wp::user([
+ 'user_login' => 'mayron',
+ 'user_nicename' => 'mayron',
+ 'display_name' => 'Autor Um',
+ 'user_email' => 'autor@example.com',
+ ]);
+
+ $this->post = Wp::post([
+ 'post_author' => $this->author->ID,
+ 'post_title' => 'Primeiro post',
+ 'post_name' => 'primeiro-post',
+ 'post_date' => '2026-07-15 12:00:00',
+ ]);
+
+ Wp::categorise($this->post->ID, 'games');
+ Wp::categorise($this->post->ID, 'lancamentos', 'post_tag');
+ Wp::thumbnail($this->post->ID);
+});
+
+it('renders the home page', function () {
+ $this->get('/')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('Home')
+ ->has('posts.data', 1)
+ ->where('posts.data.0.title', 'Primeiro post')
+ );
+});
+
+it('excludes highlighted posts from the home listing', function () {
+ $highlighted = Wp::post(['post_title' => 'Em destaque', 'post_name' => 'em-destaque']);
+ Wp::categorise($highlighted->ID, 'destaques');
+
+ $this->get('/')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->has('posts.data', 1)
+ ->has('highlightedPosts.data', 1)
+ ->where('posts.data.0.title', 'Primeiro post')
+ ->where('highlightedPosts.data.0.title', 'Em destaque')
+ );
+});
+
+it('renders a single post', function () {
+ $this->get('/2026/07/primeiro-post')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('PostContent')
+ ->where('post.data.title', 'Primeiro post')
+ ->where('post.data.slug', 'primeiro-post')
+ );
+});
+
+it('returns 404 for an unknown post slug', function () {
+ $this->get('/2026/07/nao-existe')->assertNotFound();
+});
+
+it('renders the category listing', function () {
+ $this->get('/category/games')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('CategoryPosts')
+ ->has('posts.data', 1)
+ );
+});
+
+it('renders the tag listing', function () {
+ $this->get('/tag/lancamentos')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('TagPosts')
+ ->has('posts.data', 1)
+ );
+});
+
+it('renders the author listing', function () {
+ $this->get('/author/mayron')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('AuthorPosts')
+ ->has('posts.data', 1)
+ );
+});
+
+it('renders the year and month archive', function () {
+ $this->get('/2026/07')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('YearMonthPosts')
+ ->has('posts.data', 1)
+ );
+});
+
+it('renders the privacy policy page', function () {
+ Wp::post([
+ 'post_title' => 'Politica de Privacidade',
+ 'post_name' => 'politica-de-privacidade',
+ 'post_type' => 'page',
+ ]);
+
+ $this->get('/politica-de-privacidade')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->component('PrivacyPolicy')
+ ->where('page.data.title', 'Politica de Privacidade')
+ );
+});
+
+it('finds posts by search term', function () {
+ Wp::post(['post_title' => 'Outro assunto', 'post_name' => 'outro-assunto']);
+
+ $this->get('/?s=Primeiro')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ // normalised to lower case before querying and before being echoed
+ ->where('searchTerm', 'primeiro')
+ ->has('posts.data', 1)
+ ->where('posts.data.0.title', 'Primeiro post')
+ );
+});
+
+it('hides posts that are not published', function () {
+ Wp::post(['post_title' => 'Rascunho', 'post_name' => 'rascunho', 'post_status' => 'draft']);
+ Wp::post(['post_title' => 'Futuro', 'post_name' => 'futuro', 'post_date' => '2099-01-01 00:00:00']);
+
+ $this->get('/')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page->has('posts.data', 1));
+});
diff --git a/tests/Feature/SearchTest.php b/tests/Feature/SearchTest.php
new file mode 100644
index 0000000..c96f4b2
--- /dev/null
+++ b/tests/Feature/SearchTest.php
@@ -0,0 +1,81 @@
+ 'autor', 'user_nicename' => 'autor']);
+
+ foreach (['Guia de Linux', 'Analise de games', 'Noticia sobre hardware'] as $i => $title) {
+ $post = Wp::post([
+ 'post_title' => $title,
+ 'post_name' => 'post-'.($i + 1),
+ 'post_date' => '2026-07-0'.($i + 1).' 12:00:00',
+ ]);
+ Wp::categorise($post->ID, 'geral');
+ }
+});
+
+it('normalises whitespace and case', function (?string $input, ?string $expected) {
+ expect(WpPostService::normaliseSearchTerm($input))->toBe($expected);
+})->with([
+ ['Linux', 'linux'],
+ [' linux ', 'linux'],
+ ["linux\tmint", 'linux mint'],
+ ['LINUX MINT', 'linux mint'],
+ [null, null],
+ ['', null],
+ [' ', null],
+ // below MIN_SEARCH_LENGTH
+ ['ab', null],
+ [' a ', null],
+]);
+
+it('caps very long terms', function () {
+ $term = str_repeat('a', 200);
+
+ expect(mb_strlen(WpPostService::normaliseSearchTerm($term)))
+ ->toBe(WpPostService::MAX_SEARCH_LENGTH);
+});
+
+it('finds posts by term', function () {
+ $this->get('/?s=linux')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->where('searchTerm', 'linux')
+ ->has('posts.data', 1)
+ ->where('posts.data.0.title', 'Guia de Linux')
+ );
+});
+
+it('is case insensitive', function () {
+ $this->get('/?s=LINUX')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->where('searchTerm', 'linux')
+ ->has('posts.data', 1)
+ );
+});
+
+it('ignores terms that are too short, instead of scanning for them', function () {
+ // The page must behave as if no search was made: all posts, no term echoed.
+ $this->get('/?s=ab')
+ ->assertOk()
+ ->assertInertia(fn ($page) => $page
+ ->where('searchTerm', null)
+ ->has('posts.data', 3)
+ );
+});
+
+it('rate limits search requests but not ordinary traffic', function () {
+ // Plain home page requests are not limited.
+ for ($i = 0; $i < 25; $i++) {
+ $this->get('/')->assertOk();
+ }
+
+ for ($i = 0; $i < 20; $i++) {
+ $this->get('/?s=linux')->assertOk();
+ }
+
+ $this->get('/?s=linux')->assertStatus(429);
+});
diff --git a/tests/Pest.php b/tests/Pest.php
index 40d096b..3c76ee0 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -13,6 +13,17 @@
pest()->extend(Tests\TestCase::class)
->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
+ ->beforeEach(function () {
+ // The app reads an existing WordPress database, so there are no
+ // migrations for wp_* tables. Build them per test instead.
+ Tests\Support\WordPressSchema::create();
+
+ // Rendering the root Blade view resolves @vite, which needs a built
+ // manifest. Stub it so the suite does not depend on `npm run build`.
+ $this->withoutVite();
+
+ cache()->flush();
+ })
->in('Feature');
/*
diff --git a/tests/Support/WordPressSchema.php b/tests/Support/WordPressSchema.php
new file mode 100644
index 0000000..df23af6
--- /dev/null
+++ b/tests/Support/WordPressSchema.php
@@ -0,0 +1,104 @@
+ Drop order matters only for readability; sqlite has no FKs here.
+ */
+ private const TABLES = [
+ 'wp_posts',
+ 'wp_postmeta',
+ 'wp_users',
+ 'wp_usermeta',
+ 'wp_terms',
+ 'wp_term_taxonomy',
+ 'wp_term_relationships',
+ ];
+
+ public static function create(): void
+ {
+ self::drop();
+
+ Schema::create('wp_posts', function (Blueprint $table) {
+ $table->id('ID');
+ $table->unsignedBigInteger('post_author')->default(0);
+ $table->dateTime('post_date')->nullable();
+ $table->longText('post_content')->nullable();
+ $table->text('post_title')->nullable();
+ $table->text('post_excerpt')->nullable();
+ $table->string('post_status', 20)->default('publish');
+ $table->string('post_name', 200)->default('');
+ $table->string('post_type', 20)->default('post');
+ $table->string('guid', 255)->default('');
+ $table->integer('menu_order')->default(0);
+ $table->unsignedBigInteger('post_parent')->default(0);
+ });
+
+ Schema::create('wp_postmeta', function (Blueprint $table) {
+ $table->id('meta_id');
+ $table->unsignedBigInteger('post_id')->default(0);
+ $table->string('meta_key', 255)->nullable();
+ $table->longText('meta_value')->nullable();
+ });
+
+ Schema::create('wp_users', function (Blueprint $table) {
+ $table->id('ID');
+ $table->string('user_login', 60)->default('');
+ $table->string('user_pass', 255)->default('');
+ $table->string('user_nicename', 50)->default('');
+ $table->string('user_email', 100)->default('');
+ $table->string('display_name', 250)->default('');
+ });
+
+ Schema::create('wp_usermeta', function (Blueprint $table) {
+ $table->id('umeta_id');
+ $table->unsignedBigInteger('user_id')->default(0);
+ $table->string('meta_key', 255)->nullable();
+ $table->longText('meta_value')->nullable();
+ });
+
+ Schema::create('wp_terms', function (Blueprint $table) {
+ $table->id('term_id');
+ $table->string('name', 200)->default('');
+ $table->string('slug', 200)->default('');
+ });
+
+ Schema::create('wp_term_taxonomy', function (Blueprint $table) {
+ $table->id('term_taxonomy_id');
+ $table->unsignedBigInteger('term_id')->default(0);
+ $table->string('taxonomy', 32)->default('');
+ $table->longText('description')->nullable();
+ $table->unsignedBigInteger('parent')->default(0);
+ $table->bigInteger('count')->default(0);
+ });
+
+ Schema::create('wp_term_relationships', function (Blueprint $table) {
+ $table->unsignedBigInteger('object_id')->default(0);
+ $table->unsignedBigInteger('term_taxonomy_id')->default(0);
+ $table->integer('term_order')->default(0);
+ });
+ }
+
+ public static function drop(): void
+ {
+ foreach (self::TABLES as $table) {
+ Schema::dropIfExists($table);
+ }
+ }
+}
diff --git a/tests/Support/Wp.php b/tests/Support/Wp.php
new file mode 100644
index 0000000..9c29ebf
--- /dev/null
+++ b/tests/Support/Wp.php
@@ -0,0 +1,130 @@
+insertGetId(array_merge([
+ 'user_login' => 'autor',
+ 'user_pass' => '$P$Bexamplehashexamplehashexample',
+ 'user_nicename' => 'autor',
+ 'user_email' => 'autor@example.com',
+ 'display_name' => 'Autor de Teste',
+ ], $attributes), 'ID');
+
+ return WpUser::query()->findOrFail($id);
+ }
+
+ public static function post(array $attributes = []): WpPost
+ {
+ $id = DB::table('wp_posts')->insertGetId(array_merge([
+ 'post_author' => 1,
+ 'post_date' => '2026-07-15 12:00:00',
+ 'post_title' => 'Post de teste',
+ 'post_excerpt' => 'Resumo do post.',
+ 'post_content' => 'Conteudo do post.',
+ 'post_name' => 'post-de-teste',
+ 'post_status' => 'publish',
+ 'post_type' => 'post',
+ ], $attributes), 'ID');
+
+ return WpPost::withoutGlobalScopes()->findOrFail($id);
+ }
+
+ /**
+ * Creates a term in the given taxonomy and returns its term_taxonomy_id.
+ */
+ public static function term(string $slug, string $taxonomy = 'category', ?string $name = null): int
+ {
+ $termId = DB::table('wp_terms')->insertGetId([
+ 'name' => $name ?? ucfirst($slug),
+ 'slug' => $slug,
+ ], 'term_id');
+
+ return DB::table('wp_term_taxonomy')->insertGetId([
+ 'term_id' => $termId,
+ 'taxonomy' => $taxonomy,
+ ], 'term_taxonomy_id');
+ }
+
+ public static function attach(int $postId, int $termTaxonomyId): void
+ {
+ DB::table('wp_term_relationships')->insert([
+ 'object_id' => $postId,
+ 'term_taxonomy_id' => $termTaxonomyId,
+ ]);
+ }
+
+ /**
+ * Convenience: create the term if needed and attach it in one call.
+ */
+ public static function categorise(int $postId, string $slug, string $taxonomy = 'category'): int
+ {
+ $ttId = DB::table('wp_term_taxonomy')
+ ->join('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
+ ->where('wp_terms.slug', $slug)
+ ->where('wp_term_taxonomy.taxonomy', $taxonomy)
+ ->value('wp_term_taxonomy.term_taxonomy_id');
+
+ $ttId ??= self::term($slug, $taxonomy);
+
+ self::attach($postId, $ttId);
+
+ return $ttId;
+ }
+
+ /**
+ * Attaches a featured image: an attachment post plus the _thumbnail_id meta
+ * that WpPost::getThumbnail() resolves.
+ */
+ public static function thumbnail(int $postId, string $url = 'https://example.com/capa.jpg'): int
+ {
+ $attachmentId = DB::table('wp_posts')->insertGetId([
+ 'post_title' => 'capa',
+ 'post_name' => 'capa',
+ 'post_type' => 'attachment',
+ 'post_status' => 'inherit',
+ 'post_date' => '2026-07-15 12:00:00',
+ 'guid' => $url,
+ ], 'ID');
+
+ DB::table('wp_postmeta')->insert([
+ 'post_id' => $postId,
+ 'meta_key' => '_thumbnail_id',
+ 'meta_value' => (string) $attachmentId,
+ ]);
+
+ return $attachmentId;
+ }
+
+ public static function postMeta(int $postId, string $key, string $value): void
+ {
+ DB::table('wp_postmeta')->insert([
+ 'post_id' => $postId,
+ 'meta_key' => $key,
+ 'meta_value' => $value,
+ ]);
+ }
+
+ public static function userMeta(int $userId, string $key, string $value): void
+ {
+ DB::table('wp_usermeta')->insert([
+ 'user_id' => $userId,
+ 'meta_key' => $key,
+ 'meta_value' => $value,
+ ]);
+ }
+}