Always return bool values from cache function.

This commit is contained in:
Vedanshu Jain 2023-08-21 14:20:29 +05:30
parent d663c304c9
commit 031530305d
2 changed files with 59 additions and 3 deletions

View File

@ -34,7 +34,7 @@ class WPCacheEngine implements CacheEngine {
*/
public function cache_object( string $key, $object, int $expiration, string $group = '' ): bool {
$prefixed_key = self::get_prefixed_key( $key, $group );
return wp_cache_set( $prefixed_key, $object, $group, $expiration );
return false !== wp_cache_set( $prefixed_key, $object, $group, $expiration );
}
/**
@ -47,7 +47,7 @@ class WPCacheEngine implements CacheEngine {
*/
public function delete_cached_object( string $key, string $group = '' ): bool {
$prefixed_key = self::get_prefixed_key( $key, $group );
return wp_cache_delete( $prefixed_key, $group );
return false !== wp_cache_delete( $prefixed_key, $group );
}
/**
@ -71,6 +71,6 @@ class WPCacheEngine implements CacheEngine {
* @return bool True if the group is deleted successfully, false otherwise.
*/
public function delete_cache_group( string $group = '' ): bool {
return self::invalidate_cache_group( $group );
return false !== self::invalidate_cache_group( $group );
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Automattic\WooCommerce\Tests\Caching;
use Automattic\WooCommerce\Caching\WPCacheEngine;
/**
* Tests for WPCacheEngine.
*/
class WPCacheEngineTest extends \WC_Unit_Test_Case {
/**
* System under test.
*
* @var WPCacheEngine
*/
private $sut;
/**
* Setup test.
*/
public function setUp(): void {
parent::setUp();
$this->sut = wc_get_container()->get( WPCacheEngine::class );
}
/**
* @testDox Test that the cache engine can be used to cache and retrieve objects.
*/
public function test_caching_crud() {
$object_to_cache = new \stdClass();
$object_to_cache->prop1 = 'dummy_value_1';
$object_to_cache->prop2 = 'dummy_value_2';
$key = 'dummy_object_key';
$group = 'dummy_group';
$this->assertFalse( $this->sut->is_cached( $key, $group ) );
$this->sut->cache_object( $key, $object_to_cache, HOUR_IN_SECONDS, $group );
$this->assertTrue( $this->sut->is_cached( $key, $group ) );
$cached_obj = $this->sut->get_cached_object( $key, $group );
$this->assertEquals( $object_to_cache->prop1, $cached_obj->prop1 );
$this->assertEquals( $object_to_cache->prop2, $cached_obj->prop2 );
$this->sut->delete_cached_object( $key, $group );
$this->assertFalse( $this->sut->is_cached( $key, $group ) );
$this->assertNull( ( $this->sut->get_cached_object( $key, $group ) ) );
$this->sut->cache_object( $key, $object_to_cache, HOUR_IN_SECONDS, $group );
$this->assertTrue( $this->sut->is_cached( $key, $group ) );
$this->sut->delete_cache_group( $group );
$this->assertFalse( $this->sut->is_cached( $key, $group ) );
$this->assertNull( ( $this->sut->get_cached_object( $group ) ) );
}
}