From e1ff4cd7cd007c18ae7a65c01394cfd21cd39d49 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Mon, 24 Sep 2018 20:56:30 +0000 Subject: [PATCH] General: Introduce `wp_unique_id()`, a PHP implementation of Underscore's `uniqueId` method. A static variable contains an integer that is incremented with each call. This number is returned with the optional prefix. As such the returned value is not universally unique, but it is unique across the life of the PHP process. Props westonruter, dlh. See #44883. git-svn-id: https://develop.svn.wordpress.org/trunk@43658 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 20 ++++++++++++++++++++ tests/phpunit/tests/functions.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index e2f3f0751f..f3070315f6 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -6167,6 +6167,26 @@ function wp_is_uuid( $uuid, $version = null ) { return (bool) preg_match( $regex, $uuid ); } +/** + * Get unique ID. + * + * This is a PHP implementation of Underscore's uniqueId method. A static variable + * contains an integer that is incremented with each call. This number is returned + * with the optional prefix. As such the returned value is not universally unique, + * but it is unique across the life of the PHP process. + * + * @since 4.9.9 + * + * @staticvar int $id_counter + * + * @param string $prefix Prefix for the returned ID. + * @return string Unique ID. + */ +function wp_unique_id( $prefix = '' ) { + static $id_counter = 0; + return $prefix . (string) ++$id_counter; +} + /** * Get last changed date for the specified cache group. * diff --git a/tests/phpunit/tests/functions.php b/tests/phpunit/tests/functions.php index d6d5d066e0..2557f1f92a 100644 --- a/tests/phpunit/tests/functions.php +++ b/tests/phpunit/tests/functions.php @@ -1117,6 +1117,34 @@ class Tests_Functions extends WP_UnitTestCase { } } + /** + * Tests wp_unique_id(). + * + * @covers ::wp_unique_id + * @ticket 44883 + */ + function test_wp_unique_id() { + + // Test without prefix. + $ids = array(); + for ( $i = 0; $i < 20; $i += 1 ) { + $id = wp_unique_id(); + $this->assertInternalType( 'string', $id ); + $this->assertTrue( is_numeric( $id ) ); + $ids[] = $id; + } + $this->assertEquals( $ids, array_unique( $ids ) ); + + // Test with prefix. + $ids = array(); + for ( $i = 0; $i < 20; $i += 1 ) { + $id = wp_unique_id( 'foo-' ); + $this->assertRegExp( '/^foo-\d+$/', $id ); + $ids[] = $id; + } + $this->assertEquals( $ids, array_unique( $ids ) ); + } + /** * @ticket 40017 * @dataProvider _wp_get_image_mime