Skip to content

Commit

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

* remove

* ignore vscode

* add title to search terms

* refactor search terms implementation

* fix phpstan

* revert settings

---------

Co-authored-by: Albin N <[email protected]>
  • Loading branch information
cleanSumo and nivv authored Jun 19, 2024
1 parent cb1778d commit 39fd896
Show file tree
Hide file tree
Showing 9 changed files with 117 additions and 44 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

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

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('search_terms', function (Blueprint $table) {
$table->string('title')->after('locale')->nullable();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('search_terms', function (Blueprint $table) {
$table->dropColumn('title');
});
}
};
5 changes: 4 additions & 1 deletion src/Actions/BustCacheWithWebhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@

class BustCacheWithWebhook
{
public function handle(array $keysToForget, array $tagsToFlush = [])
public function handle(array $keysToForget, array $tagsToFlush = []): void
{
if (! config('fabriq.webhooks.enabled')) {
return;
}
// 1 per 5 seconds for the same key
RateLimiter::attempt(
key: hash('adler32', json_encode([$keysToForget, $tagsToFlush])),
Expand Down
43 changes: 26 additions & 17 deletions src/Concerns/HasPaths.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function getAbsolutePath($path): string
{
return config('fabriq.front_end_domain')
.$this->currentLocaleString()
.($path ?? '/'.$this->latestSlug->slug);
.$path;
}

public function getPermalinkPath(): string
Expand Down Expand Up @@ -74,30 +74,39 @@ public function getPathsAttribute(): Collection

$supportedLocales = Fabriq::getModelClass('locale')->cachedLocales();

foreach ($supportedLocales as $locale => $item) {
$localizedSlugs = $this->menuItems->map(function ($item) use ($locale) {
if (! $item->ancestors->count()) {
return '';
}

return collect($item->ancestors)->reduce(function ($carry, $subItem) use ($locale) {
/** @var MenuItem $subItem * */
if (! $subItem->page) {
return;
if ($this->menuItems !== null && $this->menuItems->count()) {
foreach ($supportedLocales as $locale => $item) {
$localizedSlugs = $this->menuItems->map(function ($item) use ($locale) {
if (! $item->ancestors->count()) {
return '';
}

return $carry.'/'.$subItem->getSlugString($locale);
}, '').'/'.$item->getSlugString($locale);
})->unique();
return collect($item->ancestors)->reduce(function ($carry, $subItem) use ($locale) {
/** @var MenuItem $subItem * */
if (! $subItem->page) {
return;
}

return $carry.'/'.$subItem->getSlugString($locale);
}, '').'/'.$item->getSlugString($locale);
})->unique();

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

return $slugGroups;
}

foreach ($supportedLocales as $locale) {
$slugGroups->push([
$locale => $this->slugs->where('locale', $locale)->pluck('slug')->map(function ($item) {
return '/'.$item;
}),
]);
}

return $slugGroups;

}

public function getLocalizedPathsAttribute(): Collection
Expand Down
1 change: 1 addition & 0 deletions src/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class EventServiceProvider extends ServiceProvider
DefinitionsUpdated::class => [
UpdateSlugListener::class,
CallCacheBustingWebhook::class,
UpdateSearchTerms::class,
],
DefinitionsPublished::class => [
BustPageCacheListener::class,
Expand Down
20 changes: 20 additions & 0 deletions src/Helpers/RecursiveArrayValues.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Ikoncept\Fabriq\Helpers;

use Illuminate\Support\Collection;

class RecursiveArrayValues
{
public static function fromCollection(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 ?? [];
}
}
57 changes: 34 additions & 23 deletions src/Listeners/UpdateSearchTerms.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Ikoncept\Fabriq\Listeners;

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

class UpdateSearchTerms
{
Expand All @@ -13,34 +15,55 @@ class UpdateSearchTerms
*
* @return void
*/
public function __construct()
{

}
public function __construct() {}

/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(DefinitionsPublished $event)
public function handle(DefinitionsUpdated|DefinitionsPublished $event)
{
if (! $event->model->getRevisionOptions()->isIndexable) {
$options = $event->model->getRevisionOptions();

if (! $options->isIndexable) {
return;
}

$event->model->paths->each(function ($path) use ($event) {
if ($options->indexFunction) {
call_user_func_array($options->indexFunction, [
'args' => [
'definitions' => $event->definitions,
],
]);

return;
}

if (get_class($event) === DefinitionsUpdated::class && Fabriq::getFqnModel('page') === get_class($event->model)) {

return;
}

$event->model->paths->each(function ($path) use ($event, $options) {

/** @var array<string, string> $path */
$locale = collect($path)->keys()->first();

$indexableKeys = $this->array_value_recursive($event->definitions[$locale], $event->model->getRevisionOptions()->indexableKeys);
if (! isset($event->definitions[$locale][$options->titleKey])) {
return;
}

$indexedKeys = RecursiveArrayValues::fromCollection($event->definitions[$locale], $options->indexableKeys);
$title = $event->definitions[$locale][$options->titleKey];

$data = [
'model_id' => $event->model->id,
'model_type' => get_class($event->model),
'title' => $title,
'locale' => $locale,
'path' => collect($path)->flatten()->first(),
'search_string' => implode(' ', $indexableKeys),
'search_string' => implode(' ', $indexedKeys),
];

SearchTerm::updateOrCreate([
Expand All @@ -50,16 +73,4 @@ public function handle(DefinitionsPublished $event)
], $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 ?? [];
}
}
2 changes: 1 addition & 1 deletion src/Models/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public function getRevisionOptions(): RevisionOptions
'smartBlock' => 'getSmartBlock',
])
->registerCacheTagsToFlush(['fabriq_menu', 'fabriq_pages|slug'])
->setIndexable(true, ['page_title', 'header']);
->setIndexable(indexable: true, indexableKeys: ['page_title', 'header'], titleKey: 'page_title');
}

/**
Expand Down
1 change: 1 addition & 0 deletions tests/AdminUserTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public function setUpDatabase($app)

protected function getEnvironmentSetUp($app)
{
$app['config']->set('fabriq.webhooks.enabled', false);
$app['config']->set('database.default', 'mysql');
$app['config']->set('database.connections.mysql', [
'driver' => 'mysql',
Expand Down
4 changes: 2 additions & 2 deletions tests/SearchTermsFeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ public function test_it_can_include_content_for_a_single_page()
'model_id' => $page->id,
'model_type' => config('fabriq.models.page'),
'locale' => 'dk',
'path' => 'en-siee-saom-skau-paublisers',
'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',
'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',
]);

Expand Down

0 comments on commit 39fd896

Please sign in to comment.