38
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP UUID version4 を生成する

Last updated at Posted at 2019-10-29

環境

PHP 7.3.1

コード

uuid_v4_factory.php

<?php declare(strict_types=1);

/**
 * UUID version 4
 */
class UuidV4Factory
{
    const PATTERN = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';

    /**
     * UUID 生成
     * @return string
     * @throws \Exception
     */
    public static function generate(): string
    {
        $chars = str_split(self::PATTERN);

        foreach ($chars as $i => $char) {
            if ($char === 'x') {
                $chars[$i] = dechex(random_int(0, 15));
            } elseif ($char === 'y') {
                $chars[$i] = dechex(random_int(8, 11));
            }
        }

        return implode('', $chars);
    }
}

使い方

$ php -a
php > require('uuid_v4_factory.php');
php > echo UuidV4Factory::generate();
3c68e561-2281-40a1-bcf6-91fe971b00e8
php > echo UuidV4Factory::generate();
de527f63-8f60-4034-aa21-bc091db13d6d
php > echo UuidV4Factory::generate();
4d052519-cc4f-4a51-9910-ed3c2842e457
php > echo UuidV4Factory::generate();
b796ef1a-1bb9-4d37-97d4-45f2f6da742f

500万回のUUID衝突テスト

<?php declare(strict_types=1);

ini_set('memory_limit', '-1');

require('./uuid_v4_factory.php');

$baseMemoryUsage = memory_get_usage();
$baseTime = microtime(true);

$data = [];
for ($i = 0; $i < 5000000; $i++) {
    $uuid = UuidV4Factory::generate();
    if (isset($data[$uuid])) {
        echo 'UuidDuplicateError' . PHP_EOL;
    }
    $data[$uuid] = true;
}

$maxMemoryUsage = (memory_get_peak_usage() - $baseMemoryUsage) / (1024 * 1024);
$processTime = microtime(true) - $baseTime;

echo sprintf('Max Memory Usage: %.3f [MB]', $maxMemoryUsage) . PHP_EOL;
echo sprintf('Process Time: %.2f [s]', $processTime) . PHP_EOL;
$ php uuid_v4_factory_test.php
Max Memory Usage: 736.000 [MB]
Process Time: 187.68 [s]

500万回を3回実行してみましたが、衝突はしませんでした。

参考

38
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?