ソースを参照

Don't allow subzero values in increment/decrement.

Signal the bad data more visibly with an exception.
Mark Story 7 年 前
コミット
609a1928eb
2 ファイル変更28 行追加4 行削除
  1. 6 4
      src/Cache/Cache.php
  2. 22 0
      tests/TestCase/Cache/CacheTest.php

+ 6 - 4
src/Cache/Cache.php

@@ -359,11 +359,12 @@ class Cache
      * @param string $config Optional string configuration name. Defaults to 'default'
      * @return mixed new value, or false if the data doesn't exist, is not integer,
      *    or if there was an error fetching it.
+     * @throws \Cake\Cache\InvalidArgumentException when offset < 0
      */
     public static function increment(string $key, int $offset = 1, string $config = 'default')
     {
-        if (!is_int($offset) || $offset < 0) {
-            return false;
+        if ($offset < 0) {
+            throw new InvalidArgumentException('Offset cannot be less than 0.');
         }
 
         return static::pool($config)->increment($key, $offset);
@@ -377,11 +378,12 @@ class Cache
      * @param string $config Optional string configuration name. Defaults to 'default'
      * @return mixed new value, or false if the data doesn't exist, is not integer,
      *   or if there was an error fetching it
+     * @throws \Cake\Cache\InvalidArgumentException when offset < 0
      */
     public static function decrement(string $key, int $offset = 1, string $config = 'default')
     {
-        if (!is_int($offset) || $offset < 0) {
-            return false;
+        if ($offset < 0) {
+            throw new InvalidArgumentException('Offset cannot be less than 0.');
         }
 
         return static::pool($config)->decrement($key, $offset);

+ 22 - 0
tests/TestCase/Cache/CacheTest.php

@@ -340,6 +340,17 @@ class CacheTest extends TestCase
     }
 
     /**
+     * Test increment with value < 0
+     *
+     * @return void
+     */
+    public function testIncrementSubZero()
+    {
+        $this->expectException(InvalidArgumentException::class);
+        $this->assertFalse(Cache::increment('key', -1));
+    }
+
+    /**
      * Test write from a config that is undefined.
      *
      * @return void
@@ -351,6 +362,17 @@ class CacheTest extends TestCase
     }
 
     /**
+     * Test decrement value < 0
+     *
+     * @return void
+     */
+    public function testDecrementSubZero()
+    {
+        $this->expectException(InvalidArgumentException::class);
+        $this->assertFalse(Cache::decrement('key', -1));
+    }
+
+    /**
      * Data provider for valid config data sets.
      *
      * @return array