Make WordPress Core

Opened 8 weeks ago

Last modified 8 weeks ago

#62236 new enhancement

Why do wp_cache_incr / wp_cache_decr not allow negative values?

Reported by: docjojo's profile docjojo Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 6.6.2
Component: Cache API Keywords:
Focuses: Cc:

Description

Both functions have this line of code:

[https://developer.wordpress.org/reference/classes/wp_object_cache/decr/
]
[https://developer.wordpress.org/reference/classes/wp_object_cache/incr/
]

<?php
if ( $this->cache[ $group ][ $id ] < 0 )
$this->cache[ $group ][ $id ] = 0;

Why are negative values turned to zero, making it impossible to inc/dec negative values?

wp_cache_set accepts any integer – so negative values can be set, but once incr/decr are called this value will be set to zero or zero + offset.

No other programming language handles inc/dec this way.

PHP, Javascript, C++ and so on have the inc/dec operator ++, -- that work with negative values.

When it comes to caching and APCu is used for example.

[https://www.php.net/manual/en/function.apcu-inc.php
]

APCu handles negative values.

Same with redis and memcached:

[https://redis.io/docs/latest/commands/incr/
]

[https://www.php.net/manual/en/memcache.increment.php
]

I think this is inconsistent unless there is a special reason to prevent negative values – but then, negative values should not be allow in the first place (wp_cache_set).

Change History (3)

#1 @swissspidy
8 weeks ago

  • Focuses performance php-compatibility removed
  • Keywords changes-requested removed

#2 @dd32
8 weeks ago

I believe this would be caused by it being modeled on one of the original object caches in use, Memcache.

https://www.php.net/manual/en/memcached.decrement.php

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will set the item to the initial_value parameter if the key doesn't exist.

#3 @docjojo
8 weeks ago

but does it make sense?

Memcached::decrement() will set the item to the initial_value parameter if the key doesn't exist.
Initial_value is 0 if not set.

wp_cache_incr returns false, if key is not set, memcached returns 0.
That is also not consistent.

Question remains, why not allow negative integer?

Note: See TracTickets for help on using tickets.