Make WordPress Core

Changeset 43658


Ignore:
Timestamp:
09/24/2018 08:56:30 PM (6 years ago)
Author:
SergeyBiryukov
Message:

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.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.php

    r43657 r43658  
    61696169
    61706170/**
     6171 * Get unique ID.
     6172 *
     6173 * This is a PHP implementation of Underscore's uniqueId method. A static variable
     6174 * contains an integer that is incremented with each call. This number is returned
     6175 * with the optional prefix. As such the returned value is not universally unique,
     6176 * but it is unique across the life of the PHP process.
     6177 *
     6178 * @since 4.9.9
     6179 *
     6180 * @staticvar int $id_counter
     6181 *
     6182 * @param string $prefix Prefix for the returned ID.
     6183 * @return string Unique ID.
     6184 */
     6185function wp_unique_id( $prefix = '' ) {
     6186    static $id_counter = 0;
     6187    return $prefix . (string) ++$id_counter;
     6188}
     6189
     6190/**
    61716191 * Get last changed date for the specified cache group.
    61726192 *
  • trunk/tests/phpunit/tests/functions.php

    r43633 r43658  
    11191119
    11201120    /**
     1121     * Tests wp_unique_id().
     1122     *
     1123     * @covers ::wp_unique_id
     1124     * @ticket 44883
     1125     */
     1126    function test_wp_unique_id() {
     1127
     1128        // Test without prefix.
     1129        $ids = array();
     1130        for ( $i = 0; $i < 20; $i += 1 ) {
     1131            $id = wp_unique_id();
     1132            $this->assertInternalType( 'string', $id );
     1133            $this->assertTrue( is_numeric( $id ) );
     1134            $ids[] = $id;
     1135        }
     1136        $this->assertEquals( $ids, array_unique( $ids ) );
     1137
     1138        // Test with prefix.
     1139        $ids = array();
     1140        for ( $i = 0; $i < 20; $i += 1 ) {
     1141            $id = wp_unique_id( 'foo-' );
     1142            $this->assertRegExp( '/^foo-\d+$/', $id );
     1143            $ids[] = $id;
     1144        }
     1145        $this->assertEquals( $ids, array_unique( $ids ) );
     1146    }
     1147
     1148    /**
    11211149     * @ticket 40017
    11221150     * @dataProvider _wp_get_image_mime
Note: See TracChangeset for help on using the changeset viewer.