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

Fix: Accessor caching #633

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions app/Models/Question.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,21 @@ public static function incrementViews(array $ids): void
*/
public function getContentAttribute(?string $value): ?string
{
$content = new ParsableContent();

return $value !== null && $value !== '' && $value !== '0' ? $content->parse($value) : null;
return $this->runParser(
attribute: 'content',
value: $value,
);
}

/**
* The attributes that should be cast.
*/
public function getAnswerAttribute(?string $value): ?string
{
$content = new ParsableContent();

return $value !== null && $value !== '' && $value !== '0' ? $content->parse($value) : null;
return $this->runParser(
attribute: 'answer',
value: $value,
);
}

/**
Expand Down Expand Up @@ -220,4 +222,22 @@ public function hashtags(): BelongsToMany
{
return $this->belongsToMany(Hashtag::class);
}

/**
* Run the parser for the given attribute and value.
*/
private function runParser(string $attribute, ?string $value): ?string
{
$key = "question.{$this->id}.{$attribute}.parsed";

if (ParsableContent::has($key) && $this->isDirty($attribute)) {
ParsableContent::flush($key);
}

if ($value !== null && $value !== '' && $value !== '0') {
return ParsableContent::parse($key, $value);
}

return null;
}
}
26 changes: 26 additions & 0 deletions app/Providers/ParsableContentServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Services\ParsableContent;
use Illuminate\Support\ServiceProvider;

final class ParsableContentServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*/
public function register(): void {}

/**
* Boot the service provider.
*/
public function boot(): void
{
$this->app->terminating(static function (): void {
ParsableContent::flush(all: true);
});
}
}
65 changes: 62 additions & 3 deletions app/Services/ParsableContent.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,21 @@
use App\Services\ParsableContentProviders\MentionProviderParsable;
use App\Services\ParsableContentProviders\StripProviderParsable;

final readonly class ParsableContent
final class ParsableContent
{
/**
* The cache of parsed content.
*
* @var array<string, string>
*/
private static array $cache = [];

/**
* Creates a new parsable content instance.
*
* @param array<int, class-string<ParsableContentProvider>> $providers
*/
public function __construct(private array $providers = [
public function __construct(private readonly array $providers = [
StripProviderParsable::class,
CodeProviderParsable::class,
ImageProviderParsable::class,
Expand All @@ -33,10 +40,62 @@ public function __construct(private array $providers = [
//
}

/**
* Flushes the cache for the given content.
*/
public static function flush(?string $key = null, ?bool $all = null): void
{
if ($key === null && $all === true) {
self::$cache = [];

return;
}

unset(self::$cache[$key]);
}

/**
* Parses the given content.
*/
public function parse(string $content): string
public static function parse(string $key, string $content): ?string
{
if (self::has($key)) {
return self::get($key);
}

return self::$cache[$key] = (new self())->parseContent($content);
}

/**
* Checks if the cache has the given key.
*/
public static function has(string $key): bool
{
return isset(self::$cache[$key]);
}

/**
* Gets the cache for the given key.
*/
public static function get(string $key): ?string
{
return self::$cache[$key] ?? null;
}

/**
* Gets the providers.
*
* @return array<int, class-string<ParsableContentProvider>>
*/
public function getProviders(): array
CamKem marked this conversation as resolved.
Show resolved Hide resolved
{
return $this->providers;
}

/**
* Parses the content using the providers.
*/
public function parseContent(string $content): string
{
return (string) collect($this->providers)
->reduce(function (string $parsed, string $provider): string {
Expand Down
1 change: 1 addition & 0 deletions bootstrap/providers.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@
App\Providers\FortifyServiceProvider::class,
App\Providers\GitHubServiceProvider::class,
App\Providers\PulseServiceProvider::class,
App\Providers\ParsableContentServiceProvider::class,
];
1 change: 1 addition & 0 deletions tests/ArchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
'App\Providers',
'App\View',
App\Services\Autocomplete::class,
App\Services\ParsableContent::class,
]);

arch('avoid inheritance')
Expand Down
51 changes: 51 additions & 0 deletions tests/Unit/Models/QuestionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use App\Models\Like;
use App\Models\Question;
use App\Models\User;
use App\Services\ParsableContent;

test('to array', function () {
$question = Question::factory()->create()->fresh();
Expand Down Expand Up @@ -108,3 +109,53 @@

expect($question->fresh()->views)->toBe(0);
});

test('caches the parsed answer', function () {
$question = Question::factory()->create([
'answer' => 'Hello',
]);

$contextKey = "question.{$question->id}.answer.parsed";

expect(ParsableContent::has($contextKey))->toBeTrue()
->and(ParsableContent::parse($contextKey, $question->answer))->toBe($question->answer);
});

test('re-caches the parsed answer when the answer is updated', function () {
$question = Question::factory()->create([
'answer' => 'Hello',
]);

$contextKey = "question.{$question->id}.answer.parsed";

$question->answer = 'Hi';
$question->save();

expect(ParsableContent::has($contextKey))->toBeTrue()
->and(ParsableContent::get($contextKey))->toBe('Hi');
});

test('caches the parsed content', function () {
$question = Question::factory()->create([
'content' => 'Hello',
]);

$contextKey = "question.{$question->id}.content.parsed";

expect(ParsableContent::has($contextKey))->toBeTrue()
->and(ParsableContent::parse($contextKey, $question->content))->toBe($question->content);
});

test('re-caches the parsed content when the content is updated', function () {
$question = Question::factory()->create([
'content' => 'Hello',
]);

$contextKey = "question.{$question->id}.content.parsed";

$question->content = 'Hi';
$question->save();

expect(ParsableContent::has($contextKey))->toBeTrue()
->and(ParsableContent::get($contextKey))->toBe('Hi');
});
88 changes: 88 additions & 0 deletions tests/Unit/Services/ParsableContentTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

declare(strict_types=1);

use App\Services\ParsableContent;
use App\Services\ParsableContentProviders\BrProviderParsable;
use App\Services\ParsableContentProviders\CodeProviderParsable;
use App\Services\ParsableContentProviders\HashtagProviderParsable;
use App\Services\ParsableContentProviders\ImageProviderParsable;
use App\Services\ParsableContentProviders\LinkProviderParsable;
use App\Services\ParsableContentProviders\MentionProviderParsable;
use App\Services\ParsableContentProviders\StripProviderParsable;

covers(ParsableContent::class);
CamKem marked this conversation as resolved.
Show resolved Hide resolved

test('link', function () {
$content = 'Sure, here is the link: https://example.com. Let me know if you have any questions.';

$provider = new ParsableContent();

expect($provider->parseContent($content))->toBe('Sure, here is the link: <a data-navigate-ignore="true" class="text-blue-500 hover:underline hover:text-blue-700 cursor-pointer" target="_blank" href="https://example.com">example.com</a>. Let me know if you have any questions.');
});

test('mention', function () {
$content = '@nunomaduro, let me know if you have any questions. Thanks @xiCO2k.';

$provider = new ParsableContent();

expect($provider->parseContent($content))->toBe('<a href="/@nunomaduro" data-navigate-ignore="true" class="text-blue-500 hover:underline hover:text-blue-700 cursor-pointer" wire-navigate>@nunomaduro</a>, let me know if you have any questions. Thanks <a href="/@xiCO2k" data-navigate-ignore="true" class="text-blue-500 hover:underline hover:text-blue-700 cursor-pointer" wire-navigate>@xiCO2k</a>.');
});

it('ignores mention inside <a>', function () {
$content = 'https://pinkary.com/@nunomaduro';

$provider = new ParsableContent();

expect($provider->parseContent($content))->toBe('<a data-navigate-ignore="true" class="text-blue-500 hover:underline hover:text-blue-700 cursor-pointer" target="_blank" href="https://pinkary.com/@nunomaduro">pinkary.com/@nunomaduro</a>');
});

it('has all the parsable providers in array', function () {
$provider = new ParsableContent();

expect($provider->getProviders())->toBe([
StripProviderParsable::class,
CodeProviderParsable::class,
ImageProviderParsable::class,
BrProviderParsable::class,
LinkProviderParsable::class,
MentionProviderParsable::class,
HashtagProviderParsable::class,
]);
});

it('can flush all the cache when the application is terminating', function () {
$provider = new ParsableContent();

$provider::parse('key', 'content');
$provider::parse('key2', 'content2');

expect($provider::has('key'))->toBeTrue()
->and($provider::has('key2'))->toBeTrue();

$provider::flush(all: true);

expect($provider::has('key'))->toBeFalse()
->and($provider::has('key2'))->toBeFalse();
});

it('can flush the cache for the given key', function () {
$provider = new ParsableContent();

$provider::parse('key', 'content');
$provider::parse('key2', 'content2');

expect($provider::has('key'))->toBeTrue()
->and($provider::has('key2'))->toBeTrue();

$provider::flush('key');

expect($provider::has('key'))->toBeFalse()
->and($provider::has('key2'))->toBeTrue();
});

it('can parse the content', function () {
$provider = new ParsableContent();

expect($provider::parse('key', 'content'))->toBe('content');
});