diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3dd9bf4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +/.gitattributes export-ignore +/.github/ export-ignore +/.gitignore export-ignore +/phpstan.neon.dist export-ignore +/phpunit.xml.dist export-ignore +/phpunit.xml.legacy export-ignore +/tests export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9964f62 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,60 @@ +name: CI + +on: + push: + pull_request: + +jobs: + PHPUnit: + name: PHPUnit (PHP ${{ matrix.php }}) + runs-on: ubuntu-24.04 + strategy: + matrix: + php: + - 8.5 + - 8.4 + - 8.3 + - 8.2 + - 8.1 + - 8.0 + - 7.4 + - 7.3 + - 7.2 + - 7.1 + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: xdebug + ini-file: development + - run: composer install + - run: vendor/bin/phpunit --coverage-text + if: ${{ matrix.php >= 7.3 }} + - run: vendor/bin/phpunit --coverage-text -c phpunit.xml.legacy + if: ${{ matrix.php < 7.3 }} + + PHPStan: + name: PHPStan (PHP ${{ matrix.php }}) + runs-on: ubuntu-24.04 + strategy: + matrix: + php: + - 8.5 + - 8.4 + - 8.3 + - 8.2 + - 8.1 + - 8.0 + - 7.4 + - 7.3 + - 7.2 + - 7.1 + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + - run: composer install + - run: vendor/bin/phpstan diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..987e2a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +composer.lock +vendor diff --git a/ArrayCache.php b/ArrayCache.php deleted file mode 100644 index 03dcc15..0000000 --- a/ArrayCache.php +++ /dev/null @@ -1,29 +0,0 @@ -data[$key])) { - return Promise\reject(); - } - - return Promise\resolve($this->data[$key]); - } - - public function set($key, $value) - { - $this->data[$key] = $value; - } - - public function remove($key) - { - unset($this->data[$key]); - } -} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ab59f18 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,96 @@ +# Changelog + +## 1.2.0 (2022-11-30) + +* Feature: Support PHP 8.1 and PHP 8.2. + (#47 by @SimonFrings and #52 by @WyriHaximus) + +* Minor documentation improvements. + (#48 by @SimonFrings and #51 by @nhedger) + +* Update test suite and use GitHub actions for continuous integration (CI). + (#45 and #49 by @SimonFrings and #54 by @clue) + +## 1.1.0 (2020-09-18) + +* Feature: Forward compatibility with react/promise 3. + (#39 by @WyriHaximus) + +* Add `.gitattributes` to exclude dev files from exports. + (#40 by @reedy) + +* Improve test suite, update to support PHP 8 and PHPUnit 9.3. + (#41 and #43 by @SimonFrings and #42 by @WyriHaximus) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.6.0 release. + +## 0.6.0 (2019-07-04) + +* Feature / BC break: Add support for `getMultiple()`, `setMultiple()`, `deleteMultiple()`, `clear()` and `has()` + supporting multiple cache items (inspired by PSR-16). + (#32 by @krlv and #37 by @clue) + +* Documentation for TTL precision with millisecond accuracy or below and + use high-resolution timer for cache TTL on PHP 7.3+. + (#35 and #38 by @clue) + +* Improve API documentation and allow legacy HHVM to fail in Travis CI config. + (#34 and #36 by @clue) + +* Prefix all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#31 by @WyriHaximus) + +## 0.5.0 (2018-06-25) + +* Improve documentation by describing what is expected of a class implementing `CacheInterface`. + (#21, #22, #23, #27 by @WyriHaximus) + +* Implemented (optional) Least Recently Used (LRU) cache algorithm for `ArrayCache`. + (#26 by @clue) + +* Added support for cache expiration (TTL). + (#29 by @clue and @WyriHaximus) + +* Renamed `remove` to `delete` making it more in line with `PSR-16`. + (#30 by @clue) + +## 0.4.2 (2017-12-20) + +* Improve documentation with usage and installation instructions + (#10 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` and + add forward compatibility with PHPUnit 5 and PHPUnit 6 and + sanitize Composer autoload paths + (#14 by @shaunbramley and #12 and #18 by @clue) + +## 0.4.1 (2016-02-25) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#9 by @clue) +* Adjust compatibility to 5.3 (#7 by @clue) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.0 (2013-04-14) + +* Version bump + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS diff --git a/CacheInterface.php b/CacheInterface.php deleted file mode 100644 index fd5f2d5..0000000 --- a/CacheInterface.php +++ /dev/null @@ -1,13 +0,0 @@ - **Development version:** This branch contains the code for the upcoming v3 +> release. For the code of the current stable v1 release, check out the +> [`1.x` branch](https://github.com/reactphp/cache/tree/1.x). +> +> The upcoming v3 release will be the way forward for this package. However, +> we will still actively support v1 for those not yet on the latest version. +> See also [installation instructions](#install) for more details. -### get +The cache component provides a +[Promise](https://github.com/reactphp/promise)-based +[`CacheInterface`](#cacheinterface) and an in-memory [`ArrayCache`](#arraycache) +implementation of that. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. +This project is heavily inspired by +[PSR-16: Common Interface for Caching Libraries](https://www.php-fig.org/psr/psr-16/), +but uses an interface more suited for async, non-blocking applications. - $cache - ->get('foo') - ->then('var_dump'); +**Table of Contents** + +* [Usage](#usage) + * [CacheInterface](#cacheinterface) + * [get()](#get) + * [set()](#set) + * [delete()](#delete) + * [getMultiple()](#getmultiple) + * [setMultiple()](#setmultiple) + * [deleteMultiple()](#deletemultiple) + * [clear()](#clear) + * [has()](#has) + * [ArrayCache](#arraycache) +* [Common usage](#common-usage) + * [Fallback get](#fallback-get) + * [Fallback-get-and-set](#fallback-get-and-set) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +### CacheInterface + +The `CacheInterface` describes the main interface of this component. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. + +#### get() + +The `get(string $key, mixed $default = null): PromiseInterface` method can be used to +retrieve an item from the cache. + +This method will resolve with the cached value on success or with the +given `$default` value when no item can be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache + ->get('foo') + ->then('var_dump'); +``` This example fetches the value of the key `foo` and passes it to the `var_dump` function. You can use any of the composition provided by [promises](https://github.com/reactphp/promise). -If the key `foo` does not exist, the promise will be rejected. +#### set() -### set +The `set(string $key, mixed $value, ?float $ttl = null): PromiseInterface` method can be used to +store an item in the cache. - $cache->set('foo', 'bar'); +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for this cache item. If this parameter is omitted (or `null`), the item +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache item results in a cache miss, +see also [`get()`](#get). + +```php +$cache->set('foo', 'bar', 60); +``` This example eventually sets the value of the key `foo` to `bar`. If it -already exists, it is overridden. No guarantees are made as to when the cache -value is set. If the cache implementation has to go over the network to store +already exists, it is overridden. + +This interface does not enforce any particular TTL resolution, so special +care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Cache implementations SHOULD work on a +best effort basis and SHOULD provide at least second accuracy unless +otherwise noted. Many existing cache implementations are known to provide +microsecond or millisecond accuracy, but it's generally not recommended +to rely on this high precision. + +This interface suggests that cache implementations SHOULD use a monotonic +time source if available. Given that a monotonic time source is only +available as of PHP 7.3 by default, cache implementations MAY fall back +to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s and then +adjust your system time forward by 20s, the cache item SHOULD still +expire in 30s. + +#### delete() + +The `delete(string $key): PromiseInterface` method can be used to +delete an item from the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. When no item for `$key` is found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->delete('foo'); +``` + +This example eventually deletes the key `foo` from the cache. As with +`set()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### getMultiple() + +The `getMultiple(iterable $keys, mixed $default = null): PromiseInterface>` method can be used to +retrieve multiple cache items by their unique keys. + +This method will resolve with an array of cached values on success or with the +given `$default` value when an item can not be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache->getMultiple(['name', 'age'])->then(function (iterable $values): void { + $array = is_array($values) ? $values : iterator_to_array($values); + $name = $array['name'] ?? 'User'; + $age = $array['age'] ?? 'n/a'; + + echo $name . ' is ' . $age . PHP_EOL; +}); +``` + +This example fetches the cache items for the `name` and `age` keys and +prints some example output. You can use any of the composition provided +by [promises](https://github.com/reactphp/promise). + +#### setMultiple() + +The `setMultiple(iterable $values, ?float $ttl = null): PromiseInterface` method can be used to +persist a set of key => value pairs in the cache, with an optional TTL. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store it, it may take a while. -### remove +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for these cache items. If this parameter is omitted (or `null`), these items +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache items results in a cache miss, +see also [`getMultiple()`](#getmultiple). + +```php +$cache->setMultiple(['foo' => 1, 'bar' => 2], 60); +``` + +This example eventually sets the list of values - the key `foo` to `1` value +and the key `bar` to `2`. If some of the keys already exist, they are overridden. + +#### deleteMultiple() + +The `setMultiple(iterable $keys): PromiseInterface` method can be used to +delete multiple cache items in a single operation. + +This method will resolve with `true` on success or `false` when an error +occurs. When no items for `$keys` are found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->deleteMultiple(['foo', 'bar, 'baz']); +``` + +This example eventually deletes keys `foo`, `bar` and `baz` from the cache. +As with `setMultiple()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### clear() - $cache->remove('foo'); +The `clear(): PromiseInterface` method can be used to +wipe clean the entire cache. -This example eventually removes the key `foo` from the cache. As with `set`, -this may not happen instantly. +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->clear(); +``` + +This example eventually deletes all keys from the cache. As with `deleteMultiple()`, +this may not happen instantly and a promise is returned to provide guarantees +whether or not all the items have been removed from cache. + +#### has() + +The `has(string $key): PromiseInterface` method can be used to +determine whether an item is present in the cache. + +This method will resolve with `true` on success or `false` when no item can be found +or when an error occurs. Similarly, an expired cache item (once the time-to-live +is expired) is considered a cache miss. + +```php +$cache + ->has('foo') + ->then('var_dump'); +``` + +This example checks if the value of the key `foo` is set in the cache and passes +the result to the `var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +NOTE: It is recommended that has() is only to be used for cache warming type purposes +and not to be used within your live applications operations for get/set, as this method +is subject to a race condition where your has() will return true and immediately after, +another script can remove it making the state of your app out of date. + +### ArrayCache + +The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface). + +```php +$cache = new ArrayCache(); + +$cache->set('foo', 'bar'); +``` + +Its constructor accepts an optional `?int $limit` parameter to limit the +maximum number of entries to store in the LRU cache. If you add more +entries to this instance, it will automatically take care of removing +the one that was least recently used (LRU). + +For example, this snippet will overwrite the first value and only store +the last two entries: + +```php +$cache = new ArrayCache(2); + +$cache->set('foo', '1'); +$cache->set('bar', '2'); +$cache->set('baz', '3'); +``` + +This cache implementation is known to rely on wall-clock time to schedule +future cache expiration times when using any version before PHP 7.3, +because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s on PHP < 7.3 +and then adjust your system time forward by 20s, the cache item may +expire in 10s. See also [`set()`](#set) for more details. ## Common usage @@ -44,15 +280,23 @@ A common use case of caches is to attempt fetching a cached value and as a fallback retrieve it from the original data source if not found. Here is an example of that: - $cache - ->get('foo') - ->then(null, 'getFooFromDb') - ->then('var_dump'); +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return getFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); +``` -First an attempt is made to retrieve the value of `foo`. A promise rejection -handler of the function `getFooFromDb` is registered. `getFooFromDb` is a -function (can be any PHP callable) that will be called if the key does not -exist in the cache. +First an attempt is made to retrieve the value of `foo`. A callback function is +registered that will call `getFooFromDb` when the resulting value is null. +`getFooFromDb` is a function (can be any PHP callable) that will be called if the +key does not exist in the cache. `getFooFromDb` can handle the missing key by returning a promise for the actual value from the database (or any other data source). As a result, this @@ -63,24 +307,75 @@ chain will correctly fall back, and provide the value in both cases. To expand on the fallback get example, often you want to set the value on the cache after fetching it from the data source. - $cache - ->get('foo') - ->then(null, array($this, 'getAndCacheFooFromDb')) - ->then('var_dump'); +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return $this->getAndCacheFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); - public function getAndCacheFooFromDb() - { - return $this->db - ->get('foo') - ->then(array($this, 'cacheFooFromDb')); - } +public function getAndCacheFooFromDb() +{ + return $this->db + ->get('foo') + ->then([$this, 'cacheFooFromDb']); +} - public function cacheFooFromDb($foo) - { - $this->cache->set('foo', $foo); +public function cacheFooFromDb($foo) +{ + $this->cache->set('foo', $foo); - return $foo; - } + return $foo; +} +``` By using chaining you can easily conditionally cache the value if it is fetched from the database. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +Once released, this project will follow [SemVer](https://semver.org/). +At the moment, this will install the latest development version: + +```bash +composer require react/cache:^3@dev +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on PHP 7.1 through current PHP 8+. +It's *highly recommended to use the latest supported PHP version* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +On top of this, we use PHPStan on max level to ensure type safety across the project: + +```bash +vendor/bin/phpstan +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/composer.json b/composer.json index 5446a08..ea14955 100644 --- a/composer.json +++ b/composer.json @@ -1,18 +1,46 @@ { "name": "react/cache", - "description": "Async caching.", - "keywords": ["cache"], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": ["cache", "caching", "promise", "ReactPHP"], "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], "require": { - "php": ">=5.4.0", - "react/promise": "~2.0" + "php": ">=7.1", + "react/promise": "^3.0" + }, + "require-dev": { + "phpstan/phpstan": "1.11.1 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^8.5 || ^7.5" }, "autoload": { - "psr-4": { "React\\Cache\\": "" } + "psr-4": { + "React\\Cache\\": "src/" + } }, - "extra": { - "branch-alias": { - "dev-master": "0.4-dev" + "autoload-dev": { + "psr-4": { + "React\\Tests\\Cache\\": "tests/" } } } diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..895c841 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,6 @@ +parameters: + level: max + + paths: + - src/ + - tests/ diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..ac542e7 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,28 @@ + + + + + + + ./tests/ + + + + + ./src/ + + + + + + + + + + + diff --git a/phpunit.xml.legacy b/phpunit.xml.legacy new file mode 100644 index 0000000..0086860 --- /dev/null +++ b/phpunit.xml.legacy @@ -0,0 +1,26 @@ + + + + + + + ./tests/ + + + + + ./src/ + + + + + + + + + + + diff --git a/src/ArrayCache.php b/src/ArrayCache.php new file mode 100644 index 0000000..4da7860 --- /dev/null +++ b/src/ArrayCache.php @@ -0,0 +1,187 @@ + */ + private $data = []; + + /** @var array */ + private $expires = []; + + /** @var bool */ + private $supportsHighResolution; + + /** + * The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface). + * + * ```php + * $cache = new ArrayCache(); + * + * $cache->set('foo', 'bar'); + * ``` + * + * Its constructor accepts an optional `?int $limit` parameter to limit the + * maximum number of entries to store in the LRU cache. If you add more + * entries to this instance, it will automatically take care of removing + * the one that was least recently used (LRU). + * + * For example, this snippet will overwrite the first value and only store + * the last two entries: + * + * ```php + * $cache = new ArrayCache(2); + * + * $cache->set('foo', '1'); + * $cache->set('bar', '2'); + * $cache->set('baz', '3'); + * ``` + * + * This cache implementation is known to rely on wall-clock time to schedule + * future cache expiration times when using any version before PHP 7.3, + * because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s on PHP < 7.3 + * and then adjust your system time forward by 20s, the cache item may + * expire in 10s. See also [`set()`](#set) for more details. + * + * @param int|null $limit maximum number of entries to store in the LRU cache + */ + public function __construct(?int $limit = null) + { + $this->limit = $limit; + + // prefer high-resolution timer, available as of PHP 7.3+ + $this->supportsHighResolution = \function_exists('hrtime'); + } + + public function get(string $key, $default = null): PromiseInterface + { + // delete key if it is already expired => below will detect this as a cache miss + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return resolve($default); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return resolve($value); + } + + public function set(string $key, $value, ?float $ttl = null): PromiseInterface + { + // unset before setting to ensure this entry will be added to end of array (LRU info) + unset($this->data[$key]); + $this->data[$key] = $value; + + // sort expiration times if TTL is given (first will expire first) + unset($this->expires[$key]); + if ($ttl !== null) { + $this->expires[$key] = $this->now() + $ttl; + \asort($this->expires); + } + + // ensure size limit is not exceeded or remove first entry from array + if ($this->limit !== null && \count($this->data) > $this->limit) { + // first try to check if there's any expired entry + // expiration times are sorted, so we can simply look at the first one + \reset($this->expires); + $key = \key($this->expires); + + // check to see if the first in the list of expiring keys is already expired + // if the first key is not expired, we have to overwrite by using LRU info + if ($key === null || $this->now() - $this->expires[$key] < 0) { + \reset($this->data); + $key = \key($this->data); + } + unset($this->data[$key], $this->expires[$key]); + } + + return resolve(true); + } + + public function delete(string $key): PromiseInterface + { + unset($this->data[$key], $this->expires[$key]); + + return resolve(true); + } + + public function getMultiple(iterable $keys, $default = null): PromiseInterface + { + $values = []; + + foreach ($keys as $key) { + $values[$key] = $this->get($key, $default); + } + + /** @var PromiseInterface> */ + return all($values); + } + + public function setMultiple(iterable $values, ?float $ttl = null): PromiseInterface + { + foreach ($values as $key => $value) { + $this->set($key, $value, $ttl); + } + + return resolve(true); + } + + public function deleteMultiple(iterable $keys): PromiseInterface + { + foreach ($keys as $key) { + unset($this->data[$key], $this->expires[$key]); + } + + return resolve(true); + } + + public function clear(): PromiseInterface + { + $this->data = []; + $this->expires = []; + + return resolve(true); + } + + public function has(string $key): PromiseInterface + { + // delete key if it is already expired + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return resolve(false); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return resolve(true); + } + + private function now(): float + { + return $this->supportsHighResolution ? \hrtime(true) * 1e-9 : \microtime(true); + } +} diff --git a/src/CacheInterface.php b/src/CacheInterface.php new file mode 100644 index 0000000..2342eaf --- /dev/null +++ b/src/CacheInterface.php @@ -0,0 +1,195 @@ +get('foo') + * ->then('var_dump'); + * ``` + * + * This example fetches the value of the key `foo` and passes it to the + * `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * @param string $key + * @param mixed $default Default value to return for cache miss or null if not given. + * @return PromiseInterface + */ + public function get(string $key, $default = null): PromiseInterface; + + /** + * Stores an item in the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for this cache item. If this parameter is omitted (or `null`), the item + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache item results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->set('foo', 'bar', 60); + * ``` + * + * This example eventually sets the value of the key `foo` to `bar`. If it + * already exists, it is overridden. + * + * This interface does not enforce any particular TTL resolution, so special + * care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Cache implementations SHOULD work on a + * best effort basis and SHOULD provide at least second accuracy unless + * otherwise noted. Many existing cache implementations are known to provide + * microsecond or millisecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * This interface suggests that cache implementations SHOULD use a monotonic + * time source if available. Given that a monotonic time source is only + * available as of PHP 7.3 by default, cache implementations MAY fall back + * to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s and then + * adjust your system time forward by 20s, the cache item SHOULD still + * expire in 30s. + * + * @param string $key + * @param mixed $value + * @param ?float $ttl + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function set(string $key, $value, ?float $ttl = null): PromiseInterface; + + /** + * Deletes an item from the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. When no item for `$key` is found in the cache, it also resolves + * to `true`. If the cache implementation has to go over the network to + * delete it, it may take a while. + * + * ```php + * $cache->delete('foo'); + * ``` + * + * This example eventually deletes the key `foo` from the cache. As with + * `set()`, this may not happen instantly and a promise is returned to + * provide guarantees whether or not the item has been removed from cache. + * + * @param string $key + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function delete(string $key): PromiseInterface; + + /** + * Retrieves multiple cache items by their unique keys. + * + * This method will resolve with an array of cached values on success or with the + * given `$default` value when an item can not be found or when an error occurs. + * Similarly, an expired cache item (once the time-to-live is expired) is + * considered a cache miss. + * + * ```php + * $cache->getMultiple(['name', 'age'])->then(function (iterable $values): void { + * $array = is_array($values) ? $values : iterator_to_array($values); + * $name = $array['name'] ?? 'User'; + * $age = $array['age'] ?? 'n/a'; + * + * echo $name . ' is ' . $age . PHP_EOL; + * }); + * ``` + * + * This example fetches the cache items for the `name` and `age` keys and + * prints some example output. You can use any of the composition provided + * by [promises](https://github.com/reactphp/promise). + * + * @param iterable $keys A list of keys that can obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * @return PromiseInterface> Returns a promise which resolves to an `array` of cached values + */ + public function getMultiple(iterable $keys, $default = null): PromiseInterface; + + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for these cache items. If this parameter is omitted (or `null`), these items + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache items results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->setMultiple(['foo' => 1, 'bar' => 2], 60); + * ``` + * + * This example eventually sets the list of values - the key `foo` to 1 value + * and the key `bar` to 2. If some of the keys already exist, they are overridden. + * + * @param iterable $values A list of key => value pairs for a multiple-set operation. + * @param ?float $ttl Optional. The TTL value of this item. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function setMultiple(iterable $values, ?float $ttl = null): PromiseInterface; + + /** + * Deletes multiple cache items in a single operation. + * + * @param iterable $keys A list of string-based keys to be deleted. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function deleteMultiple(iterable $keys): PromiseInterface; + + /** + * Wipes clean the entire cache. + * + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function clear(): PromiseInterface; + + /** + * Determines whether an item is present in the cache. + * + * This method will resolve with `true` on success or `false` when no item can be found + * or when an error occurs. Similarly, an expired cache item (once the time-to-live + * is expired) is considered a cache miss. + * + * ```php + * $cache + * ->has('foo') + * ->then('var_dump'); + * ``` + * + * This example checks if the value of the key `foo` is set in the cache and passes + * the result to the `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * NOTE: It is recommended that has() is only to be used for cache warming type purposes + * and not to be used within your live applications operations for get/set, as this method + * is subject to a race condition where your has() will return true and immediately after, + * another script can remove it making the state of your app out of date. + * + * @param string $key The cache item key. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function has(string $key): PromiseInterface; +} diff --git a/tests/ArrayCacheTest.php b/tests/ArrayCacheTest.php new file mode 100644 index 0000000..d37a570 --- /dev/null +++ b/tests/ArrayCacheTest.php @@ -0,0 +1,330 @@ +cache = new ArrayCache(); + } + + /** @test */ + public function getShouldResolvePromiseWithNullForNonExistentKey(): void + { + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + /** @test */ + public function setShouldSetKey(): void + { + $this->cache->set('foo', 'bar')->then($this->expectCallableOnceWith(true)); + + $this->cache->get('foo')->then($this->expectCallableOnceWith('bar')); + } + + /** @test */ + public function deleteShouldDeleteKey(): void + { + $this->cache->set('foo', 'bar'); + + $this->cache->delete('foo')->then($this->expectCallableOnceWith(true)); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + public function testGetWillResolveWithNullForCacheMiss(): void + { + $this->cache = new ArrayCache(); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + public function testGetWillResolveWithDefaultValueForCacheMiss(): void + { + $this->cache = new ArrayCache(); + + $this->cache->get('foo', 'bar')->then($this->expectCallableOnceWith('bar')); + } + + public function testGetWillResolveWithExplicitNullValueForCacheHit(): void + { + $this->cache = new ArrayCache(); + + $this->cache->set('foo', null); + $this->cache->get('foo', 'bar')->then($this->expectCallableOnceWith(null)); + } + + public function testLimitSizeToZeroDoesNotStoreAnyData(): void + { + $this->cache = new ArrayCache(0); + + $this->cache->set('foo', 'bar'); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + public function testLimitSizeToOneWillOnlyReturnLastWrite(): void + { + $this->cache = new ArrayCache(1); + + $this->cache->set('foo', '1'); + $this->cache->set('bar', '2'); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + $this->cache->get('bar')->then($this->expectCallableOnceWith('2')); + } + + public function testOverwriteWithLimitedSizeWillUpdateLRUInfo(): void + { + $this->cache = new ArrayCache(2); + + $this->cache->set('foo', '1'); + $this->cache->set('bar', '2'); + $this->cache->set('foo', '3'); + $this->cache->set('baz', '4'); + + $this->cache->get('foo')->then($this->expectCallableOnceWith('3')); + $this->cache->get('bar')->then($this->expectCallableOnceWith(null)); + $this->cache->get('baz')->then($this->expectCallableOnceWith('4')); + } + + public function testGetWithLimitedSizeWillUpdateLRUInfo(): void + { + $this->cache = new ArrayCache(2); + + $this->cache->set('foo', '1'); + $this->cache->set('bar', '2'); + $this->cache->get('foo')->then($this->expectCallableOnceWith('1')); + $this->cache->set('baz', '3'); + + $this->cache->get('foo')->then($this->expectCallableOnceWith('1')); + $this->cache->get('bar')->then($this->expectCallableOnceWith(null)); + $this->cache->get('baz')->then($this->expectCallableOnceWith('3')); + } + + public function testGetWillResolveWithValueIfItemIsNotExpired(): void + { + $this->cache = new ArrayCache(); + + $this->cache->set('foo', '1', 10); + + $this->cache->get('foo')->then($this->expectCallableOnceWith('1')); + } + + public function testGetWillResolveWithDefaultIfItemIsExpired(): void + { + $this->cache = new ArrayCache(); + + $this->cache->set('foo', '1', 0); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + public function testSetWillOverwritOldestItemIfNoEntryIsExpired(): void + { + $this->cache = new ArrayCache(2); + + $this->cache->set('foo', '1', 10); + $this->cache->set('bar', '2', 20); + $this->cache->set('baz', '3', 30); + + $this->cache->get('foo')->then($this->expectCallableOnceWith(null)); + } + + public function testSetWillOverwriteExpiredItemIfAnyEntryIsExpired(): void + { + $this->cache = new ArrayCache(2); + + $this->cache->set('foo', '1', 10); + $this->cache->set('bar', '2', 0); + $this->cache->set('baz', '3', 30); + + $this->cache->get('foo')->then($this->expectCallableOnceWith('1')); + $this->cache->get('bar')->then($this->expectCallableOnceWith(null)); + } + + public function testGetMultiple(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', '1'); + + $this->cache + ->getMultiple(['foo', 'bar'], 'baz') + ->then($this->expectCallableOnceWith(['foo' => '1', 'bar' => 'baz'])); + } + + public function testGetMultipleWithIterableKeysFromGenerator(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', '1'); + + $keys = (function (): \Generator { yield from ['foo', 'bar']; })(); + + $this->cache + ->getMultiple($keys, 'baz') + ->then($this->expectCallableOnceWith(['foo' => '1', 'bar' => 'baz'])); + } + + public function testSetMultiple(): void + { + $this->cache = new ArrayCache(); + $this->cache->setMultiple(['foo' => '1', 'bar' => '2'], 10); + + $this->cache + ->getMultiple(['foo', 'bar']) + ->then($this->expectCallableOnceWith(['foo' => '1', 'bar' => '2'])); + } + + public function testSetMultipleWithIterableValuesFromGenerator(): void + { + $values = (function(): \Generator { yield from ['foo' => '1', 'bar' => '2']; })(); + + $this->cache = new ArrayCache(); + $this->cache->setMultiple($values, 10); + + $this->cache + ->getMultiple(['foo', 'bar']) + ->then($this->expectCallableOnceWith(['foo' => '1', 'bar' => '2'])); + } + + public function testDeleteMultiple(): void + { + $this->cache = new ArrayCache(); + $this->cache->setMultiple(['foo' => 1, 'bar' => 2, 'baz' => 3]); + + $this->cache + ->deleteMultiple(['foo', 'baz']) + ->then($this->expectCallableOnceWith(true)); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(false)); + + $this->cache + ->has('bar') + ->then($this->expectCallableOnceWith(true)); + + $this->cache + ->has('baz') + ->then($this->expectCallableOnceWith(false)); + } + + public function testDeleteMultipleWithIterableKeysFromGenerator(): void + { + $this->cache = new ArrayCache(); + $this->cache->setMultiple(['foo' => 1, 'bar' => 2, 'baz' => 3]); + + $keys = (function (): \Generator { yield from ['foo', 'baz']; })(); + + $this->cache + ->deleteMultiple($keys) + ->then($this->expectCallableOnceWith(true)); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(false)); + + $this->cache + ->has('bar') + ->then($this->expectCallableOnceWith(true)); + + $this->cache + ->has('baz') + ->then($this->expectCallableOnceWith(false)); + } + + public function testClearShouldClearCache(): void + { + $this->cache = new ArrayCache(); + $this->cache->setMultiple(['foo' => 1, 'bar' => 2, 'baz' => 3]); + + $this->cache->clear(); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(false)); + + $this->cache + ->has('bar') + ->then($this->expectCallableOnceWith(false)); + + $this->cache + ->has('baz') + ->then($this->expectCallableOnceWith(false)); + } + + public function hasShouldResolvePromiseForExistingKey(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', 'bar'); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(true)); + } + + public function hasShouldResolvePromiseForNonExistentKey(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', 'bar'); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(false)); + } + + public function testHasWillResolveIfItemIsNotExpired(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', '1', 10); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(true)); + } + + public function testHasWillResolveIfItemIsExpired(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', '1', 0); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(false)); + } + + public function testHasWillResolveForExplicitNullValue(): void + { + $this->cache = new ArrayCache(); + $this->cache->set('foo', null); + + $this->cache + ->has('foo') + ->then($this->expectCallableOnceWith(true)); + } + + public function testHasWithLimitedSizeWillUpdateLRUInfo(): void + { + $this->cache = new ArrayCache(2); + + $this->cache->set('foo', 1); + $this->cache->set('bar', 2); + $this->cache->has('foo')->then($this->expectCallableOnceWith(true)); + $this->cache->set('baz', 3); + + $this->cache->has('foo')->then($this->expectCallableOnceWith(1)); + $this->cache->has('bar')->then($this->expectCallableOnceWith(false)); + $this->cache->has('baz')->then($this->expectCallableOnceWith(3)); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..9088454 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,49 @@ +createCallableMock(); + $mock->expects($this->once())->method('__invoke'); + assert(is_callable($mock)); + + return $mock; + } + + /** @param mixed $argument */ + protected function expectCallableOnceWith($argument): callable + { + $mock = $this->createCallableMock(); + $mock->expects($this->once())->method('__invoke')->with($argument); + assert(is_callable($mock)); + + return $mock; + } + + protected function expectCallableNever(): callable + { + $mock = $this->createCallableMock(); + $mock->expects($this->never())->method('__invoke'); + assert(is_callable($mock)); + + return $mock; + } + + protected function createCallableMock(): MockObject + { + $builder = $this->getMockBuilder(\stdClass::class); + if (method_exists($builder, 'addMethods')) { + // PHPUnit 9+ + return $builder->addMethods(['__invoke'])->getMock(); + } else { + // legacy PHPUnit + return $builder->setMethods(['__invoke'])->getMock(); + } + } +}