Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
faizansf committed Jan 14, 2024
2 parents b19897b + 80e7af7 commit 88ce7f7
Show file tree
Hide file tree
Showing 12 changed files with 29 additions and 63 deletions.
2 changes: 1 addition & 1 deletion config/metafields.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@
'cache_ttl' => null,

// The prefix used for cache keys when storing individual meta field values.
'cache_key_prefix' => "LaravelMetafields",
'cache_key_prefix' => 'LaravelMetafields',
];
4 changes: 1 addition & 3 deletions src/Exceptions/InvalidKeyException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
namespace FaizanSf\LaravelMetafields\Exceptions;

use Exception;
use InvalidArgumentException;

class InvalidKeyException extends Exception
{
public static function withMessage(mixed $key): self
{
return new self(
'Expected key to be string or string backed Enum Got' . gettype($key)
'Expected key to be string or string backed Enum Got'.gettype($key)
);
}

}
3 changes: 1 addition & 2 deletions src/Exceptions/MetafieldNotFoundException.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ class MetafieldNotFoundException extends Exception
public static function withMessage(mixed $key): self
{
return new self(
'Metafield Not found having key ' . $key
'Metafield Not found having key '.$key
);
}

}
1 change: 0 additions & 1 deletion src/Facades/LaravelMetafields.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
*/
class LaravelMetafields extends Facade
{

protected static function getFacadeAccessor(): string
{
return \FaizanSf\LaravelMetafields\LaravelMetafields::class;
Expand Down
37 changes: 12 additions & 25 deletions src/LaravelMetafields.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

declare(strict_types=1);


namespace FaizanSf\LaravelMetafields;

use BackedEnum;
Expand All @@ -12,7 +11,6 @@
use FaizanSf\LaravelMetafields\Utils\CacheContext;
use Illuminate\Support\Facades\Cache;


class LaravelMetafields
{
protected bool $withCache = true;
Expand All @@ -32,16 +30,17 @@ public function withOutCache(): self
/**
* Normalizes the given key into a string.
*
* @param string|BackedEnum $key The key to normalize. Can be either a string or a BackedEnum instance.
* @param string|BackedEnum $key The key to normalize. Can be either a string or a BackedEnum instance.
* @return string The normalized key as a string.
*
* @throws InvalidKeyException If the key is a BackedEnum instance and its value is not a string.
*/
public function normalizeKey(string|BackedEnum $key): string
{
if ($key instanceof BackedEnum) {
$value = $key->value;

if (!is_string($value)) {
if (! is_string($value)) {
throw InvalidKeyException::withMessage(key: $value);
}

Expand All @@ -54,24 +53,21 @@ public function normalizeKey(string|BackedEnum $key): string
/**
* Clears the cache for the given model and the given key.
*
* @param Metafieldable $model The model for which to clear the cache.
* @param string $key The key for which to clear the cache.
* @param Metafieldable $model The model for which to clear the cache.
* @param string $key The key for which to clear the cache.
*/
public function clearCache(Metafieldable $model, string|null $key = null): void
public function clearCache(Metafieldable $model, ?string $key = null): void
{
Cache::forget($this->getCacheKey($model, $key));
}


/**
* Executes the given closure and caches its result for the given time if cache is enabled.
*
* @param CacheContext $cacheContext
* @param $cacheKey
* @param Closure $callback The closure to execute.
* @param Closure $callback The closure to execute.
* @return mixed The result of the executed closure.
*/
public function runCachedOrDirect(CacheContext $cacheContext, $cacheKey, Closure $callback,): mixed
public function runCachedOrDirect(CacheContext $cacheContext, $cacheKey, Closure $callback): mixed
{
if ($this->canUseCache($cacheContext)) {
return Cache::remember(
Expand All @@ -89,41 +85,32 @@ public function runCachedOrDirect(CacheContext $cacheContext, $cacheKey, Closure
* and primary key. The optional key parameter, when provided, specifies a particular metafield; otherwise,
* it represents all metafields. Null values in model details are substituted with 'null'.
*
* @param Metafieldable $model The model for which the cache key is being generated.
* @param string|null $key An optional key for a specific metafield. If null, the key represents all metafields.
* @param Metafieldable $model The model for which the cache key is being generated.
* @param string|null $key An optional key for a specific metafield. If null, the key represents all metafields.
* @return string The constructed cache key.
*/
public function getCacheKey(Metafieldable $model, string|null $key = null): string
public function getCacheKey(Metafieldable $model, ?string $key = null): string
{
return collect([
config('metafields.cache_key_prefix'),
class_basename($model),
$model->getKey() ?? 'null',

Check failure on line 97 in src/LaravelMetafields.php

View workflow job for this annotation

GitHub Actions / phpstan

Call to an undefined method FaizanSf\LaravelMetafields\Contracts\Metafieldable::getKey().
$key
$key,
])->filter(function ($value) {
return $value !== null;
})->join(':');
}


/**
*
* @param Metafieldable $model
* @return string
*/
public function getAllMetaFieldsCacheKey(Metafieldable $model): string
{
return $this->getCacheKey($model);
}

/**
* Checks if cache is enabled and the current instance is configured to use it.
* @param CacheContext $cacheContext
* @return bool
*/
protected function canUseCache(CacheContext $cacheContext): bool
{
return $cacheContext->isCacheEnabled() && $this->withCache;
}

}
2 changes: 0 additions & 2 deletions src/Models/Metafield.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ class Metafield extends Model
*/
protected $hidden = ['model_type', 'model_id'];


/**
* The model relationship.
*/
Expand All @@ -42,5 +41,4 @@ public function __construct(array $attributes = [])

$this->setTable(config('metafields.table'));
}

}
9 changes: 3 additions & 6 deletions src/Utils/CacheContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ class CacheContext
public function __construct(
protected bool $cacheEnabled,
protected ?int $ttl
) {}
) {
}

/**
* Create a new CacheContext instance.
*
* @param string $class The class name to create the context for.
* @return CacheContext
* @param string $class The class name to create the context for.
*/
public static function make(string $class): CacheContext
{
Expand All @@ -25,8 +25,6 @@ public static function make(string $class): CacheContext

/**
* Check if caching is enabled.
*
* @return bool
*/
public function isCacheEnabled(): bool
{
Expand All @@ -42,5 +40,4 @@ public function getTtl(): ?int
{
return $this->ttl;
}

}
4 changes: 2 additions & 2 deletions tests/Pest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

uses(TestCase::class)->in(__DIR__);


function makeCarInstance(){
function makeCarInstance()
{
$car = Car::newFactory()->make();
$car->id = 1;

Expand Down
2 changes: 1 addition & 1 deletion tests/TestSupport/Enums/CarMetafieldsEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace FaizanSf\LaravelMetafields\Tests\TestSupport\Enums;

enum CarMetafieldsEnum:string
enum CarMetafieldsEnum: string
{
case MODEL = 'MODEL';
case COLOR = 'COLOR';
Expand Down
1 change: 0 additions & 1 deletion tests/TestSupport/Models/Car.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use FaizanSf\LaravelMetafields\Concerns\HasMetafields;
use FaizanSf\LaravelMetafields\Contracts\Metafieldable;
use FaizanSf\LaravelMetafields\Tests\TestSupport\Factories\CarFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Car extends Model implements Metafieldable
Expand Down
25 changes: 8 additions & 17 deletions tests/Unit/LaravelMetafieldsUnitTest.php
Original file line number Diff line number Diff line change
@@ -1,39 +1,35 @@
<?php


use FaizanSf\LaravelMetafields\Exceptions\InvalidKeyException;
use FaizanSf\LaravelMetafields\Facades\LaravelMetafields;


it('normalizes enum key', function($testKey){
it('normalizes enum key', function ($testKey) {
$key = $testKey;
$normalizedKey = LaravelMetafields::normalizeKey($key);

expect($normalizedKey)->toBeString()->toEqual($key->value);
})->with('testKeys');


it('throws exception where enum key is not a string', function($invalidTestKey){
it('throws exception where enum key is not a string', function ($invalidTestKey) {
LaravelMetafields::normalizeKey($invalidTestKey);
})->throws(InvalidKeyException::class)->with('invalidTestKeys');

it('does not normalize string key', function($stringKey){
it('does not normalize string key', function ($stringKey) {
$key = $stringKey;
$normalizedKey = LaravelMetafields::normalizeKey($key);

expect($normalizedKey)->toBeString()->toEqual($key);
})->with('stringKeys');

it('returns single field cache key in correct format', function($key){
it('returns single field cache key in correct format', function ($key) {
$key = LaravelMetafields::normalizeKey($key);
$car = makeCarInstance();
$prefix = 'LaravelMetafields';


config()->set('metafields.cache_key_prefix', $prefix);

$cacheKey = LaravelMetafields::getCacheKey($car, $key);
$expected = $prefix . ':Car:' . $car->getKey() . ':' . $key;
$expected = $prefix.':Car:'.$car->getKey().':'.$key;

expect($cacheKey)->toBeString()->toEqual($expected);
})->with('stringKeys', 'testKeys');
Expand All @@ -44,7 +40,7 @@
$car = makeCarInstance();

$cacheKey = LaravelMetafields::getAllMetaFieldsCacheKey($car);
$expected = $prefix . ':Car:' . $car->getKey();
$expected = $prefix.':Car:'.$car->getKey();

expect($cacheKey)->toBeString()->toEqual($expected);

Expand All @@ -55,7 +51,7 @@
$key = 'model';
$cacheKey = LaravelMetafields::getCacheKey($car, $key);

LaravelMetafields::runCachedOrDirect($car->getCacheContext(), $cacheKey, function(){
LaravelMetafields::runCachedOrDirect($car->getCacheContext(), $cacheKey, function () {
return 1999;
});

Expand All @@ -67,21 +63,16 @@

});


it('doesnt caches the result when cache is disabled', function () {
config()->set('metafields.cache_enabled', false);

$car = makeCarInstance();
$key = 'model';
$cacheKey = LaravelMetafields::getCacheKey($car, $key);


LaravelMetafields::runCachedOrDirect($car->getCacheContext(), $cacheKey, function(){
LaravelMetafields::runCachedOrDirect($car->getCacheContext(), $cacheKey, function () {
return 1999;
});

expect(cache()->has($cacheKey))->toBeFalse();
});



2 changes: 0 additions & 2 deletions tests/Unit/StandardCastUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use FaizanSf\LaravelMetafields\Casts\StandardCast;
use FaizanSf\LaravelMetafields\Models\Metafield;


beforeEach(function () {
$this->cast = new StandardCast();
$this->model = new Metafield();
Expand Down Expand Up @@ -44,4 +43,3 @@
expect($this->cast->get($this->model, 'value', $serialized, []))
->toBeInstanceOf(__PHP_Incomplete_Class::class);
});

0 comments on commit 88ce7f7

Please sign in to comment.