Skip to content

Commit

Permalink
add option to index specific keys for a model (#19)
Browse files Browse the repository at this point in the history
* add option to index specific keys for a model

* remove

* ignore vscode
  • Loading branch information
cleanSumo committed Jun 17, 2024
1 parent f55f143 commit cb1778d
Show file tree
Hide file tree
Showing 9 changed files with 207 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ node_modules
.php-cs-fixer.cache
pnpm-lock.yaml
.phpunit.cache
.vscode
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('search_terms', function (Blueprint $table) {
$table->id();
$table->morphs('model');
$table->string('locale')->default('sv');
$table->string('path')->nullable();
$table->text('search_string')->nullable();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('search_terms');
}
};
11 changes: 8 additions & 3 deletions src/Concerns/HasPaths.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,15 @@ public function getPathsAttribute(): Collection
return;
}

return $carry.'/'.$subItem->getSlugString($locale);
return $carry.'/'.$subItem->getSlugString($locale);
}, '').'/'.$item->getSlugString($locale);
})->unique();
$slugGroups->push([$locale => $localizedSlugs]);

if (! $localizedSlugs->count()) {
$slugGroups->push([$locale => $this->slugs->where('locale', $locale)->pluck('slug')]);
} else {
$slugGroups->push([$locale => $localizedSlugs]);
}
}

return $slugGroups;
Expand All @@ -109,7 +114,7 @@ public function getLocalizedPathsAttribute(): Collection
return;
}

return $carry.'/'.$subItem->getSlugString();
return $carry.'/'.$subItem->getSlugString();
}, '').'/'.$item->getSlugString();
})->unique();
$slugGroups->push($localizedSlugs);
Expand Down
2 changes: 2 additions & 0 deletions src/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Ikoncept\Fabriq\Listeners\BustPageCacheListener;
use Ikoncept\Fabriq\Listeners\CallCacheBustingWebhook;
use Ikoncept\Fabriq\Listeners\FlushTagCacheListener;
use Ikoncept\Fabriq\Listeners\UpdateSearchTerms;
use Ikoncept\Fabriq\Listeners\UpdateSlugListener;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
Expand All @@ -27,6 +28,7 @@ class EventServiceProvider extends ServiceProvider
DefinitionsPublished::class => [
BustPageCacheListener::class,
CallCacheBustingWebhook::class,
UpdateSearchTerms::class,
],
TranslatedRevisionDeleted::class => [
FlushTagCacheListener::class,
Expand Down
65 changes: 65 additions & 0 deletions src/Listeners/UpdateSearchTerms.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace Ikoncept\Fabriq\Listeners;

use Ikoncept\Fabriq\Models\SearchTerm;
use Illuminate\Support\Collection;
use Infab\TranslatableRevisions\Events\DefinitionsPublished;

class UpdateSearchTerms
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{

}

/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(DefinitionsPublished $event)

Check failure on line 27 in src/Listeners/UpdateSearchTerms.php

View workflow job for this annotation

GitHub Actions / Laravel (PHP 8.3 on ubuntu-latest)

PHPDoc tag @param for parameter $event with type object is not subtype of native type Infab\TranslatableRevisions\Events\DefinitionsPublished.
{
if (! $event->model->getRevisionOptions()->isIndexable) {
return;
}

$event->model->paths->each(function ($path) use ($event) {
$locale = collect($path)->keys()->first();

Check failure on line 34 in src/Listeners/UpdateSearchTerms.php

View workflow job for this annotation

GitHub Actions / Laravel (PHP 8.3 on ubuntu-latest)

Unable to resolve the template type TKey in call to function collect

Check failure on line 34 in src/Listeners/UpdateSearchTerms.php

View workflow job for this annotation

GitHub Actions / Laravel (PHP 8.3 on ubuntu-latest)

Unable to resolve the template type TValue in call to function collect

$indexableKeys = $this->array_value_recursive($event->definitions[$locale], $event->model->getRevisionOptions()->indexableKeys);

$data = [
'model_id' => $event->model->id,
'model_type' => get_class($event->model),
'locale' => $locale,
'path' => collect($path)->flatten()->first(),

Check failure on line 42 in src/Listeners/UpdateSearchTerms.php

View workflow job for this annotation

GitHub Actions / Laravel (PHP 8.3 on ubuntu-latest)

Unable to resolve the template type TKey in call to function collect

Check failure on line 42 in src/Listeners/UpdateSearchTerms.php

View workflow job for this annotation

GitHub Actions / Laravel (PHP 8.3 on ubuntu-latest)

Unable to resolve the template type TValue in call to function collect
'search_string' => implode(' ', $indexableKeys),
];

SearchTerm::updateOrCreate([
'model_id' => $data['model_id'],
'model_type' => $data['model_type'],
'locale' => $data['locale'],
], $data);
});
}

protected function array_value_recursive(Collection $collection, ?array $keys = null, bool $unique = true): array
{
$arr = $collection->toArray();
array_walk_recursive($arr, function ($v, $k) use ($keys, &$val) {
if (in_array($k, $keys)) {
$val[] = strip_tags($v);
}
});

return $unique ? array_unique($val ?? []) : $val ?? [];
}
}
3 changes: 2 additions & 1 deletion src/Models/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ public function getRevisionOptions(): RevisionOptions
'buttons' => 'getButtons',
'smartBlock' => 'getSmartBlock',
])
->registerCacheTagsToFlush(['fabriq_menu', 'fabriq_pages|slug']);
->registerCacheTagsToFlush(['fabriq_menu', 'fabriq_pages|slug'])
->setIndexable(true, ['page_title', 'header']);
}

/**
Expand Down
13 changes: 13 additions & 0 deletions src/Models/SearchTerm.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Ikoncept\Fabriq\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SearchTerm extends Model
{
use HasFactory;

protected $guarded = [];
}
2 changes: 1 addition & 1 deletion tests/AdminUserTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ protected function getEnvironmentSetUp($app)
'port' => env('DB_PORT', '3306'),
'database' => 'fabriq_testing',
'username' => 'root',
'password' => 'password',
'password' => '',
]);
$app['config']->set('filesystems.disks.__test', [
'driver' => 'local',
Expand Down
82 changes: 82 additions & 0 deletions tests/SearchTermsFeatureTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace Tests\Feature;

use Ikoncept\Fabriq\Database\Seeders\DatabaseSeeder;
use Ikoncept\Fabriq\Database\Seeders\PageTemplateSeeder;
use Ikoncept\Fabriq\Tests\AdminUserTestCase;
use Infab\TranslatableRevisions\Models\RevisionTemplate;

class SearchTermsFeatureTest extends AdminUserTestCase
{
public function setUp(): void
{
parent::setUp();

app(DatabaseSeeder::class)->call(PageTemplateSeeder::class);
}

public function test_it_can_include_content_for_a_single_page()
{
// Arrange
$page = \Ikoncept\Fabriq\Models\Page::factory()->create([
'name' => 'En sida som ska publiceras',
'template_id' => RevisionTemplate::all()->first()->id,
'revision' => 1,
]);

$page->updateContent([
'page_title' => 'The page title for the page',
'page_header' => 'The page title for the page',
'page_content' => '<h1>Wow, a header</h1><p>Ok lets see</p>',
'meta_title' => 'Meta title',
'meta_description' => 'Describing the page',
'meta_og_image' => 'https://placehold.it/40',
'boxes' => [
['header' => 'EN Box 1 title!', 'url' => 'https://google.com'],
['header' => 'EN Box 2 title!', 'url' => 'https://bog.com'],
['header' => 'EN Box 3 title!', 'url' => 'http://flank.se'],
],
], 'en');
$page->updateContent([
'page_title' => 'En siee saom skau paublisers',
'page_header' => 'En siee saom skau paublisers',
'page_content' => '<h1>Wow</h1><p>Da ska vi se...</p>',
'meta_title' => 'Meta titel',
'meta_description' => 'En forklaring av sidan',
'meta_og_image' => 'https://placehold.it/40',
'boxes' => [
['header' => 'DK fosta titeln!', 'url' => 'https://google.com'],
['header' => 'DK andra titeln!', 'url' => 'https://bog.com'],
],
], 'dk');

// Act
$response = $this->json('POST', "/pages/{$page->id}/publish");

// Assert
$this->assertDatabaseHas('pages', [
'id' => $page->id,
'revision' => 2,
'published_version' => 1,
]);

$this->assertDatabaseHas('search_terms', [
'model_id' => $page->id,
'model_type' => config('fabriq.models.page'),
'locale' => 'dk',
'path' => 'en-siee-saom-skau-paublisers',
'search_string' => 'DK fosta titeln! DK andra titeln! En siee saom skau paublisers',
]);

$this->assertDatabaseHas('search_terms', [
'model_id' => $page->id,
'model_type' => config('fabriq.models.page'),
'locale' => 'en',
'path' => 'the-page-title-for-the-page',
'search_string' => 'EN Box 1 title! EN Box 2 title! EN Box 3 title! The page title for the page',
]);

$this->assertDatabaseCount('search_terms', 3);
}
}

0 comments on commit cb1778d

Please sign in to comment.