Skip to content
Permalink
Browse files

General: Introduce `wp_unique_id()`, a PHP implementation of Undersco…

…re'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.

Merges [43658] and [44406] to the 5.0 branch.
See #44883.

git-svn-id: https://develop.svn.wordpress.org/branches/5.0@44407 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information...
desrosj committed Jan 6, 2019
1 parent 3f6df95 commit f95257f204040e0045647f3af7765a5851116d58
Showing with 48 additions and 0 deletions.
  1. +20 −0 src/wp-includes/functions.php
  2. +28 −0 tests/phpunit/tests/functions.php
@@ -5793,6 +5793,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 5.0.3
*
* @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.
*
@@ -959,6 +959,34 @@ function test_wp_is_valid_uuid() {
}
}
/**
* 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

0 comments on commit f95257f

Please sign in to comment.
You can’t perform that action at this time.