mirror of
git://develop.git.wordpress.org/
synced 2025-04-21 20:51:55 +02:00
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. 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
This commit is contained in:
parent
3f6df95e64
commit
f95257f204
@ -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 @@ 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
|
||||
|
Loading…
x
Reference in New Issue
Block a user