WordPress.org

Make WordPress Core

Changeset 44407


Ignore:
Timestamp:
01/06/2019 08:07:34 PM (11 months ago)
Author:
desrosj
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.

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

Location:
branches/5.0
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branches/5.0

  • branches/5.0/src/wp-includes/functions.php

    r43988 r44407  
    57955795
    57965796/**
     5797 * Get unique ID.
     5798 *
     5799 * This is a PHP implementation of Underscore's uniqueId method. A static variable
     5800 * contains an integer that is incremented with each call. This number is returned
     5801 * with the optional prefix. As such the returned value is not universally unique,
     5802 * but it is unique across the life of the PHP process.
     5803 *
     5804 * @since 5.0.3
     5805 *
     5806 * @staticvar int $id_counter
     5807 *
     5808 * @param string $prefix Prefix for the returned ID.
     5809 * @return string Unique ID.
     5810 */
     5811function wp_unique_id( $prefix = '' ) {
     5812    static $id_counter = 0;
     5813    return $prefix . (string) ++$id_counter;
     5814}
     5815
     5816/**
    57975817 * Get last changed date for the specified cache group.
    57985818 *
  • branches/5.0/tests/phpunit/tests/functions.php

    r43988 r44407  
    961961
    962962    /**
     963     * Tests wp_unique_id().
     964     *
     965     * @covers ::wp_unique_id
     966     * @ticket 44883
     967     */
     968    function test_wp_unique_id() {
     969
     970        // Test without prefix.
     971        $ids = array();
     972        for ( $i = 0; $i < 20; $i += 1 ) {
     973            $id = wp_unique_id();
     974            $this->assertInternalType( 'string', $id );
     975            $this->assertTrue( is_numeric( $id ) );
     976            $ids[] = $id;
     977        }
     978        $this->assertEquals( $ids, array_unique( $ids ) );
     979
     980        // Test with prefix.
     981        $ids = array();
     982        for ( $i = 0; $i < 20; $i += 1 ) {
     983            $id = wp_unique_id( 'foo-' );
     984            $this->assertRegExp( '/^foo-\d+$/', $id );
     985            $ids[] = $id;
     986        }
     987        $this->assertEquals( $ids, array_unique( $ids ) );
     988    }
     989
     990    /**
    963991     * @ticket 40017
    964992     * @dataProvider _wp_get_image_mime
Note: See TracChangeset for help on using the changeset viewer.