Repository: ramsey/uuid Branch: 4.x Commit: 39d47ce3362c Files: 287 Total size: 1002.0 KB Directory structure: gitextract_l3omq1zh/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── CODEOWNERS │ ├── ISSUE_TEMPLATE/ │ │ ├── Bug_Report.md │ │ ├── Feature_Request.md │ │ ├── Question.md │ │ └── config.yml │ ├── dependabot.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── continuous-integration.yml │ └── merge-me.yml ├── .gitignore ├── .readthedocs.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── build/ │ ├── .gitignore │ ├── cache/ │ │ └── .gitkeep │ └── logs/ │ └── .gitkeep ├── captainhook.json ├── codecov.yml ├── composer.json ├── docs/ │ ├── .gitignore │ ├── LICENSE │ ├── Makefile │ ├── README.md │ ├── _static/ │ │ └── .gitkeep │ ├── conf.py │ ├── copyright.rst │ ├── customize/ │ │ ├── calculators.rst │ │ ├── factory.rst │ │ ├── ordered-time-codec.rst │ │ ├── timestamp-first-comb-codec.rst │ │ └── validators.rst │ ├── customize.rst │ ├── database.rst │ ├── faq.rst │ ├── index.rst │ ├── introduction.rst │ ├── nonstandard/ │ │ ├── guid.rst │ │ ├── other.rst │ │ └── version6.rst │ ├── nonstandard.rst │ ├── quickstart.rst │ ├── reference/ │ │ ├── calculators.rst │ │ ├── exceptions.rst │ │ ├── fields-fieldsinterface.rst │ │ ├── guid-fields.rst │ │ ├── guid-guid.rst │ │ ├── helper.rst │ │ ├── name-based-namespaces.rst │ │ ├── nonstandard-fields.rst │ │ ├── nonstandard-uuid.rst │ │ ├── nonstandard-uuidv6.rst │ │ ├── rfc4122-fieldsinterface.rst │ │ ├── rfc4122-uuidinterface.rst │ │ ├── rfc4122-uuidv1.rst │ │ ├── rfc4122-uuidv2.rst │ │ ├── rfc4122-uuidv3.rst │ │ ├── rfc4122-uuidv4.rst │ │ ├── rfc4122-uuidv5.rst │ │ ├── rfc4122-uuidv6.rst │ │ ├── rfc4122-uuidv7.rst │ │ ├── rfc4122-uuidv8.rst │ │ ├── types.rst │ │ ├── uuid.rst │ │ ├── uuidfactoryinterface.rst │ │ ├── uuidinterface.rst │ │ └── validators.rst │ ├── reference.rst │ ├── requirements.txt │ ├── rfc4122/ │ │ ├── version1.rst │ │ ├── version2.rst │ │ ├── version3.rst │ │ ├── version4.rst │ │ ├── version5.rst │ │ ├── version6.rst │ │ ├── version7.rst │ │ └── version8.rst │ ├── rfc4122.rst │ ├── testing.rst │ ├── upgrading/ │ │ ├── 2-to-3.rst │ │ └── 3-to-4.rst │ └── upgrading.rst ├── phpbench.json ├── phpcs.xml.dist ├── phpstan.neon.dist ├── phpunit.xml.dist ├── resources/ │ └── vagrant/ │ ├── .gitignore │ ├── README.md │ ├── freebsd/ │ │ ├── README.md │ │ └── Vagrantfile │ ├── linux/ │ │ ├── README.md │ │ └── Vagrantfile │ └── windows/ │ ├── README.md │ └── Vagrantfile ├── src/ │ ├── BinaryUtils.php │ ├── Builder/ │ │ ├── BuilderCollection.php │ │ ├── DefaultUuidBuilder.php │ │ ├── DegradedUuidBuilder.php │ │ ├── FallbackBuilder.php │ │ └── UuidBuilderInterface.php │ ├── Codec/ │ │ ├── CodecInterface.php │ │ ├── GuidStringCodec.php │ │ ├── OrderedTimeCodec.php │ │ ├── StringCodec.php │ │ ├── TimestampFirstCombCodec.php │ │ └── TimestampLastCombCodec.php │ ├── Converter/ │ │ ├── Number/ │ │ │ ├── BigNumberConverter.php │ │ │ ├── DegradedNumberConverter.php │ │ │ └── GenericNumberConverter.php │ │ ├── NumberConverterInterface.php │ │ ├── Time/ │ │ │ ├── BigNumberTimeConverter.php │ │ │ ├── DegradedTimeConverter.php │ │ │ ├── GenericTimeConverter.php │ │ │ ├── PhpTimeConverter.php │ │ │ └── UnixTimeConverter.php │ │ └── TimeConverterInterface.php │ ├── DegradedUuid.php │ ├── DeprecatedUuidInterface.php │ ├── DeprecatedUuidMethodsTrait.php │ ├── Exception/ │ │ ├── BuilderNotFoundException.php │ │ ├── DateTimeException.php │ │ ├── DceSecurityException.php │ │ ├── InvalidArgumentException.php │ │ ├── InvalidBytesException.php │ │ ├── InvalidUuidStringException.php │ │ ├── NameException.php │ │ ├── NodeException.php │ │ ├── RandomSourceException.php │ │ ├── TimeSourceException.php │ │ ├── UnableToBuildUuidException.php │ │ ├── UnsupportedOperationException.php │ │ └── UuidExceptionInterface.php │ ├── FeatureSet.php │ ├── Fields/ │ │ ├── FieldsInterface.php │ │ └── SerializableFieldsTrait.php │ ├── Generator/ │ │ ├── CombGenerator.php │ │ ├── DceSecurityGenerator.php │ │ ├── DceSecurityGeneratorInterface.php │ │ ├── DefaultNameGenerator.php │ │ ├── DefaultTimeGenerator.php │ │ ├── NameGeneratorFactory.php │ │ ├── NameGeneratorInterface.php │ │ ├── PeclUuidNameGenerator.php │ │ ├── PeclUuidRandomGenerator.php │ │ ├── PeclUuidTimeGenerator.php │ │ ├── RandomBytesGenerator.php │ │ ├── RandomGeneratorFactory.php │ │ ├── RandomGeneratorInterface.php │ │ ├── RandomLibAdapter.php │ │ ├── TimeGeneratorFactory.php │ │ ├── TimeGeneratorInterface.php │ │ └── UnixTimeGenerator.php │ ├── Guid/ │ │ ├── Fields.php │ │ ├── Guid.php │ │ └── GuidBuilder.php │ ├── Lazy/ │ │ └── LazyUuidFromString.php │ ├── Math/ │ │ ├── BrickMathCalculator.php │ │ ├── CalculatorInterface.php │ │ └── RoundingMode.php │ ├── Nonstandard/ │ │ ├── Fields.php │ │ ├── Uuid.php │ │ ├── UuidBuilder.php │ │ └── UuidV6.php │ ├── Provider/ │ │ ├── Dce/ │ │ │ └── SystemDceSecurityProvider.php │ │ ├── DceSecurityProviderInterface.php │ │ ├── Node/ │ │ │ ├── FallbackNodeProvider.php │ │ │ ├── NodeProviderCollection.php │ │ │ ├── RandomNodeProvider.php │ │ │ ├── StaticNodeProvider.php │ │ │ └── SystemNodeProvider.php │ │ ├── NodeProviderInterface.php │ │ ├── Time/ │ │ │ ├── FixedTimeProvider.php │ │ │ └── SystemTimeProvider.php │ │ └── TimeProviderInterface.php │ ├── Rfc4122/ │ │ ├── Fields.php │ │ ├── FieldsInterface.php │ │ ├── MaxTrait.php │ │ ├── MaxUuid.php │ │ ├── NilTrait.php │ │ ├── NilUuid.php │ │ ├── TimeTrait.php │ │ ├── UuidBuilder.php │ │ ├── UuidInterface.php │ │ ├── UuidV1.php │ │ ├── UuidV2.php │ │ ├── UuidV3.php │ │ ├── UuidV4.php │ │ ├── UuidV5.php │ │ ├── UuidV6.php │ │ ├── UuidV7.php │ │ ├── UuidV8.php │ │ ├── Validator.php │ │ ├── VariantTrait.php │ │ └── VersionTrait.php │ ├── Type/ │ │ ├── Decimal.php │ │ ├── Hexadecimal.php │ │ ├── Integer.php │ │ ├── NumberInterface.php │ │ ├── Time.php │ │ └── TypeInterface.php │ ├── Uuid.php │ ├── UuidFactory.php │ ├── UuidFactoryInterface.php │ ├── UuidInterface.php │ ├── Validator/ │ │ ├── GenericValidator.php │ │ └── ValidatorInterface.php │ └── functions.php └── tests/ ├── BinaryUtilsTest.php ├── Builder/ │ ├── DefaultUuidBuilderTest.php │ └── FallbackBuilderTest.php ├── Codec/ │ ├── GuidStringCodecTest.php │ ├── OrderedTimeCodecTest.php │ └── StringCodecTest.php ├── Converter/ │ ├── Number/ │ │ ├── BigNumberConverterTest.php │ │ └── GenericNumberConverterTest.php │ └── Time/ │ ├── BigNumberTimeConverterTest.php │ ├── GenericTimeConverterTest.php │ ├── PhpTimeConverterTest.php │ └── UnixTimeConverterTest.php ├── DeprecatedUuidMethodsTraitTest.php ├── Encoder/ │ ├── TimestampFirstCombCodecTest.php │ └── TimestampLastCombCodecTest.php ├── ExpectedBehaviorTest.php ├── FeatureSetTest.php ├── FunctionsTest.php ├── Generator/ │ ├── CombGeneratorTest.php │ ├── DceSecurityGeneratorTest.php │ ├── DefaultNameGeneratorTest.php │ ├── DefaultTimeGeneratorTest.php │ ├── NameGeneratorFactoryTest.php │ ├── PeclUuidNameGeneratorTest.php │ ├── PeclUuidRandomGeneratorTest.php │ ├── PeclUuidTimeGeneratorTest.php │ ├── RandomBytesGeneratorTest.php │ ├── RandomGeneratorFactoryTest.php │ ├── RandomLibAdapterTest.php │ ├── TimeGeneratorFactoryTest.php │ └── UnixTimeGeneratorTest.php ├── Guid/ │ ├── FieldsTest.php │ └── GuidBuilderTest.php ├── Math/ │ └── BrickMathCalculatorTest.php ├── Nonstandard/ │ ├── FieldsTest.php │ ├── UuidBuilderTest.php │ └── UuidV6Test.php ├── Provider/ │ ├── Dce/ │ │ └── SystemDceSecurityProviderTest.php │ ├── Node/ │ │ ├── FallbackNodeProviderTest.php │ │ ├── RandomNodeProviderTest.php │ │ ├── StaticNodeProviderTest.php │ │ └── SystemNodeProviderTest.php │ └── Time/ │ ├── FixedTimeProviderTest.php │ └── SystemTimeProviderTest.php ├── Rfc4122/ │ ├── FieldsTest.php │ ├── UuidBuilderTest.php │ ├── UuidV1Test.php │ ├── UuidV2Test.php │ ├── UuidV3Test.php │ ├── UuidV4Test.php │ ├── UuidV5Test.php │ ├── UuidV6Test.php │ ├── UuidV7Test.php │ ├── UuidV8Test.php │ ├── ValidatorTest.php │ └── VariantTraitTest.php ├── TestCase.php ├── Type/ │ ├── DecimalTest.php │ ├── HexadecimalTest.php │ ├── IntegerTest.php │ └── TimeTest.php ├── UuidFactoryTest.php ├── UuidTest.php ├── Validator/ │ └── GenericValidatorTest.php ├── benchmark/ │ ├── GuidConversionBench.php │ ├── NonLazyUuidConversionBench.php │ ├── UuidFieldExtractionBench.php │ ├── UuidGenerationBench.php │ ├── UuidSerializationBench.php │ └── UuidStringConversionBench.php ├── bootstrap.php └── static-analysis/ ├── UuidIsImmutable.php ├── UuidIsNeverEmpty.php ├── ValidUuidIsNonEmpty.php └── stubs.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig http://EditorConfig.org # top-most EditorConfig file root = true # This applies to all files [*] end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true charset = utf-8 indent_style = space indent_size = 4 [*.{yml,yaml}] indent_size = 2 ================================================ FILE: .gitattributes ================================================ /.allowed-licenses export-ignore /.editorconfig export-ignore /.gitattributes export-ignore /.github/ export-ignore /.gitignore export-ignore /.readthedocs.yml export-ignore /bin/ export-ignore /build/ export-ignore /captainhook.json export-ignore /CHANGELOG.md export-ignore /composer.lock export-ignore /codecov.yml export-ignore /CODE_OF_CONDUCT.md export-ignore /CONTRIBUTING.md export-ignore /conventional-commits.json export-ignore /docs/ export-ignore /phpbench.json export-ignore /phpcs.xml.dist export-ignore /phpstan-tests.neon export-ignore /phpstan.neon.dist export-ignore /phpunit.xml.dist export-ignore /resources/ export-ignore /SECURITY.md export-ignore /tests/ export-ignore ================================================ FILE: .github/CODEOWNERS ================================================ * @ramsey ================================================ FILE: .github/ISSUE_TEMPLATE/Bug_Report.md ================================================ --- name: Bug Report about: Create a bug report to help us improve labels: bug assignees: --- ## Description ## Steps to reproduce 1. Step one... 2. Step two... 3. Step three... ## Expected behavior ## Screenshots or output ## Environment details - version of this package: *e.g. 1.0.0, 1.0.1, 1.1.0* - PHP version: *e.g. 7.3.16, 7.4.4* - OS: *e.g. Windows 10, Linux (Ubuntu 18.04.1), macOS Catalina (10.15.3)* ## Additional context ================================================ FILE: .github/ISSUE_TEMPLATE/Feature_Request.md ================================================ --- name: Feature Request about: Suggest a feature for this project labels: enhancement assignees: --- ## My feature title ## Background/problem ## Proposal/solution ## Alternatives ## Additional context ================================================ FILE: .github/ISSUE_TEMPLATE/Question.md ================================================ --- name: Question about: Ask a question about how to use this library labels: question assignees: --- ## How do I... ? ## Example code ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "composer" allow: - dependency-type: all directory: "/" schedule: interval: "weekly" open-pull-requests-limit: 1 versioning-strategy: "increase-if-necessary" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" open-pull-requests-limit: 1 ================================================ FILE: .github/pull_request_template.md ================================================ ## Description ## Motivation and context ## How has this been tested? ## Types of changes - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) ## PR checklist - [ ] My change requires a change to the documentation. - [ ] I have updated the documentation accordingly. - [ ] I have read the **CONTRIBUTING.md** document. - [ ] I have added tests to cover my changes. ================================================ FILE: .github/workflows/continuous-integration.yml ================================================ # GitHub Actions Documentation: https://docs.github.com/en/actions name: "Continuous Integration" on: push: branches: - "*.x" tags: - "*" pull_request: branches: - "*.x" # Cancels all previous workflow runs for the same branch that have not yet completed. concurrency: # The concurrency group contains the workflow name and the branch name. group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true env: COMPOSER_ROOT_VERSION: "1.99.99" jobs: coding-standards: name: "Coding standards" runs-on: "ubuntu-latest" steps: - name: "Checkout repository" uses: "actions/checkout@v6" - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: php-version: "latest" coverage: "none" - name: "Install dependencies (Composer)" uses: "ramsey/composer-install@v4" with: dependency-versions: "highest" - name: "Check syntax (php-parallel-lint)" run: "composer dev:lint:syntax" - name: "Check coding standards (PHP_CodeSniffer)" run: "composer dev:lint:style" static-analysis: name: "Static analysis" runs-on: "ubuntu-latest" steps: - name: "Checkout repository" uses: "actions/checkout@v6" - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: php-version: "latest" coverage: "none" - name: "Install dependencies (Composer)" uses: "ramsey/composer-install@v4" with: dependency-versions: "highest" - name: "Statically analyze code (PHPStan)" run: "composer dev:analyze:phpstan" benchmark: name: "Benchmark" needs: ["coding-standards", "static-analysis"] runs-on: "ubuntu-latest" strategy: fail-fast: false matrix: php-version: - "8.0" - "8.1" - "8.2" - "8.3" - "8.4" - "8.5" steps: - name: "Checkout repository" uses: "actions/checkout@v6" - name: "Install dependencies (apt)" run: | sudo apt-get update sudo apt-get -y install libsodium-dev uuid-dev - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: php-version: "${{ matrix.php-version }}" extensions: bcmath, gmp, sodium, uuid coverage: "none" ini-values: "memory_limit=-1" - name: "Install dependencies (Composer)" uses: "ramsey/composer-install@v4" with: dependency-versions: "highest" - name: "Run benchmarks (PHPBench)" run: "composer dev:bench" code-coverage: name: "Code coverage" needs: ["coding-standards", "static-analysis"] runs-on: "ubuntu-latest" steps: - name: "Checkout repository" uses: "actions/checkout@v6" - name: "Install dependencies (apt)" run: | sudo apt-get update sudo apt-get -y install libsodium-dev uuid-dev - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: php-version: "latest" extensions: bcmath, gmp, sodium, uuid coverage: "xdebug" ini-values: "memory_limit=-1" - name: "Install dependencies (Composer)" uses: "ramsey/composer-install@v4" with: dependency-versions: "highest" - name: "Run unit tests (PHPUnit)" run: "composer dev:test:coverage:ci" - name: "Publish coverage report to Codecov" uses: "codecov/codecov-action@v5" - name: "Upload test results to Codecov" if: ${{ !cancelled() }} uses: "codecov/test-results-action@v1" with: disable_search: true file: "./build/junit.xml" unit-tests: name: "Unit Tests" needs: ["code-coverage"] runs-on: ${{ matrix.operating-system }} strategy: fail-fast: false matrix: php-version: - "8.0" - "8.1" - "8.2" - "8.3" - "8.4" - "8.5" operating-system: - "ubuntu-latest" - "windows-latest" dependency-versions: - "locked" - "highest" steps: - name: "Configure Git (for Windows)" if: ${{ matrix.operating-system == 'windows-latest' }} run: | git config --system core.autocrlf false git config --system core.eol lf - name: "Checkout repository" uses: "actions/checkout@v6" - name: "Install dependencies (apt)" if: ${{ matrix.operating-system == 'ubuntu-latest' }} run: | sudo apt-get update sudo apt-get -y install libsodium-dev uuid-dev - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: php-version: "${{ matrix.php-version }}" extensions: bcmath, gmp, sodium, uuid coverage: "none" ini-values: "memory_limit=-1" - name: "Downgrade brick/math in lock file for PHP 8.0" run: | composer update brick/math:"0.8.16" - name: "Install dependencies (Composer)" uses: "ramsey/composer-install@v4" with: dependency-versions: "${{ matrix.dependency-versions }}" - name: "Run unit tests (PHPUnit)" run: "composer dev:test:unit" ================================================ FILE: .github/workflows/merge-me.yml ================================================ # Merge Me! Documentation: https://github.com/ridedott/merge-me-action/ name: "Merge Dependabot PRs" on: workflow_run: types: - "completed" workflows: - "Continuous Integration" jobs: merge-me: name: "Merge me!" runs-on: "ubuntu-latest" steps: - name: "Auto-merge" if: ${{ github.event.workflow_run.conclusion == 'success' }} uses: "ridedott/merge-me-action@v2" with: # This must be used as the GitHub Actions token does not support pushing # to protected branches. # # Create a token with repository permissions: # https://github.com/settings/tokens/new?scopes=repo&description=Merge+Me!+GitHub+Actions+Workflow # # Set MERGE_TOKEN as an environment variable on your repository: # https://github.com/yourname/repo-name/settings/secrets/actions/new GITHUB_TOKEN: ${{ secrets.MERGE_TOKEN }} ================================================ FILE: .gitignore ================================================ /captainhook.config.json /phpcs.xml /phpunit.xml /vendor/ ================================================ FILE: .readthedocs.yml ================================================ version: 2 build: os: ubuntu-22.04 tools: python: "3.12" sphinx: configuration: docs/conf.py formats: all python: install: - requirements: docs/requirements.txt ================================================ FILE: CHANGELOG.md ================================================ # ramsey/uuid Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## 4.9.2 - 2025-12-14 ### Fixed * Remove explicit `(int)` cast to avoid float-string cast warnings in PHP 8.5. * Bump the lowest supported version of brick/math to `^0.8.16` from `^0.8.8`. ramsey/uuid had been using `BigInteger::toBytes()` in `UnixTimeGenerator` (for version 7 UUIDs) since v4.6.0, but it wasn't added to brick/math until v0.8.16. ## 4.9.1 - 2025-09-04 ### Fixed * Allow brick/math version `^0.14`; fixed in [#617](https://github.com/ramsey/uuid/pull/617). * Default to `microtime()` instead of `DateTimeImmutable` in `Ramsey\Uuid\Generator\UnixTimeGenerator`. ## 4.9.0 - 2025-06-25 ### Added * Add new `@pure` annotations to the following ([#605](https://github.com/ramsey/uuid/pull/605)): * `Ramsey\Uuid\Codec\CodecInterface::encode()` * `Ramsey\Uuid\Codec\CodecInterface::encodeBinary()` * `Ramsey\Uuid\Codec\CodecInterface::decode()` * `Ramsey\Uuid\Codec\CodecInterface::decodeBytes()` * `Ramsey\Uuid\Fields\FieldsInterface::getBytes()` * `Ramsey\Uuid\Math\CalculatorInterface::add()` * `Ramsey\Uuid\Math\CalculatorInterface::subtract()` * `Ramsey\Uuid\Math\CalculatorInterface::multiply()` * `Ramsey\Uuid\Math\CalculatorInterface::divide()` * `Ramsey\Uuid\Math\CalculatorInterface::fromBase()` * `Ramsey\Uuid\Math\CalculatorInterface::toBase()` * `Ramsey\Uuid\Math\CalculatorInterface::toHexadecimal()` * `Ramsey\Uuid\Math\CalculatorInterface::toInteger()` * `Ramsey\Uuid\Nonstandard\Uuid` * `Ramsey\Uuid\Rfc4122\Fields::isMax()` * `Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()` * `Ramsey\Uuid\Rfc4122\FieldsInterface::isNil()` * `Ramsey\Uuid\Type\Time::getSeconds()` * `Ramsey\Uuid\Type\Time::getMicroseconds()` * `Ramsey\Uuid\Type\TypeInterface::toString()` * `Ramsey\Uuid\UuidInterface::getBytes()` * `Ramsey\Uuid\UuidInterface::toString()` * `Ramsey\Uuid\Validator\ValidatorInterface::validate()` ### Fixed * Restore the `@pure` annotations that were removed in 4.8.0 ([#603](https://github.com/ramsey/uuid/pull/603)). ## 4.8.1 - 2025-06-01 ### Fixed * This tagged release ensures the stable documentation build matches the current stable release. ## 4.8.0 - 2025-06-01 ### Deprecated The following will be removed in ramsey/uuid 5.0.0: * `Ramsey\Uuid\Codec\OrderedTimeCodec` is deprecated; please migrate to [version 6 UUIDs](https://uuid.ramsey.dev/en/stable/rfc4122/version6.html). * `Ramsey\Uuid\Codec\TimestampFirstCombCodec` is deprecated; please migrate to [version 7 UUIDs](https://uuid.ramsey.dev/en/stable/rfc4122/version7.html). * `Ramsey\Uuid\Codec\TimestampLastCombCodec` is deprecated; please use `Ramsey\Uuid\Codec\StringCodec` instead. * `Ramsey\Uuid\Generator\CombGenerator` is deprecated; please migrate to [version 7 UUIDs](https://uuid.ramsey.dev/en/stable/rfc4122/version7.html). ### Fixed * Allow brick/math version `^0.13`; fixed in [#589](https://github.com/ramsey/uuid/pull/589). * Update call to `str_getcsv()` to avoid deprecation notice in PHP 8.4; fixed in [#590](https://github.com/ramsey/uuid/pull/590). * Hexadecimal is never an empty string; fixed in [#593](https://github.com/ramsey/uuid/pull/593). * Update docblocks for `Uuid::fromBytes()`, `Uuid::fromString()`, `Uuid::fromDateTime()`, `Uuid::fromHexadecimal()`, and `Uuid::fromInteger()` to note that each can throw `InvalidArgumentException`, addressing PHPStan errors occurring at call sites; fixed in [#552](https://github.com/ramsey/uuid/pull/552). * `getVariant()` for `MaxUuid` now correctly returns `Uuid::RESERVED_FUTURE`, as specified in [RFC 9562, section 5.10](https://www.rfc-editor.org/rfc/rfc9562#section-5.10). * `getVariant()` for `NilUuid` now correctly returns `Uuid::RESERVED_NCS`, as specified in [RFC 9562, section 5.9](https://www.rfc-editor.org/rfc/rfc9562#section-5.9). ## 4.7.6 - 2024-04-27 ### Fixed * Allow brick/math version `^0.12`. ## 4.7.5 - 2023-11-08 ### Fixed * Protect against UUIDv7 collisions within the same millisecond, as reported in [#518](https://github.com/ramsey/uuid/issues/518) and fixed in [#522](https://github.com/ramsey/uuid/pull/522). * Improve the return type hint for `UuidInterface::compareTo()`. ## 4.7.4 - 2023-04-15 ### Fixed * Allow brick/math version `^0.11`. * Add explicit `Stringable` interface to `UuidInterface`. * Fix namespace conflict reported in [#490](https://github.com/ramsey/uuid/issues/490). * Fix unserialize error with `OrderedTimeCodec` reported in [#494](https://github.com/ramsey/uuid/issues/494). ## 4.7.3 - 2023-01-12 ### Fixed * The original 4.7.2 tag accidentally pointed to a commit in the 5.x branch. I have replaced the 4.7.2 tag with a new tag that points to the correct commit, but I am creating this tag to help notify users and automated processes who might have already updated to the bad 4.7.2 tag. ## 4.7.2 - 2023-01-12 ### Fixed * Amend Psalm assertion syntax on `Uuid::isValid()` to prevent incorrect type inference ([#486](https://github.com/ramsey/uuid/pull/486)). * Re-tagged with the correct commit hash, since the first tag was pointing to a commit in the 5.x branch. ## 4.7.1 - 2022-12-31 ### Fixed * Allow the use of ramsey/collection ^2.0 with ramsey/uuid. ## 4.7.0 - 2022-12-19 ### Added * Add `Uuid::fromHexadecimal()` and `UuidFactory::fromHexadecimal()`. These methods are not required by the interfaces. ### Fixed * Ignore MAC addresses consisting of all zeroes (i.e., `00:00:00:00:00:00`). ## 4.6.0 - 2022-11-05 ### Added * Add support for version 8, Unix Epoch time UUIDs, as defined in [draft-ietf-uuidrev-rfc4122bis-00, section 5.8][version8]. While still an Internet-Draft, version 8 is stable and unlikely to change in any way that breaks compatibility. * Use `Ramsey\Uuid\Uuid::uuid8()` to generate version 8 UUIDs. * Version 8 UUIDs are of type `Ramsey\Uuid\Rfc4122\UuidV8`. * The constant `Ramsey\Uuid\Uuid::UUID_TYPE_CUSTOM` exists for version 8 UUIDs. ### Fixed * Ensure monotonicity of version 7 UUIDs. ## 4.5.1 - 2022-09-16 ### Fixed * Update RFC 4122 validator to recognize version 6 and 7 UUIDs. ## 4.5.0 - 2022-09-15 ### Added * Promote version 6, reordered time UUIDs from the `Nonstandard` namespace to the `Rfc4122` namespace. Version 6 UUIDs are defined in [draft-ietf-uuidrev-rfc4122bis-00, section 5.6][version6]. While still an Internet-Draft version 6 is stable and unlikely to change in any way that breaks compatibility. * Add support for version 7, Unix Epoch time UUIDs, as defined in [draft-ietf-uuidrev-rfc4122bis-00, section 5.7][version7]. While still an Internet-Draft, version 7 is stable and unlikely to change in any way that breaks compatibility. * Use `Ramsey\Uuid\Uuid::uuid7()` to generate version 7 UUIDs. * Version 7 UUIDs are of type `Ramsey\Uuid\Rfc4122\UuidV7`. * The constant `Ramsey\Uuid\Uuid::UUID_TYPE_UNIX_TIME` exists for version 7 UUIDs. * Add `Ramsey\Uuid\Converter\Time\UnixTimeConverter` and `Ramsey\Uuid\Generator\UnixTimeGenerator` to support version 7 UUID generation. * Add support for [max UUIDs][] through `Ramsey\Uuid\Uuid::MAX` and `Ramsey\Uuid\Rfc4122\MaxUuid`. ### Changed * The lowest version of brick/math allowed is now `^0.8.8`. ### Deprecated The following will be removed in ramsey/uuid 5.0.0: * `Ramsey\Uuid\Nonstandard\UuidV6` is deprecated in favor of `Ramsey\Uuid\Rfc4122\UuidV6`. * `Ramsey\Uuid\Uuid::UUID_TYPE_PEABODY`; use `Ramsey\Uuid\Uuid::UUID_TYPE_REORDERED_TIME` instead. ### Fixed * For `Ramsey\Uuid\Uuid::isValid()`, Psalm now asserts the UUID is a non-empty-string when it is valid. * Nil UUIDs are properly treated as RFC 4122 variants, and `getVariant()` now returns a `2` when called on a nil UUID. ## 4.4.0 - 2022-08-05 ### Changed * Allow brick/math 0.10. * Remove dev dependency to moontoast/math. * Un-deprecate `UuidInterface::getUrn()`. ## 4.3.1 - 2022-03-27 ### Deprecated The following will be removed in ramsey/uuid 5.0.0: * `Ramsey\Uuid\Generator\RandomLibAdapter` ## 4.3.0 - 2022-03-26 ### Changed * Remove support for PHP 7.2, 7.3, and 7.4. This is not a BC break, since Composer will do the right thing for your environment and select a compatible version of this library. * Require `ext-ctype` extension. For applications that run in environments where the `ext-ctype` is not present, please require a polyfill, such as [symfony/polyfill-ctype](https://packagist.org/packages/symfony/polyfill-ctype). * Use `iterable` instead of `BuilderCollection` types. * Use `iterable` instead of `NodeProviderCollection` types. ### Deprecated The following will be removed in ramsey/uuid 5.0.0: * `Ramsey\Uuid\Builder\BuilderCollection` * `Ramsey\Uuid\Provider\Node\NodeProviderCollection` * Dependency on ramsey/collection ### Fixed * Support valid UUIDs in uppercase in `LazyUuidFromString`. ## 4.2.3 - 2021-09-25 ### Fixed * Switch back to `^8.0` in the PHP version requirement. ## 4.2.2 - 2021-09-24 ### Fixed * Indicate support for PHP 8.1, using `~8.1.0` to prevent installations on 8.2 until the library is ready. ## 4.2.1 - 2021-08-10 ### Fixed * Fix *soft* BC break with `Uuid::fromString()` signature. The change from `string` to `non-empty-string` on the parameter annotation introduced a BC break for those using static analysis tools. This release reverts this change and provides an assertion to guard against empty strings. See [ramsey/uuid#383](https://github.com/ramsey/uuid/pull/383). ## 4.2.0 - 2021-08-06 ### Added * Add `Ramsey\Uuid\Exception\UuidExceptionInterface` for all ramsey/uuid exceptions to implement. See [ramsey/uuid#340](https://github.com/ramsey/uuid/pull/340). ### Fixed * Fix serialization of UUIDs. See [ramsey/uuid#361](https://github.com/ramsey/uuid/pull/361). ## 4.1.3 - 2021-09-25 ### Fixed * Switch back to `^8.0` in the PHP version requirement. ## 4.1.2 - 2021-09-24 ### Fixed * Lock 4.1.x to `~8.0.0` to indicate it does not support PHP 8.1. ## 4.1.1 - 2020-08-18 ### Fixed * Allow use of brick/math version 0.9 ## 4.1.0 - 2020-07-28 ### Changed * Improve performance of `Uuid::fromString()`, `Uuid::fromBytes()`, `UuidInterface#toString()`, and `UuidInterface#getBytes()`. See PR [#324](https://github.com/ramsey/uuid/pull/324) for more information. ## 4.0.3 - 2021-09-25 ### Fixed * Switch back to `^8.0` in the PHP version requirement. ## 4.0.2 - 2021-09-24 ### Fixed * Lock 4.0.x to `~8.0.0` to indicate it does not support PHP 8.1. ## 4.0.1 - 2020-03-29 ### Fixed * Fix collection deserialization errors due to upstream `allowed_classes` being set to `false`. For details, see [ramsey/uuid#303](https://github.com/ramsey/uuid/issues/303) and [ramsey/collection#47](https://github.com/ramsey/collection/issues/47). ## 4.0.0 - 2020-03-22 ### Added * Add support for version 6 UUIDs, as defined by , including the static method `Uuid::uuid6()`, which returns a `Nonstandard\UuidV6` instance. * Add ability to generate version 2 (DCE Security) UUIDs, including the static method `Uuid::uuid2()`, which returns an `Rfc4122\UuidV2` instance. * Add classes to represent each version of RFC 4122 UUID. When generating new UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID is an RFC 4122 variant, one of these instances will be returned: * `Rfc4122\UuidV1` * `Rfc4122\UuidV2` * `Rfc4122\UuidV3` * `Rfc4122\UuidV4` * `Rfc4122\UuidV5` * `Rfc4122\NilUuid` * Add classes to represent version 6 UUIDs, GUIDs, and nonstandard (non-RFC 4122 variant) UUIDs: * `Nonstandard\UuidV6` * `Guid\Guid` * `Nonstandard\Uuid` * Add `Uuid::fromDateTime()` to create version 1 UUIDs from instances of `\DateTimeInterface`. * The `\DateTimeInterface` instance returned by `UuidInterface::getDateTime()` (and now `Rfc4122\UuidV1::getDateTime()`) now includes microseconds, as specified by the version 1 UUID. * Add `Validator\ValidatorInterface` and `Validator\GenericValidator` to allow flexibility in validating UUIDs/GUIDs. * The default validator continues to validate UUID strings using the same relaxed validation pattern found in the 3.x series of ramsey/uuid. * Introduce `Rfc4122\Validator` that may be used for strict validation of RFC 4122 UUID strings. * Add ability to change the default validator used by `Uuid` through `FeatureSet::setValidator()`. * Add `getValidator()` and `setValidator()` to `UuidFactory`. * Add `Provider\Node\StaticNodeProvider` to assist in setting a custom static node value with the multicast bit set for version 1 UUIDs. * Add the following new exceptions: * `Exception\BuilderNotFoundException` - Thrown to indicate that no suitable UUID builder could be found. * `Exception\DateTimeException` - Thrown to indicate that the PHP DateTime extension encountered an exception/error. * `Exception\DceSecurityException` - Thrown to indicate an exception occurred while dealing with DCE Security (version 2) UUIDs. * `Exception\InvalidArgumentException` - Thrown to indicate that the argument received is not valid. This extends the built-in PHP `\InvalidArgumentException`, so there should be no BC breaks with ramsey/uuid throwing this exception, if you are catching the PHP exception. * `Exception\InvalidBytesException` - Thrown to indicate that the bytes being operated on are invalid in some way. * `Exception\NameException` - Thrown to indicate that an error occurred while attempting to hash a namespace and name. * `Exception\NodeException` - Throw to indicate that attempting to fetch or create a node ID encountered an error. * `Exception\RandomSourceException` - Thrown to indicate that the source of random data encountered an error. * `Exception\TimeSourceException` - Thrown to indicate that the source of time encountered an error. * `Exception\UnableToBuildUuidException` - Thrown to indicate a builder is unable to build a UUID. * Introduce a `Builder\FallbackBuilder`, used by `FeatureSet` to help decide whether to return a `Uuid` or `Nonstandard\Uuid` when decoding a UUID string or bytes. * Add `Rfc4122\UuidInterface` to specifically represent RFC 4122 variant UUIDs. * Add `Rfc4122\UuidBuilder` to build RFC 4122 variant UUIDs. This replaces the existing `Builder\DefaultUuidBuilder`, which is now deprecated. * Introduce `Math\CalculatorInterface` for representing calculators to perform arithmetic operations on integers. * Depend on [brick/math](https://github.com/brick/math) for the `Math\BrickMathCalculator`, which is the default calculator used by this library when math cannot be performed in native PHP due to integer size limitations. The calculator is configurable and may be changed, if desired. * Add `Converter\Number\GenericNumberConverter` and `Converter\Time\GenericTimeConverter` which will use the calculator provided to convert numbers and time to values for UUIDs. * Introduce `Type\Hexadecimal`, `Type\Integer`, `Type\Decimal`, and `Type\Time` for improved type-safety when dealing with arbitrary string values. * Add a `Type\TypeInterface` that each of the ramsey/uuid types implements. * Add `Fields\FieldsInterface` and `Rfc4122\FieldsInterface` to define field layouts for UUID variants. The implementations `Rfc4122\Fields`, `Guid\Fields`, and `Nonstandard\Fields` store the 16-byte, binary string representation of the UUID internally, and these manage conversion of the binary string into the hexadecimal field values. * Introduce `Builder\BuilderCollection` and `Provider\Node\NodeProviderCollection`. These are typed collections for providing builders and node providers to `Builder\FallbackBuilder` and `Provider\Node\FallbackNodeProvider`, respectively. * Add `Generator\NameGeneratorInterface` to support alternate methods of generating bytes for version 3 and version 5 name-based UUID. By default, ramsey/uuid uses the `Generator\DefaultNameGenerator`, which uses the standard algorithm this library has used since the beginning. You may choose to use the new `Generator\PeclUuidNameGenerator` to make use of the new `uuid_generate_md5()` and `uuid_generate_sha1()` functions in [ext-uuid version 1.1.0](https://pecl.php.net/package/uuid). ### Changed * Set minimum required PHP version to 7.2. * This library now works on 32-bit and 64-bit systems, with no degradation in functionality. * By default, the following static methods will now return specific instance types. This should not cause any BC breaks if typehints target `UuidInterface`: * `Uuid::uuid1` returns `Rfc4122\UuidV1` * `Uuid::uuid3` returns `Rfc4122\UuidV3` * `Uuid::uuid4` returns `Rfc4122\UuidV4` * `Uuid::uuid5` returns `Rfc4122\UuidV5` * Accept `Type\Hexadecimal` for the `$node` parameter for `UuidFactoryInterface::uuid1()`. This is in addition to the `int|string` types already accepted, so there are no BC breaks. `Type\Hexadecimal` is now the recommended type to pass for `$node`. * Out of the box, `Uuid::fromString()`, `Uuid::fromBytes()`, and `Uuid::fromInteger()` will now return either an `Rfc4122\UuidInterface` instance or an instance of `Nonstandard\Uuid`, depending on whether the input contains an RFC 4122 variant UUID with a valid version identifier. Both implement `UuidInterface`, so BC breaks should not occur if typehints use the interface. * Change `Uuid::getFields()` to return an instance of `Fields\FieldsInterface`. Previously, it returned an array of integer values (on 64-bit systems only). * `Uuid::getDateTime()` now returns an instance of `\DateTimeImmutable` instead of `\DateTime`. * Make the following changes to `UuidInterface`: * `getHex()` now returns a `Type\Hexadecimal` instance. * `getInteger()` now returns a `Type\Integer` instance. The `Type\Integer` instance holds a string representation of a 128-bit integer. You may then use a math library of your choice (bcmath, gmp, etc.) to operate on the string integer. * `getDateTime()` now returns `\DateTimeInterface` instead of `\DateTime`. * Add `__toString()` method. * Add `getFields()` method. It returns an instance of `Fields\FieldsInterface`. * Add the following new methods to `UuidFactoryInterface`: * `uuid2()` * `uuid6()` * `fromDateTime()` * `fromInteger()` * `getValidator()` * This library no longer throws generic exceptions. However, this should not result in BC breaks, since the new exceptions extend from built-in PHP exceptions that this library previously threw. * `Exception\UnsupportedOperationException` is now descended from `\LogicException`. Previously, it descended from `\RuntimeException`. * Change required constructor parameters for `Uuid`: * Change the first required constructor parameter for `Uuid` from `array $fields` to `Rfc4122\FieldsInterface $fields`. * Add `Converter\TimeConverterInterface $timeConverter` as the fourth required constructor parameter for `Uuid`. * Change the second required parameter of `Builder\UuidBuilderInterface::build()` from `array $fields` to `string $bytes`. Rather than accepting an array of hexadecimal strings as UUID fields, the `build()` method now expects a byte string. * Add `Converter\TimeConverterInterface $timeConverter` as the second required constructor parameter for `Rfc4122\UuidBuilder`. This also affects the now-deprecated `Builder\DefaultUuidBuilder`, since this class now inherits from `Rfc4122\UuidBuilder`. * Add `convertTime()` method to `Converter\TimeConverterInterface`. * Add `getTime()` method to `Provider\TimeProviderInterface`. It replaces the `currentTime()` method. * `Provider\Node\FallbackNodeProvider` now accepts only a `Provider\Node\NodeProviderCollection` as its constructor parameter. * `Provider\Time\FixedTimeProvider` no longer accepts an array but accepts only `Type\Time` instances. * `Provider\NodeProviderInterface::getNode()` now returns `Type\Hexadecimal` instead of `string|false|null`. * `Converter/TimeConverterInterface::calculateTime()` now returns `Type\Hexadecimal` instead of `array`. The value is the full UUID timestamp value (count of 100-nanosecond intervals since the Gregorian calendar epoch) in hexadecimal format. * Change methods in `NumberConverterInterface` to accept and return string values instead of `mixed`; this simplifies the interface and makes it consistent. * `Generator\DefaultTimeGenerator` no longer adds the variant and version bits to the bytes it returns. These must be applied to the bytes afterwards. * When encoding to bytes or decoding from bytes, `OrderedTimeCodec` now checks whether the UUID is an RFC 4122 variant, version 1 UUID. If not, it will throw an exception—`InvalidArgumentException` when using `OrderedTimeCodec::encodeBinary()` and `UnsupportedOperationException` when using `OrderedTimeCodec::decodeBytes()`. ### Deprecated The following functionality is deprecated and will be removed in ramsey/uuid 5.0.0. * The following methods from `UuidInterface` and `Uuid` are deprecated. Use their counterparts on the `Rfc4122\FieldsInterface` returned by `Uuid::getFields()`. * `getClockSeqHiAndReservedHex()` * `getClockSeqLowHex()` * `getClockSequenceHex()` * `getFieldsHex()` * `getNodeHex()` * `getTimeHiAndVersionHex()` * `getTimeLowHex()` * `getTimeMidHex()` * `getTimestampHex()` * `getVariant()` * `getVersion()` * The following methods from `Uuid` are deprecated. Use the `Rfc4122\FieldsInterface` instance returned by `Uuid::getFields()` to get the `Type\Hexadecimal` value for these fields. You may use the new `Math\CalculatorInterface::toIntegerValue()` method to convert the `Type\Hexadecimal` instances to instances of `Type\Integer`. This library provides `Math\BrickMathCalculator`, which may be used for this purpose, or you may use the arbitrary-precision arithmetic library of your choice. * `getClockSeqHiAndReserved()` * `getClockSeqLow()` * `getClockSequence()` * `getNode()` * `getTimeHiAndVersion()` * `getTimeLow()` * `getTimeMid()` * `getTimestamp()` * `getDateTime()` on `UuidInterface` and `Uuid` is deprecated. Use this method only on instances of `Rfc4122\UuidV1` or `Nonstandard\UuidV6`. * `getUrn()` on `UuidInterface` and `Uuid` is deprecated. It is available on `Rfc4122\UuidInterface` and classes that implement it. * The following methods are deprecated and have no direct replacements. However, you may obtain the same information by calling `UuidInterface::getHex()` and splitting the return value in half. * `UuidInterface::getLeastSignificantBitsHex()` * `UuidInterface::getMostSignificantBitsHex()` * `Uuid::getLeastSignificantBitsHex()` * `Uuid::getMostSignificantBitsHex()` * `Uuid::getLeastSignificantBits()` * `Uuid::getMostSignificantBits()` * `UuidInterface::getNumberConverter()` and `Uuid::getNumberConverter()` are deprecated. There is no alternative recommendation, so plan accordingly. * `Builder\DefaultUuidBuilder` is deprecated; transition to `Rfc4122\UuidBuilder`. * `Converter\Number\BigNumberConverter` is deprecated; transition to `Converter\Number\GenericNumberConverter`. * `Converter\Time\BigNumberTimeConverter` is deprecated; transition to `Converter\Time\GenericTimeConverter`. * The classes for representing and generating *degraded* UUIDs are deprecated. These are no longer necessary; this library now behaves the same on 32-bit and 64-bit systems. * `Builder\DegradedUuidBuilder` * `Converter\Number\DegradedNumberConverter` * `Converter\Time\DegradedTimeConverter` * `DegradedUuid` * The `Uuid::UUID_TYPE_IDENTIFIER` constant is deprecated. Use `Uuid::UUID_TYPE_DCE_SECURITY` instead. * The `Uuid::VALID_PATTERN` constant is deprecated. Use `Validator\GenericValidator::getPattern()` or `Rfc4122\Validator::getPattern()` instead. ### Removed * Remove the following bytes generators and recommend `Generator\RandomBytesGenerator` as a suitable replacement: * `Generator\MtRandGenerator` * `Generator\OpenSslGenerator` * `Generator\SodiumRandomGenerator` * Remove `Exception\UnsatisfiedDependencyException`. This library no longer throws this exception. * Remove the method `Provider\TimeProviderInterface::currentTime()`. Use `Provider\TimeProviderInterface::getTime()` instead. ## 4.0.0-beta2 - 2020-03-01 ## Added * Add missing convenience methods for `Rfc4122\UuidV2`. * Add `Provider\Node\StaticNodeProvider` to assist in setting a custom static node value with the multicast bit set for version 1 UUIDs. ## Changed * `Provider\NodeProviderInterface::getNode()` now returns `Type\Hexadecimal` instead of `string|false|null`. ## 4.0.0-beta1 - 2020-02-27 ### Added * Add `ValidatorInterface::getPattern()` to return the regular expression pattern used by the validator. * Add `v6()` helper function for version 6 UUIDs. ### Changed * Set the pattern constants on validators as `private`. Use the `getPattern()` method instead. * Change the `$node` parameter for `UuidFactoryInterface::uuid6()` to accept `null` or `Type\Hexadecimal`. * Accept `Type\Hexadecimal` for the `$node` parameter for `UuidFactoryInterface::uuid1()`. This is in addition to the `int|string` types already accepted, so there are no BC breaks. `Type\Hexadecimal` is now the recommended type to pass for `$node`. ### Removed * Remove `currentTime()` method from `Provider\Time\FixedTimeProvider` and `Provider\Time\SystemTimeProvider`; it had previously been removed from `Provider\TimeProviderInterface`. ## 4.0.0-alpha5 - 2020-02-23 ### Added * Introduce `Builder\BuilderCollection` and `Provider\Node\NodeProviderCollection`. ### Changed * `Builder\FallbackBuilder` now accepts only a `Builder\BuilderCollection` as its constructor parameter. * `Provider\Node\FallbackNodeProvider` now accepts only a `Provider\Node\NodeProviderCollection` as its constructor parameter. * `Provider\Time\FixedTimeProvider` no longer accepts an array but accepts only `Type\Time` instances. ## 4.0.0-alpha4 - 2020-02-23 ### Added * Add a `Type\TypeInterface` that each of the ramsey/uuid types implements. * Support version 6 UUIDs; see . ### Changed * Rename `Type\IntegerValue` to `Type\Integer`. It was originally named `IntegerValue` because static analysis sees `Integer` in docblock annotations and treats it as the native `int` type. `Integer` is not a reserved word in PHP, so it should be named `Integer` for consistency with other types in this library. When using it, a class alias prevents static analysis from complaining. * Mark `Guid\Guid` and `Nonstandard\Uuid` classes as `final`. * Add `uuid6()` method to `UuidFactoryInterface`. ### Deprecated * `Uuid::UUID_TYPE_IDENTIFIER` is deprecated. Use `Uuid::UUID_TYPE_DCE_SECURITY` instead. * `Uuid::VALID_PATTERN` is deprecated. Use `Validator\GenericValidator::VALID_PATTERN` instead. ## 4.0.0-alpha3 - 2020-02-21 ### Fixed * Fix microsecond rounding error on 32-bit systems. ## 4.0.0-alpha2 - 2020-02-21 ### Added * Add `Uuid::fromDateTime()` to create version 1 UUIDs from instances of `\DateTimeInterface`. * Add `Generator\NameGeneratorInterface` to support alternate methods of generating bytes for version 3 and version 5 name-based UUID. By default, ramsey/uuid uses the `Generator\DefaultNameGenerator`, which uses the standard algorithm this library has used since the beginning. You may choose to use the new `Generator\PeclUuidNameGenerator` to make use of the new `uuid_generate_md5()` and `uuid_generate_sha1()` functions in ext-uuid version 1.1.0. ### Changed * Add `fromDateTime()` method to `UuidFactoryInterface`. * Change `UuidInterface::getHex()` to return a `Ramsey\Uuid\Type\Hexadecimal` instance. * Change `UuidInterface::getInteger()` to return a `Ramsey\Uuid\Type\IntegerValue` instance. ### Fixed * Round microseconds to six digits when getting DateTime from v1 UUIDs. This circumvents a needless exception for an otherwise valid time-based UUID. ## 4.0.0-alpha1 - 2020-01-22 ### Added * Add `Validator\ValidatorInterface` and `Validator\GenericValidator` to allow flexibility in validating UUIDs/GUIDs. * Add ability to change the default validator used by `Uuid` through `FeatureSet::setValidator()`. * Add `getValidator()` and `setValidator()` to `UuidFactory`. * Add an internal `InvalidArgumentException` that descends from the built-in PHP `\InvalidArgumentException`. All places that used to throw `\InvalidArgumentException` now throw `Ramsey\Uuid\Exception\InvalidArgumentException`. This should not cause any BC breaks, however. * Add an internal `DateTimeException` that descends from the built-in PHP `\RuntimeException`. `Uuid::getDateTime()` may throw this exception if `\DateTimeImmutable` throws an error or exception. * Add `RandomSourceException` that descends from the built-in PHP `\RuntimeException`. `DefaultTimeGenerator`, `RandomBytesGenerator`, and `RandomNodeProvider` may throw this exception if `random_bytes()` or `random_int()` throw an error or exception. * Add `Fields\FieldsInterface` and `Rfc4122\FieldsInterface` to define field layouts for UUID variants. The implementations `Rfc4122\Fields`, `Guid\Fields`, and `Nonstandard\Fields` store the 16-byte, binary string representation of the UUID internally, and these manage conversion of the binary string into the hexadecimal field values. * Add `Rfc4122\UuidInterface` to specifically represent RFC 4122 variant UUIDs. * Add classes to represent each version of RFC 4122 UUID. When generating new UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID is an RFC 4122 variant, one of these instances will be returned: * `Rfc4122\UuidV1` * `Rfc4122\UuidV2` * `Rfc4122\UuidV3` * `Rfc4122\UuidV4` * `Rfc4122\UuidV5` * `Rfc4122\NilUuid` * Add `Rfc4122\UuidBuilder` to build RFC 4122 variant UUIDs. This replaces the existing `Builder\DefaultUuidBuilder`, which is now deprecated. * Add ability to generate version 2 (DCE Security) UUIDs, including the static method `Uuid::uuid2()`, which returns an `Rfc4122\UuidV2` instance. * Add classes to represent GUIDs and nonstandard (non-RFC 4122 variant) UUIDs: * `Guid\Guid` * `Nonstandard\Uuid`. * Introduce a `Builder\FallbackBuilder`, used by `FeatureSet` to help decide whether to return a `Uuid` or `Nonstandard\Uuid` when decoding a UUID string or bytes. * Introduce `Type\Hexadecimal`, `Type\IntegerValue`, and `Type\Time` for improved type-safety when dealing with arbitrary string values. * Introduce `Math\CalculatorInterface` for representing calculators to perform arithmetic operations on integers. * Depend on [brick/math](https://github.com/brick/math) for the `Math\BrickMathCalculator`, which is the default calculator used by this library when math cannot be performed in native PHP due to integer size limitations. The calculator is configurable and may be changed, if desired. * Add `Converter\Number\GenericNumberConverter` and `Converter\Time\GenericTimeConverter` which will use the calculator provided to convert numbers and time to values for UUIDs. * The `\DateTimeInterface` instance returned by `UuidInterface::getDateTime()` (and now `Rfc4122\UuidV1::getDateTime()`) now includes microseconds, as specified by the version 1 UUID. ### Changed * Set minimum required PHP version to 7.2. * Add `__toString()` method to `UuidInterface`. * The `UuidInterface::getDateTime()` method now specifies `\DateTimeInterface` as the return value, rather than `\DateTime`; `Uuid::getDateTime()` now returns an instance of `\DateTimeImmutable` instead of `\DateTime`. * Add `getFields()` method to `UuidInterface`. * Add `getValidator()` method to `UuidFactoryInterface`. * Add `uuid2()` method to `UuidFactoryInterface`. * Add `convertTime()` method to `Converter\TimeConverterInterface`. * Add `getTime()` method to `Provider\TimeProviderInterface`. * Change `Uuid::getFields()` to return an instance of `Fields\FieldsInterface`. Previously, it returned an array of integer values (on 64-bit systems only). * Change the first required constructor parameter for `Uuid` from `array $fields` to `Rfc4122\FieldsInterface $fields`. * Introduce `Converter\TimeConverterInterface $timeConverter` as fourth required constructor parameter for `Uuid` and second required constructor parameter for `Builder\DefaultUuidBuilder`. * Change `UuidInterface::getInteger()` to always return a `string` value instead of `mixed`. This is a string representation of a 128-bit integer. You may then use a math library of your choice (bcmath, gmp, etc.) to operate on the string integer. * Change the second required parameter of `Builder\UuidBuilderInterface::build()` from `array $fields` to `string $bytes`. Rather than accepting an array of hexadecimal strings as UUID fields, the `build()` method now expects a byte string. * `Generator\DefaultTimeGenerator` no longer adds the variant and version bits to the bytes it returns. These must be applied to the bytes afterwards. * `Converter/TimeConverterInterface::calculateTime()` now returns `Type\Hexadecimal` instead of `array`. The value is the full UUID timestamp value (count of 100-nanosecond intervals since the Gregorian calendar epoch) in hexadecimal format. * Change methods in converter interfaces to accept and return string values instead of `mixed`; this simplifies the interface and makes it consistent: * `NumberConverterInterface::fromHex(string $hex): string` * `NumberConverterInterface::toHex(string $number): string` * `TimeConverterInterface::calculateTime(string $seconds, string $microseconds): array` * `UnsupportedOperationException` is now descended from `\LogicException`. Previously, it descended from `\RuntimeException`. * When encoding to bytes or decoding from bytes, `OrderedTimeCodec` now checks whether the UUID is an RFC 4122 variant, version 1 UUID. If not, it will throw an exception—`InvalidArgumentException` when using `OrderedTimeCodec::encodeBinary()` and `UnsupportedOperationException` when using `OrderedTimeCodec::decodeBytes()`. * Out of the box, `Uuid::fromString()`, `Uuid::fromBytes()`, and `Uuid::fromInteger()` will now return either an `Rfc4122\UuidInterface` instance or an instance of `Nonstandard\Uuid`, depending on whether the input contains an RFC 4122 variant UUID with a valid version identifier. Both implement `UuidInterface`, so BC breaks should not occur if typehints use the interface. * By default, the following static methods will now return the specific instance types. This should not cause any BC breaks if typehints target `UuidInterface`: * `Uuid::uuid1` returns `Rfc4122\UuidV1` * `Uuid::uuid3` returns `Rfc4122\UuidV3` * `Uuid::uuid4` returns `Rfc4122\UuidV4` * `Uuid::uuid5` returns `Rfc4122\UuidV5` ### Deprecated The following functionality is deprecated and will be removed in ramsey/uuid 5.0.0. * The following methods from `UuidInterface` and `Uuid` are deprecated. Use their counterparts on the `Rfc4122\FieldsInterface` returned by `Uuid::getFields()`. * `getClockSeqHiAndReservedHex()` * `getClockSeqLowHex()` * `getClockSequenceHex()` * `getFieldsHex()` * `getNodeHex()` * `getTimeHiAndVersionHex()` * `getTimeLowHex()` * `getTimeMidHex()` * `getTimestampHex()` * `getVariant()` * `getVersion()` * The following methods from `Uuid` are deprecated. Use the `Rfc4122\FieldsInterface` instance returned by `Uuid::getFields()` to get the `Type\Hexadecimal` value for these fields, and then use the arbitrary-precision arithmetic library of your choice to convert them to string integers. * `getClockSeqHiAndReserved()` * `getClockSeqLow()` * `getClockSequence()` * `getNode()` * `getTimeHiAndVersion()` * `getTimeLow()` * `getTimeMid()` * `getTimestamp()` * `getDateTime()` on `UuidInterface` and `Uuid` is deprecated. Use this method only on instances of `Rfc4122\UuidV1`. * `getUrn()` on `UuidInterface` and `Uuid` is deprecated. It is available on `Rfc4122\UuidInterface` and classes that implement it. * The following methods are deprecated and have no direct replacements. However, you may obtain the same information by calling `UuidInterface::getHex()` and splitting the return value in half. * `UuidInterface::getLeastSignificantBitsHex()` * `UuidInterface::getMostSignificantBitsHex()` * `Uuid::getLeastSignificantBitsHex()` * `Uuid::getMostSignificantBitsHex()` * `Uuid::getLeastSignificantBits()` * `Uuid::getMostSignificantBits()` * `UuidInterface::getNumberConverter()` and `Uuid::getNumberConverter()` are deprecated. There is no alternative recommendation, so plan accordingly. * `Builder\DefaultUuidBuilder` is deprecated; transition to `Rfc4122\UuidBuilder`. * `Converter\Number\BigNumberConverter` is deprecated; transition to `Converter\Number\GenericNumberConverter`. * `Converter\Time\BigNumberTimeConverter` is deprecated; transition to `Converter\Time\GenericTimeConverter`. * `Provider\TimeProviderInterface::currentTime()` is deprecated; transition to the `getTimestamp()` method on the same interface. * The classes for representing and generating *degraded* UUIDs are deprecated. These are no longer necessary; this library now behaves the same on 32-bit and 64-bit PHP. * `Builder\DegradedUuidBuilder` * `Converter\Number\DegradedNumberConverter` * `Converter\Time\DegradedTimeConverter` * `DegradedUuid` ### Removed * Remove the following bytes generators and recommend `Generator\RandomBytesGenerator` as a suitable replacement: * `Generator\MtRandGenerator` * `Generator\OpenSslGenerator` * `Generator\SodiumRandomGenerator` * Remove `Exception\UnsatisfiedDependencyException`. This library no longer throws this exception. ## 3.9.7 - 2022-12-19 ### Fixed * Add `#[ReturnTypeWillChange]` to `Uuid::jsonSerialize()` method. ## 3.9.6 - 2021-09-25 ### Fixed * Switch back to `^8.0` in the PHP version requirement. ## 3.9.5 - 2021-09-24 ### Fixed * Indicate support for PHP 8.1, using `~8.1.0` to prevent installations on 8.2 until the library is ready. ## 3.9.4 - 2021-08-06 ### Fixed * Allow installation of paragonie/random_compat v9.99.100 (for PHP 8 compatibility). ## 3.9.3 - 2020-02-20 ### Fixed * For v1 UUIDs, round down for timestamps so that microseconds do not bump the timestamp to the next second. As an example, consider the case of timestamp `1` with `600000` microseconds (`1.600000`). This is the first second after midnight on January 1, 1970, UTC. Previous versions of this library had a bug that would round this to `2`, so the rendered time was `1970-01-01 00:00:02`. This was incorrect. Despite having `600000` microseconds, the time should not round up to the next second. Rather, the time should be `1970-01-01 00:00:01.600000`. Since this version of ramsey/uuid does not support microseconds, the microseconds are dropped, and the time is `1970-01-01 00:00:01`. No rounding should occur. ## 3.9.2 - 2019-12-17 ### Fixed * Check whether files returned by `/sys/class/net/*/address` are readable before attempting to read them. This avoids a PHP warning that was being emitted on hosts that do not grant permission to read these files. ## 3.9.1 - 2019-12-01 ### Fixed * Fix `RandomNodeProvider` behavior on 32-bit systems. The `RandomNodeProvider` was converting a 6-byte string to a decimal number, which is a 48-bit, unsigned integer. This caused problems on 32-bit systems and has now been resolved. ## 3.9.0 - 2019-11-30 ### Added * Add function API as convenience. The functions are available in the `Ramsey\Uuid` namespace. * `v1(int|string|null $node = null, int|null $clockSeq = null): string` * `v3(string|UuidInterface $ns, string $name): string` * `v4(): string` * `v5(string|UuidInterface $ns, string $name): string` ### Changed * Use paragonie/random-lib instead of ircmaxell/random-lib. This is a non-breaking change. * Use a high-strength generator by default, when using `RandomLibAdapter`. This is a non-breaking change. ### Deprecated These will be removed in ramsey/uuid version 4.0.0: * `MtRandGenerator`, `OpenSslGenerator`, and `SodiumRandomGenerator` are deprecated in favor of using the default `RandomBytesGenerator`. ### Fixed * Set `ext-json` as a required dependency in `composer.json`. * Use `PHP_OS` instead of `php_uname()` when determining the system OS, for cases when `php_uname()` is disabled for security reasons. ## 3.8.0 - 2018-07-19 ### Added * Support discovery of MAC addresses on FreeBSD systems * Use a polyfill to provide PHP ctype functions when running on systems where the ctype functions are not part of the PHP build * Disallow a trailing newline character when validating UUIDs * Annotate thrown exceptions for improved IDE hinting ## 3.7.3 - 2018-01-19 ### Fixed * Gracefully handle cases where `glob()` returns false when searching `/sys/class/net/*/address` files on Linux * Fix off-by-one error in `DefaultTimeGenerator` ### Security * Switch to `random_int()` from `mt_rand()` for better random numbers ## 3.7.2 - 2018-01-13 ### Fixed * Check sysfs on Linux to determine the node identifier; this provides a reliable way to identify the node on Docker images, etc. ## 3.7.1 - 2017-09-22 ### Fixed * Set the multicast bit for random nodes, according to RFC 4122, §4.5 ### Security * Use `random_bytes()` when generating random nodes ## 3.7.0 - 2017-08-04 ### Added * Add the following UUID version constants: * `Uuid::UUID_TYPE_TIME` * `Uuid::UUID_TYPE_IDENTIFIER` * `Uuid::UUID_TYPE_HASH_MD5` * `Uuid::UUID_TYPE_RANDOM` * `Uuid::UUID_TYPE_HASH_SHA1` ## 3.6.1 - 2017-03-26 ### Fixed * Optimize UUID string decoding by using `str_pad()` instead of `sprintf()` ## 3.6.0 - 2017-03-18 ### Added * Add `InvalidUuidStringException`, which is thrown when attempting to decode an invalid string UUID; this does not introduce any BC issues, since the new exception inherits from the previously used `InvalidArgumentException` ### Fixed * Improve memory usage when generating large quantities of UUIDs (use `str_pad()` and `dechex()` instead of `sprintf()`) ## 3.5.2 - 2016-11-22 ### Fixed * Improve test coverage ## 3.5.1 - 2016-10-02 ### Fixed * Fix issue where the same UUIDs were not being treated as equal when using mixed cases ## 3.5.0 - 2016-08-02 ### Added * Add `OrderedTimeCodec` to store UUID in an optimized way for InnoDB ### Fixed * Fix invalid node generation in `RandomNodeProvider` * Avoid multiple unnecessary system calls by caching failed attempt to retrieve system node ## 3.4.1 - 2016-04-23 ### Fixed * Fix test that violated a PHP CodeSniffer rule, breaking the build ## 3.4.0 - 2016-04-23 ### Added * Add `TimestampFirstCombCodec` and `TimestampLastCombCodec` codecs to provide the ability to generate [COMB sequential UUIDs] with the timestamp encoded as either the first 48 bits or the last 48 bits * Improve logic of `CombGenerator` for COMB sequential UUIDs ## 3.3.0 - 2016-03-22 ### Security * Drop the use of OpenSSL as a fallback and use [paragonie/random_compat] to support `RandomBytesGenerator` in versions of PHP earlier than 7.0; this addresses and fixes the [collision issue] ## 3.2.0 - 2016-02-17 ### Added * Add `SodiumRandomGenerator` to allow use of the [PECL libsodium extension] as a random bytes generator when creating UUIDs ## 3.1.0 - 2015-12-17 ### Added * Implement the PHP `Serializable` interface to provide the ability to serialize/unserialize UUID objects ## 3.0.1 - 2015-10-21 ### Added * Adopt the [Contributor Code of Conduct] for this project ## 3.0.0 - 2015-09-28 The 3.0.0 release represents a significant step for the ramsey/uuid library. While the simple and familiar API used in previous versions remains intact, this release provides greater flexibility to integrators, including the ability to inject your own number generators, UUID codecs, node and time providers, and more. *Please note: The changelog for 3.0.0 includes all notes from the alpha and beta versions leading up to this release.* ### Added * Add a number of generators that may be used to override the library defaults for generating random bytes (version 4) or time-based (version 1) UUIDs * `CombGenerator` to allow generation of sequential UUIDs * `OpenSslGenerator` to generate random bytes on systems where `openssql_random_pseudo_bytes()` is present * `MtRandGenerator` to provide a fallback in the event other random generators are not present * `RandomLibAdapter` to allow use of [ircmaxell/random-lib] * `RandomBytesGenerator` for use with PHP 7; ramsey/uuid will default to use this generator when running on PHP 7 * Refactor time-based (version 1) UUIDs into a `TimeGeneratorInterface` to allow for other sources to generate version 1 UUIDs in this library * `PeclUuidTimeGenerator` and `PeclUuidRandomGenerator` for creating version 1 or version 4 UUIDs using the pecl-uuid extension * Add a `setTimeGenerator` method on `UuidFactory` to override the default time generator * Add option to enable `PeclUuidTimeGenerator` via `FeatureSet` * Support GUID generation by configuring a `FeatureSet` to use GUIDs * Allow UUIDs to be serialized as JSON through `JsonSerializable` ### Changed * Change root namespace from "Rhumsaa" to "Ramsey;" in most cases, simply making this change in your applications is the only upgrade path you will need—everything else should work as expected * No longer consider `Uuid` class as `final`; everything is now based around interfaces and factories, allowing you to use this package as a base to implement other kinds of UUIDs with different dependencies * Return an object of type `DegradedUuid` on 32-bit systems to indicate that certain features are not available * Default `RandomLibAdapter` to a medium-strength generator with [ircmaxell/random-lib]; this is configurable, so other generator strengths may be used ### Removed * Remove `PeclUuidFactory` in favor of using pecl-uuid with generators * Remove `timeConverter` and `timeProvider` properties, setters, and getters in both `FeatureSet` and `UuidFactory` as those are now exclusively used by the default `TimeGenerator` * Move UUID [Doctrine field type] to [ramsey/uuid-doctrine] * Move `uuid` console application to [ramsey/uuid-console] * Remove `Uuid::VERSION` package version constant ### Fixed * Improve GUID support to ensure that: * On little endian (LE) architectures, the byte order of the first three fields is LE * On big endian (BE) architectures, it is the same as a GUID * String representation is always the same * Fix exception message for `DegradedNumberConverter::fromHex()` ## 3.0.0-beta1 - 2015-08-31 ### Fixed * Improve GUID support to ensure that: * On little endian (LE) architectures, the byte order of the first three fields is LE * On big endian (BE) architectures, it is the same as a GUID * String representation is always the same * Fix exception message for `DegradedNumberConverter::fromHex()` ## 3.0.0-alpha3 - 2015-07-28 ### Added * Enable use of custom `TimeGenerator` implementations * Add a `setTimeGenerator` method on `UuidFactory` to override the default time generator * Add option to enable `PeclUuidTimeGenerator` via `FeatureSet` ### Removed * Remove `timeConverter` and `timeProvider` properties, setters, and getters in both `FeatureSet` and `UuidFactory` as those are now exclusively used by the default `TimeGenerator` ## 3.0.0-alpha2 - 2015-07-28 ### Added * Refactor time-based (version 1) UUIDs into a `TimeGeneratorInterface` to allow for other sources to generate version 1 UUIDs in this library * Add `PeclUuidTimeGenerator` and `PeclUuidRandomGenerator` for creating version 1 or version 4 UUIDs using the pecl-uuid extension * Add `RandomBytesGenerator` for use with PHP 7. ramsey/uuid will default to use this generator when running on PHP 7 ### Changed * Default `RandomLibAdapter` to a medium-strength generator with [ircmaxell/random-lib]; this is configurable, so other generator strengths may be used ### Removed * Remove `PeclUuidFactory` in favor of using pecl-uuid with generators ## 3.0.0-alpha1 - 2015-07-16 ### Added * Allow dependency injection through `UuidFactory` and/or extending `FeatureSet` to override any package defaults * Add a number of generators that may be used to override the library defaults: * `CombGenerator` to allow generation of sequential UUIDs * `OpenSslGenerator` to generate random bytes on systems where `openssql_random_pseudo_bytes()` is present * `MtRandGenerator` to provide a fallback in the event other random generators are not present * `RandomLibAdapter` to allow use of [ircmaxell/random-lib] * Support GUID generation by configuring a `FeatureSet` to use GUIDs * Allow UUIDs to be serialized as JSON through `JsonSerializable` ### Changed * Change root namespace from "Rhumsaa" to "Ramsey;" in most cases, simply making this change in your applications is the only upgrade path you will need—everything else should work as expected * No longer consider `Uuid` class as `final`; everything is now based around interfaces and factories, allowing you to use this package as a base to implement other kinds of UUIDs with different dependencies * Return an object of type `DegradedUuid` on 32-bit systems to indicate that certain features are not available ### Removed * Move UUID [Doctrine field type] to [ramsey/uuid-doctrine] * Move `uuid` console application to [ramsey/uuid-console] * Remove `Uuid::VERSION` package version constant ## 2.9.0 - 2016-03-22 ### Security * Drop the use of OpenSSL as a fallback and use [paragonie/random_compat] to support `RandomBytesGenerator` in versions of PHP earlier than 7.0; this addresses and fixes the [collision issue] ## 2.8.4 - 2015-12-17 ### Added * Add support for symfony/console v3 in the `uuid` CLI application ## 2.8.3 - 2015-08-31 ### Fixed * Fix exception message in `Uuid::calculateUuidTime()` ## 2.8.2 - 2015-07-23 ### Fixed * Ensure the release tag makes it into the rhumsaa/uuid package ## 2.8.1 - 2015-06-16 ### Fixed * Use `passthru()` and output buffering in `getIfconfig()` * Cache the system node in a static variable so that we process it only once per runtime ## 2.8.0 - 2014-11-09 ### Added * Add static `fromInteger()` method to create UUIDs from string integer or `Moontoast\Math\BigNumber` ### Fixed * Improve Doctrine conversion to Uuid or string for the ramsey/uuid [Doctrine field type] ## 2.7.4 - 2014-10-29 ### Fixed * Change loop in `generateBytes()` from `foreach` to `for` ## 2.7.3 - 2014-08-27 ### Fixed * Fix upper range for `mt_rand` used in version 4 UUIDs ## 2.7.2 - 2014-07-28 ### Changed * Upgrade to PSR-4 autoloading ## 2.7.1 - 2014-02-19 ### Fixed * Move moontoast/math and symfony/console to require-dev * Support symfony/console 2.3 (LTS version) ## 2.7.0 - 2014-01-31 ### Added * Add `Uuid::VALID_PATTERN` constant containing a UUID validation regex pattern ## 2.6.1 - 2014-01-27 ### Fixed * Fix bug where `uuid` console application could not find the Composer autoloader when installed in another project ## 2.6.0 - 2014-01-17 ### Added * Introduce `uuid` console application for generating and decoding UUIDs from CLI (run `./bin/uuid` for details) * Add `Uuid::getInteger()` to retrieve a `Moontoast\Math\BigNumber` representation of the 128-bit integer representing the UUID * Add `Uuid::getHex()` to retrieve the hexadecimal representation of the UUID * Use `netstat` on Linux to capture the node for a version 1 UUID * Require moontoast/math as part of the regular package requirements ## 2.5.0 - 2013-10-30 ### Added * Use `openssl_random_pseudo_bytes()`, if available, to generate random bytes ## 2.4.0 - 2013-07-29 ### Added * Return `null` from `Uuid::getVersion()` if the UUID isn't an RFC 4122 variant * Support string UUIDs without dashes passed to `Uuid::fromString()` ## 2.3.0 - 2013-07-16 ### Added * Support creation of UUIDs from bytes with `Uuid::fromBytes()` ## 2.2.0 - 2013-07-04 ### Added * Add `Doctrine\UuidType::requiresSQLCommentHint()` method ## 2.1.2 - 2013-07-03 ### Fixed * Fix cases where the system node was coming back with uppercase hexadecimal digits; this ensures that case in the node is converted to lowercase ## 2.1.1 - 2013-04-29 ### Fixed * Fix bug in `Uuid::isValid()` where the NIL UUID was not reported as valid ## 2.1.0 - 2013-04-15 ### Added * Allow checking the validity of a UUID through the `Uuid::isValid()` method ## 2.0.0 - 2013-02-11 ### Added * Support UUID generation on 32-bit platforms ### Changed * Mark `Uuid` class `final` * Require moontoast/math on 64-bit platforms for `Uuid::getLeastSignificantBits()` and `Uuid::getMostSignificantBits()`; the integers returned by these methods are *unsigned* 64-bit integers and unsupported even on 64-bit builds of PHP * Move `UnsupportedOperationException` to the `Exception` subnamespace ## 1.1.2 - 2012-11-29 ### Fixed * Relax [Doctrine field type] conversion rules for UUIDs ## 1.1.1 - 2012-08-27 ### Fixed * Remove `final` keyword from `Uuid` class ## 1.1.0 - 2012-08-06 ### Added * Support ramsey/uuid UUIDs as a Doctrine Database Abstraction Layer (DBAL) field mapping type ## 1.0.0 - 2012-07-19 ### Added * Support generation of version 1, 3, 4, and 5 UUIDs [comb sequential uuids]: http://www.informit.com/articles/article.aspx?p=25862&seqNum=7 [paragonie/random_compat]: https://github.com/paragonie/random_compat [collision issue]: https://github.com/ramsey/uuid/issues/80 [contributor code of conduct]: https://github.com/ramsey/uuid/blob/main/CODE_OF_CONDUCT.md [pecl libsodium extension]: http://pecl.php.net/package/libsodium [ircmaxell/random-lib]: https://github.com/ircmaxell/RandomLib [doctrine field type]: http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html [ramsey/uuid-doctrine]: https://github.com/ramsey/uuid-doctrine [ramsey/uuid-console]: https://github.com/ramsey/uuid-console [version6]: https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.6 [version7]: https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.7 [version8]: https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.8 [max uuids]: https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#section-5.4 ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintainer(s) at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at . [homepage]: http://contributor-covenant.org ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Contributions are welcome. This project accepts pull requests on [GitHub][]. This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating in this project and its community, you are expected to uphold this code. ## Communication Channels You can find help and discussion in the following places: * GitHub Issues: ## Reporting Bugs Report bugs using the project's [issue tracker][issues]. ⚠️ _**ATTENTION!!!** DO NOT include passwords or other sensitive information in your bug report._ When submitting a bug report, please include enough information to reproduce the bug. A good bug report includes the following sections: * **Description** Provide a short and clear description of the bug. * **Steps to reproduce** Provide steps to reproduce the behavior you are experiencing. Please try to keep this as short as possible. If able, create a reproducible script outside of any framework you are using. This will help us to quickly debug the issue. * **Expected behavior** Provide a short and clear description of what you expect to happen. * **Screenshots or output** If applicable, add screenshots or program output to help explain your problem. * **Environment details** Provide details about the system where you're using this package, such as PHP version and operating system. * **Additional context** Provide any additional context that may help us debug the problem. ## Fixing Bugs This project welcomes pull requests to fix bugs! If you see a bug report that you'd like to fix, please feel free to do so. Following the directions and guidelines described in the "Adding New Features" section below, you may create bugfix branches and send pull requests. ## Adding New Features If you have an idea for a new feature, it's a good idea to check out the [issues][] or active [pull requests][] first to see if anyone is already working on the feature. If not, feel free to submit an issue first, asking whether the feature is beneficial to the project. This will save you from doing a lot of development work only to have your feature rejected. We don't enjoy rejecting your hard work, but some features don't fit with the goals of the project. When you do begin working on your feature, here are some guidelines to consider: * Your pull request description should clearly detail the changes you have made. We will use this description to update the CHANGELOG. If there is no description, or it does not adequately describe your feature, we may ask you to update the description. * ramsey/uuid follows a superset of **[PSR-12 coding standard][psr-12]**. Please ensure your code does, too. _Hint: run `composer phpcs` to check._ * Please **write tests** for any new features you add. * Please **ensure that tests pass** before submitting your pull request. ramsey/uuid automatically runs tests for pull requests. However, running the tests locally will help save time. _Hint: run `composer test`._ * **Use topic/feature branches.** Please do not ask to pull from your main branch. * For more information, see "[Understanding the GitHub flow][gh-flow]." * **Submit one feature per pull request.** If you have multiple features you wish to submit, please break them into separate pull requests. ## Developing To develop this project, you will need [PHP](https://www.php.net) 8.0 or greater and [Composer](https://getcomposer.org). After cloning this repository locally, execute the following commands: ``` bash cd /path/to/repository composer install ``` Now, you are ready to develop! ### Tooling This project uses [CaptainHook](https://github.com/captainhook-git/captainhook) to validate all staged changes prior to commit. ### Commands To see all the commands available for contributing to this project: ``` bash composer list ``` ### Coding Standards This project follows a superset of [PSR-12](https://www.php-fig.org/psr/psr-12/) coding standards, enforced by [PHP_CodeSniffer](https://github.com/PHPCSStandards/PHP_CodeSniffer). CaptainHook will run coding standards checks before committing. You may lint the codebase manually using the following commands: ``` bash # Lint composer dev:lint # Attempt to auto-fix coding standards issues composer dev:lint:fix ``` ### Static Analysis This project uses [PHPStan](https://github.com/phpstan/phpstan) to provide static analysis of PHP code. CaptainHook will run static analysis checks before committing. You may run static analysis manually across the whole codebase with the following command: ``` bash # Static analysis composer dev:analyze ``` ### Project Structure This project uses [pds/skeleton](https://github.com/php-pds/skeleton) as its base folder structure and layout. ### Running Tests The following must pass before we will accept a pull request. If this does not pass, it will result in a complete build failure. Before you can run this, be sure to `composer install`. To run all the tests and coding standards checks, execute the following from the command line, while in the project root directory: ``` composer test ``` CaptainHook will automatically run all tests before pushing to the remote repository. [github]: https://github.com/ramsey/uuid [issues]: https://github.com/ramsey/uuid/issues [pull requests]: https://github.com/ramsey/uuid/pulls [psr-12]: https://www.php-fig.org/psr/psr-12/ [gh-flow]: https://guides.github.com/introduction/flow/ ================================================ FILE: LICENSE ================================================ Copyright (c) 2012-2025 Ben Ramsey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

ramsey/uuid

A PHP library for generating and working with UUIDs.

Source Code Download Package PHP Programming Language Read License Build Status Codecov Code Coverage

ramsey/uuid is a PHP library for generating and working with universally unique identifiers (UUIDs). This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating in this project and its community, you are expected to uphold this code. Much inspiration for this library came from the [Java][javauuid] and [Python][pyuuid] UUID libraries. ## Installation The preferred method of installation is via [Composer][]. Run the following command to install the package and add it as a requirement to your project's `composer.json`: ```bash composer require ramsey/uuid ``` ## Upgrading to Version 4 See the documentation for a thorough upgrade guide: * [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/stable/upgrading/3-to-4.html) ## Documentation Please see for documentation, tips, examples, and frequently asked questions. ## Contributing Contributions are welcome! To contribute, please familiarize yourself with [CONTRIBUTING.md](CONTRIBUTING.md). ## Coordinated Disclosure Keeping user information safe and secure is a top priority, and we welcome the contribution of external security researchers. If you believe you've found a security issue in software that is maintained in this repository, please read [SECURITY.md][] for instructions on submitting a vulnerability report. ## ramsey/uuid for Enterprise Available as part of the Tidelift Subscription. The maintainers of ramsey/uuid and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-ramsey-uuid?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Copyright and License The ramsey/uuid library is copyright © [Ben Ramsey](https://benramsey.com/) and licensed for use under the MIT License (MIT). Please see [LICENSE][] for more information. [rfc4122]: http://tools.ietf.org/html/rfc4122 [conduct]: https://github.com/ramsey/uuid/blob/4.x/CODE_OF_CONDUCT.md [javauuid]: http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html [pyuuid]: http://docs.python.org/3/library/uuid.html [composer]: http://getcomposer.org/ [contributing.md]: https://github.com/ramsey/uuid/blob/4.x/CONTRIBUTING.md [security.md]: https://github.com/ramsey/uuid/blob/4.x/SECURITY.md [license]: https://github.com/ramsey/uuid/blob/4.x/LICENSE ================================================ FILE: SECURITY.md ================================================ # Vulnerability Disclosure Policy (VDP) ## Brand Promise Keeping user information safe and secure is a top priority, and we welcome the contribution of external security researchers. ## Scope If you believe you've found a security issue in software that is maintained in this repository, we encourage you to notify us. | Version | In scope | Source code | | ------------ | -------- |-----------------------------------------| | latest (4.x) | ✅ | https://github.com/ramsey/uuid/tree/4.x | | 3.9 | ✅ | https://github.com/ramsey/uuid/tree/3.x | | 3.8 | ✅ | https://github.com/ramsey/uuid/tree/3.x | ## How to Submit a Report To submit a vulnerability report, please contact us at security@ramsey.dev. Your submission will be reviewed and validated by a member of our team. ## Safe Harbor We support safe harbor for security researchers who: * Make a good faith effort to avoid privacy violations, destruction of data, and interruption or degradation of our services. * Only interact with accounts you own or with explicit permission of the account holder. If you do encounter Personally Identifiable Information (PII) contact us immediately, do not proceed with access, and immediately purge any local information. * Provide us with a reasonable amount of time to resolve vulnerabilities prior to any disclosure to the public or a third party. We will consider activities conducted consistent with this policy to constitute "authorized" conduct and will not pursue civil action or initiate a complaint to law enforcement. We will help to the extent we can if legal action is initiated by a third party against you. Please submit a report to us before engaging in conduct that may be inconsistent with or unaddressed by this policy. ## Preferences * Please provide detailed reports with reproducible steps and a clearly defined impact. * Include the version number of the vulnerable package in your report * Social engineering (e.g. phishing, vishing, smishing) is prohibited. ## Encryption Key for security@ramsey.dev For increased privacy when reporting sensitive issues, you may encrypt your message using the following public key: ``` -----BEGIN PGP PUBLIC KEY BLOCK----- mQINBF+Z9gEBEACbT/pIx8RR0K18t8Z2rDnmEV44YdT7HNsMdq+D6SAlx8UUb6AU jGIbV9dgBgGNtOLU1pxloaJwL9bWIRbj+X/Qb2WNIP//Vz1Y40ox1dSpfCUrizXx kb4p58Xml0PsB8dg3b4RDUgKwGC37ne5xmDnigyJPbiB2XJ6Xc46oPCjh86XROTK wEBB2lY67ClBlSlvC2V9KmbTboRQkLdQDhOaUosMb99zRb0EWqDLaFkZVjY5HI7i 0pTveE6dI12NfHhTwKjZ5pUiAZQGlKA6J1dMjY2unxHZkQj5MlMfrLSyJHZxccdJ xD94T6OTcTHt/XmMpI2AObpewZDdChDQmcYDZXGfAhFoJmbvXsmLMGXKgzKoZ/ls RmLsQhh7+/r8E+Pn5r+A6Hh4uAc14ApyEP0ckKeIXw1C6pepHM4E8TEXVr/IA6K/ z6jlHORixIFX7iNOnfHh+qwOgZw40D6JnBfEzjFi+T2Cy+JzN2uy7I8UnecTMGo3 5t6astPy6xcH6kZYzFTV7XERR6LIIVyLAiMFd8kF5MbJ8N5ElRFsFHPW+82N2HDX c60iSaTB85k6R6xd8JIKDiaKE4sSuw2wHFCKq33d/GamYezp1wO+bVUQg88efljC 2JNFyD+vl30josqhw1HcmbE1TP3DlYeIL5jQOlxCMsgai6JtTfHFM/5MYwARAQAB tBNzZWN1cml0eUByYW1zZXkuZGV2iQJUBBMBCAA+FiEE4drPD+/ofZ570fAYq0bv vXQCywIFAl+Z9gECGwMFCQeGH4AFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQ q0bvvXQCywIkEA//Qcwv8MtTCy01LHZd9c7VslwhNdXQDYymcTyjcYw8x7O22m4B 3hXE6vqAplFhVxxkqXB2ef0tQuzxhPHNJgkCE4Wq4i+V6qGpaSVHQT2W6DN/NIhL vS8OdScc6zddmIbIkSrzVVAtjwehFNEIrX3DnbbbK+Iku7vsKT5EclOluIsjlYoX goW8IeReyDBqOe2H3hoCGw6EA0D/NYV2bJnfy53rXVIyarsXXeOLp7eNEH6Td7aW PVSrMZJe1t+knrEGnEdrXWzlg4lCJJCtemGv+pKBUomnyISXSdqyoRCCzvQjqyig 2kRebUX8BXPW33p4OXPj9sIboUOjZwormWwqqbFMO+J4TiVCUoEoheI7emPFRcNN QtPJrjbY1++OznBc0GRpfeUkGoU1cbRl1bnepnFIZMTDLkrVW6I1Y4q8ZVwX3BkE N81ctFrRpHBlU36EdHvjPQmGtuiL77Qq3fWmMv7yTvK1wHJAXfEb0ZJWHZCbck3w l0CVq0Z+UUAOM8Rp1N0N8m92xtapav0qCFU9qzf2J5qX6GRmWv+d29wPgFHzDWBm nnrYYIA4wJLx00U6SMcVBSnNe91B+RfGY5XQhbWPjQQecOGCSDsxaFAq2MeOVJyZ bIjLYfG9GxoLKr5R7oLRJvZI4nKKBc1Kci/crZbdiSdQhSQGlDz88F1OHeCIdQQQ EQgAHRYhBOhdAxHd+lus86YQ57Atl5icjAcbBQJfmfdIAAoJELAtl5icjAcbFVcA /1LqB3ZjsnXDAvvAXZVjSPqofSlpMLeRQP6IM/A9Odq0AQCZrtZc1knOMGEcjppK Rk+sy/R0Mshy8TDuaZIRgh2Ux7kCDQRfmfYBARAAmchKzzVz7IaEq7PnZDb3szQs T/+E9F3m39yOpV4fEB1YzObonFakXNT7Gw2tZEx0eitUMqQ/13jjfu3UdzlKl2bR qA8LrSQRhB+PTC9A1XvwxCUYhhjGiLzJ9CZL6hBQB43qHOmE9XJPme90geLsF+gK u39Waj1SNWzwGg+Gy1Gl5f2AJoDTxznreCuFGj+Vfaczt/hlfgqpOdb9jsmdoE7t 3DSWppA9dRHWwQSgE6J28rR4QySBcqyXS6IMykqaJn7Z26yNIaITLnHCZOSY8zhP ha7GFsN549EOCgECbrnPt9dmI2+hQE0RO0e7SOBNsIf5sz/i7urhwuj0CbOqhjc2 X1AEVNFCVcb6HPi/AWefdFCRu0gaWQxn5g+9nkq5slEgvzCCiKYzaBIcr8qR6Hb4 FaOPVPxO8vndRouq57Ws8XpAwbPttioFuCqF4u9K+tK/8e2/R8QgRYJsE3Cz/Fu8 +pZFpMnqbDEbK3DL3ss+1ed1sky+mDV8qXXeI33XW5hMFnk1JWshUjHNlQmE6ftC U0xSTMVUtwJhzH2zDp8lEdu7qi3EsNULOl68ozDr6soWAvCbHPeTdTOnFySGCleG /3TonsoZJs/sSPPJnxFQ1DtgQL6EbhIwa0ZwU4eKYVHZ9tjxuMX3teFzRvOrJjgs +ywGlsIURtEckT5Y6nMAEQEAAYkCPAQYAQgAJhYhBOHazw/v6H2ee9HwGKtG7710 AssCBQJfmfYBAhsMBQkHhh+AAAoJEKtG7710AssC8NcP/iDAcy1aZFvkA0EbZ85p i7/+ywtE/1wF4U4/9OuLcoskqGGnl1pJNPooMOSBCfreoTB8HimT0Fln0CoaOm4Q pScNq39JXmf4VxauqUJVARByP6zUfgYarqoaZNeuFF0S4AZJ2HhGzaQPjDz1uKVM PE6tQSgQkFzdZ9AtRA4vElTH6yRAgmepUsOihk0b0gUtVnwtRYZ8e0Qt3ie97a73 DxLgAgedFRUbLRYiT0vNaYbainBsLWKpN/T8odwIg/smP0Khjp/ckV60cZTdBiPR szBTPJESMUTu0VPntc4gWwGsmhZJg/Tt/qP08XYo3VxNYBegyuWwNR66zDWvwvGH muMv5UchuDxp6Rt3JkIO4voMT1JSjWy9p8krkPEE4V6PxAagLjdZSkt92wVLiK5x y5gNrtPhU45YdRAKHr36OvJBJQ42CDaZ6nzrzghcIp9CZ7ANHrI+QLRM/csz+AGA szSp6S4mc1lnxxfbOhPPpebZPn0nIAXoZnnoVKdrxBVedPQHT59ZFvKTQ9Fs7gd3 sYNuc7tJGFGC2CxBH4ANDpOQkc5q9JJ1HSGrXU3juxIiRgfA26Q22S9c71dXjElw Ri584QH+bL6kkYmm8xpKF6TVwhwu5xx/jBPrbWqFrtbvLNrnfPoapTihBfdIhkT6 nmgawbBHA02D5xEqB5SU3WJu =eJNx -----END PGP PUBLIC KEY BLOCK----- ``` ================================================ FILE: build/.gitignore ================================================ * !.gitignore !cache !cache/.gitkeep !logs !logs/.gitkeep ================================================ FILE: build/cache/.gitkeep ================================================ ================================================ FILE: build/logs/.gitkeep ================================================ ================================================ FILE: captainhook.json ================================================ { "config": { "ansi-colors": true, "fail-on-first-error": false, "plugins": [], "verbosity": "normal" }, "commit-msg": { "enabled": false, "actions": [] }, "pre-push": { "enabled": true, "actions": [ { "action": "composer test" } ] }, "pre-commit": { "enabled": true, "actions": [ { "action": "composer validate", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\Any", "args": [["composer.json"]] } ] }, { "action": "composer normalize --dry-run", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\Any", "args": [["composer.json"]] } ] }, { "action": "composer dev:lint:syntax -- {$STAGED_FILES|of-type:php}", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\OfType", "args": ["php"] } ] }, { "action": "composer dev:lint:style -- {$STAGED_FILES|of-type:php}", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\OfType", "args": ["php"] } ] } ] }, "prepare-commit-msg": { "enabled": false, "actions": [] }, "post-commit": { "enabled": false, "actions": [] }, "post-merge": { "enabled": true, "actions": [ { "action": "composer install --ansi", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileChanged\\Any", "args": [["composer.json", "composer.lock"]] } ] } ] }, "post-checkout": { "enabled": true, "actions": [ { "action": "composer install --ansi", "conditions": [ { "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileChanged\\Any", "args": [["composer.json", "composer.lock"]] } ] } ] }, "post-rewrite": { "enabled": false, "actions": [] }, "post-change": { "enabled": false, "actions": [] } } ================================================ FILE: codecov.yml ================================================ codecov: require_ci_to_pass: yes coverage: precision: 2 round: down range: "70...100" status: project: default: target: auto threshold: 0% patch: default: target: auto threshold: 0% parsers: gcov: branch_detection: conditional: yes loop: yes method: no macro: no comment: layout: "reach,diff,flags,tree" behavior: default require_changes: false ================================================ FILE: composer.json ================================================ { "name": "ramsey/uuid", "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", "license": "MIT", "type": "library", "keywords": [ "uuid", "identifier", "guid" ], "require": { "php": "^8.0", "brick/math": "^0.8.16 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14", "ramsey/collection": "^1.2 || ^2.0" }, "require-dev": { "captainhook/captainhook": "^5.25", "captainhook/plugin-composer": "^5.3", "dealerdirect/phpcodesniffer-composer-installer": "^1.0", "ergebnis/composer-normalize": "^2.47", "mockery/mockery": "^1.6", "paragonie/random-lib": "^2", "php-mock/php-mock": "^2.6", "php-mock/php-mock-mockery": "^1.5", "php-parallel-lint/php-parallel-lint": "^1.4.0", "phpbench/phpbench": "^1.2.14", "phpstan/extension-installer": "^1.4", "phpstan/phpstan": "^2.1", "phpstan/phpstan-mockery": "^2.0", "phpstan/phpstan-phpunit": "^2.0", "phpunit/phpunit": "^9.6", "slevomat/coding-standard": "^8.18", "squizlabs/php_codesniffer": "^3.13" }, "replace": { "rhumsaa/uuid": "self.version" }, "suggest": { "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." }, "minimum-stability": "dev", "prefer-stable": true, "autoload": { "psr-4": { "Ramsey\\Uuid\\": "src/" }, "files": [ "src/functions.php" ] }, "autoload-dev": { "psr-4": { "Ramsey\\Uuid\\Benchmark\\": "tests/benchmark/", "Ramsey\\Uuid\\StaticAnalysis\\": "tests/static-analysis/", "Ramsey\\Uuid\\Test\\": "tests/" } }, "config": { "allow-plugins": { "captainhook/plugin-composer": true, "dealerdirect/phpcodesniffer-composer-installer": true, "ergebnis/composer-normalize": true, "phpstan/extension-installer": true }, "sort-packages": true }, "extra": { "captainhook": { "force-install": true } }, "scripts": { "dev:analyze": "@dev:analyze:phpstan", "dev:analyze:phpstan": "phpstan analyse --ansi --memory-limit 1G", "dev:bench": "@php -d 'error_reporting=24575' vendor/bin/phpbench run", "dev:build:clean": "git clean -fX build/", "dev:lint": [ "@dev:lint:syntax", "@dev:lint:style" ], "dev:lint:fix": "phpcbf --cache=build/cache/phpcs.cache", "dev:lint:style": "phpcs --cache=build/cache/phpcs.cache --colors", "dev:lint:syntax": "parallel-lint --colors src/ tests/", "dev:test": [ "@dev:lint", "@dev:bench", "@dev:analyze", "@dev:test:unit" ], "dev:test:coverage:ci": "@php -d 'xdebug.mode=coverage' vendor/bin/phpunit --colors=always --coverage-text --coverage-clover build/coverage/clover.xml --coverage-cobertura build/coverage/cobertura.xml --coverage-crap4j build/coverage/crap4j.xml --coverage-xml build/coverage/coverage-xml --log-junit build/junit.xml", "dev:test:coverage:html": "@php -d 'xdebug.mode=coverage' vendor/bin/phpunit --colors=always --coverage-html build/coverage/coverage-html/", "dev:test:unit": "phpunit --colors=always", "test": "@dev:test" }, "scripts-descriptions": { "dev:analyze": "Runs all static analysis checks.", "dev:analyze:phpstan": "Runs the PHPStan static analyzer.", "dev:bench": "Runs PHPBench benchmark tests.", "dev:build:clean": "Cleans the build/ directory.", "dev:lint": "Runs all linting checks.", "dev:lint:fix": "Auto-fixes coding standards issues, if possible.", "dev:lint:style": "Checks for coding standards issues.", "dev:lint:syntax": "Checks for syntax errors.", "dev:test": "Runs linting, static analysis, and unit tests.", "dev:test:coverage:ci": "Runs unit tests and generates CI coverage reports.", "dev:test:coverage:html": "Runs unit tests and generates HTML coverage report.", "dev:test:unit": "Runs unit tests.", "test": "Runs linting, static analysis, and unit tests." } } ================================================ FILE: docs/.gitignore ================================================ _build/ ================================================ FILE: docs/LICENSE ================================================ Attribution 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: docs/Makefile ================================================ # Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) ================================================ FILE: docs/README.md ================================================ # ramsey/uuid Documentation Changes to the documentation are automatically built by [Read the Docs][] and viewable from . ## Getting Started It's probably best to do this in a virtualenv environment, so set one up first: ``` bash pip install virtualenvwrapper mkvirtualenv ramsey-uuid-docs cd docs/ workon ramsey-uuid-docs pip install -r requirements.txt ``` ## Building the Docs To build the docs, change to the `docs/` directory, and make sure you're working on the virtualenv environment created in the last step. ``` bash cd docs/ workon ramsey-uuid-docs make html ``` Then, to view the docs after building them: ``` bash open _build/html/index.html ``` [read the docs]: https://readthedocs.org ================================================ FILE: docs/_static/.gitkeep ================================================ ================================================ FILE: docs/conf.py ================================================ # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import os import sphinx_rtd_theme import sys import datetime from pygments.lexers.web import PhpLexer from sphinx.highlighting import lexers from subprocess import Popen, PIPE def get_version(): if os.environ.get('READTHEDOCS') == 'True': return os.environ.get('READTHEDOCS_VERSION') pipe = Popen('git branch | grep \\*', stdout=PIPE, shell=True, universal_newlines=True) version = pipe.stdout.read() if version: return version[2:] else: return 'unknown' # -- Project information ----------------------------------------------------- project = 'ramsey/uuid' copyright = '2012-{year}, Ben Ramsey'.format(year = datetime.date.today().strftime('%Y')) author = 'Ben Ramsey' version = get_version().strip() release = version today = datetime.date.today().strftime('%Y-%m-%d') # -- General configuration --------------------------------------------------- master_doc = 'index' highlight_language = 'php' # enable highlighting for PHP code not between ```` by default lexers['php'] = PhpLexer(startinline=True) lexers['php-annotations'] = PhpLexer(startinline=True) # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinxcontrib.phpdomain', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" html_theme_options = { 'collapse_navigation': False, 'display_version': False } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] html_title = "ramsey/uuid %s Manual" % get_version() html_show_sphinx = False htmlhelp_basename = 'ramsey-uuid-doc' html_context = { "display_github": True, "github_user": "ramsey", "github_repo": "uuid", "github_version": version, "conf_py_path": "/docs/", } current_year = datetime.date.today().strftime('%Y') rst_prolog = """ .. |current_year| replace:: {0} """.format(current_year) ================================================ FILE: docs/copyright.rst ================================================ .. _copyright: ========= Copyright ========= Copyright © 2012-|current_year| `Ben Ramsey `_ and `contributors `_. Documentation for ramsey/uuid is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. ramsey/uuid is open source software: you can distribute it and/or modify it under the terms of the MIT License (the "License"). You may not use ramsey/uuid except in compliance with the License. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. You should have received a copy of the MIT License along with this program. If not, see https://opensource.org/license/mit/. ================================================ FILE: docs/customize/calculators.rst ================================================ .. _customize.calculators: ========================= Using a Custom Calculator ========================= By default, ramsey/uuid uses `brick/math`_ as its internal calculator. However, you may change the calculator, if your needs require something else. To swap the default calculator with your custom one, first make an adapter that wraps your custom calculator and implements :php:interface:`Ramsey\\Uuid\\Math\\CalculatorInterface`. This might look something like this: .. code-block:: php :caption: Create a custom calculator wrapper that implements CalculatorInterface :name: customize.calculators.wrapper-example namespace MyProject; use Other\OtherCalculator; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\NumberInterface; class MyUuidCalculator implements CalculatorInterface { private $internalCalculator; public function __construct(OtherCalculator $customCalculator) { $this->internalCalculator = $customCalculator; } public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface { $value = $augend->toString(); foreach ($addends as $addend) { $value = $this->internalCalculator->plus($value, $addend->toString()); } return new IntegerObject($value); } /* ... Class truncated for brevity ... */ } The easiest way to use your custom calculator wrapper is to instantiate a new FeatureSet, set the calculator on it, and pass the FeatureSet into a new UuidFactory. Using the factory, you may then generate and work with UUIDs, using your custom calculator. .. code-block:: php :caption: Use your custom calculator wrapper when working with UUIDs :name: customize.calculators.use-wrapper-example use MyProject\MyUuidCalculator; use Other\OtherCalculator; use Ramsey\Uuid\FeatureSet; use Ramsey\Uuid\UuidFactory; $otherCalculator = new OtherCalculator(); $myUuidCalculator = new MyUuidCalculator($otherCalculator); $featureSet = new FeatureSet(); $featureSet->setCalculator($myUuidCalculator); $factory = new UuidFactory($featureSet); $uuid = $factory->uuid1(); .. _brick/math: https://github.com/brick/math ================================================ FILE: docs/customize/factory.rst ================================================ .. _customize.factory: =========================== Replace the Default Factory =========================== In many of the examples throughout this documentation, we've seen how to configure the factory and then use that factory to generate and work with UUIDs. For example: .. code-block:: php :caption: Configure the factory and use it to generate a version 1 UUID :name: customize.factory.example use Ramsey\Uuid\Codec\OrderedTimeCodec; use Ramsey\Uuid\UuidFactory; $factory = new UuidFactory(); $codec = new OrderedTimeCodec($factory->getUuidBuilder()); $factory->setCodec($codec); $orderedTimeUuid = $factory->uuid1(); When doing this, the default behavior of ramsey/uuid is left intact. If we call ``Uuid::uuid1()`` to generate a version 1 UUID after configuring the factory as shown above, it won't use :ref:`OrderedTimeCodec ` to generate the UUID. .. code-block:: php :caption: The behavior differs between $factory->uuid1() and Uuid::uuid1() :name: customize.factory.behavior-example $orderedTimeUuid = $factory->uuid1(); printf( "UUID: %s\nBytes: %s\n\n", $orderedTimeUuid->toString(), bin2hex($orderedTimeUuid->getBytes()) ); $uuid = Uuid::uuid1(); printf( "UUID: %s\nBytes: %s\n\n", $uuid->toString(), bin2hex($uuid->getBytes()) ); In this example, we print out details for two different UUIDs. The first was generated with the :ref:`OrderedTimeCodec ` using ``$factory->uuid1()``. The second was generated using ``Uuid::uuid1()``. It looks something like this: .. code-block:: text UUID: 2ff06620-6251-11ea-9791-0242ac130003 Bytes: 11ea62512ff0662097910242ac130003 UUID: 2ff09730-6251-11ea-ba64-0242ac130003 Bytes: 2ff09730625111eaba640242ac130003 Notice the arrangement of the bytes. The first set of bytes has been rearranged, according to the ordered-time codec rules, but the second set of bytes remains in the same order as the UUID string. *Configuring the factory does not change the default behavior.* If we want to change the default behavior, we must *replace* the factory used by the Uuid static methods, and we can do this using the :php:meth:`Uuid::setFactory() ` static method. .. code-block:: php :caption: Replace the factory to globally affect Uuid behavior :name: customize.factory.replace-factory-example Uuid::setFactory($factory); $uuid = Uuid::uuid1(); Now, every time we call :php:meth:`Uuid::uuid() `, ramsey/uuid will use the factory configured with the :ref:`OrderedTimeCodec ` to generate version 1 UUIDs. .. warning:: Calling :php:meth:`Uuid::setFactory() ` to replace the factory will change the behavior of Uuid no matter where it is used, so keep this in mind when replacing the factory. If you replace the factory deep inside a method somewhere, any later code that calls a static method on :php:class:`Ramsey\\Uuid\\Uuid` will use the new factory to generate UUIDs. ================================================ FILE: docs/customize/ordered-time-codec.rst ================================================ .. _customize.ordered-time-codec: ================== Ordered-time Codec ================== .. attention:: The :php:class:`Ramsey\\Uuid\\Codec\\OrderedTimeCodec` class is deprecated. Please migrate to :ref:`version 6, reordered Gregorian time UUIDs `. UUIDs arrange their bytes according to the standard recommended by `RFC 9562`_ (formerly `RFC 4122`_). Unfortunately, this means the bytes aren't in an arrangement that supports sorting by creation time or an otherwise incrementing value. The Percona article, "`Storing UUID Values in MySQL`_," explains at length the problems this can cause. It also recommends a solution: the *ordered-time UUID*. `RFC 9562 version 1, Gregorian time UUIDs `_ rearrange the bytes of the time fields so that the lowest bytes appear first, the middle bytes are next, and the highest bytes come last. Logical sorting is not possible with this arrangement. An ordered-time UUID is a version 1 UUID with the time fields arranged in logical order so that the UUIDs can be sorted by creation time. These UUIDs are *monotonically increasing*, each one coming after the previously-created one, in a proper sort order. .. code-block:: php :caption: Use the ordered-time codec to generate a version 1 UUID :name: customize.ordered-time-codec-example use Ramsey\Uuid\Codec\OrderedTimeCodec; use Ramsey\Uuid\UuidFactory; $factory = new UuidFactory(); $codec = new OrderedTimeCodec($factory->getUuidBuilder()); $factory->setCodec($codec); $orderedTimeUuid = $factory->uuid1(); printf( "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\nBytes: %s\n", $orderedTimeUuid->toString(), $orderedTimeUuid->getFields()->getVersion(), $orderedTimeUuid->getDateTime()->format('r'), $orderedTimeUuid->getFields()->getNode()->toString(), bin2hex($orderedTimeUuid->getBytes()) ); This will use the ordered-time codec to generate a version 1 UUID and will print out details about the UUID similar to these: .. code-block:: text UUID: 593200aa-61ae-11ea-bbf2-0242ac130003 Version: 1 Date: Mon, 09 Mar 2020 02:33:23 +0000 Node: 0242ac130003 Bytes: 11ea61ae593200aabbf20242ac130003 .. attention:: Only the byte representation is rearranged. The string representation follows the format of a standard version 1 UUID. This means only the byte representation of an ordered-time codec encoded UUID may be used for sorting, such as with database results. To store the byte representation to a database field, see :ref:`database.bytes`. .. hint:: If you use this codec and store the bytes of the UUID to the database, as recommended above, you will need to use this codec to decode the bytes, as well. Otherwise, the UUID string value will be incorrect. .. code-block:: php // Using a factory configured with the OrderedTimeCodec, as shown above. $orderedTimeUuid = $factory->fromBytes($bytes); .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _Storing UUID Values in MySQL: https://www.percona.com/blog/store-uuid-optimized-way/ ================================================ FILE: docs/customize/timestamp-first-comb-codec.rst ================================================ .. _customize.timestamp-first-comb-codec: ========================== Timestamp-first COMB Codec ========================== .. attention:: The :php:class:`Ramsey\\Uuid\\Codec\\TimestampFirstCombCodec` class is deprecated. Please migrate to :ref:`version 7, Unix Epoch time UUIDs `. :ref:`Version 4, random UUIDs ` are doubly problematic when it comes to sorting and storing to databases (see :ref:`database.order`), since their values are random, and there is no timestamp associated with them that may be rearranged, like with the :ref:`ordered-time codec `. In 2002, Jimmy Nilsson recognized this problem with random UUIDs and proposed a solution he called "COMBs" (see "`The Cost of GUIDs as Primary Keys`_"). So-called because they *combine* random bytes with a timestamp, the timestamp-first COMB codec replaces the first 48 bits of a version 4, random UUID with a Unix timestamp and microseconds, creating an identifier that can be sorted by creation time. These UUIDs are *monotonically increasing*, each one coming after the previously-created one, in a proper sort order. .. code-block:: php :caption: Use the timestamp-first COMB codec to generate a version 4 UUID :name: customize.timestamp-first-comb-codec-example use Ramsey\Uuid\Codec\TimestampFirstCombCodec; use Ramsey\Uuid\Generator\CombGenerator; use Ramsey\Uuid\UuidFactory; $factory = new UuidFactory(); $codec = new TimestampFirstCombCodec($factory->getUuidBuilder()); $factory->setCodec($codec); $factory->setRandomGenerator(new CombGenerator( $factory->getRandomGenerator(), $factory->getNumberConverter() )); $timestampFirstComb = $factory->uuid4(); printf( "UUID: %s\nVersion: %d\nBytes: %s\n", $timestampFirstComb->toString(), $timestampFirstComb->getFields()->getVersion(), bin2hex($timestampFirstComb->getBytes()) ); This will use the timestamp-first COMB codec to generate a version 4 UUID with the timestamp replacing the first 48 bits and will print out details about the UUID similar to these: .. code-block:: text UUID: 9009ebcc-cd99-4b5f-90cf-9155607d2de9 Version: 4 Bytes: 9009ebcccd994b5f90cf9155607d2de9 Note that the bytes are in the same order as the string representation. Unlike the :ref:`ordered-time codec `, the timestamp-first COMB codec affects both the string representation and the byte representation. This means either the string UUID or the bytes may be stored to a datastore and sorted. To learn more, see :ref:`database`. .. _The Cost of GUIDs as Primary Keys: https://web.archive.org/web/20240118030355/https://www.informit.com/articles/printerfriendly/25862 ================================================ FILE: docs/customize/validators.rst ================================================ .. _customize.validators: ======================== Using a Custom Validator ======================== By default, ramsey/uuid validates UUID strings with the lenient validator :php:class:`Ramsey\\Uuid\\Validator\\GenericValidator`. This validator ensures the string is 36 characters, has the dashes in the correct places, and uses only hexadecimal values. It does not ensure the string is of the `RFC 9562`_ (formerly `RFC 4122`_) variant or contains a valid version. The validator :php:class:`Ramsey\\Uuid\\Rfc4122\\Validator` validates UUID strings to ensure they match the `RFC 9562`_ (formerly `RFC 4122`_) variant and contain a valid version. Since it is not enabled by default, you will need to configure ramsey/uuid to use it, if you want stricter validation. .. code-block:: php :caption: Set an alternate validator to use for Uuid::isValid() :name: customize.validators-example use Ramsey\Uuid\Rfc4122\Validator as Rfc4122Validator; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidFactory; $factory = new UuidFactory(); $factory->setValidator(new Rfc4122Validator()); Uuid::setFactory($factory); if (!Uuid::isValid('2bfb5006-087b-9553-5082-e8f39337ad29')) { echo "This UUID is not valid!\n"; } .. tip:: If you want to use your own validation, create a class that implements :php:interface:`Ramsey\\Uuid\\Validator\\ValidatorInterface` and use the same method to set your validator on the factory. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/customize.rst ================================================ .. _customize: ============= Customization ============= .. toctree:: :titlesonly: :hidden: customize/ordered-time-codec customize/timestamp-first-comb-codec customize/calculators customize/validators customize/factory ramsey/uuid offers a variety of ways to modify the standard behavior of the library through dependency injection. Using `FeatureSet`_, `UuidFactory`_, and :php:meth:`Uuid::setFactory() `, you are able to replace just about any `builder`_, `codec`_, `converter`_, `generator`_, `provider`_, and more. Ordered-time Codec *(deprecated)* The ordered-time codec exists to rearrange the bytes of a version 1, Gregorian time UUID so that the timestamp portion of the UUID is monotonically increasing. To learn more, see :ref:`customize.ordered-time-codec`. Timestamp-first COMB Codec *(deprecated)* The timestamp-first COMB codec replaces part of a version 4, random UUID with a timestamp, so that the UUID becomes monotonically increasing. To learn more, see :ref:`customize.timestamp-first-comb-codec`. Using a Custom Calculator It's possible to replace the default calculator ramsey/uuid uses. If your requirements require a different solution for making calculations, see :ref:`customize.calculators`. Using a Custom Validator If your requirements require a different level of validation or a different UUID format, you may replace the default validator. See :ref:`customize.validators`, to learn more. Replace the Default Factory Not only are you able to inject alternate builders, codecs, etc. into the factory and use the factory to generate UUIDs, you may also replace the global, static factory used by the static methods on the Uuid class. To find out how, see :ref:`customize.factory`. .. _UuidFactory: https://github.com/ramsey/uuid/blob/4.x/src/UuidFactory.php .. _FeatureSet: https://github.com/ramsey/uuid/blob/4.x/src/FeatureSet.php .. _codec: https://github.com/ramsey/uuid/tree/4.x/src/Codec .. _builder: https://github.com/ramsey/uuid/tree/4.x/src/Builder .. _converter: https://github.com/ramsey/uuid/tree/4.x/src/Converter .. _provider: https://github.com/ramsey/uuid/tree/4.x/src/Provider .. _generator: https://github.com/ramsey/uuid/tree/4.x/src/Generator ================================================ FILE: docs/database.rst ================================================ .. _database: =================== Using In a Database =================== .. tip:: `ramsey/uuid-doctrine`_ allows the use of ramsey/uuid as a `Doctrine field type`_. If you use Doctrine, it's a great option for working with UUIDs and databases. There are several strategies to consider when working with UUIDs in a database. Among these are whether to store the string representation or bytes and whether the UUID column should be treated as a primary key. We'll discuss a few of these approaches here, but the final decision on how to use UUIDs in a database is up to you since your needs will be different from those of others. .. note:: All database code examples in this section assume the use of `MariaDB`_ and `PHP Data Objects (PDO)`_. If using a different database engine or connection library, your code will differ, but the general concepts should remain the same. .. _database.string: Storing As a String ################### Perhaps the easiest way to store a UUID to a database is to create a ``char(36)`` column and store the UUID as a string. When stored as a string, UUIDs require no special treatment in SQL statements or when displaying them. The primary drawback is the size. At 36 characters, UUIDs can take up a lot of space, and when handling a lot of data, this can add up. .. code-block:: sql :caption: Create a table with a column for UUIDs :name: database.uuid-column-example CREATE TABLE `notes` ( `uuid` char(36) NOT NULL, `notes` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Using this database table, we can store the string UUID using code similar to this (assume some of the variables in this example have been set beforehand): .. code-block:: php :caption: Store a string UUID to the uuid column :name: database.uuid-column-store-example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid4(); $dbh = new PDO($dsn, $username, $password); $sth = $dbh->prepare(' INSERT INTO notes ( uuid, notes ) VALUES ( :uuid, :notes ) '); $sth->execute([ ':uuid' => $uuid->toString(), ':notes' => $notes, ]); .. _database.bytes: Storing As Bytes ################ In :ref:`the previous example `, we saw how to store the string representation of a UUID to a ``char(36)`` column. As discussed, the primary drawback is the size. However, if we store the UUID in byte form, we only need a ``char(16)`` column, saving over half the space. The primary drawback with this approach is ease-of-use. Since the UUID bytes are stored in the database, querying and selecting data becomes more difficult. .. code-block:: sql :caption: Create a table with a column for UUID bytes :name: database.uuid-bytes-example CREATE TABLE `notes` ( `uuid` char(16) NOT NULL, `notes` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Using this database table, we can store the UUID bytes using code similar to this (again, assume some of the variables in this example have been set beforehand): .. code-block:: php :caption: Store UUID bytes to the uuid column :name: database.uuid-bytes-store-example $sth->execute([ ':uuid' => $uuid->getBytes(), ':notes' => $notes, ]); Now, when we ``SELECT`` the records from the database, we will need to convert the ``notes.uuid`` column to a ramsey/uuid object, so that we are able to use it. .. code-block:: php :caption: Covert database UUID bytes to UuidInterface instance :name: database.uuid-bytes-convert-example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid4(); $dbh = new PDO($dsn, $username, $password); $sth = $dbh->prepare('SELECT uuid, notes FROM notes'); $sth->execute(); foreach ($sth->fetchAll() as $record) { $uuid = Uuid::fromBytes($record['uuid']); printf( "UUID: %s\nNotes: %s\n\n", $uuid->toString(), $record['notes'] ); } We'll also need to query the database using the bytes. .. code-block:: php :caption: Look-up the record from the database, using the UUID bytes :name: database.uuid-bytes-select-example use Ramsey\Uuid\Uuid; $uuid = Uuid::fromString('278198d3-fa96-4833-abab-82f9e67f4712'); $dbh = new PDO($dsn, $username, $password); $sth = $dbh->prepare(' SELECT uuid, notes FROM notes WHERE uuid = :uuid '); $sth->execute([ ':uuid' => $uuid->getBytes(), ]); $record = $sth->fetch(); if ($record) { $uuid = Uuid::fromBytes($record['uuid']); printf( "UUID: %s\nNotes: %s\n\n", $uuid->toString(), $record['notes'] ); } .. _database.pk: Using As a Primary Key ###################### In the previous examples, we didn't use the UUID as a primary key, but it's logical to use the ``notes.uuid`` field as a primary key. There's nothing wrong with this approach, but there are a couple of points to consider: * InnoDB stores data in the primary key order * All the secondary keys also contain the primary key (in InnoDB) We'll deal with the first point in the section, :ref:`database.order`. For the second point, if you are using the string version of the UUID (i.e., ``char(36)``), then not only will the primary key be large and take up a lot of space, but every secondary key that uses that primary key will also be much larger. For this reason, if you choose to use UUIDs as primary keys, it might be worth the drawbacks to use UUID bytes (i.e., ``char(16)``) instead of the string representation (see :ref:`database.bytes`). .. hint:: If not using InnoDB with MySQL or MariaDB, consult your database engine documentation to find whether it also has similar properties that will factor into your use of UUIDs. .. _database.uk: Using As a Unique Key ##################### Instead of :ref:`using UUIDs as a primary key `, you may choose to use an ``AUTO_INCREMENT`` column with the ``int unsigned`` data type as a primary key, while using a ``char(36)`` for UUIDs and setting a ``UNIQUE KEY`` on this column. This will aid in lookups while helping keep your secondary keys small. .. code-block:: sql :caption: Use an auto-incrementing column as primary key, with UUID as a unique key :name: database.id-auto-increment-uuid-unique-key CREATE TABLE `notes` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uuid` char(36) NOT NULL, `notes` text NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `notes_uuid_uk` (`uuid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; .. _database.order: Insertion Order and Sorting ########################### UUID versions 1, 2, 3, 4, and 5 are not *monotonically increasing*. If using these versions as primary keys, the inserts will be random, and the data will be scattered on disk (for InnoDB). Over time, as the database size grows, lookups will become slower and slower. .. tip:: See Percona's "`Storing UUID Values in MySQL`_" post, for more details on the performance of UUIDs as primary keys. To minimize these problems, two solutions have been devised: 1. :ref:`rfc4122.version6` UUIDs 2. :ref:`rfc4122.version7` UUIDs .. note:: We previously recommended the use of the :ref:`timestamp-first COMB ` or :ref:`ordered-time ` codecs to solve these problems. However, UUID versions 6 and 7 were defined to provide these solutions in a standardized way. .. _ramsey/uuid-doctrine: https://github.com/ramsey/uuid-doctrine .. _Doctrine field type: https://www.doctrine-project.org/projects/doctrine-dbal/en/stable/reference/types.html .. _MariaDB: https://mariadb.org .. _PHP Data Objects (PDO): https://www.php.net/pdo .. _Storing UUID Values in MySQL: https://www.percona.com/blog/store-uuid-optimized-way/ ================================================ FILE: docs/faq.rst ================================================ .. _faq: ================================= Frequently Asked Questions (FAQs) ================================= .. contents:: :local: :depth: 1 .. _faq.rhumsaa-abandoned: How do I fix "rhumsaa/uuid is abandoned" messages? ################################################## When installing your project's dependencies using Composer, you might see the following message: .. code-block:: text Package rhumsaa/uuid is abandoned; you should avoid using it. Use ramsey/uuid instead. Don't panic. Simply execute the following commands with Composer: .. code-block:: bash composer remove rhumsaa/uuid composer require ramsey/uuid=^2.9 After doing so, you will have the latest ramsey/uuid package in the 2.x series, and there will be no need to modify any code; the namespace in the 2.x series is still ``Rhumsaa``. .. _faq.final: Why does ramsey/uuid use ``final``? ################################### You might notice that many of the concrete classes returned in ramsey/uuid are marked as ``final``. There are specific reasons for this choice, and I will offer a few solutions for those looking to extend or mock the classes for testing purposes. But Why? -------- .. raw:: html

via GIPHY

First, let's take a look at why ramsey/uuid uses ``final``. UUIDs are defined by a set of rules --- published as `RFC 9562`_ (formerly `RFC 4122`_) --- and those rules shouldn't change. If they do, then it's no longer a UUID --- at least not as defined by `RFC 9562`_. As an example, let's think about :php:class:`Rfc4122\\UuidV1 `. If our application wants to do something special with this type, it might use the ``instanceof`` operator to check that a variable is a UuidV1, or it might use a type hint on a method argument. If a third-party library passes a UUID object to us that extends UuidV1 but overrides some very important internal logic, then we may no longer have a version 1 UUID. Perhaps we can all be adults and play nicely, but ramsey/uuid cannot make any guarantees for any subclasses of UuidV1. However, ramsey/uuid *can* make guarantees about classes that implement :php:interface:`UuidInterface ` or :php:interface:`Rfc4122\\UuidInterface `. So, if we're working with an instance of a class that is marked ``final``, we can guarantee that the rules for the creation of that object will not change, even if a third-party library passes us an instance of the same class. This is the reason why ramsey/uuid specifies certain :ref:`argument and return types ` that are marked ``final``. Since these are ``final``, ramsey/uuid is able to guarantee the type of data these value objects contain. :php:class:`Type\\Integer ` should never contain any characters other than numeral digits, and :php:class:`Type\\Hexadecimal ` should never contain any characters other than hexadecimal digits. If other libraries could extend these and return them from UUID instances, then ramsey/uuid cannot guarantee their values. This is very similar to using strict types with ``int``, ``float``, or ``bool``. These types cannot change, so think of final classes in ramsey/uuid as types that cannot change. Overriding Behavior ------------------- You may override the behavior of ramsey/uuid as much as you want. Despite the use of ``final``, the library is very flexible. Take a look at the myriad opportunities to change how the library works: * :ref:`rfc4122.version1.random` * :ref:`customize.timestamp-first-comb-codec` * :ref:`customize.factory` * :ref:`And more... ` ramsey/uuid is able to provide this flexibility through the use of `interfaces`_, `factories`_, and `dependency injection`_. At the same time, ramsey/uuid is able to guarantee that neither a :php:class:`UuidV1 ` nor a :php:class:`UuidV4 ` nor an :php:class:`Integer ` nor a :php:class:`Time `, etc. will ever change because of `downstream`_ code. UUIDs have specific rules that make them practically unique. ramsey/uuid ensures that other code cannot change this expectation while allowing your code and third-party libraries to change how UUIDs are generated and to return different types of UUIDs not specified by `RFC 9562`_. Testing With UUIDs ------------------ Sometimes, the use of ``final`` can throw a wrench in our ability to write tests, but it doesn't have to be that way. To learn a few techniques for using ramsey/uuid instances in your tests, take a look at :ref:`testing`. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _interfaces: https://www.php.net/interfaces .. _factories: https://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29 .. _dependency injection: https://en.wikipedia.org/wiki/Dependency_injection .. _downstream: https://en.wikipedia.org/wiki/Downstream_(software_development) ================================================ FILE: docs/index.rst ================================================ .. _index: ====================== ramsey/uuid User Guide ====================== For `ramsey/uuid `_ |version|. Updated on |today|. Contents -------- .. toctree:: :maxdepth: 2 :includehidden: introduction quickstart rfc4122 nonstandard database customize testing upgrading FAQs reference copyright Indices and Tables ------------------ * :ref:`genindex` * :ref:`search` ================================================ FILE: docs/introduction.rst ================================================ .. _introduction: ============ Introduction ============ ramsey/uuid is a PHP library for generating and working with `RFC 9562`_ (formerly `RFC 4122`_) version 1, 2, 3, 4, 5, 6, 7, and 8 universally unique identifiers (UUID). ramsey/uuid also supports optional and non-standard features, such as GUIDs and other approaches for encoding/decoding UUIDs. What Is a UUID? ############### A universally unique identifier, or UUID, is a 128-bit unsigned integer, usually represented as a hexadecimal string split into five groups with dashes. The most widely-known and used types of UUIDs are defined by `RFC 9562`_ (formerly `RFC 4122`_). A UUID, when encoded in hexadecimal string format, looks like: .. code-block:: text ebb5c735-0308-4e3c-9aea-8a270aebfe15 The probability of duplicating a UUID is close to zero, so they are a great choice for generating unique identifiers in distributed systems. UUIDs can also be stored in binary format, as a string of 16 bytes. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/nonstandard/guid.rst ================================================ .. _nonstandard.guid: =================================== Globally Unique Identifiers (GUIDs) =================================== .. tip:: Using these techniques to work with GUIDs is useful if you're working with identifiers that have been stored in GUID byte order. For example, this is the case if working with the ``UNIQUEIDENTIFIER`` data type in Microsoft SQL Server. This is a GUID, stored as a 16-byte binary string. If working directly with the bytes, you may use the GUID functionality in ramsey/uuid to properly handle this data type. According to the Windows Dev Center article on `GUID structure`_, "GUIDs are the Microsoft implementation of the distributed computing environment (DCE) universally unique identifier." For all intents and purposes, a GUID string representation is identical to that of an `RFC 9562`_ (formerly `RFC 4122`_) UUID. For historical reasons, *the byte order is not*. The `.NET Framework documentation`_ explains: Note that the order of bytes in the returned byte array is different from the string representation of a Guid value. The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the last two-byte group and the closing six-byte group is the same. This is best explained by example. .. code-block:: php :caption: Decoding a GUID from byte representation :name: nonstandard.guid.decode-bytes-example use Ramsey\Uuid\FeatureSet; use Ramsey\Uuid\UuidFactory; // The bytes of a GUID previously stored in some datastore. $guidBytes = hex2bin('0eab93fc9ec9584b975e9c5e68c53624'); $useGuids = true; $featureSet = new FeatureSet($useGuids); $factory = new UuidFactory($featureSet); $guid = $factory->fromBytes($guidBytes); printf( "Class: %s\nGUID: %s\nVersion: %d\nBytes: %s\n", get_class($guid), $guid->toString(), $guid->getFields()->getVersion(), bin2hex($guid->getBytes()) ); This transforms the bytes of a GUID, as represented by ``$guidBytes``, into a :php:class:`Ramsey\\Uuid\\Guid\\Guid` instance and prints out some details about it. It looks something like this: .. code-block:: text Class: Ramsey\Uuid\Guid\Guid GUID: fc93ab0e-c99e-4b58-975e-9c5e68c53624 Version: 4 Bytes: 0eab93fc9ec9584b975e9c5e68c53624 Note the difference between the string GUID and the bytes. The bytes are arranged like this: .. code-block:: text 0e ab 93 fc 9e c9 58 4b 97 5e 9c 5e 68 c5 36 24 In an `RFC 9562`_ (formerly `RFC 4122`_) UUID, the bytes are stored in the same order as you see presented in the string representation. This is often called *network byte order*, or *big-endian* order. In a GUID, the order of the bytes are reversed in each grouping for the first 64 bits and stored in *little-endian* order. The remaining 64 bits are stored in network byte order. See `Endianness <#nonstandard-guid-endianness>`_ to learn more. .. caution:: The bytes themselves do not indicate their order. If you decode GUID bytes as a UUID or UUID bytes as a GUID, you will get the wrong values. However, you can always create a GUID or UUID from the same string value; the bytes for each will be in a different order, even though the string is the same. The key is to know ahead of time in what order the bytes are stored. Then, you will be able to decode them using the correct approach. Converting GUIDs to UUIDs ######################### Continuing from the example, :ref:`nonstandard.guid.decode-bytes-example`, we can take the GUID string representation and convert it into a standard UUID. .. code-block:: php :caption: Convert a GUID to a UUID :name: nonstandard.guid.convert-example $uuid = Uuid::fromString($guid->toString()); printf( "Class: %s\nUUID: %s\nVersion: %d\nBytes: %s\n", get_class($uuid), $uuid->toString(), $uuid->getFields()->getVersion(), bin2hex($uuid->getBytes()) ); Because the GUID was a version 4, random UUID, this creates an instance of :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV4` from the GUID string and prints out a few details about it. It looks something like this: .. code-block:: text Class: Ramsey\Uuid\Rfc4122\UuidV4 UUID: fc93ab0e-c99e-4b58-975e-9c5e68c53624 Version: 4 Bytes: fc93ab0ec99e4b58975e9c5e68c53624 Note how the UUID string is identical to the GUID string. However, the byte order is different, since they are in big-endian order. The bytes are now arranged like this: .. code-block:: text fc 93 ab 0e c9 9e 4b 58 97 5e 9c 5e 68 c5 36 24 .. admonition:: Endianness :name: nonstandard.guid.endianness Big-endian and little-endian refer to the ordering of bytes in a multi-byte number. Big-endian order places the most significant byte first, followed by the other bytes in descending order. Little-endian order places the least significant byte first, followed by the other bytes in ascending order. Take the hexadecimal number ``0x1234``, for example. In big-endian order, the bytes are stored as ``12 34``, and in little-endian order, they are stored as ``34 12``. In either case, the number is still ``0x1234``. Networking protocols usually use big-endian ordering, while computer processor architectures often use little-endian ordering. The terms originated in Jonathan Swift's *Gulliver's Travels*, where the Lilliputians argue over which end of a hard-boiled egg is the best end to crack. .. _GUID structure: https://learn.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _.NET Framework documentation: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tobytearray ================================================ FILE: docs/nonstandard/other.rst ================================================ .. _nonstandard.other: ======================= Other Nonstandard UUIDs ======================= Sometimes, you might encounter a string that looks like a UUID but doesn't follow the `RFC 9562`_ (formerly `RFC 4122`_) specification. Take this string, for example: .. code-block:: text d95959bc-2ff5-43eb-fccd-14883ba8f174 At a glance, this looks like a valid UUID, but the variant bits don't match `RFC 9562`_ (formerly `RFC 4122`_). Instead of throwing a validation exception, ramsey/uuid will assume this is a UUID, since it fits the format and has 128 bits, but it will represent it as a :php:class:`Ramsey\\Uuid\\Nonstandard\\Uuid`. .. code-block:: php :caption: Create an instance of :php:class:`Ramsey\\Uuid\\Nonstandard\\Uuid` from a non-RFC 9562 UUID use Ramsey\Uuid\Uuid; $uuid = Uuid::fromString('d95959bc-2ff5-43eb-fccd-14883ba8f174'); printf( "Class: %s\nUUID: %s\nVersion: %d\nVariant: %s\n", get_class($uuid), $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getFields()->getVariant() ); This will create a :php:class:`Ramsey\\Uuid\\Nonstandard\\Uuid` from the given string and print out a few details about it. It will look something like this: .. code-block:: text Class: Ramsey\Uuid\Nonstandard\Uuid UUID: d95959bc-2ff5-43eb-fccd-14883ba8f174 Version: 0 Variant: 7 Note that the version is 0. Since the variant is 7, and there is no formal specification for this variant of UUID, ramsey/uuid has no way of knowing what type of UUID this is. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/nonstandard/version6.rst ================================================ .. _nonstandard.version6: =================================== Version 6: Reordered Gregorian Time =================================== .. attention:: This documentation has moved to :ref:`RFC 9562 UUIDs: Version 6: Reordered Gregorian Time `. The :php:class:`Ramsey\\Uuid\\Nonstandard\\UuidV6` class is deprecated in favor of :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV6`. ================================================ FILE: docs/nonstandard.rst ================================================ .. _nonstandard: ================= Nonstandard UUIDs ================= .. toctree:: :titlesonly: :hidden: nonstandard/version6 nonstandard/guid nonstandard/other Outside of `RFC 9562`_ (formerly `RFC 4122`_), other types of UUIDs are in-use, following rules of their own. Some of these are on their way to becoming accepted standards, while others have historical reasons for remaining valid today. Still, others are completely random and do not follow any rules. For these cases, ramsey/uuid provides a special functionality to handle these alternate, nonstandard forms. Globally Unique Identifiers (GUIDs) A globally unique identifier, or GUID, is often used as a synonym for UUID. A key difference is the order of the bytes. Any `RFC 9562`_ version UUID may be represented as a GUID. For more details, see :ref:`nonstandard.guid`. Other Nonstandard UUIDs Sometimes, UUID string or byte representations don't follow `RFC 9562`_. Rather than reject these identifiers, ramsey/uuid returns them with the special Nonstandard\\Uuid instance type. For more details, see :ref:`nonstandard.other`. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/quickstart.rst ================================================ .. _quickstart: =============== Getting Started =============== Requirements ############ ramsey/uuid |version| requires the following: * PHP 8.0+ * `ext-json `_ The JSON extension is normally enabled by default, but it is possible to disable it. Other required extensions include `PCRE `_ and `SPL `_. These standard extensions cannot be disabled without patching PHP's build system and/or C sources. ramsey/uuid recommends installing/enabling the following extensions. While not required, these extensions improve the performance of ramsey/uuid. * `ext-gmp `_ * `ext-bcmath `_ Install With Composer ##################### The only supported installation method for ramsey/uuid is `Composer `_. Use the following command to add ramsey/uuid to your project dependencies: .. code-block:: bash composer require ramsey/uuid Using ramsey/uuid ################# After installing ramsey/uuid, the quickest way to get up-and-running is to use the static generation methods. .. code-block:: php use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid4(); printf( "UUID: %s\nVersion: %d\n", $uuid->toString(), $uuid->getFields()->getVersion() ); This will return an instance of :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV4`. .. tip:: .. rubric:: Use the Interfaces Feel free to use ``instanceof`` to check the specific instance types of UUIDs. However, when using type hints, it's best to use the interfaces. The most lenient interface is :php:interface:`Ramsey\\Uuid\\UuidInterface`, while :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface` ensures the UUIDs you're using conform to the `RFC 9562`_ (formerly `RFC 4122`_) standard. If you're not sure which one to use, start with the stricter :php:interface:`Rfc4122\\UuidInterface `. ramsey/uuid provides a number of helpful static methods that help you work with and generate most types of UUIDs, without any special customization of the library. .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - :php:meth:`Uuid::uuid1() ` - This generates a :ref:`rfc4122.version1` UUID. * - :php:meth:`Uuid::uuid2() ` - This generates a :ref:`rfc4122.version2` UUID. * - :php:meth:`Uuid::uuid3() ` - This generates a :ref:`rfc4122.version3` UUID. * - :php:meth:`Uuid::uuid4() ` - This generates a :ref:`rfc4122.version4` UUID. * - :php:meth:`Uuid::uuid5() ` - This generates a :ref:`rfc4122.version5` UUID. * - :php:meth:`Uuid::uuid6() ` - This generates a :ref:`rfc4122.version6` UUID. * - :php:meth:`Uuid::uuid7() ` - This generates a :ref:`rfc4122.version7` UUID. * - :php:meth:`Uuid::uuid8() ` - This generates a :ref:`rfc4122.version8` UUID. * - :php:meth:`Uuid::isValid() ` - Checks whether a string is a valid UUID. * - :php:meth:`Uuid::fromString() ` - Creates a UUID instance from a string UUID. * - :php:meth:`Uuid::fromBytes() ` - Creates a UUID instance from a 16-byte string. * - :php:meth:`Uuid::fromInteger() ` - Creates a UUID instance from a string integer. * - :php:meth:`Uuid::fromDateTime() ` - Creates a version 1 UUID instance from a PHP `DateTimeInterface`_. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _DateTimeInterface: https://www.php.net/datetimeinterface ================================================ FILE: docs/reference/calculators.rst ================================================ .. _reference.calculators: =========== Calculators =========== .. php:namespace:: Ramsey\Uuid\Math .. php:interface:: CalculatorInterface Provides functionality for performing mathematical calculations. .. php:method:: add($augend, ...$addends) :param Ramsey\\Uuid\\Type\\NumberInterface $augend: The first addend (the integer being added to) :param Ramsey\\Uuid\\Type\\NumberInterface ...$addends: The additional integers to a add to the augend :returns: The sum of all the parameters :returntype: Ramsey\\Uuid\\Type\\NumberInterface .. php:method:: subtract($minuend, ...$subtrahends) :param Ramsey\\Uuid\\Type\\NumberInterface $minuend: The integer being subtracted from :param Ramsey\\Uuid\\Type\\NumberInterface ...$subtrahends: The integers to subtract from the minuend :returns: The difference after subtracting all parameters :returntype: Ramsey\\Uuid\\Type\\NumberInterface .. php:method:: multiply($multiplicand, ...$multipliers) :param Ramsey\\Uuid\\Type\\NumberInterface $multiplicand: The integer to be multiplied :param Ramsey\\Uuid\\Type\\NumberInterface ...$multipliers: The factors by which to multiply the multiplicand :returns: The product of multiplying all the provided parameters :returntype: Ramsey\\Uuid\\Type\\NumberInterface .. php:method:: divide($roundingMode, $scale, $dividend, ...$divisors) :param int $roundingMode: The strategy for rounding the quotient; one of the :php:class:`Ramsey\\Uuid\\Math\\RoundingMode` constants :param int $scale: The scale to use for the operation :param Ramsey\\Uuid\\Type\\NumberInterface $dividend: The integer to be divided :param Ramsey\\Uuid\\Type\\NumberInterface ...$divisors: The integers to divide ``$dividend`` by, in the order in which the division operations should take place (left-to-right) :returns: The quotient of dividing the provided parameters left-to-right :returntype: Ramsey\\Uuid\\Type\\NumberInterface .. php:method:: fromBase($value, $base) Converts a value from an arbitrary base to a base-10 integer value. :param string $value: The value to convert :param int $base: The base to convert from (i.e., 2, 16, 32, etc.) :returns: The base-10 integer value of the converted value :returntype: Ramsey\\Uuid\\Type\\Integer .. php:method:: toBase($value, $base) Converts a base-10 integer value to an arbitrary base. :param Ramsey\\Uuid\\Type\\Integer $value: The integer value to convert :param int $base: The base to convert to (i.e., 2, 16, 32, etc.) :returns: The value represented in the specified base :returntype: ``string`` .. php:method:: toHexadecimal($value) Converts an Integer instance to a Hexadecimal instance. :param Ramsey\\Uuid\\Type\\Integer $value: The Integer to convert to Hexadecimal :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: toInteger($value) Converts a Hexadecimal instance to an Integer instance. :param Ramsey\\Uuid\\Type\\Hexadecimal $value: The Hexadecimal to convert to Integer :returntype: Ramsey\\Uuid\\Type\\Integer .. php:class:: RoundingMode .. php:const:: UNNECESSARY Asserts that the requested operation has an exact result, hence no rounding is necessary. .. php:const:: UP Rounds away from zero. Always increments the digit prior to a nonzero discarded fraction. Note that this rounding mode never decreases the magnitude of the calculated value. .. php:const:: DOWN Rounds towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value. .. php:const:: CEILING Rounds towards positive infinity. If the result is positive, behaves as for :php:const:`UP `; if negative, behaves as for :php:const:`DOWN `. Note that this rounding mode never decreases the calculated value. .. php:const:: FLOOR Rounds towards negative infinity. If the result is positive, behave as for :php:const:`DOWN `; if negative, behave as for :php:const:`UP `. Note that this rounding mode never increases the calculated value. .. php:const:: HALF_UP Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for :php:const:`UP ` if the discarded fraction is >= 0.5; otherwise, behaves as for :php:const:`DOWN `. Note that this is the rounding mode commonly taught at school. .. php:const:: HALF_DOWN Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for :php:const:`UP ` if the discarded fraction is > 0.5; otherwise, behaves as for :php:const:`DOWN `. .. php:const:: HALF_CEILING Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity. If the result is positive, behaves as for :php:const:`HALF_UP `; if negative, behaves as for :php:const:`HALF_DOWN `. .. php:const:: HALF_FLOOR Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity. If the result is positive, behaves as for :php:const:`HALF_DOWN `; if negative, behaves as for :php:const:`HALF_UP `. .. php:const:: HALF_EVEN Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor. Behaves as for :php:const:`HALF_UP ` if the digit to the left of the discarded fraction is odd; behaves as for :php:const:`HALF_DOWN ` if it's even. Note that this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. It is sometimes known as "Banker's rounding", and is chiefly used in the USA. ================================================ FILE: docs/reference/exceptions.rst ================================================ .. _reference.exceptions: ========== Exceptions ========== All exceptions in the :php:ns:`Ramsey\\Uuid` namespace implement :php:interface:`Ramsey\\Uuid\\Exception\\UuidExceptionInterface`. This provides a base type you may use to catch any and all exceptions that originate from this library. .. php:namespace:: Ramsey\Uuid\Exception .. php:interface:: UuidExceptionInterface This is the interface all exceptions in ramsey/uuid must implement. .. php:exception:: BuilderNotFoundException Extends `RuntimeException `_. Thrown to indicate that no suitable UUID builder could be found. .. php:exception:: DateTimeException Extends `RuntimeException `_. Thrown to indicate that the PHP DateTime extension encountered an exception or error. .. php:exception:: DceSecurityException Extends `RuntimeException `_. Thrown to indicate an exception occurred while dealing with DCE Security (version 2) UUIDs .. php:exception:: InvalidArgumentException Extends `InvalidArgumentException `_. Thrown to indicate that the argument received is not valid. .. php:exception:: InvalidBytesException Extends `RuntimeException `_. Thrown to indicate that the bytes being operated on are invalid in some way. .. php:exception:: InvalidUuidStringException Extends :php:exc:`Ramsey\\Uuid\\Exception\\InvalidArgumentException`. Thrown to indicate that the string received is not a valid UUID. .. php:exception:: NameException Extends `RuntimeException `_. Thrown to indicate that an error occurred while attempting to hash a namespace and name .. php:exception:: NodeException Extends `RuntimeException `_. Thrown to indicate that attempting to fetch or create a node ID encountered an error. .. php:exception:: RandomSourceException Extends `RuntimeException `_. Thrown to indicate that the source of random data encountered an error. .. php:exception:: TimeSourceException Extends `RuntimeException `_. Thrown to indicate that the source of time encountered an error. .. php:exception:: UnableToBuildUuidException Extends `RuntimeException `_. Thrown to indicate a builder is unable to build a UUID. .. php:exception:: UnsupportedOperationException Extends `LogicException `_. Thrown to indicate that the requested operation is not supported. ================================================ FILE: docs/reference/fields-fieldsinterface.rst ================================================ .. _reference.fields.fieldsinterface: ======================== Fields\\FieldsInterface ======================== .. php:namespace:: Ramsey\Uuid\Fields .. php:interface:: FieldsInterface Represents the fields of a UUID. .. php:method:: getBytes() :returns: The bytes that comprise these fields. :returntype: ``string`` ================================================ FILE: docs/reference/guid-fields.rst ================================================ .. _reference.guid.fields: ============ Guid\\Fields ============ .. php:namespace:: Ramsey\Uuid\Guid .. php:class:: Fields Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\FieldsInterface`. Guid\Fields represents the fields of a GUID. ================================================ FILE: docs/reference/guid-guid.rst ================================================ .. _reference.guid.guid: ========== Guid\\Guid ========== .. php:namespace:: Ramsey\Uuid\Guid .. php:class:: Guid Implements :php:interface:`Ramsey\\Uuid\\UuidInterface`. Guid represents a :ref:`nonstandard.guid`. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getFields() :returns: The fields that comprise this GUID. :returntype: Ramsey\\Uuid\\Guid\\Fields ================================================ FILE: docs/reference/helper.rst ================================================ .. _reference.helper: ================ Helper Functions ================ ramsey/uuid additionally provides the following helper functions, which return only the string standard representation of a UUID. .. php:function:: Ramsey\Uuid\v1([$node[, $clockSeq]]) Generates a string standard representation of a version 1, Gregorian time UUID. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A string standard representation of a version 1 UUID :returntype: string .. php:function:: Ramsey\Uuid\v2($localDomain[, $localIdentifier[, $node[, $clockSeq]]]) Generates a string standard representation of a version 2, DCE Security UUID. :param int $localDomain: The local domain to use (one of ``Uuid::DCE_DOMAIN_PERSON``, ``Uuid::DCE_DOMAIN_GROUP``, or ``Uuid::DCE_DOMAIN_ORG``) :param Ramsey\\Uuid\\Type\\Integer|null $localIdentifier: A local identifier for the domain (defaults to system UID or GID for *person* or *group*) :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A string standard representation of a version 2 UUID :returntype: string .. php:function:: Ramsey\Uuid\v3($ns, $name) Generates a string standard representation of a version 3, name-based (MD5) UUID. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A string standard representation of a version 3 UUID :returntype: string .. php:function:: Ramsey\Uuid\v4() Generates a string standard representation of a version 4, random UUID. :returns: A string standard representation of a version 4 UUID :returntype: string .. php:function:: Ramsey\Uuid\v5($ns, $name) Generates a string standard representation of a version 5, name-based (SHA-1) UUID. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A string standard representation of a version 5 UUID :returntype: string .. php:function:: Ramsey\Uuid\v6([$node[, $clockSeq]]) Generates a string standard representation of a version 6, reordered Gregorian time UUID. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A string standard representation of a version 6 UUID :returntype: string .. php:function:: Ramsey\Uuid\v7([$dateTime]) Generates a string standard representation of a version 7, Unix Epoch time UUID. :param \\DatetimeInterface|null $node: An optional date/time from which to create the version 7 UUID. If not provided, the UUID is generated using the current date/time :returns: A string standard representation of a version 7 UUID :returntype: string .. php:function:: Ramsey\Uuid\v8($bytes) Generates a string standard representation of a version 8, implementation-specific, custom format UUID. :param string $bytes: A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 and 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs. :returns: A string standard representation of a version 8 UUID :returntype: string ================================================ FILE: docs/reference/name-based-namespaces.rst ================================================ .. _reference.name-based-namespaces: ===================== Predefined Namespaces ===================== `RFC 9562`_ (formerly `RFC 4122`_) defines a handful of UUIDs to use with "for some potentially interesting name spaces." .. list-table:: :widths: 30 70 :align: center :header-rows: 1 * - Constant - Description * - :php:const:`Uuid::NAMESPACE_DNS ` - The name string is a fully-qualified domain name. * - :php:const:`Uuid::NAMESPACE_URL ` - The name string is a URL. * - :php:const:`Uuid::NAMESPACE_OID ` - The name string is an `ISO object identifier (OID)`_. * - :php:const:`Uuid::NAMESPACE_X500 ` - The name string is an `X.500`_ `DN`_ in `DER`_ or a text output format. .. _RFC 4122: https://tools.ietf.org/html/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _ISO object identifier (OID): http://www.oid-info.com .. _X.500: https://en.wikipedia.org/wiki/X.500 .. _DN: https://en.wikipedia.org/wiki/Distinguished_Name .. _DER: https://www.itu.int/rec/T-REC-X.690/ ================================================ FILE: docs/reference/nonstandard-fields.rst ================================================ .. _reference.nonstandard.fields: =================== Nonstandard\\Fields =================== .. php:namespace:: Ramsey\Uuid\Nonstandard .. php:class:: Fields Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\FieldsInterface`. Nonstandard\\Fields represents the fields of a nonstandard UUID. ================================================ FILE: docs/reference/nonstandard-uuid.rst ================================================ .. _reference.nonstandard.uuid: ================= Nonstandard\\Uuid ================= .. php:namespace:: Ramsey\Uuid\Nonstandard .. php:class:: Uuid Implements :php:interface:`Ramsey\\Uuid\\UuidInterface`. Nonstandard\\Uuid represents :ref:`nonstandard.other`. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getFields() :returns: The fields that comprise this UUID :returntype: Ramsey\\Uuid\\Nonstandard\\Fields ================================================ FILE: docs/reference/nonstandard-uuidv6.rst ================================================ .. _reference.nonstandard.uuidv6: =================== Nonstandard\\UuidV6 =================== .. php:namespace:: Ramsey\Uuid\Nonstandard .. php:class:: UuidV6 .. attention:: :php:class:`Ramsey\\Uuid\\Nonstandard\\UuidV6` is deprecated in favor of :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV6`. Please migrate any code using ``Nonstandard\UuidV6`` to ``Rfc4122\UuidV6``. Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV6 represents a :ref:`version 6, reordered Gregorian time UUID `. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getDateTime() :returns: A date object representing the timestamp associated with the UUID :returntype: ``\DateTimeInterface`` .. php:method:: toUuidV1() :returns: A version 1 UUID, converted from this version 6 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 .. php:staticmethod:: fromUuidV1() :param Ramsey\\Uuid\\Rfc4122\\UuidV1 $uuidV1: A version 1 UUID :returns: A version 6 UUID, converted from the given version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV6 ================================================ FILE: docs/reference/rfc4122-fieldsinterface.rst ================================================ .. _reference.rfc4122.fieldsinterface: ======================== Rfc4122\\FieldsInterface ======================== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:interface:: FieldsInterface Implements :php:interface:`Ramsey\\Uuid\\Fields\\FieldsInterface`. Rfc4122\\FieldsInterface represents the fields of an `RFC 9562`_ (formerly `RFC 4122`_) UUID. In addition to the methods defined on the interface, this class additionally defines the following methods. .. php:method:: getClockSeq() :returns: The full 16-bit clock sequence, with the variant bits (two most significant bits) masked out. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getClockSeqHiAndReserved() :returns: The high field of the clock sequence multiplexed with the variant. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getClockSeqLow() :returns: The low field of the clock sequence. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getNode() :returns: The node field. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getTimeHiAndVersion() :returns: The high field of the timestamp multiplexed with the version. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getTimeLow() :returns: The low field of the timestamp. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getTimeMid() :returns: The middle field of the timestamp. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getTimestamp() :returns: The full 60-bit timestamp, without the version. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getVariant() Returns the variant, which, for `RFC 9562`_ (formerly `RFC 4122`_) variant UUIDs, should always be the value ``2``. :returns: The UUID variant. :returntype: ``int`` .. php:method:: getVersion() :returns: The UUID version. :returntype: ``int`` .. php:method:: isNil() A *nil* UUID is a special type of UUID with all 128 bits set to zero. Its string standard representation is always ``00000000-0000-0000-0000-000000000000``. :returns: True if this UUID represents a nil UUID. :returntype: ``bool`` .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/reference/rfc4122-uuidinterface.rst ================================================ .. _reference.rfc4122.uuidinterface: ====================== Rfc4122\\UuidInterface ====================== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:interface:: UuidInterface Implements :php:interface:`Ramsey\\Uuid\\UuidInterface`. Rfc4122\\UuidInterface represents an `RFC 9562`_ (formerly `RFC 4122`_) UUID. In addition to the methods defined on the interface, this interface additionally defines the following methods. .. php:method:: getFields() :returns: The fields that comprise this UUID. :returntype: Ramsey\\Uuid\\Rfc4122\\FieldsInterface .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/reference/rfc4122-uuidv1.rst ================================================ .. _reference.rfc4122.uuidv1: =============== Rfc4122\\UuidV1 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV1 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV1 represents a :ref:`version 1, Gregorian time UUID `. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getDateTime() :returns: A date object representing the timestamp associated with the UUID. :returntype: ``\DateTimeInterface`` ================================================ FILE: docs/reference/rfc4122-uuidv2.rst ================================================ .. _reference.rfc4122.uuidv2: =============== Rfc4122\\UuidV2 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV2 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV2 represents a :ref:`version 2, DCE Security UUID `. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getDateTime() Returns a `DateTimeInterface `_ instance representing the timestamp associated with the UUID .. caution:: It is important to note that version 2 UUIDs suffer from some loss of timestamp precision. See :ref:`rfc4122.version2.timestamp-problems` to learn more. :returns: A date object representing the timestamp associated with the UUID :returntype: ``\DateTimeInterface`` .. php:method:: getLocalDomain() :returns: The local domain identifier for this UUID, which is one of :php:const:`Ramsey\\Uuid\\Uuid::DCE_DOMAIN_PERSON`, :php:const:`Ramsey\\Uuid\\Uuid::DCE_DOMAIN_GROUP`, or :php:const:`Ramsey\\Uuid\\Uuid::DCE_DOMAIN_ORG` :returntype: ``int`` .. php:method:: getLocalDomainName() :returns: A string name associated with the local domain identifier (one of "person," "group," or "org") :returntype: ``string`` .. php:method:: getLocalIdentifier() :returns: The local identifier used when creating this UUID :returntype: Ramsey\\Uuid\\Type\\Integer ================================================ FILE: docs/reference/rfc4122-uuidv3.rst ================================================ .. _reference.rfc4122.uuidv3: =============== Rfc4122\\UuidV3 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV3 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV3 represents a :ref:`version 3, name-based (MD5 hashed) UUID `. ================================================ FILE: docs/reference/rfc4122-uuidv4.rst ================================================ .. _reference.rfc4122.uuidv4: =============== Rfc4122\\UuidV4 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV4 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV4 represents a :ref:`version 4, random UUID `. ================================================ FILE: docs/reference/rfc4122-uuidv5.rst ================================================ .. _reference.rfc4122.uuidv5: =============== Rfc4122\\UuidV5 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV5 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV5 represents a :ref:`version 5, name-based (SHA-1 hashed) UUID `. ================================================ FILE: docs/reference/rfc4122-uuidv6.rst ================================================ .. _reference.rfc4122.uuidv6: =============== Rfc4122\\UuidV6 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV6 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV6 represents a :ref:`version 6, reordered Gregorian time UUID `. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getDateTime() :returns: A date object representing the timestamp associated with the UUID :returntype: ``\DateTimeInterface`` .. php:method:: toUuidV1() :returns: A version 1 UUID, converted from this version 6 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 .. php:staticmethod:: fromUuidV1() :param Ramsey\\Uuid\\Rfc4122\\UuidV1 $uuidV1: A version 1 UUID :returns: A version 6 UUID, converted from the given version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV6 ================================================ FILE: docs/reference/rfc4122-uuidv7.rst ================================================ .. _reference.rfc4122.uuidv7: =============== Rfc4122\\UuidV7 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV7 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV7 represents a :ref:`version 7, Unix Epoch time UUID `. In addition to providing the methods defined on the interface, this class additionally provides the following methods. .. php:method:: getDateTime() :returns: A date object representing the timestamp associated with the UUID. :returntype: ``\DateTimeInterface`` ================================================ FILE: docs/reference/rfc4122-uuidv8.rst ================================================ .. _reference.rfc4122.uuidv8: =============== Rfc4122\\UuidV8 =============== .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: UuidV8 Implements :php:interface:`Ramsey\\Uuid\\Rfc4122\\UuidInterface`. UuidV8 represents a :ref:`version 8, implementation-specific, custom format UUID `. ================================================ FILE: docs/reference/types.rst ================================================ .. _reference.types: ===== Types ===== .. php:namespace:: Ramsey\Uuid\Type .. php:class:: TypeInterface Implements `JsonSerializable `_ and `Serializable `_. TypeInterface ensures consistency in typed values returned by ramsey/uuid. .. php:method:: toString() :returntype: ``string`` .. php:method:: __toString() :returntype: ``string`` .. php:class:: NumberInterface Implements :php:interface:`Ramsey\\Uuid\\Type\\TypeInterface`. NumberInterface ensures consistency in numeric values returned by ramsey/uuid. .. php:method:: isNegative() :returns: True if this number is less than zero, false otherwise. :returntype: ``bool`` .. php:class:: Decimal Implements :php:interface:`Ramsey\\Uuid\\Type\\NumberInterface`. A value object representing a decimal, for type-safety purposes, to ensure that decimals returned from ramsey/uuid methods as strings are truly decimals and not some other kind of string. To support values as true decimals and not as floats or doubles, we store the decimals as strings. .. php:class:: Hexadecimal Implements :php:interface:`Ramsey\\Uuid\\Type\\TypeInterface`. A value object representing a hexadecimal number, for type-safety purposes, to ensure that hexadecimal numbers returned from ramsey/uuid methods as strings are truly hexadecimal and not some other kind of string. .. php:class:: Integer Implements :php:interface:`Ramsey\\Uuid\\Type\\NumberInterface`. A value object representing an integer, for type-safety purposes, to ensure that integers returned from ramsey/uuid methods as strings are truly integers and not some other kind of string. To support large integers beyond ``PHP_INT_MAX`` and ``PHP_INT_MIN`` on both 64-bit and 32-bit systems, we store the integers as strings. .. php:class:: Time Implements :php:interface:`Ramsey\\Uuid\\Type\\TypeInterface`. A value object representing a timestamp, for type-safety purposes, to ensure that timestamps used by ramsey/uuid are truly timestamp integers and not some other kind of string or integer. .. php:method:: getSeconds() :returntype: :php:class:`Ramsey\\Uuid\\Type\\Integer` .. php:method:: getMicroseconds() :returntype: :php:class:`Ramsey\\Uuid\\Type\\Integer` ================================================ FILE: docs/reference/uuid.rst ================================================ .. _reference.uuid: ==== Uuid ==== Ramsey\\Uuid\\Uuid provides static methods for the most common functionality for generating and working with UUIDs. It also provides constants used throughout the ramsey/uuid library. .. php:namespace:: Ramsey\Uuid .. php:class:: Uuid .. php:const:: UUID_TYPE_TIME :ref:`rfc4122.version1` UUID. .. php:const:: UUID_TYPE_DCE_SECURITY :ref:`rfc4122.version2` UUID. .. php:const:: UUID_TYPE_HASH_MD5 :ref:`rfc4122.version3` UUID. .. php:const:: UUID_TYPE_RANDOM :ref:`rfc4122.version4` UUID. .. php:const:: UUID_TYPE_HASH_SHA1 :ref:`rfc4122.version5` UUID. .. php:const:: UUID_TYPE_REORDERED_TIME :ref:`rfc4122.version6` UUID. .. php:const:: UUID_TYPE_PEABODY *Deprecated.* Use :php:const:`Uuid::UUID_TYPE_REORDERED_TIME` instead. .. php:const:: UUID_TYPE_UNIX_TIME :ref:`rfc4122.version7` UUID. .. php:const:: UUID_TYPE_CUSTOM :ref:`rfc4122.version8` UUID. .. php:const:: NAMESPACE_DNS The name string is a fully-qualified domain name. .. php:const:: NAMESPACE_URL The name string is a URL. .. php:const:: NAMESPACE_OID The name string is an `ISO object identifier (OID)`_. .. php:const:: NAMESPACE_X500 The name string is an `X.500`_ `DN`_ in `DER`_ or a text output format. .. php:const:: NIL The nil UUID is a special form of UUID that is specified to have all 128 bits set to zero. .. php:const:: DCE_DOMAIN_PERSON DCE Security principal (person) domain. .. php:const:: DCE_DOMAIN_GROUP DCE Security group domain. .. php:const:: DCE_DOMAIN_ORG DCE Security organization domain. .. php:const:: RESERVED_NCS Variant identifier: reserved, NCS backward compatibility. .. php:const:: RFC_4122 An alias for :php:const:`Uuid::RFC_9562`. .. php:const:: RFC_9562 Variant identifier: the UUID layout specified in `RFC 9562`_ (formerly `RFC 4122`_). .. php:const:: RESERVED_MICROSOFT Variant identifier: reserved, Microsoft Corporation backward compatibility. .. php:const:: RESERVED_FUTURE Variant identifier: reserved for future definition. .. php:staticmethod:: uuid1([$node[, $clockSeq]]) Generates a version 1, Gregorian time UUID. See :ref:`rfc4122.version1`. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 .. php:staticmethod:: uuid2($localDomain[, $localIdentifier[, $node[, $clockSeq]]]) Generates a version 2, DCE Security UUID. See :ref:`rfc4122.version2`. :param int $localDomain: The local domain to use (one of :php:const:`Uuid::DCE_DOMAIN_PERSON`, :php:const:`Uuid::DCE_DOMAIN_GROUP`, or :php:const:`Uuid::DCE_DOMAIN_ORG`) :param Ramsey\\Uuid\\Type\\Integer|null $localIdentifier: A local identifier for the domain (defaults to system UID or GID for *person* or *group*) :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 2 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV2 .. php:staticmethod:: uuid3($ns, $name) Generates a version 3, name-based (MD5) UUID. See :ref:`rfc4122.version3`. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A version 3 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV3 .. php:staticmethod:: uuid4() Generates a version 4, random UUID. See :ref:`rfc4122.version4`. :returns: A version 4 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV4 .. php:staticmethod:: uuid5($ns, $name) Generates a version 5, name-based (SHA-1) UUID. See :ref:`rfc4122.version5`. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A version 5 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV5 .. php:staticmethod:: uuid6([$node[, $clockSeq]]) Generates a version 6, reordered Gregorian time UUID. See :ref:`rfc4122.version6`. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 6 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV6 .. php:staticmethod:: uuid7([$dateTime]) Generates a version 7, Unix Epoch time UUID. See :ref:`rfc4122.version7`. :param DateTimeInterface|null $dateTime: The date from which to create the UUID instance :returns: A version 7 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV7 .. php:staticmethod:: uuid8($bytes) Generates a version 8, implementation-specific, custom format UUID. See :ref:`rfc4122.version8`. :param string $bytes: A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 and 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs. :returns: A version 8 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV8 .. php:staticmethod:: fromString($uuid) Creates an instance of UuidInterface from the string standard representation. :param string $uuid: The string standard representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:staticmethod:: fromBytes($bytes) Creates an instance of UuidInterface from a 16-byte string. :param string $bytes: A 16-byte binary string representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:staticmethod:: fromInteger($integer) Creates an instance of UuidInterface from a 128-bit string integer. :param string $integer: A 128-bit string integer representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:staticmethod:: fromDateTime($dateTime[, $node[, $clockSeq]]) Creates a version 1 UUID instance from a `DateTimeInterface `_ instance. :param DateTimeInterface $dateTime: The date from which to create the UUID instance :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 .. php:staticmethod:: isValid($uuid) Validates the string standard representation of a UUID. :param string $uuid: The string standard representation of a UUID :returntype: ``bool`` .. php:staticmethod:: setFactory($factory) Sets the factory used to create UUIDs. :param Ramsey\\Uuid\\UuidFactoryInterface $factory: A UUID factory to use for all UUID generation :returntype: void .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _ISO object identifier (OID): http://www.oid-info.com .. _X.500: https://en.wikipedia.org/wiki/X.500 .. _DN: https://en.wikipedia.org/wiki/Distinguished_Name .. _DER: https://www.itu.int/rec/T-REC-X.690/ ================================================ FILE: docs/reference/uuidfactoryinterface.rst ================================================ .. _reference.uuidfactoryinterface: ==================== UuidFactoryInterface ==================== .. php:namespace:: Ramsey\Uuid .. php:interface:: UuidFactoryInterface Represents a UUID factory. .. php:method:: getValidator() :returntype: Ramsey\\Uuid\\Validator\\ValidatorInterface .. php:method:: uuid1([$node[, $clockSeq]]) Generates a version 1, Gregorian time UUID. See :ref:`rfc4122.version1`. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 .. php:method:: uuid2($localDomain[, $localIdentifier[, $node[, $clockSeq]]]) Generates a version 2, DCE Security UUID. See :ref:`rfc4122.version2`. :param int $localDomain: The local domain to use (one of :php:const:`Uuid::DCE_DOMAIN_PERSON`, :php:const:`Uuid::DCE_DOMAIN_GROUP`, or :php:const:`Uuid::DCE_DOMAIN_ORG`) :param Ramsey\\Uuid\\Type\\Integer|null $localIdentifier: A local identifier for the domain (defaults to system UID or GID for *person* or *group*) :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 2 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV2 .. php:method:: uuid3($ns, $name) Generates a version 3, name-based (MD5) UUID. See :ref:`rfc4122.version3`. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A version 3 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV3 .. php:method:: uuid4() Generates a version 4, random UUID. See :ref:`rfc4122.version4`. :returns: A version 4 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV4 .. php:method:: uuid5($ns, $name) Generates a version 5, name-based (SHA-1) UUID. See :ref:`rfc4122.version5`. :param Ramsey\\Uuid\\UuidInterface|string $ns: The namespace for this identifier :param string $name: The name from which to generate an identifier :returns: A version 5 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV5 .. php:method:: uuid6([$node[, $clockSeq]]) Generates a version 6, reordered Gregorian time UUID. See :ref:`rfc4122.version6`. :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 6 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV6 .. php:method:: fromString($uuid) Creates an instance of UuidInterface from the string standard representation. :param string $uuid: The string standard representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:method:: fromBytes($bytes) Creates an instance of UuidInterface from a 16-byte string. :param string $bytes: A 16-byte binary string representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:method:: fromInteger($integer) Creates an instance of UuidInterface from a 128-bit string integer. :param string $integer: A 128-bit string integer representation of a UUID :returntype: Ramsey\\Uuid\\UuidInterface .. php:method:: fromDateTime($dateTime[, $node[, $clockSeq]]) Creates a version 1 UUID instance from a `DateTimeInterface `_ instance. :param DateTimeInterface $dateTime: The date from which to create the UUID instance :param Ramsey\\Uuid\\Type\\Hexadecimal|null $node: An optional hexadecimal node to use :param int|null $clockSeq: An optional clock sequence to use :returns: A version 1 UUID :returntype: Ramsey\\Uuid\\Rfc4122\\UuidV1 ================================================ FILE: docs/reference/uuidinterface.rst ================================================ .. _reference.uuidinterface: ============= UuidInterface ============= .. php:namespace:: Ramsey\Uuid .. php:interface:: UuidInterface Represents a UUID. .. php:method:: compareTo($other) :param Ramsey\\Uuid\\UuidInterface $other: The UUID to compare :returns: Returns ``-1``, ``0``, or ``1`` if the UUID is less than, equal to, or greater than the other UUID. :returntype: ``int`` .. php:method:: equals($other) :param object|null $other: An object to test for equality with this UUID. :returns: Returns true if the UUID is equal to the provided object. :returntype: ``bool`` .. php:method:: getBytes() :returns: A binary string representation of the UUID. :returntype: ``string`` .. php:method:: getFields() :returns: The fields that comprise this UUID. :returntype: Ramsey\\Uuid\\Fields\\FieldsInterface .. php:method:: getHex() :returns: The hexadecimal representation of the UUID. :returntype: Ramsey\\Uuid\\Type\\Hexadecimal .. php:method:: getInteger() :returns: The integer representation of the UUID. :returntype: Ramsey\\Uuid\\Type\\Integer .. php:method:: getUrn() :returns: The string standard representation of the UUID as a `URN`_. :returntype: ``string`` .. php:method:: toString() :returns: The string standard representation of the UUID. :returntype: ``string`` .. php:method:: __toString() :returns: The string standard representation of the UUID. :returntype: ``string`` .. _URN: https://www.rfc-editor.org/rfc/rfc8141 ================================================ FILE: docs/reference/validators.rst ================================================ .. _reference.validators: ========== Validators ========== .. php:namespace:: Ramsey\Uuid\Validator .. php:interface:: ValidatorInterface .. php:method:: getPattern() :returns: The regular expression pattern used by this validator :returntype: ``string`` .. php:method:: validate($uuid) :param string $uuid: The string to validate as a UUID :returns: True if the provided string represents a UUID, false otherwise :returntype: ``bool`` .. php:class:: GenericValidator Implements :php:interface:`Ramsey\\Uuid\\Validator\\ValidatorInterface`. GenericValidator validates strings as UUIDs of any variant. .. php:namespace:: Ramsey\Uuid\Rfc4122 .. php:class:: Validator Implements :php:interface:`Ramsey\\Uuid\\Validator\\ValidatorInterface`. Rfc4122\\Validator validates strings as UUIDs of the `RFC 9562`_ (formerly `RFC 4122`_) variant. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/reference.rst ================================================ .. _reference: ========= Reference ========= .. toctree:: :titlesonly: reference/uuid reference/uuidinterface reference/fields-fieldsinterface reference/rfc4122-uuidinterface reference/rfc4122-fieldsinterface reference/rfc4122-uuidv1 reference/rfc4122-uuidv2 reference/rfc4122-uuidv3 reference/rfc4122-uuidv4 reference/rfc4122-uuidv5 reference/rfc4122-uuidv6 reference/rfc4122-uuidv7 reference/rfc4122-uuidv8 reference/guid-fields reference/guid-guid reference/nonstandard-fields reference/nonstandard-uuid reference/nonstandard-uuidv6 reference/uuidfactoryinterface reference/types reference/exceptions reference/helper reference/name-based-namespaces reference/calculators reference/validators ================================================ FILE: docs/requirements.txt ================================================ Sphinx==7.3.7 sphinx-rtd-theme==2.0.0 sphinxcontrib-phpdomain==0.11.1 ================================================ FILE: docs/rfc4122/version1.rst ================================================ .. _rfc4122.version1: ========================= Version 1: Gregorian Time ========================= .. attention:: If you need a time-based UUID, and you don't need the other features included in version 1 UUIDs, we recommend using :ref:`version 7 UUIDs `. A version 1 UUID uses the current time, along with the MAC address (or *node*) for a network interface on the local machine. This serves two purposes: 1. You can know *when* the identifier was created. 2. You can know *where* the identifier was created. In a distributed system, these two pieces of information can be valuable. Not only is there no need for a central authority to generate identifiers, but you can determine what nodes in your infrastructure created the UUIDs and at what time. .. tip:: It is also possible to use a **randomly-generated node**, rather than a hardware address. This is useful for when you don't want to leak machine information, while still using a UUID based on time. Keep reading to find out how. By default, ramsey/uuid will attempt to look up a MAC address for the machine it is running on, using this value as the node. If it cannot find a MAC address, it will generate a random node. .. code-block:: php :caption: Generate a version 1, Gregorian time UUID :name: rfc4122.version1.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid1(); printf( "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\n", $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getDateTime()->format('r'), $uuid->getFields()->getNode()->toString() ); This will generate a version 1 UUID and print out its string representation, the time the UUID was created, and the node used to create the UUID. It will look something like this: .. code-block:: text UUID: e22e1622-5c14-11ea-b2f3-0242ac130003 Version: 1 Date: Sun, 01 Mar 2020 23:32:15 +0000 Node: 0242ac130003 You may provide custom values for version 1 UUIDs, including node and clock sequence. .. code-block:: php :caption: Provide custom node and clock sequence to create a version 1, Gregorian time UUID :name: rfc4122.version1.custom-example use Ramsey\Uuid\Provider\Node\StaticNodeProvider; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Uuid; $nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212')); $clockSequence = 16383; $uuid = Uuid::uuid1($nodeProvider->getNode(), $clockSequence); .. tip:: Version 1 UUIDs generated in ramsey/uuid are instances of UuidV1. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV1` API documentation to learn more about what you can do with a UuidV1 instance. .. _rfc4122.version1.custom: Providing a Custom Node ####################### You may override the default behavior by passing your own node value when generating a version 1 UUID. In the :ref:`example above `, we saw how to pass a custom node and clock sequence. An interesting thing to note about the example is its use of StaticNodeProvider. Why didn't we pass in a :php:class:`Hexadecimal ` value, instead? According to `RFC 9562, section 6.10`_, node values that do not identify the host --- in other words, our own custom node value --- should set the unicast/multicast bit to one (1). This bit will never be set in IEEE 802 addresses obtained from network cards, so it helps to distinguish it from a hardware MAC address. The StaticNodeProvider sets this bit for you. This is why we used it rather than providing a :php:class:`Hexadecimal ` value directly. Recall from the example that the node value we set was ``121212121212``, but if you take a look at this value with ``$uuid->getFields()->getNode()->toString()``, it becomes: .. code-block:: text 131212121212 That's a result of this bit being set by the StaticNodeProvider. .. _rfc4122.version1.random: Generating a Random Node ######################## Instead of providing a custom node, you may also generate a random node each time you generate a version 1 UUID. The RandomNodeProvider may be used to generate a random node value, and like the StaticNodeProvider, it also sets the unicast/multicast bit for you. .. code-block:: php :caption: Provide a random node value to create a version 1, Gregorian time UUID :name: rfc4122.version1.random-example use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Uuid; $nodeProvider = new RandomNodeProvider(); $uuid = Uuid::uuid1($nodeProvider->getNode()); .. _rfc4122.version1.clock: What's a Clock Sequence? ######################## The clock sequence part of a version 1 UUID helps prevent collisions. Since this UUID is based on a timestamp and a machine node value, it is possible for collisions to occur for multiple UUIDs generated within the same microsecond on the same machine. The clock sequence is the solution to this problem. The clock sequence is a 14-bit number --- this supports values from 0 to 16,383 --- which means it should be possible to generate up to 16,384 UUIDs per microsecond with the same node value, before hitting a collision. .. caution:: ramsey/uuid does not use *stable storage* for clock sequence values. Instead, all clock sequences are randomly-generated. If you are generating a lot of version 1 UUIDs every microsecond, it is possible to hit collisions because of the random values. If this is the case, you should use your own mechanism for generating clock sequence values, to ensure against randomly-generated duplicates. See `section 6.3 of RFC 9562`_, for more information. .. _rfc4122.version1.privacy: Privacy Concerns ################ As discussed earlier in this section, version 1 UUIDs use a MAC address from a local hardware network interface. This means it is possible to uniquely identify the machine on which a version 1 UUID was created. If the value provided by the timestamp of a version 1 UUID is important to you, but you do not wish to expose the interface address of any of your local machines, see :ref:`rfc4122.version1.random` or :ref:`rfc4122.version1.custom`. If you do not need an identifier with a timestamp value embedded in it, see :ref:`rfc4122.version4` to learn about random UUIDs. .. _RFC 9562, section 6.10: https://www.rfc-editor.org/rfc/rfc9562#section-6.10 .. _section 6.3 of RFC 9562: https://www.rfc-editor.org/rfc/rfc9562#section-6.3 ================================================ FILE: docs/rfc4122/version2.rst ================================================ .. _rfc4122.version2: ======================= Version 2: DCE Security ======================= .. tip:: DCE Security UUIDs are so-called because they were defined as part of the "Authentication and Security Services" for the `Distributed Computing Environment`_ (DCE) in the early 1990s. Version 2 UUIDs are not widely used. See :ref:`rfc4122.version2.problems` before deciding whether to use them. Like a :ref:`version 1 UUID `, a version 2 UUID uses the current time, along with the MAC address (or *node*) for a network interface on the local machine. Additionally, a version 2 UUID replaces the low part of the time field with a local identifier such as the user ID or group ID of the local account that created the UUID. This serves three purposes: 1. You can know *when* the identifier was created (see :ref:`rfc4122.version2.timestamp-problems`). 2. You can know *where* the identifier was created. 3. You can know *who* created the identifier. In a distributed system, these three pieces of information can be valuable. Not only is there no need for a central authority to generate identifiers, but you can determine what nodes in your infrastructure created the UUIDs, at what time they were created, and the account on the machine that created them. By default, ramsey/uuid will attempt to look up a MAC address for the machine it is running on, using this value as the node. If it cannot find a MAC address, it will generate a random node. .. code-block:: php :caption: Use a domain to generate a version 2, DCE Security UUID :name: rfc4122.version2.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid2(Uuid::DCE_DOMAIN_PERSON); printf( "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\nDomain: %s\nID: %s\n", $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getDateTime()->format('r'), $uuid->getFields()->getNode()->toString(), $uuid->getLocalDomainName(), $uuid->getLocalIdentifier()->toString() ); This will generate a version 2 UUID and print out its string representation, the time the UUID was created, and the node used to create it, as well as the name of the local domain specified and the local domain identifier (in this case, a `POSIX`_ UID, automatically obtained from the local machine). It will look something like this: .. code-block:: text UUID: 000001f5-5e9a-21ea-9e00-0242ac130003 Version: 2 Date: Thu, 05 Mar 2020 04:30:10 +0000 Node: 0242ac130003 Domain: person ID: 501 Just as with version 1 UUIDs, you may provide custom values for version 2 UUIDs, including local identifier, node, and clock sequence. .. code-block:: php :caption: Provide custom identifier, node, and clock sequence to create a version 2, DCE Security UUID :name: rfc4122.version2.custom-example use Ramsey\Uuid\Provider\Node\StaticNodeProvider; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer; use Ramsey\Uuid\Uuid; $localId = new Integer(1001); $nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212')); $clockSequence = 63; $uuid = Uuid::uuid2( Uuid::DCE_DOMAIN_ORG, $localId, $nodeProvider->getNode(), $clockSequence ); .. tip:: Version 2 UUIDs generated in ramsey/uuid are instances of UuidV2. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV2` API documentation to learn more about what you can do with a UuidV2 instance. .. _rfc4122.version2.domains: Domains ####### The *domain* value tells what the local identifier represents. If using the *person* or *group* domains, ramsey/uuid will attempt to look up these values from the local machine. On `POSIX`_ systems, it will use ``id -u`` and ``id -g``, respectively. On Windows, it will use ``whoami`` and ``wmic``. The *org* domain is site-defined. Its intent is to identify the organization that generated the UUID, but since this can have different meanings for different companies and projects, you get to define its value. .. list-table:: DCE Security Domains :widths: 30 70 :align: center :header-rows: 1 :name: rfc4122.version2.table-domains * - Constant - Description * - :php:const:`Uuid::DCE_DOMAIN_PERSON ` - The local identifier refers to a *person* (e.g., UID). * - :php:const:`Uuid::DCE_DOMAIN_GROUP ` - The local identifier refers to a *group* (e.g., GID). * - :php:const:`Uuid::DCE_DOMAIN_ORG ` - The local identifier refers to an *organization* (this is site-defined). .. note:: According to section 5.2.1.1 of `DCE 1.1: Authentication and Security Services `_, the domain "can potentially hold values outside the range [0, 2\ :sup:`8` -- 1]; however, the only values currently registered are in the range [0, 2]." As a result, ramsey/uuid supports only the *person*, *group*, and *org* domains. .. _rfc4122.version2.nodes: Custom and Random Nodes ####################### In the :ref:`example above `, we provided a custom node when generating a version 2 UUID. You may also generate random node values. To learn more, see the :ref:`rfc4122.version1.custom` and :ref:`rfc4122.version1.random` sections under :ref:`rfc4122.version1`. .. _rfc4122.version2.clock: Clock Sequence ############## In a version 2 UUID, the clock sequence serves the same purpose as in a version 1 UUID. See :ref:`rfc4122.version1.clock` to learn more. .. warning:: The clock sequence in a version 2 UUID is a 6-bit number. It supports values from 0 to 63. This is different from the 14-bit number used by version 1 UUIDs. See :ref:`rfc4122.version2.uniqueness-problems` to understand how this affects version 2 UUIDs. .. _rfc4122.version2.problems: Problems With Version 2 UUIDs ############################# Version 2 UUIDs can be useful for the data they contain. However, there are trade-offs in choosing to use them. .. _rfc4122.version2.privacy-problems: Privacy ------- Unless using a randomly-generated node, version 2 UUIDs use the MAC address for a local hardware interface as the node value. In addition, they use a local identifier --- usually an account or group ID. Some may consider the use of these identifying features a breach of privacy. The use of a timestamp further complicates the issue, since these UUIDs could be used to identify a user account on a specific machine at a specific time. If you don't need an identifier with a local identifier and timestamp value embedded in it, see :ref:`rfc4122.version4` to learn about random UUIDs. .. _rfc4122.version2.uniqueness-problems: Limited Uniqueness ------------------ With the inclusion of the local identifier and domain comes a serious limitation in the number of unique UUIDs that may be created. This is because: 1. The local identifier replaces the lower 32 bits of the timestamp. 2. The domain replaces the lower 8 bits of the clock sequence. As a result, the timestamp advances --- the clock *ticks* --- only once every 429.49 seconds (about 7 minutes). This means the clock sequence is important to ensure uniqueness, but since the clock sequence is only 6 bits, compared to 14 bits for version 1 UUIDs, **only 64 unique UUIDs per combination of node, domain, and identifier may be generated per 7-minute tick of the clock**. You can overcome this lack of uniqueness by using a :ref:`random node `, which provides 47 bits of randomness to the UUID --- after setting the unicast/multicast bit (see discussion on :ref:`rfc4122.version1.custom`) --- increasing the number of UUIDs per 7-minute clock tick to 2\ :sup:`53` (or 9,007,199,254,740,992), at the expense of remaining locally unique. .. note:: This lack of uniqueness did not present a problem for DCE, since: [T]he security architecture of DCE depends upon the uniqueness of security-version UUIDs *only within the context of a cell*; that is, only within the context of the local [Registration Service's] (persistent) datastore, and that degree of uniqueness can be guaranteed by the RS itself (namely, the RS maintains state in its datastore, in the sense that it can always check that every UUID it maintains is different from all other UUIDs it maintains). In other words, while security-version UUIDs are (like all UUIDs) specified to be "globally unique in space and time", security is not compromised if they are merely "locally unique per cell". -- `DCE 1.1: Authentication and Security Services, section 5.2.1.1 `_ .. _rfc4122.version2.timestamp-problems: Lossy Timestamps ---------------- Version 2 UUIDs are generated in the same way as version 1 UUIDs, but the low part of the timestamp (the ``time_low`` field) is replaced by a 32-bit integer that represents a local identifier. Because of this, not only do version 2 UUIDs have :ref:`limited uniqueness `, but they also lack time precision. When reconstructing the timestamp to return a `DateTimeInterface`_ instance from :php:meth:`UuidV2::getDateTime() `, we replace the 32 lower bits of the timestamp with zeros, since the local identifier should not be part of the timestamp. This results in a loss of precision, causing the timestamp to be off by a range of 0 to 429.4967295 seconds (or 7 minutes, 9 seconds, and 496,730 microseconds). When using version 2 UUIDs, treat the timestamp as an approximation. At worst, it could be off by about 7 minutes. .. hint:: If the value 429.4967295 looks familiar, it's because it directly corresponds to 2\ :sup:`32` -- 1, or ``0xffffffff``. The local identifier is 32-bits, and we have set each of these bits to 0, so the maximum range of timestamp drift is ``0x00000000`` to ``0xffffffff`` (counted in 100-nanosecond intervals). .. _Distributed Computing Environment: https://en.wikipedia.org/wiki/Distributed_Computing_Environment .. _POSIX: https://en.wikipedia.org/wiki/POSIX .. _DateTimeInterface: https://www.php.net/datetimeinterface ================================================ FILE: docs/rfc4122/version3.rst ================================================ .. _rfc4122.version3: =========================== Version 3: Name-based (MD5) =========================== .. attention:: `RFC 9562`_ states, "Where possible, UUIDv5 SHOULD be used in lieu of UUIDv3." Unless you have a specific use-case for version 3 UUIDs, use :ref:`version 5 UUIDs `. .. note:: To learn about name-based UUIDs, read the section :ref:`rfc4122.version5`. Version 3 UUIDs behave exactly the same as :ref:`version 5 UUIDs `. The only difference is the hashing algorithm used to generate the UUID. Version 3 UUIDs use `MD5`_ as the hashing algorithm for combining the namespace and the name. Due to the use of a different hashing algorithm, version 3 UUIDs generated with any given namespace and name will differ from version 5 UUIDs generated using the same namespace and name. As an example, let's take a look at generating a version 3 UUID using the same namespace and name used in ":ref:`rfc4122.version5.url-example`." .. code-block:: php :caption: Generate a version 3, name-based UUID for a URL :name: rfc4122.version3.url-example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'https://www.php.net'); Even though the namespace and name are the same, the version 3 UUID generated will always be ``3f703955-aaba-3e70-a3cb-baff6aa3b28f``. Likewise, we can use the custom namespace we created in ":ref:`rfc4122.version5.create-namespace`" to generate a version 3 UUID, but the result will be different from the version 5 UUID with the same custom namespace and name. .. code-block:: php :caption: Use a custom namespace to create version 3, name-based UUIDs :name: rfc4122.version3.custom-example use Ramsey\Uuid\Uuid; const WIDGET_NAMESPACE = '4bdbe8ec-5cb5-11ea-bc55-0242ac130003'; $uuid = Uuid::uuid3(WIDGET_NAMESPACE, 'widget/1234567890'); With this custom namespace, the version 3 UUID for the name "widget/1234567890" will always be ``53564aa3-4154-3ca5-ac90-dba59dc7d3cb``. .. tip:: Version 3 UUIDs generated in ramsey/uuid are instances of UuidV3. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV3` API documentation to learn more about what you can do with a UuidV3 instance. .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _MD5: https://en.wikipedia.org/wiki/MD5 ================================================ FILE: docs/rfc4122/version4.rst ================================================ .. _rfc4122.version4: ================= Version 4: Random ================= Version 4 UUIDs are perhaps the most popular form of UUID. They are randomly-generated and do not contain any information about the time they are created or the machine that generated them. If you don't care about this information, then a version 4 UUID might be perfect for your needs. .. code-block:: php :caption: Generate a version 4, random UUID :name: rfc4122.version4.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid4(); printf( "UUID: %s\nVersion: %d\n", $uuid->toString(), $uuid->getFields()->getVersion() ); This will generate a version 4 UUID and print out its string representation. It will look something like this: .. code-block:: text UUID: 1ee9aa1b-6510-4105-92b9-7171bb2f3089 Version: 4 .. tip:: Version 4 UUIDs generated in ramsey/uuid are instances of UuidV4. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV4` API documentation to learn more about what you can do with a UuidV4 instance. ================================================ FILE: docs/rfc4122/version5.rst ================================================ .. _rfc4122.version5: ============================= Version 5: Name-based (SHA-1) ============================= .. danger:: Since :ref:`version 3 ` and version 5 UUIDs essentially use a *salt* (the namespace) to hash data, it may be tempting to use them to hash passwords. **DO NOT do this under any circumstances!** You should not store any sensitive information in a version 3 or version 5 UUID, since `MD5 and SHA-1 are insecure and have known attacks demonstrated against them `_. *Use these types of UUIDs as identifiers only.* The first thing that comes to mind with most people think of a UUID is a *random* identifier, but name-based UUIDs aren't random at all. In fact, they're deterministic. For any given identical namespace and name, you will always generate the same UUID. Name-based UUIDs are useful when you need an identifier that's based on something's *name* --- think *identity* --- and will always be the same no matter where or when it is created. For example, let's say I want to create an identifier for a URL. I could use a :ref:`version 1 ` or :ref:`version 4 ` UUID to create an identifier for the URL, but what if I'm working with a distributed system, and I want to ensure that every client in this system can always generate the same identifier for any given URL? This is where a name-based UUID comes in handy. Name-based UUIDs combine a namespace with a name. This way, the UUIDs are unique to the namespace they're created in. `RFC 9562`_ defines some :ref:`predefined namespaces `, one of which is for URLs. .. note:: Version 5 UUIDs use `SHA-1`_ as the hashing algorithm for combining the namespace and the name. .. code-block:: php :caption: Generate a version 5, name-based UUID for a URL :name: rfc4122.version5.url-example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'https://www.php.net'); The UUID generated will always be the same, as long as the namespace and name are the same. The version 5 UUID for "https://www.php.net" in the URL namespace will always be ``a8f6ae40-d8a7-58f0-be05-a22f94eca9ec``. See for yourself. Run the code above, and you'll see it always generates the same UUID. .. tip:: Version 5 UUIDs generated in ramsey/uuid are instances of UuidV5. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV5` API documentation to learn more about what you can do with a UuidV5 instance. .. _rfc4122.version5.custom-namespaces: Custom Namespaces ################# If you're working with name-based UUIDs for names that don't fit into any of the :ref:`predefined namespaces `, or you don't want to use any of the predefined namespaces, you can create your own namespace. The best way to do this is to generate a :ref:`version 1 ` or :ref:`version 4 ` UUID and save this UUID as your namespace. .. code-block:: php :caption: Generate a custom namespace UUID :name: rfc4122.version5.create-namespace use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid1(); printf("My namespace UUID is %s\n", $uuid->toString()); This will generate a version 1, Gregorian time UUID, which we'll store to a constant so we can reuse it as our own custom namespace. .. code-block:: php :caption: Use a custom namespace to create version 5, name-based UUIDs :name: rfc4122.version5.custom-example use Ramsey\Uuid\Uuid; const WIDGET_NAMESPACE = '4bdbe8ec-5cb5-11ea-bc55-0242ac130003'; $uuid = Uuid::uuid5(WIDGET_NAMESPACE, 'widget/1234567890'); With this custom namespace, the version 5 UUID for the name "widget/1234567890" will always be ``a35477ae-bfb1-5f2e-b5a4-4711594d855f``. We can publish this namespace, allowing others to use it to generate identifiers for widgets. When two or more systems try to reference the same widget, they'll end up generating the same identifier for it, which is exactly what we want. .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 .. _SHA-1: https://en.wikipedia.org/wiki/SHA-1 ================================================ FILE: docs/rfc4122/version6.rst ================================================ .. _rfc4122.version6: =================================== Version 6: Reordered Gregorian Time =================================== .. attention:: If you need a time-based UUID, and you don't need the other features included in version 6 UUIDs, we recommend using :ref:`version 7 UUIDs `. Version 6 UUIDs solve `two problems that have long existed`_ with the use of :ref:`version 1 ` UUIDs: 1. Scattered database records 2. Inability to sort by an identifier in a meaningful way (i.e., insert order) To overcome these issues, we need the ability to generate UUIDs that are *monotonically increasing* while still providing all the benefits of version 1 UUIDs. Version 6 UUIDs do this by storing the time in standard byte order, instead of breaking it up and rearranging the time bytes, according to the `RFC 9562`_ (formerly `RFC 4122`_) definition for version 1 UUIDs. All other fields remain the same. In all other ways, version 6 UUIDs function like version 1 UUIDs. .. tip:: Prior to version 4.0.0, ramsey/uuid provided a solution for this with the :ref:`ordered-time codec `. The ordered-time codec is now deprecated and will be removed in ramsey/uuid 5.0.0. However, you may replace UUIDs generated using the ordered-time codec with version 6 UUIDs. Keep reading to find out how. .. code-block:: php :caption: Generate a version 6, reordered Gregorian time UUID :name: rfc4122.version6.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid6(); printf( "UUID: %s\nVersion: %d\nDate: %s\nNode: %s\n", $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getDateTime()->format('r'), $uuid->getFields()->getNode()->toString() ); This will generate a version 6 UUID and print out its string representation, the time the UUID was created, and the node used to create the UUID. It will look something like this: .. code-block:: text UUID: 1ea60f56-b67b-61fc-829a-0242ac130003 Version: 6 Date: Sun, 08 Mar 2020 04:29:37 +0000 Node: 0242ac130003 You may provide custom values for version 6 UUIDs, including node and clock sequence. .. code-block:: php :caption: Provide custom node and clock sequence to create a version 6, reordered Gregorian time UUID :name: rfc4122.version6.custom-example use Ramsey\Uuid\Provider\Node\StaticNodeProvider; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Uuid; $nodeProvider = new StaticNodeProvider(new Hexadecimal('121212121212')); $clockSequence = 16383; $uuid = Uuid::uuid6($nodeProvider->getNode(), $clockSequence); .. tip:: Version 6 UUIDs generated in ramsey/uuid are instances of UuidV6. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV6` API documentation to learn more about what you can do with a UuidV6 instance. .. _rfc4122.version6.nodes: Custom and Random Nodes ####################### In the :ref:`example above `, we provided a custom node when generating a version 6 UUID. You may also generate random node values. To learn more, see the :ref:`rfc4122.version1.custom` and :ref:`rfc4122.version1.random` sections under :ref:`rfc4122.version1`. .. _rfc4122.version6.clock: Clock Sequence ############## In a version 6 UUID, the clock sequence serves the same purpose as in a version 1 UUID. See :ref:`rfc4122.version1.clock` to learn more. .. _rfc4122.version6.version1-conversion: Version 1-to-6 Conversion ######################### It is possible to convert back-and-forth between version 6 and version 1 UUIDs. .. code-block:: php :caption: Convert a version 1 UUID to a version 6 UUID :name: rfc4122.version6.convert-version1-example use Ramsey\Uuid\Rfc4122\UuidV1; use Ramsey\Uuid\Rfc4122\UuidV6; use Ramsey\Uuid\Uuid; $uuid1 = Uuid::fromString('3960c5d8-60f8-11ea-bc55-0242ac130003'); if ($uuid1 instanceof UuidV1) { $uuid6 = UuidV6::fromUuidV1($uuid1); } .. code-block:: php :caption: Convert a version 6 UUID to a version 1 UUID :name: rfc4122.version6.convert-version6-example use Ramsey\Uuid\Rfc4122\UuidV6; use Ramsey\Uuid\Uuid; $uuid6 = Uuid::fromString('1ea60f83-960c-65d8-bc55-0242ac130003'); if ($uuid6 instanceof UuidV6) { $uuid1 = $uuid6->toUuidV1(); } .. _rfc4122.version6.ordered-time-conversion: Ordered-time to Version 6 Conversion #################################### You may convert UUIDs previously generated and stored using the :ref:`ordered-time codec ` into version 6 UUIDs. .. caution:: If you perform this conversion, the bytes and string representation of your UUIDs will change. This will break any software that expects your identifiers to be fixed. .. code-block:: php :caption: Convert an ordered-time codec encoded UUID to a version 6 UUID :name: rfc4122.version6.convert-ordered-time-example use Ramsey\Uuid\Codec\OrderedTimeCodec; use Ramsey\Uuid\Rfc4122\UuidV1; use Ramsey\Uuid\Rfc4122\UuidV6; use Ramsey\Uuid\UuidFactory; // The bytes of a version 1 UUID previously stored in some datastore // after encoding to bytes with the OrderedTimeCodec. $bytes = hex2bin('11ea60faf17c8af6ad23acde48001122'); $factory = new UuidFactory(); $codec = new OrderedTimeCodec($factory->getUuidBuilder()); $factory->setCodec($codec); $orderedTimeUuid = $factory->fromBytes($bytes); if ($orderedTimeUuid instanceof UuidV1) { $uuid6 = UuidV6::fromUuidV1($orderedTimeUuid); } .. _rfc4122.version6.privacy: Privacy Concerns ################ Like :ref:`version 1 UUIDs `, version 6 UUIDs use a MAC address from a local hardware network interface. This means it is possible to uniquely identify the machine on which a version 6 UUID was created. If the value provided by the timestamp of a version 6 UUID is important to you, but you do not wish to expose the interface address of any of your local machines, see :ref:`rfc4122.version6.nodes`. If you do not need an identifier with a node value embedded in it, but you still need the benefit of a monotonically increasing unique identifier, see :ref:`rfc4122.version7`. .. _two problems that have long existed: https://www.percona.com/blog/store-uuid-optimized-way/ .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/rfc4122/version7.rst ================================================ .. _rfc4122.version7: ========================== Version 7: Unix Epoch Time ========================== .. admonition:: ULIDs and Version 7 UUIDs :class: hint Version 7 UUIDs are binary-compatible with `ULIDs`_ (universally unique lexicographically-sortable identifiers). Both use a 48-bit timestamp in milliseconds since the Unix Epoch, filling the rest with random data. Version 7 UUIDs then add the version and variant bits required by the UUID specification, which reduces the randomness from 80 bits to 74. Otherwise, they are identical. You may even convert a version 7 UUID to a ULID. :ref:`See below for an example. ` Version 7 UUIDs solve `two problems that have long existed`_ with the use of :ref:`version 1 ` UUIDs: 1. Scattered database records 2. Inability to sort by an identifier in a meaningful way (i.e., insert order) To overcome these issues, we need the ability to generate UUIDs that are *monotonically increasing*. :ref:`Version 6 UUIDs ` provide an excellent solution for those who need monotonically increasing, sortable UUIDs with the features of version 1 UUIDs (MAC address and clock sequence), but if those features aren't necessary for your application, using a version 6 UUID might be overkill. Version 7 UUIDs combine random data (like version 4 UUIDs) with a timestamp (in milliseconds since the Unix Epoch, i.e., 1970-01-01 00:00:00 UTC) to create a monotonically increasing, sortable UUID that doesn't have any privacy concerns, since it doesn't include a MAC address. For this reason, implementations should use version 7 UUIDs over versions 1 and 6, if possible. .. code-block:: php :caption: Generate a version 7, Unix Epoch time UUID :name: rfc4122.version7.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid7(); printf( "UUID: %s\nVersion: %d\nDate: %s\n", $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getDateTime()->format('r'), ); This will generate a version 7 UUID and print out its string representation and the time it was created. It will look something like this: .. code-block:: text UUID: 01833ce0-3486-7bfd-84a1-ad157cf64005 Version: 7 Date: Wed, 14 Sep 2022 16:41:10 +0000 To use an existing date and time to generate a version 7 UUID, you may pass a ``\DateTimeInterface`` instance to the ``uuid7()`` method. .. code-block:: php :caption: Generate a version 7 UUID from an existing date and time :name: rfc4122.version7.example-datetime use DateTimeImmutable; use Ramsey\Uuid\Uuid; $dateTime = new DateTimeImmutable('@281474976710.655'); $uuid = Uuid::uuid7($dateTime); printf( "UUID: %s\nVersion: %d\nDate: %s\n", $uuid->toString(), $uuid->getFields()->getVersion(), $uuid->getDateTime()->format('r'), ); Which will print something like this: .. code-block:: text UUID: ffffffff-ffff-7964-a8f6-001336ac20cb Version: 7 Date: Tue, 02 Aug 10889 05:31:50 +0000 .. tip:: Version 7 UUIDs generated in ramsey/uuid are instances of UuidV7. Check out the :php:class:`Ramsey\\Uuid\\Rfc4122\\UuidV7` API documentation to learn more about what you can do with a UuidV7 instance. .. _rfc4122.version7.ulid: Convert a Version 7 UUID to a ULID ################################## As mentioned in the callout above, version 7 UUIDs are binary-compatible with `ULIDs`_. This means you can encode a version 7 UUID using `Crockford's Base 32 algorithm`_ and it will be a valid ULID, timestamp and all. Using the third-party library `tuupola/base32`_, here's how we can encode a version 7 UUID as a ULID. Note that there's a little bit of work to perform the conversion, since you're working with different bases. .. code-block:: php :caption: Encode a version 7, Unix Epoch time UUID as a ULID :name: rfc4122.version7.example-ulid use Ramsey\Uuid\Uuid; use Tuupola\Base32; $crockford = new Base32([ 'characters' => Base32::CROCKFORD, 'padding' => false, 'crockford' => true, ]); $uuid = Uuid::uuid7(); // First, we must pad the 16-byte string to 20 bytes // for proper conversion without data loss. $bytes = str_pad($uuid->getBytes(), 20, "\x00", STR_PAD_LEFT); // Use Crockford's Base 32 encoding algorithm. $encoded = $crockford->encode($bytes); // That 20-byte string was encoded to 32 characters to avoid loss // of data. We must strip off the first 6 characters--which are // all zeros--to get a valid 26-character ULID string. $ulid = substr($encoded, 6); printf("ULID: %s\n", $ulid); This will print something like this: .. code-block:: text ULID: 01GCZ05N3JFRKBRWKNGCQZGP44 .. caution:: Be aware that all version 7 UUIDs may be converted to ULIDs but not all ULIDs may be converted to UUIDs. For that matter, all UUIDs of any version may be encoded as ULIDs, but they will not be monotonically increasing and sortable unless they are version 7 UUIDs. You will also not be able to extract a meaningful timestamp from the ULID, unless it was converted from a version 7 UUID. .. _ULIDs: https://github.com/ulid/spec .. _two problems that have long existed: https://www.percona.com/blog/store-uuid-optimized-way/ .. _Crockford's Base 32 algorithm: https://www.crockford.com/base32.html .. _tuupola/base32: https://packagist.org/packages/tuupola/base32 ================================================ FILE: docs/rfc4122/version8.rst ================================================ .. _rfc4122.version8: ======================== Version 8: Custom Format ======================== Version 8 UUIDs allow applications to create custom UUIDs in an RFC-compatible way. The only requirement is the version and variant bits must be set according to the UUID specification. The bytes provided may contain any value according to your application's needs. Be aware, however, that other applications may not understand the semantics of the value. .. warning:: The bytes should be a 16-byte octet string, an open blob of data that you may fill with 128 bits of information. However, bits 48 through 51 will be replaced with the UUID version field, and bits 64 and 65 will be replaced with the UUID variant. You must not rely on these bits for your application needs. .. code-block:: php :caption: Generate a version 8, custom UUID :name: rfc4122.version8.example use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"); printf( "UUID: %s\nVersion: %d\n", $uuid->toString(), $uuid->getFields()->getVersion() ); This will generate a version 8 UUID and print out its string representation. It will look something like this: .. code-block:: text UUID: 00112233-4455-8677-8899-aabbccddeeff Version: 8 ================================================ FILE: docs/rfc4122.rst ================================================ .. _rfc4122: ================================== RFC 9562 (formerly RFC 4122) UUIDs ================================== .. toctree:: :titlesonly: :hidden: rfc4122/version1 rfc4122/version2 rfc4122/version3 rfc4122/version4 rfc4122/version5 rfc4122/version6 rfc4122/version7 rfc4122/version8 `RFC 9562`_ (formerly `RFC 4122`_) defines eight versions of UUIDs. Each version has different generation algorithms and properties. Which one you choose depends on your use-case. You can find out more about their applications on the specific page for that version. Version 1: Gregorian Time This version of UUID combines a timestamp, node value (in the form of a MAC address from the local computer's network interface), and a clock sequence to ensure uniqueness. For more details, see :doc:`rfc4122/version1`. Version 2: DCE Security This version of UUID is the same as Version 1, except the ``clock_seq_low`` field is replaced with a *local domain* and the ``time_low`` field is replaced with a *local identifier*. For more details, see :doc:`rfc4122/version2`. Version 3: Name-based (MD5) This version of UUID hashes together a namespace and a name to create a deterministic UUID. The hashing algorithm used is MD5. For more details, see :doc:`rfc4122/version3`. Version 4: Random This version creates a UUID using truly-random or pseudo-random numbers. For more details, see :doc:`rfc4122/version4`. Version 5: Named-based (SHA-1) This version of UUID hashes together a namespace and a name to create a deterministic UUID. The hashing algorithm used is SHA-1. For more details, see :doc:`rfc4122/version5`. Version 6: Reordered Gregorian Time This version of UUID combines the features of a :ref:`version 1 UUID ` with a *monotonically increasing* UUID. For more details, see :ref:`rfc4122.version6`. Version 7: Unix Epoch Time This version of UUID combines a timestamp--based on milliseconds elapsed since the Unix Epoch--and random bytes to create a monotonically increasing, sortable UUID without the privacy and entropy concerns associated with version 1 and version 6 UUIDs. For more details, see :ref:`rfc4122.version7`. Version 8: Implementation-Specific, Custom Format This version of UUID allows applications to generate custom identifiers in an RFC-compatible format. For more details, see :doc:`rfc4122/version8`. .. _RFC 4122: https://www.rfc-editor.org/rfc/rfc4122 .. _RFC 9562: https://www.rfc-editor.org/rfc/rfc9562 ================================================ FILE: docs/testing.rst ================================================ .. _testing: ================== Testing With UUIDs ================== One problem with the use of ``final`` is the inability to create a `mock object`_ to use in tests. However, the following techniques should help with testing. .. tip:: To learn why ramsey/uuid uses ``final``, take a look at :ref:`faq.final`. .. _testing.inject: Inject a UUID of a Specific Type -------------------------------- Let's say we have a method that uses a type hint for :php:class:`UuidV1 `. .. code-block:: php public function tellTime(UuidV1 $uuid): string { return $uuid->getDateTime()->format('Y-m-d H:i:s'); } Since this method uses UuidV1 as the type hint, we're not able to pass another object that implements UuidInterface, and we cannot extend or mock UuidV1, so how do we test this? One way is to use :php:meth:`Uuid::uuid1() ` to create a regular UuidV1 instance and pass it. .. code-block:: php public function testTellTime(): void { $uuid = Uuid::uuid1(); $myObj = new MyClass(); $this->assertIsString($myObj->tellTime($uuid)); } This might satisfy our testing needs if we only want to assert that the method returns a string. If we want to test for a specific string, we can do that, too, by generating a UUID ahead of time and using it as a known value. .. code-block:: php public function testTellTime(): void { // We generated this version 1 UUID ahead of time and know the // exact date and time it contains, so we can use it to test the // return value of our method. $uuid = Uuid::fromString('177ef0d8-6630-11ea-b69a-0242ac130003'); $myObj = new MyClass(); $this->assertSame('2020-03-14 20:12:12', $myObj->tellTime($uuid)); } .. note:: These examples assume the use of `PHPUnit`_ for tests. The concepts will work no matter what testing framework you use. .. _testing.static: Returning Specific UUIDs From a Static Method --------------------------------------------- Sometimes, rather than pass UUIDs as method arguments, we might call the static methods on the Uuid class from inside the method we want to test. This can be tricky to test. .. code-block:: php public function tellTime(): string { $uuid = Uuid::uuid1(); return $uuid->getDateTime()->format('Y-m-d H:i:s'); } We can call this in a test and assert that it returns a string, but we can't return a specific UUID value from the static method call --- or can we? We can do this by :ref:`overriding the default factory `. First, we create our own factory class for testing. In this example, we extend UuidFactory, but you may create your own separate factory class for testing, as long as you implement :php:interface:`Ramsey\\Uuid\\UuidFactoryInterface`. .. code-block:: php namespace MyPackage; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidInterface; class MyTestUuidFactory extends UuidFactory { public $uuid1; public function uuid1($node = null, ?int $clockSeq = null): UuidInterface { return $this->uuid1; } } Now, from our tests, we can replace the default factory with our new factory, and we can even change the value returned by the :php:meth:`uuid1() ` method for our tests. .. code-block:: php /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testTellTime(): void { $factory = new MyTestUuidFactory(); Uuid::setFactory($factory); $myObj = new MyClass(); $factory->uuid1 = Uuid::fromString('177ef0d8-6630-11ea-b69a-0242ac130003'); $this->assertSame('2020-03-14 20:12:12', $myObj->tellTime()); $factory->uuid1 = Uuid::fromString('13814000-1dd2-11b2-9669-00007ffffffe'); $this->assertSame('1970-01-01 00:00:00', $myObj->tellTime()); } .. attention:: The factory is a static property on the Uuid class. By replacing it like this, all uses of the Uuid class after this point will continue to use the new factory. This is why we must run the test in a separate process. Otherwise, this could cause other tests to fail. Running tests in separate processes can significantly slow down your tests, so try to use this technique sparingly, and if possible, pass your dependencies to your objects, rather than creating (or fetching them) from within. This makes testing easier. .. _testing.mock: Mocking UuidInterface --------------------- Another technique for testing with UUIDs is to mock :php:interface:`UuidInterface `. Consider a method that accepts a UuidInterface. .. code-block:: php public function tellTime(UuidInterface $uuid): string { return $uuid->getDateTime()->format('Y-m-d H:i:s'); } We can mock UuidInterface, passing that mocked value into this method. Then, we can make assertions about what methods were called on the mock object. In the following example test, we don't care whether the return value matches an actual date format. What we care about is that the methods on the UuidInterface object were called. .. code-block:: php public function testTellTime(): void { $dateTime = Mockery::mock(DateTime::class); $dateTime->expects()->format('Y-m-d H:i:s')->andReturn('a test date'); $uuid = Mockery::mock(UuidInterface::class, [ 'getDateTime' => $dateTime, ]); $myObj = new MyClass(); $this->assertSame('a test date', $myObj->tellTime($uuid)); } .. note:: One of my favorite mocking libraries is `Mockery`_, so that's what I use in these examples. However, other mocking libraries exist, and PHPUnit provides built-in mocking capabilities. .. _mock object: https://en.wikipedia.org/wiki/Mock_object .. _PHPUnit: https://phpunit.de .. _Mockery: https://github.com/mockery/mockery ================================================ FILE: docs/upgrading/2-to-3.rst ================================================ .. _upgrading.2-to-3: ============== Version 2 to 3 ============== While we have made significant internal changes to the library, we have made every effort to ensure a seamless upgrade path from the 2.x series of this library to 3.x. One major breaking change is the transition from the ``Rhumsaa`` root namespace to ``Ramsey``. In most cases, all you will need is to change the namespace to ``Ramsey`` in your code, and everything will "just work." .. note:: For more details on the namespace change, including reasons for the change, read the blog post "`Introducing ramsey/uuid `_". Here are full details on the breaking changes to the public API of this library: 1. All namespace references of ``Rhumsaa`` have changed to ``Ramsey``. Simply change the namespace to ``Ramsey`` in your code and everything should work. 2. The console application has moved to `ramsey/uuid-console `_. If using the console functionality, use Composer to require ``ramsey/uuid-console``. 3. The Doctrine field type mapping has moved to `ramsey/uuid-doctrine `_. If using the Doctrine functionality, use Composer to require ``ramsey/uuid-doctrine``. ================================================ FILE: docs/upgrading/3-to-4.rst ================================================ .. _upgrading.3-to-4: ============== Version 3 to 4 ============== I've made great efforts to ensure that the upgrade experience for most will be seamless and uneventful. However, no matter the degree to which you use ramsey/uuid (customized or unchanged), there are a number of things to be aware of as you upgrade your code to use version 4. .. tip:: These are the changes that are most likely to affect you. For a full list of changes, take a look at the `4.0.0 changelog`_. .. _upgrading.3-to-4.new: What's New? ########### There are a lot of new features in ramsey/uuid! Here are a few of them: * Support :ref:`version 6 UUIDs `. * Support :ref:`version 2 (DCE Security) UUIDs `. * Add classes to represent each version of RFC 4122 UUID. When generating new UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID is an RFC 4122 variant, one of these instances will be returned: * :php:class:`Rfc4122\\UuidV1 ` * :php:class:`Rfc4122\\UuidV2 ` * :php:class:`Rfc4122\\UuidV3 ` * :php:class:`Rfc4122\\UuidV4 ` * :php:class:`Rfc4122\\UuidV5 ` * :php:class:`Rfc4122\\NilUuid ` * Add classes to represent version 6 UUIDs, GUIDs, and nonstandard (non-RFC 4122 variants) UUIDs: * :php:class:`Nonstandard\\UuidV6 ` * :php:class:`Nonstandard\\Uuid ` * :php:class:`Guid\\Guid ` * Add :php:meth:`Uuid::fromDateTime() ` to create version 1 UUIDs from instances of DateTimeInterface. .. _upgrading.3-to-4.changed: What's Changed? ############### .. attention:: ramsey/uuid version 4 requires PHP 7.2 or later. Quite a bit has changed, but much remains familiar. Unless you've changed the behavior of ramsey/uuid through custom codecs, providers, generators, etc., the standard functionality and API found in version 3 will not differ much. .. rubric:: Here are the highlights: * ramsey/uuid now works on 32-bit and 64-bit systems, with no degradation in functionality! All Degraded\* classes are deprecated and no longer used; they'll go away in ramsey/uuid version 5. * Pay attention to the :ref:`return types for the static methods ` on the :php:class:`Uuid ` class. They've changed slightly, but this won't affect you if your type hints use :php:interface:`UuidInterface `. * The :ref:`return types for three methods ` defined on :php:interface:`UuidInterface ` have changed, breaking backwards compatibility. **Take note and update your code.** * :ref:`There are a number of deprecations. ` These shouldn't affect you now, but please take a look at the recommendations and update your code soon. These will go away in ramsey/uuid version 5. * ramsey/uuid now :ref:`throws custom exceptions for everything `. The exception UnsatisfiedDependencyException no longer exists. * If you customize ramsey/uuid at all by implementing the interfaces, take a look at the :ref:`interface ` and :ref:`constructor ` changes and update your code. .. tip:: If you maintain a public project that uses ramsey/uuid version 3 and you find that **your code does not require any changes to upgrade** to version 4, consider using the following version constraint in your project's ``composer.json`` file: .. code-block:: bash composer require ramsey/uuid:"^3 || ^4" This will allow any `downstream users`_ of your project who aren't ready to upgrade to version 4 the ability to continue using your project while deciding on an appropriate upgrade schedule. If your downstream users do not specify ramsey/uuid as a dependency, and they use functionality specific to version 3, they may need to update their own Composer dependencies to use ramsey/uuid ``^3`` to avoid using version 4. .. _upgrading.3-to-4.static-methods: Uuid Static Methods ################### All the static methods on the :php:class:`Uuid ` class continue to work as they did in version 3, with this slight change: **they now return more-specific types**, all of which implement the new interface :php:interface:`Rfc4122\\UuidInterface `, which implements the familiar interface :php:interface:`UuidInterface `. If your type hints are for :php:interface:`UuidInterface `, then you should not require any changes. .. list-table:: Return types for Uuid static methods :align: center :header-rows: 1 * - Method - 3.x Returned - 4.x Returns * - :php:meth:`Uuid::uuid1() ` - :php:class:`Uuid ` - :php:class:`Rfc4122\\UuidV1 ` * - :php:meth:`Uuid::uuid3() ` - :php:class:`Uuid ` - :php:class:`Rfc4122\\UuidV3 ` * - :php:meth:`Uuid::uuid4() ` - :php:class:`Uuid ` - :php:class:`Rfc4122\\UuidV4 ` * - :php:meth:`Uuid::uuid5() ` - :php:class:`Uuid ` - :php:class:`Rfc4122\\UuidV5 ` :php:meth:`Uuid::fromString() `, :php:meth:`Uuid::fromBytes() `, and :php:meth:`Uuid::fromInteger() ` all return an appropriate more-specific type, based on the input value. If the input value is a version 1 UUID, for example, the return type will be an :php:class:`Rfc4122\\UuidV1 `. If the input looks like a UUID or is a 128-bit number, but it doesn't validate as an RFC 4122 UUID, the return type will be a :php:class:`Nonstandard\\Uuid `. These return types implement :php:interface:`UuidInterface `. If using this as a type hint, you shouldn't need to make any changes. .. _upgrading.3-to-4.return-types: Changed Return Types #################### The following :php:interface:`UuidInterface ` method return types have changed in version 4 and you will need to update your code, if you use these methods. .. list-table:: Changed UuidInterface method return types :widths: 40 30 30 :align: center :header-rows: 1 * - Method - 3.x Returned - 4.x Returns * - :php:meth:`UuidInterface::getFields() ` - ``array`` - :php:class:`Rfc4122\\FieldsInterface ` * - :php:meth:`UuidInterface::getHex() ` - ``string`` - :php:class:`Type\\Hexadecimal ` * - :php:meth:`UuidInterface::getInteger() ` - ``mixed`` [#f1]_ - :php:class:`Type\\Integer ` In version 3, the following :php:class:`Uuid ` methods return ``int``, ``string``, or Moontoast\\Math\\BigNumber, depending on the environment. In version 4, they all return numeric ``string`` values for the sake of consistency. These methods :ref:`are also deprecated ` and will be removed in version 5. * ``getClockSeqHiAndReserved()`` * ``getClockSeqLow()`` * ``getClockSequence()`` * ``getLeastSignificantBits()`` * ``getMostSignificantBits()`` * ``getNode()`` * ``getTimeHiAndVersion()`` * ``getTimeLow()`` * ``getTimeMid()`` * ``getTimestamp()`` .. _upgrading.3-to-4.deprecations: Deprecations ############ .. _upgrading.3-to-4.deprecations.uuidinterface: UuidInterface ------------- The following :php:interface:`UuidInterface ` methods are deprecated, but upgrading to version 4 should not cause any problems if using these methods. You are encouraged to update your code according to the recommendations, though, since these methods will go away in version 5. .. list-table:: Deprecated UuidInterface methods :widths: 30 70 :align: center :header-rows: 1 * - Deprecated Method - Update To * - ``getDateTime()`` - Use ``getDateTime()`` on :php:meth:`UuidV1 `, :php:meth:`UuidV2 `, or :php:meth:`UuidV6 ` * - ``getClockSeqHiAndReservedHex()`` - :php:meth:`getFields()->getClockSeqHiAndReserved()->toString() ` * - ``getClockSeqLowHex()`` - :php:meth:`getFields()->getClockSeqLow()->toString() ` * - ``getClockSequenceHex()`` - :php:meth:`getFields()->getClockSeq()->toString() ` * - ``getFieldsHex()`` - :php:meth:`getFields() ` [#f2]_ * - ``getLeastSignificantBitsHex()`` - ``substr($uuid->getHex()->toString(), 0, 16)`` * - ``getMostSignificantBitsHex()`` - ``substr($uuid->getHex()->toString(), 16)`` * - ``getNodeHex()`` - :php:meth:`getFields()->getNode()->toString() ` * - ``getNumberConverter()`` - This method has no replacement; plan accordingly. * - ``getTimeHiAndVersionHex()`` - :php:meth:`getFields()->getTimeHiAndVersion()->toString() ` * - ``getTimeLowHex()`` - :php:meth:`getFields()->getTimeLow()->toString() ` * - ``getTimeMidHex()`` - :php:meth:`getFields()->getTimeMid()->toString() ` * - ``getTimestampHex()`` - :php:meth:`getFields()->getTimestamp()->toString() ` * - ``getUrn()`` - :php:meth:`Ramsey\\Uuid\\Rfc4122\\UuidInterface::getUrn` * - ``getVariant()`` - :php:meth:`getFields()->getVariant() ` * - ``getVersion()`` - :php:meth:`getFields()->getVersion() ` .. _upgrading.3-to-4.deprecations.uuid: Uuid ---- :php:class:`Uuid ` as an instantiable class is deprecated. In ramsey/uuid version 5, its constructor will be ``private``, and the class will be ``final``. For more information, see :ref:`faq.final` .. note:: :php:class:`Uuid ` is being replaced by more-specific concrete classes, such as: * :php:class:`Rfc4122\\UuidV1 ` * :php:class:`Rfc4122\\UuidV3 ` * :php:class:`Rfc4122\\UuidV4 ` * :php:class:`Rfc4122\\UuidV5 ` * :php:class:`Nonstandard\\Uuid ` However, the :php:class:`Uuid ` class isn't going away. It will still hold common constants and static methods. * ``Uuid::UUID_TYPE_IDENTIFIER`` is deprecated. Use ``Uuid::UUID_TYPE_DCE_SECURITY`` instead. * ``Uuid::VALID_PATTERN`` is deprecated. Use the following instead: .. code-block:: php use Ramsey\Uuid\Validator\GenericValidator; use Ramsey\Uuid\Rfc4122\Validator as Rfc4122Validator; $genericPattern = (new GenericValidator())->getPattern(); $rfc4122Pattern = (new Rfc4122Validator())->getPattern(); The following :php:class:`Uuid ` methods are deprecated. If using these methods, you shouldn't have any problems on version 4, but you are encouraged to update your code, since they will go away in version 5. * ``getClockSeqHiAndReserved()`` * ``getClockSeqLow()`` * ``getClockSequence()`` * ``getLeastSignificantBits()`` * ``getMostSignificantBits()`` * ``getNode()`` * ``getTimeHiAndVersion()`` * ``getTimeLow()`` * ``getTimeMid()`` * ``getTimestamp()`` .. hint:: There are no direct replacements for these methods. In ramsey/uuid version 3, they returned ``int`` or Moontoast\\Math\\BigNumber values, depending on the environment. To update your code, you should use the recommended alternates listed in :ref:`Deprecations: UuidInterface `, combined with the arbitrary-precision mathematics library of your choice (e.g., `brick/math`_, `gmp`_, `bcmath`_, etc.). .. code-block:: php :caption: Using brick/math to convert a node to a string integer use Brick\Math\BigInteger; $node = BigInteger::fromBase($uuid->getFields()->getNode()->toString(), 16); .. _upgrading.3-to-4.interfaces: Interface Changes ################# For those who customize ramsey/uuid by implementing the interfaces provided, there are a few breaking changes to note. .. hint:: Most existing methods on interfaces have type hints added to them. If you implement any interfaces, please be aware of this and update your classes. UuidInterface ------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - :php:meth:`__toString() ` - New method; returns ``string`` * - :php:meth:`getDateTime() ` - Deprecated; now returns `DateTimeInterface`_ * - :php:meth:`getFields() ` - Used to return ``array``; now returns :php:class:`Rfc4122\\FieldsInterface ` * - :php:meth:`getHex() ` - Used to return ``string``; now returns :php:class:`Type\\Hexadecimal ` * - :php:meth:`getInteger() ` - New method; returns :php:class:`Type\\Integer ` UuidFactoryInterface -------------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - :php:meth:`uuid2() ` - New method; returns :php:class:`Rfc4122\\UuidV2 ` * - :php:meth:`uuid6() ` - New method; returns :php:class:`Nonstandard\\UuidV6 ` * - :php:meth:`fromDateTime() ` - New method; returns :php:class:`UuidInterface ` * - :php:meth:`fromInteger() ` - Changed to accept only strings * - :php:meth:`getValidator() ` - New method; returns :php:class:`UuidInterface ` Builder\\UuidBuilderInterface ----------------------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - ``build()`` - The second parameter used to accept ``array $fields``; now accepts ``string $bytes`` Converter\\TimeConverterInterface --------------------------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - ``calculateTime()`` - Used to return ``string[]``; now returns :php:class:`Type\\Hexadecimal ` * - ``convertTime()`` - New method; returns :php:class:`Type\\Time ` Provider\\TimeProviderInterface --------------------------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - ``currentTime()`` - Method removed from interface; use ``getTime()`` instead * - ``getTime()`` - New method; returns :php:class:`Type\\Time ` Provider\\NodeProviderInterface --------------------------------- .. list-table:: :widths: 25 75 :align: center :header-rows: 1 * - Method - Description * - ``getNode()`` - Used to return ``string|false|null``; now returns :php:class:`Type\\Hexadecimal ` .. _upgrading.3-to-4.constructors: Constructor Changes ################### There are a handful of constructor changes that might affect your use of ramsey/uuid, especially if you customize the library. Uuid ---- The constructor for :php:class:`Ramsey\\Uuid\\Uuid` is deprecated. However, there are a few changes to it that might affect your use of this class. The first constructor parameter used to be ``array $fields`` and is now :php:interface:`Rfc4122\\FieldsInterface $fields `. ``Converter\TimeConverterInterface $timeConverter`` is required as a new fourth parameter. Builder\\DefaultUuidBuilder --------------------------- While Builder\\DefaultUuidBuilder is deprecated, it now inherits from Rfc4122\\UuidBuilder, which requires ``Converter\TimeConverterInterface $timeConverter`` as its second constructor argument. Provider\\Node\\FallbackNodeProvider ------------------------------------ Provider\\Node\\FallbackNodeProvider now requires ``iterable`` as its constructor parameter. .. code-block:: use MyPackage\MyCustomNodeProvider; use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Provider\Node\SystemNodeProvider; $nodeProviders = []; $nodeProviders[] = new MyCustomNodeProvider(); $nodeProviders[] = new SystemNodeProvider(); $nodeProviders[] = new RandomNodeProvider(); $provider = new FallbackNodeProvider($nodeProviders); Provider\\Time\\FixedTimeProvider --------------------------------- The constructor for Provider\\Time\\FixedTimeProvider no longer accepts an array. It accepts :php:class:`Type\\Time ` instances. ------------------------------------------------------------------------------- .. rubric:: Footnotes .. [#f1] This ``mixed`` return type could have been an ``int``, ``string``, or Moontoast\\Math\\BigNumber. In version 4, ramsey/uuid cleans this up for the sake of consistency. .. [#f2] The :php:meth:`getFields() ` method returns a :php:class:`Type\\Hexadecimal ` instance; you will need to construct an array if you wish to match the return value of the deprecated ``getFieldsHex()`` method. .. _downstream users: https://en.wikipedia.org/wiki/Downstream_(software_development) .. _version 6 UUIDs: http://gh.peabody.io/uuidv6/ .. _4.0.0 changelog: https://github.com/ramsey/uuid/releases/tag/4.0.0 .. _brick/math: https://github.com/brick/math .. _gmp: https://www.php.net/gmp .. _bcmath: https://www.php.net/bcmath .. _DateTimeInterface: https://www.php.net/datetimeinterface ================================================ FILE: docs/upgrading.rst ================================================ .. _upgrading: ===================== Upgrading ramsey/uuid ===================== .. toctree:: :titlesonly: upgrading/3-to-4 upgrading/2-to-3 ================================================ FILE: phpbench.json ================================================ { "runner.bootstrap": "vendor/autoload.php", "runner.path": "tests/benchmark", "runner.retry_threshold": 5, "report.generators": { "report": { "extends": "aggregate" } } } ================================================ FILE: phpcs.xml.dist ================================================ ./src ./tests A common coding standard for Ramsey's PHP libraries. error 5 ================================================ FILE: phpstan.neon.dist ================================================ parameters: tmpDir: ./build/cache/phpstan level: max treatPhpDocTypesAsCertain: false paths: - ./src - ./tests bootstrapFiles: - ./tests/static-analysis/stubs.php excludePaths: analyse: - ./tests/ExpectedBehaviorTest.php - ./tests/static-analysis/stubs.php ignoreErrors: - identifier: method.resultUnused path: tests/* - identifier: staticMethod.resultUnused path: tests/* ================================================ FILE: phpunit.xml.dist ================================================ ./tests ./src ================================================ FILE: resources/vagrant/.gitignore ================================================ .vagrant/ ================================================ FILE: resources/vagrant/README.md ================================================ # Running Tests With Vagrant To run tests using these instructions, you will first need to install [Vagrant](https://www.vagrantup.com). You should be able to use [VirtualBox](https://www.virtualbox.org) with each environment. Other providers, such as VMWare and Hyper-V, may be available, depending on the box used. * [Run tests on Linux](linux/README.md) * [Run tests on FreeBSD](freebsd/README.md) * [Run tests on Windows](windows/README.md) ================================================ FILE: resources/vagrant/freebsd/README.md ================================================ # Run tests on FreeBSD ``` bash cd /path/to/uuid/resources/vagrant/freebsd vagrant up vagrant ssh ``` Once inside the VM: ``` bash cd uuid/ composer install composer run-script --timeout=0 test ``` ================================================ FILE: resources/vagrant/freebsd/Vagrantfile ================================================ # -*- mode: ruby -*- # vi: set ft=ruby : $script = <<-SCRIPT pkg update pkg install -y \ php74 \ php74-bcmath \ php74-composer \ php74-dom \ php74-gmp \ php74-json \ php74-pecl-libsodium \ php74-pecl-uuid \ php74-pecl-xdebug \ php74-simplexml \ php74-tokenizer \ php74-xml \ php74-xmlreader \ php74-xmlwriter \ php74-zip \ unzip SCRIPT Vagrant.configure("2") do |config| config.vm.box = "freebsd/FreeBSD-12.1-RELEASE" config.vm.box_version = "2019.11.01" config.vm.provision "shell", inline: $script config.vm.synced_folder "../../../", "/home/vagrant/uuid", type: "rsync" config.ssh.shell = "sh" config.vm.provider "virtualbox" do |v| v.name = "ramsey-uuid-freebsd" end end ================================================ FILE: resources/vagrant/linux/README.md ================================================ # Run tests on Linux ``` bash cd /path/to/uuid/resources/vagrant/linux vagrant up vagrant ssh ``` Once inside the VM: ``` bash cd uuid/ composer install composer run-script --timeout=0 test ``` ================================================ FILE: resources/vagrant/linux/Vagrantfile ================================================ # -*- mode: ruby -*- # vi: set ft=ruby : $script = <<-SCRIPT apt-get update apt-get install -y \ composer \ php-bcmath \ php-cli \ php-gmp \ php-json \ php-uuid \ php-xdebug \ php-xml \ php-zip \ unzip SCRIPT Vagrant.configure("2") do |config| config.vm.box = "ubuntu/eoan64" config.vm.provision "shell", inline: $script config.vm.synced_folder "../../../", "/home/vagrant/uuid", type: "rsync" config.vm.provider "virtualbox" do |v| v.name = "ramsey-uuid-linux" end end ================================================ FILE: resources/vagrant/windows/README.md ================================================ # Run tests on Windows ``` bash cd /path/to/uuid/resources/vagrant/windows vagrant up vagrant ssh ``` Once inside the VM: ``` bash refreshenv cd uuid composer install composer run-script --timeout=0 test ``` ================================================ FILE: resources/vagrant/windows/Vagrantfile ================================================ # -*- mode: ruby -*- # vi: set ft=ruby : $script = <<-SCRIPT choco install composer php unzip --no-progress -y Invoke-WebRequest -Uri https://windows.php.net/downloads/pecl/releases/xdebug/2.9.1/php_xdebug-2.9.1-7.4-nts-vc15-x64.zip -UseBasicParsing -OutFile C:\\temp\\php_xdebug.zip unzip C:\\temp\\php_xdebug.zip -d C:\\temp\\php_xdebug move C:\\temp\\php_xdebug\\php_xdebug.dll C:\\tools\\php74\\ext\\php_xdebug.dll Add-Content C:\\tools\\php74\\php.ini "`nextension=gmp" Add-Content C:\\tools\\php74\\php.ini "`nextension=sodium" Add-Content C:\\tools\\php74\\php.ini "`nzend_extension=xdebug" SCRIPT Vagrant.configure("2") do |config| config.vm.box = "jborean93/WindowsServer2019" config.vm.provision "shell", inline: $script config.vm.synced_folder "../../../", "C:\\Users\\vagrant\\uuid" config.vm.provider "virtualbox" do |vb| vb.name = "ramsey-uuid-windows" end end ================================================ FILE: src/BinaryUtils.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; /** * Provides binary math utilities */ class BinaryUtils { /** * Applies the variant field to the 16-bit clock sequence * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field * * @param int $clockSeq The 16-bit clock sequence value before the variant is applied * * @return int The 16-bit clock sequence multiplexed with the UUID variant * * @pure */ public static function applyVariant(int $clockSeq): int { return ($clockSeq & 0x3fff) | 0x8000; } /** * Applies the version field to the 16-bit `time_hi_and_version` field * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field * * @param int $timeHi The value of the 16-bit `time_hi_and_version` field before the version is applied * @param int $version The version to apply to the `time_hi` field * * @return int The 16-bit time_hi field of the timestamp multiplexed with the UUID version number * * @pure */ public static function applyVersion(int $timeHi, int $version): int { return ($timeHi & 0x0fff) | ($version << 12); } } ================================================ FILE: src/Builder/BuilderCollection.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Builder; use Ramsey\Collection\AbstractCollection; use Ramsey\Uuid\Converter\Number\GenericNumberConverter; use Ramsey\Uuid\Converter\Time\GenericTimeConverter; use Ramsey\Uuid\Converter\Time\PhpTimeConverter; use Ramsey\Uuid\Guid\GuidBuilder; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder; use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; use Traversable; /** * A collection of UuidBuilderInterface objects * * @deprecated this class has been deprecated and will be removed in 5.0.0. The use-case for this class comes from a * pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced at runtime: * that is no longer necessary, now that you can safely verify your code to be correct, and use more generic types * like `iterable` instead. * * @extends AbstractCollection */ class BuilderCollection extends AbstractCollection { public function getType(): string { return UuidBuilderInterface::class; } public function getIterator(): Traversable { return parent::getIterator(); } /** * Re-constructs the object from its serialized form * * @param string $serialized The serialized PHP string to unserialize into a UuidInterface instance */ public function unserialize($serialized): void { /** @var array $data */ $data = unserialize($serialized, [ 'allowed_classes' => [ BrickMathCalculator::class, GenericNumberConverter::class, GenericTimeConverter::class, GuidBuilder::class, NonstandardUuidBuilder::class, PhpTimeConverter::class, Rfc4122UuidBuilder::class, ], ]); $this->data = array_filter( $data, function ($unserialized): bool { /** @phpstan-ignore instanceof.alwaysTrue */ return $unserialized instanceof UuidBuilderInterface; }, ); } } ================================================ FILE: src/Builder/DefaultUuidBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; /** * @deprecated Please transition to {@see Rfc4122UuidBuilder}. * * @immutable */ class DefaultUuidBuilder extends Rfc4122UuidBuilder { } ================================================ FILE: src/Builder/DegradedUuidBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\Time\DegradedTimeConverter; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\DegradedUuid; use Ramsey\Uuid\Rfc4122\Fields as Rfc4122Fields; use Ramsey\Uuid\UuidInterface; /** * @deprecated DegradedUuid instances are no longer necessary to support 32-bit systems. Please transition to {@see DefaultUuidBuilder}. * * @immutable */ class DegradedUuidBuilder implements UuidBuilderInterface { private TimeConverterInterface $timeConverter; /** * @param NumberConverterInterface $numberConverter The number converter to use when constructing the DegradedUuid * @param TimeConverterInterface|null $timeConverter The time converter to use for converting timestamps extracted * from a UUID to Unix timestamps */ public function __construct( private NumberConverterInterface $numberConverter, ?TimeConverterInterface $timeConverter = null ) { $this->timeConverter = $timeConverter ?: new DegradedTimeConverter(); } /** * Builds and returns a DegradedUuid * * @param CodecInterface $codec The codec to use for building this DegradedUuid instance * @param string $bytes The byte string from which to construct a UUID * * @return DegradedUuid The DegradedUuidBuild returns an instance of Ramsey\Uuid\DegradedUuid * * @phpstan-impure */ public function build(CodecInterface $codec, string $bytes): UuidInterface { return new DegradedUuid(new Rfc4122Fields($bytes), $this->numberConverter, $codec, $this->timeConverter); } } ================================================ FILE: src/Builder/FallbackBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Exception\BuilderNotFoundException; use Ramsey\Uuid\Exception\UnableToBuildUuidException; use Ramsey\Uuid\UuidInterface; /** * FallbackBuilder builds a UUID by stepping through a list of UUID builders until a UUID can be constructed without exceptions * * @immutable */ class FallbackBuilder implements UuidBuilderInterface { /** * @param iterable $builders An array of UUID builders */ public function __construct(private iterable $builders) { } /** * Builds and returns a UuidInterface instance using the first builder that succeeds * * @param CodecInterface $codec The codec to use for building this instance * @param string $bytes The byte string from which to construct a UUID * * @return UuidInterface an instance of a UUID object * * @pure */ public function build(CodecInterface $codec, string $bytes): UuidInterface { $lastBuilderException = null; foreach ($this->builders as $builder) { try { return $builder->build($codec, $bytes); } catch (UnableToBuildUuidException $exception) { $lastBuilderException = $exception; continue; } } throw new BuilderNotFoundException( 'Could not find a suitable builder for the provided codec and fields', 0, $lastBuilderException, ); } } ================================================ FILE: src/Builder/UuidBuilderInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\UuidInterface; /** * A UUID builder builds instances of UuidInterface * * @immutable */ interface UuidBuilderInterface { /** * Builds and returns a UuidInterface * * @param CodecInterface $codec The codec to use for building this UuidInterface instance * @param string $bytes The byte string from which to construct a UUID * * @return UuidInterface Implementations may choose to return more specific instances of UUIDs that implement UuidInterface * * @pure */ public function build(CodecInterface $codec, string $bytes): UuidInterface; } ================================================ FILE: src/Codec/CodecInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; use Ramsey\Uuid\UuidInterface; /** * A codec encodes and decodes a UUID according to defined rules * * @immutable */ interface CodecInterface { /** * Returns a hexadecimal string representation of a UuidInterface * * @param UuidInterface $uuid The UUID for which to create a hexadecimal string representation * * @return non-empty-string Hexadecimal string representation of a UUID * * @pure */ public function encode(UuidInterface $uuid): string; /** * Returns a binary string representation of a UuidInterface * * @param UuidInterface $uuid The UUID for which to create a binary string representation * * @return non-empty-string Binary string representation of a UUID * * @pure */ public function encodeBinary(UuidInterface $uuid): string; /** * Returns a UuidInterface derived from a hexadecimal string representation * * @param string $encodedUuid The hexadecimal string representation to convert into a UuidInterface instance * * @return UuidInterface An instance of a UUID decoded from a hexadecimal string representation * * @pure */ public function decode(string $encodedUuid): UuidInterface; /** * Returns a UuidInterface derived from a binary string representation * * @param string $bytes The binary string representation to convert into a UuidInterface instance * * @return UuidInterface An instance of a UUID decoded from a binary string representation * * @pure */ public function decodeBytes(string $bytes): UuidInterface; } ================================================ FILE: src/Codec/GuidStringCodec.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; use Ramsey\Uuid\Guid\Guid; use Ramsey\Uuid\UuidInterface; use function bin2hex; use function sprintf; use function substr; /** * GuidStringCodec encodes and decodes globally unique identifiers (GUID) * * @see Guid * * @immutable */ class GuidStringCodec extends StringCodec { public function encode(UuidInterface $uuid): string { /** @phpstan-ignore possiblyImpure.methodCall */ $hex = bin2hex($uuid->getFields()->getBytes()); /** @var non-empty-string */ return sprintf( '%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s', substr($hex, 6, 2), substr($hex, 4, 2), substr($hex, 2, 2), substr($hex, 0, 2), substr($hex, 10, 2), substr($hex, 8, 2), substr($hex, 14, 2), substr($hex, 12, 2), substr($hex, 16, 4), substr($hex, 20), ); } public function decode(string $encodedUuid): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ $bytes = $this->getBytes($encodedUuid); /** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ return $this->getBuilder()->build($this, $this->swapBytes($bytes)); } public function decodeBytes(string $bytes): UuidInterface { // Call parent::decode() to preserve the correct byte order. return parent::decode(bin2hex($bytes)); } /** * Swaps bytes according to the GUID rules */ private function swapBytes(string $bytes): string { return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0] . $bytes[5] . $bytes[4] . $bytes[7] . $bytes[6] . substr($bytes, 8); } } ================================================ FILE: src/Codec/OrderedTimeCodec.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use function strlen; use function substr; /** * OrderedTimeCodec encodes and decodes a UUID, optimizing the byte order for more efficient storage * * For binary representations of version 1 UUID, this codec may be used to reorganize the time fields, making the UUID * closer to sequential when storing the bytes. According to Percona, this optimization can improve database INSERT and * SELECT statements using the UUID column as a key. * * The string representation of the UUID will remain unchanged. Only the binary representation is reordered. * * PLEASE NOTE: Binary representations of UUIDs encoded with this codec must be decoded with this codec. Decoding using * another codec can result in malformed UUIDs. * * @deprecated Please migrate to {@link https://uuid.ramsey.dev/en/stable/rfc4122/version6.html Version 6, reordered time-based UUIDs}. * * @link https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ Storing UUID Values in MySQL * * @immutable */ class OrderedTimeCodec extends StringCodec { /** * Returns a binary string representation of a UUID, with the timestamp fields rearranged for optimized storage * * @return non-empty-string */ public function encodeBinary(UuidInterface $uuid): string { if ( /** @phpstan-ignore possiblyImpure.methodCall */ !($uuid->getFields() instanceof Rfc4122FieldsInterface) /** @phpstan-ignore possiblyImpure.methodCall */ || $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME ) { throw new InvalidArgumentException('Expected version 1 (time-based) UUID'); } /** @phpstan-ignore possiblyImpure.methodCall */ $bytes = $uuid->getFields()->getBytes(); return $bytes[6] . $bytes[7] . $bytes[4] . $bytes[5] . $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3] . substr($bytes, 8); } /** * Returns a UuidInterface derived from an ordered-time binary string representation * * @throws InvalidArgumentException if $bytes is an invalid length * * @inheritDoc */ public function decodeBytes(string $bytes): UuidInterface { if (strlen($bytes) !== 16) { throw new InvalidArgumentException('$bytes string should contain 16 characters.'); } // Rearrange the bytes to their original order. $rearrangedBytes = $bytes[4] . $bytes[5] . $bytes[6] . $bytes[7] . $bytes[2] . $bytes[3] . $bytes[0] . $bytes[1] . substr($bytes, 8); $uuid = parent::decodeBytes($rearrangedBytes); /** @phpstan-ignore possiblyImpure.methodCall */ $fields = $uuid->getFields(); if (!$fields instanceof Rfc4122FieldsInterface || $fields->getVersion() !== Uuid::UUID_TYPE_TIME) { throw new UnsupportedOperationException( 'Attempting to decode a non-time-based UUID using OrderedTimeCodec', ); } return $uuid; } } ================================================ FILE: src/Codec/StringCodec.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use function bin2hex; use function hex2bin; use function implode; use function sprintf; use function str_replace; use function strlen; use function substr; /** * StringCodec encodes and decodes RFC 9562 (formerly RFC 4122) UUIDs * * @immutable */ class StringCodec implements CodecInterface { /** * Constructs a StringCodec * * @param UuidBuilderInterface $builder The builder to use when encoding UUIDs */ public function __construct(private UuidBuilderInterface $builder) { } public function encode(UuidInterface $uuid): string { /** @phpstan-ignore possiblyImpure.methodCall */ $hex = bin2hex($uuid->getFields()->getBytes()); /** @var non-empty-string */ return sprintf( '%08s-%04s-%04s-%04s-%012s', substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4), substr($hex, 16, 4), substr($hex, 20), ); } /** * @return non-empty-string */ public function encodeBinary(UuidInterface $uuid): string { /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $uuid->getFields()->getBytes(); } /** * @throws InvalidUuidStringException * * @inheritDoc */ public function decode(string $encodedUuid): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return $this->builder->build($this, $this->getBytes($encodedUuid)); } public function decodeBytes(string $bytes): UuidInterface { if (strlen($bytes) !== 16) { throw new InvalidArgumentException('$bytes string should contain 16 characters.'); } return $this->builder->build($this, $bytes); } /** * Returns the UUID builder */ protected function getBuilder(): UuidBuilderInterface { return $this->builder; } /** * Returns a byte string of the UUID */ protected function getBytes(string $encodedUuid): string { $parsedUuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}', '-'], '', $encodedUuid); $components = [ substr($parsedUuid, 0, 8), substr($parsedUuid, 8, 4), substr($parsedUuid, 12, 4), substr($parsedUuid, 16, 4), substr($parsedUuid, 20), ]; if (!Uuid::isValid(implode('-', $components))) { throw new InvalidUuidStringException('Invalid UUID string: ' . $encodedUuid); } return (string) hex2bin($parsedUuid); } } ================================================ FILE: src/Codec/TimestampFirstCombCodec.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\UuidInterface; use function bin2hex; use function sprintf; use function substr; use function substr_replace; /** * TimestampFirstCombCodec encodes and decodes COMBs, with the timestamp as the first 48 bits * * In contrast with the TimestampLastCombCodec, the TimestampFirstCombCodec adds the timestamp to the first 48 bits of * the COMB. To generate a timestamp-first COMB, set the TimestampFirstCombCodec as the codec, along with the * CombGenerator as the random generator. * * ``` * $factory = new UuidFactory(); * * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); * * $factory->setRandomGenerator(new CombGenerator( * $factory->getRandomGenerator(), * $factory->getNumberConverter(), * )); * * $timestampFirstComb = $factory->uuid4(); * ``` * * @deprecated Please migrate to {@link https://uuid.ramsey.dev/en/stable/rfc4122/version7.html Version 7, Unix Epoch Time UUIDs}. * * @link https://web.archive.org/web/20240118030355/https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys * * @immutable */ class TimestampFirstCombCodec extends StringCodec { /** * @return non-empty-string */ public function encode(UuidInterface $uuid): string { /** @phpstan-ignore possiblyImpure.methodCall */ $bytes = $this->swapBytes($uuid->getFields()->getBytes()); return sprintf( '%08s-%04s-%04s-%04s-%012s', bin2hex(substr($bytes, 0, 4)), bin2hex(substr($bytes, 4, 2)), bin2hex(substr($bytes, 6, 2)), bin2hex(substr($bytes, 8, 2)), bin2hex(substr($bytes, 10)) ); } /** * @return non-empty-string */ public function encodeBinary(UuidInterface $uuid): string { /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $this->swapBytes($uuid->getFields()->getBytes()); } /** * @throws InvalidUuidStringException * * @inheritDoc */ public function decode(string $encodedUuid): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ $bytes = $this->getBytes($encodedUuid); /** @phpstan-ignore possiblyImpure.methodCall */ return $this->getBuilder()->build($this, $this->swapBytes($bytes)); } public function decodeBytes(string $bytes): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return $this->getBuilder()->build($this, $this->swapBytes($bytes)); } /** * Swaps bytes according to the timestamp-first COMB rules * * @pure */ private function swapBytes(string $bytes): string { $first48Bits = substr($bytes, 0, 6); $last48Bits = substr($bytes, -6); return substr_replace(substr_replace($bytes, $last48Bits, 0, 6), $first48Bits, -6); } } ================================================ FILE: src/Codec/TimestampLastCombCodec.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Codec; /** * TimestampLastCombCodec encodes and decodes COMBs, with the timestamp as the last 48 bits * * The CombGenerator when used with the StringCodec (and, by proxy, the TimestampLastCombCodec) adds the timestamp to * the last 48 bits of the COMB. The TimestampLastCombCodec is provided for the sake of consistency. In practice, it is * identical to the standard StringCodec, but it may be used with the CombGenerator for additional context when reading * code. * * Consider the following code. By default, the codec used by UuidFactory is the StringCodec, but here, we explicitly * set the TimestampLastCombCodec. It is redundant, but it is clear that we intend this COMB to be generated with the * timestamp appearing at the end. * * ``` * $factory = new UuidFactory(); * * $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder())); * * $factory->setRandomGenerator(new CombGenerator( * $factory->getRandomGenerator(), * $factory->getNumberConverter(), * )); * * $timestampLastComb = $factory->uuid4(); * ``` * * @deprecated Please use {@see StringCodec} instead. * * @immutable */ class TimestampLastCombCodec extends StringCodec { } ================================================ FILE: src/Converter/Number/BigNumberConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Number; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Math\BrickMathCalculator; /** * Previously used to integrate moontoast/math as a bignum arithmetic library, BigNumberConverter is deprecated in favor * of GenericNumberConverter * * @deprecated Please transition to {@see GenericNumberConverter}. * * @immutable */ class BigNumberConverter implements NumberConverterInterface { private NumberConverterInterface $converter; public function __construct() { $this->converter = new GenericNumberConverter(new BrickMathCalculator()); } /** * @pure */ public function fromHex(string $hex): string { return $this->converter->fromHex($hex); } /** * @pure */ public function toHex(string $number): string { return $this->converter->toHex($number); } } ================================================ FILE: src/Converter/Number/DegradedNumberConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Number; /** * @deprecated DegradedNumberConverter is no longer necessary for converting numbers on 32-bit systems. Please * transition to {@see GenericNumberConverter}. * * @immutable */ class DegradedNumberConverter extends BigNumberConverter { } ================================================ FILE: src/Converter/Number/GenericNumberConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Number; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; /** * GenericNumberConverter uses the provided calculator to convert decimal numbers to and from hexadecimal values * * @immutable */ class GenericNumberConverter implements NumberConverterInterface { public function __construct(private CalculatorInterface $calculator) { } /** * @pure */ public function fromHex(string $hex): string { return $this->calculator->fromBase($hex, 16)->toString(); } /** * @pure */ public function toHex(string $number): string { /** @phpstan-ignore return.type, possiblyImpure.new */ return $this->calculator->toBase(new IntegerObject($number), 16); } } ================================================ FILE: src/Converter/NumberConverterInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter; /** * A number converter converts UUIDs from hexadecimal characters into representations of integers and vice versa * * @immutable */ interface NumberConverterInterface { /** * Converts a hexadecimal number into a string integer representation of the number * * The integer representation returned is a string representation of the integer to accommodate unsigned integers * that are greater than `PHP_INT_MAX`. * * @param string $hex The hexadecimal string representation to convert * * @return numeric-string String representation of an integer * * @pure */ public function fromHex(string $hex): string; /** * Converts a string integer representation into a hexadecimal string representation of the number * * @param string $number A string integer representation to convert; this must be a numeric string to accommodate * unsigned integers that are greater than `PHP_INT_MAX`. * * @return non-empty-string Hexadecimal string * * @pure */ public function toHex(string $number): string; } ================================================ FILE: src/Converter/Time/BigNumberTimeConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Time; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Time; /** * Previously used to integrate moontoast/math as a bignum arithmetic library, BigNumberTimeConverter is deprecated in * favor of GenericTimeConverter * * @deprecated Please transition to {@see GenericTimeConverter}. * * @immutable */ class BigNumberTimeConverter implements TimeConverterInterface { private TimeConverterInterface $converter; public function __construct() { $this->converter = new GenericTimeConverter(new BrickMathCalculator()); } public function calculateTime(string $seconds, string $microseconds): Hexadecimal { return $this->converter->calculateTime($seconds, $microseconds); } public function convertTime(Hexadecimal $uuidTimestamp): Time { return $this->converter->convertTime($uuidTimestamp); } } ================================================ FILE: src/Converter/Time/DegradedTimeConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Time; /** * @deprecated DegradedTimeConverter is no longer necessary for converting time on 32-bit systems. Please transition to * {@see GenericTimeConverter}. * * @immutable */ class DegradedTimeConverter extends BigNumberTimeConverter { } ================================================ FILE: src/Converter/Time/GenericTimeConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Time; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Math\RoundingMode; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\Time; use function explode; use function str_pad; use const STR_PAD_LEFT; /** * GenericTimeConverter uses the provided calculator to calculate and convert time values * * @immutable */ class GenericTimeConverter implements TimeConverterInterface { /** * The number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix epoch. */ private const GREGORIAN_TO_UNIX_INTERVALS = '122192928000000000'; /** * The number of 100-nanosecond intervals in one second. */ private const SECOND_INTERVALS = '10000000'; /** * The number of 100-nanosecond intervals in one microsecond. */ private const MICROSECOND_INTERVALS = '10'; public function __construct(private CalculatorInterface $calculator) { } public function calculateTime(string $seconds, string $microseconds): Hexadecimal { /** @phpstan-ignore possiblyImpure.new */ $timestamp = new Time($seconds, $microseconds); // Convert the seconds into a count of 100-nanosecond intervals. $sec = $this->calculator->multiply( $timestamp->getSeconds(), new IntegerObject(self::SECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */ ); // Convert the microseconds into a count of 100-nanosecond intervals. $usec = $this->calculator->multiply( $timestamp->getMicroseconds(), new IntegerObject(self::MICROSECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */ ); /** * Combine the intervals of seconds and microseconds and add the count of 100-nanosecond intervals from the * Gregorian calendar epoch to the Unix epoch. This gives us the correct count of 100-nanosecond intervals since * the Gregorian calendar epoch for the given seconds and microseconds. * * @var IntegerObject $uuidTime * @phpstan-ignore possiblyImpure.new */ $uuidTime = $this->calculator->add($sec, $usec, new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS)); /** * PHPStan considers CalculatorInterface::toHexadecimal, Hexadecimal:toString impure. * * @phpstan-ignore possiblyImpure.new */ return new Hexadecimal(str_pad($this->calculator->toHexadecimal($uuidTime)->toString(), 16, '0', STR_PAD_LEFT)); } public function convertTime(Hexadecimal $uuidTimestamp): Time { // From the total, subtract the number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix // epoch. This gives us the number of 100-nanosecond intervals from the Unix epoch, which also includes the microtime. $epochNanoseconds = $this->calculator->subtract( $this->calculator->toInteger($uuidTimestamp), new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS), /** @phpstan-ignore possiblyImpure.new */ ); // Convert the 100-nanosecond intervals into seconds and microseconds. $unixTimestamp = $this->calculator->divide( RoundingMode::HALF_UP, 6, $epochNanoseconds, new IntegerObject(self::SECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */ ); $split = explode('.', (string) $unixTimestamp, 2); /** @phpstan-ignore possiblyImpure.new */ return new Time($split[0], $split[1] ?? 0); } } ================================================ FILE: src/Converter/Time/PhpTimeConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Time; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\Time; use function count; use function dechex; use function explode; use function is_float; use function is_int; use function str_pad; use function strlen; use function substr; use const STR_PAD_LEFT; use const STR_PAD_RIGHT; /** * PhpTimeConverter uses built-in PHP functions and standard math operations available to the PHP programming language * to provide facilities for converting parts of time into representations that may be used in UUIDs * * @immutable */ class PhpTimeConverter implements TimeConverterInterface { /** * The number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix epoch. */ private const GREGORIAN_TO_UNIX_INTERVALS = 0x01b21dd213814000; /** * The number of 100-nanosecond intervals in one second. */ private const SECOND_INTERVALS = 10_000_000; /** * The number of 100-nanosecond intervals in one microsecond. */ private const MICROSECOND_INTERVALS = 10; private int $phpPrecision; private CalculatorInterface $calculator; private TimeConverterInterface $fallbackConverter; public function __construct( ?CalculatorInterface $calculator = null, ?TimeConverterInterface $fallbackConverter = null, ) { if ($calculator === null) { $calculator = new BrickMathCalculator(); } if ($fallbackConverter === null) { $fallbackConverter = new GenericTimeConverter($calculator); } $this->calculator = $calculator; $this->fallbackConverter = $fallbackConverter; $this->phpPrecision = (int) ini_get('precision'); } public function calculateTime(string $seconds, string $microseconds): Hexadecimal { $seconds = new IntegerObject($seconds); /** @phpstan-ignore possiblyImpure.new */ $microseconds = new IntegerObject($microseconds); /** @phpstan-ignore possiblyImpure.new */ // Calculate the count of 100-nanosecond intervals since the Gregorian calendar epoch // for the given seconds and microseconds. $uuidTime = ((int) $seconds->toString() * self::SECOND_INTERVALS) + ((int) $microseconds->toString() * self::MICROSECOND_INTERVALS) + self::GREGORIAN_TO_UNIX_INTERVALS; // Check to see whether we've overflowed the max/min integer size. // If so, we will default to a different time converter. // @phpstan-ignore function.alreadyNarrowedType (the integer value might have overflowed) if (!is_int($uuidTime)) { return $this->fallbackConverter->calculateTime( $seconds->toString(), $microseconds->toString(), ); } /** @phpstan-ignore possiblyImpure.new */ return new Hexadecimal( str_pad(dechex($uuidTime), 16, '0', STR_PAD_LEFT) ); } public function convertTime(Hexadecimal $uuidTimestamp): Time { $timestamp = $this->calculator->toInteger($uuidTimestamp); // Convert the 100-nanosecond intervals into seconds and microseconds. $splitTime = $this->splitTime( ($timestamp->toString() - self::GREGORIAN_TO_UNIX_INTERVALS) / self::SECOND_INTERVALS, ); if (count($splitTime) === 0) { return $this->fallbackConverter->convertTime($uuidTimestamp); } /** @phpstan-ignore possiblyImpure.new */ return new Time($splitTime['sec'], $splitTime['usec']); } /** * @param float | int $time The time to split into seconds and microseconds * * @return string[] * * @pure */ private function splitTime(float | int $time): array { $split = explode('.', (string) $time, 2); // If the $time value is a float but $split only has 1 element, then the float math was rounded up to the next // second, so we want to return an empty array to allow use of the fallback converter. if (is_float($time) && count($split) === 1) { return []; } if (count($split) === 1) { return ['sec' => $split[0], 'usec' => '0']; } // If the microseconds are less than six characters AND the length of the number is greater than or equal to the // PHP precision, then it's possible that we lost some precision for the microseconds. Return an empty array so // that we can choose to use the fallback converter. if (strlen($split[1]) < 6 && strlen((string) $time) >= $this->phpPrecision) { return []; } $microseconds = $split[1]; // Ensure the microseconds are no longer than 6 digits. If they are, // truncate the number to the first 6 digits and round up, if needed. if (strlen($microseconds) > 6) { $roundingDigit = (int) substr($microseconds, 6, 1); $microseconds = (int) substr($microseconds, 0, 6); if ($roundingDigit >= 5) { $microseconds++; } } return [ 'sec' => $split[0], 'usec' => str_pad((string) $microseconds, 6, '0', STR_PAD_RIGHT), ]; } } ================================================ FILE: src/Converter/Time/UnixTimeConverter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter\Time; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Math\RoundingMode; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\Time; use function explode; use function str_pad; use const STR_PAD_LEFT; /** * UnixTimeConverter converts Unix Epoch timestamps to/from hexadecimal values consisting of milliseconds elapsed since * the Unix Epoch * * @immutable */ class UnixTimeConverter implements TimeConverterInterface { private const MILLISECONDS = 1000; public function __construct(private CalculatorInterface $calculator) { } public function calculateTime(string $seconds, string $microseconds): Hexadecimal { /** @phpstan-ignore possiblyImpure.new */ $timestamp = new Time($seconds, $microseconds); // Convert the seconds into milliseconds. $sec = $this->calculator->multiply( $timestamp->getSeconds(), new IntegerObject(self::MILLISECONDS) /** @phpstan-ignore possiblyImpure.new */ ); // Convert the microseconds into milliseconds; the scale is zero because we need to discard the fractional part. $usec = $this->calculator->divide( RoundingMode::DOWN, // Always round down to stay in the previous millisecond. 0, $timestamp->getMicroseconds(), new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */ ); /** @var IntegerObject $unixTime */ $unixTime = $this->calculator->add($sec, $usec); /** @phpstan-ignore possiblyImpure.new */ return new Hexadecimal( str_pad( $this->calculator->toHexadecimal($unixTime)->toString(), 12, '0', STR_PAD_LEFT ), ); } public function convertTime(Hexadecimal $uuidTimestamp): Time { $milliseconds = $this->calculator->toInteger($uuidTimestamp); $unixTimestamp = $this->calculator->divide( RoundingMode::HALF_UP, 6, $milliseconds, new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */ ); $split = explode('.', (string) $unixTimestamp, 2); /** @phpstan-ignore possiblyImpure.new */ return new Time($split[0], $split[1] ?? '0'); } } ================================================ FILE: src/Converter/TimeConverterInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Converter; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Time; /** * A time converter converts timestamps into representations that may be used in UUIDs * * @immutable */ interface TimeConverterInterface { /** * Uses the provided seconds and micro-seconds to calculate the count of 100-nanosecond intervals since * UTC 00:00:00.00, 15 October 1582, for RFC 9562 (formerly RFC 4122) variant UUIDs * * @link https://www.rfc-editor.org/rfc/rfc9562#appendix-A RFC 9562, Appendix A. Test Vectors * * @param string $seconds A string representation of seconds since the Unix epoch for the time to calculate * @param string $microseconds A string representation of the micro-seconds associated with the time to calculate * * @return Hexadecimal The full UUID timestamp as a Hexadecimal value * * @pure */ public function calculateTime(string $seconds, string $microseconds): Hexadecimal; /** * Converts a timestamp extracted from a UUID to a Unix timestamp * * @param Hexadecimal $uuidTimestamp A hexadecimal representation of a UUID timestamp; a UUID timestamp is a count * of 100-nanosecond intervals since UTC 00:00:00.00, 15 October 1582. * * @return Time An instance of {@see Time} * * @pure */ public function convertTime(Hexadecimal $uuidTimestamp): Time; } ================================================ FILE: src/DegradedUuid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; /** * @deprecated DegradedUuid is no longer necessary to represent UUIDs on 32-bit systems. * Transition any type declarations using this class to {@see UuidInterface}. * * @immutable */ class DegradedUuid extends Uuid { } ================================================ FILE: src/DeprecatedUuidInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use DateTimeInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; /** * This interface encapsulates deprecated methods for ramsey/uuid * * @immutable */ interface DeprecatedUuidInterface { /** * @deprecated This method will be removed in 5.0.0. There is no alternative recommendation, so plan accordingly. */ public function getNumberConverter(): NumberConverterInterface; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. * * @return string[] */ public function getFieldsHex(): array; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()}. */ public function getClockSeqHiAndReservedHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()}. */ public function getClockSeqLowHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()}. */ public function getClockSequenceHex(): string; /** * @deprecated In ramsey/uuid version 5.0.0, this will be removed from the interface. It is available at * {@see UuidV1::getDateTime()}. */ public function getDateTime(): DateTimeInterface; /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getLeastSignificantBitsHex(): string; /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getMostSignificantBitsHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()}. */ public function getNodeHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()}. */ public function getTimeHiAndVersionHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()}. */ public function getTimeLowHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()}. */ public function getTimeMidHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()}. */ public function getTimestampHex(): string; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant()}. */ public function getVariant(): ?int; /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. */ public function getVersion(): ?int; } ================================================ FILE: src/DeprecatedUuidMethodsTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use DateTimeImmutable; use DateTimeInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Throwable; use function str_pad; use function substr; use const STR_PAD_LEFT; /** * This trait encapsulates deprecated methods for ramsey/uuid; this trait and its methods will be removed in ramsey/uuid 5.0.0. * * @deprecated This trait and its methods will be removed in ramsey/uuid 5.0.0. * * @immutable */ trait DeprecatedUuidMethodsTrait { /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()} and use the arbitrary-precision math * library of your choice to convert it to a string integer. */ public function getClockSeqHiAndReserved(): string { return $this->numberConverter->fromHex($this->fields->getClockSeqHiAndReserved()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()}. */ public function getClockSeqHiAndReservedHex(): string { return $this->fields->getClockSeqHiAndReserved()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()} and use the arbitrary-precision math library of * your choice to convert it to a string integer. */ public function getClockSeqLow(): string { return $this->numberConverter->fromHex($this->fields->getClockSeqLow()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()}. */ public function getClockSeqLowHex(): string { return $this->fields->getClockSeqLow()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()} and use the arbitrary-precision math library of * your choice to convert it to a string integer. */ public function getClockSequence(): string { return $this->numberConverter->fromHex($this->fields->getClockSeq()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()}. */ public function getClockSequenceHex(): string { return $this->fields->getClockSeq()->toString(); } /** * @deprecated This method will be removed in 5.0.0. There is no alternative recommendation, so plan accordingly. */ public function getNumberConverter(): NumberConverterInterface { return $this->numberConverter; } /** * @deprecated In ramsey/uuid version 5.0.0, this will be removed. It is available at {@see UuidV1::getDateTime()}. * * @return DateTimeImmutable An immutable instance of DateTimeInterface * * @throws UnsupportedOperationException if UUID is not time-based * @throws DateTimeException if DateTime throws an exception/error */ public function getDateTime(): DateTimeInterface { if ($this->fields->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); try { return new DateTimeImmutable( '@' . $time->getSeconds()->toString() . '.' . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) ); } catch (Throwable $e) { throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); } } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * * @return string[] */ public function getFieldsHex(): array { return [ 'time_low' => $this->fields->getTimeLow()->toString(), 'time_mid' => $this->fields->getTimeMid()->toString(), 'time_hi_and_version' => $this->fields->getTimeHiAndVersion()->toString(), 'clock_seq_hi_and_reserved' => $this->fields->getClockSeqHiAndReserved()->toString(), 'clock_seq_low' => $this->fields->getClockSeqLow()->toString(), 'node' => $this->fields->getNode()->toString(), ]; } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getLeastSignificantBits(): string { $leastSignificantHex = substr($this->getHex()->toString(), 16); return $this->numberConverter->fromHex($leastSignificantHex); } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getLeastSignificantBitsHex(): string { return substr($this->getHex()->toString(), 16); } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getMostSignificantBits(): string { $mostSignificantHex = substr($this->getHex()->toString(), 0, 16); return $this->numberConverter->fromHex($mostSignificantHex); } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getMostSignificantBitsHex(): string { return substr($this->getHex()->toString(), 0, 16); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()} and use the arbitrary-precision math library of your * choice to convert it to a string integer. */ public function getNode(): string { return $this->numberConverter->fromHex($this->fields->getNode()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()}. */ public function getNodeHex(): string { return $this->fields->getNode()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()} and use the arbitrary-precision math * library of your choice to convert it to a string integer. */ public function getTimeHiAndVersion(): string { return $this->numberConverter->fromHex($this->fields->getTimeHiAndVersion()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()}. */ public function getTimeHiAndVersionHex(): string { return $this->fields->getTimeHiAndVersion()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()} and use the arbitrary-precision math library of * your choice to convert it to a string integer. */ public function getTimeLow(): string { return $this->numberConverter->fromHex($this->fields->getTimeLow()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()}. */ public function getTimeLowHex(): string { return $this->fields->getTimeLow()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()} and use the arbitrary-precision math library of * your choice to convert it to a string integer. */ public function getTimeMid(): string { return $this->numberConverter->fromHex($this->fields->getTimeMid()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()}. */ public function getTimeMidHex(): string { return $this->fields->getTimeMid()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()} and use the arbitrary-precision math library of * your choice to convert it to a string integer. */ public function getTimestamp(): string { if ($this->fields->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } return $this->numberConverter->fromHex($this->fields->getTimestamp()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()}. */ public function getTimestampHex(): string { if ($this->fields->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } return $this->fields->getTimestamp()->toString(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant()}. */ public function getVariant(): ?int { return $this->fields->getVariant(); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. * If it is a {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. */ public function getVersion(): ?int { return $this->fields->getVersion(); } } ================================================ FILE: src/Exception/BuilderNotFoundException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that no suitable builder could be found */ class BuilderNotFoundException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/DateTimeException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that the PHP DateTime extension encountered an exception/error */ class DateTimeException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/DceSecurityException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate an exception occurred while dealing with DCE Security (version 2) UUIDs */ class DceSecurityException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/InvalidArgumentException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use InvalidArgumentException as PhpInvalidArgumentException; /** * Thrown to indicate that the argument received is not valid */ class InvalidArgumentException extends PhpInvalidArgumentException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/InvalidBytesException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that the bytes being operated on are invalid in some way */ class InvalidBytesException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/InvalidUuidStringException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; /** * Thrown to indicate that the string received is not a valid UUID * * The InvalidArgumentException that this extends is the ramsey/uuid version of this exception. It exists in the same * namespace as this class. */ class InvalidUuidStringException extends InvalidArgumentException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/NameException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that an error occurred while attempting to hash a namespace and name */ class NameException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/NodeException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that attempting to fetch or create a node ID encountered an error */ class NodeException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/RandomSourceException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that the source of random data encountered an error * * This exception is used mostly to indicate that random_bytes() or random_int() threw an exception. However, it may be * used for other sources of random data. */ class RandomSourceException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/TimeSourceException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate that the source of time encountered an error */ class TimeSourceException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/UnableToBuildUuidException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use RuntimeException as PhpRuntimeException; /** * Thrown to indicate a builder is unable to build a UUID */ class UnableToBuildUuidException extends PhpRuntimeException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/UnsupportedOperationException.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use LogicException as PhpLogicException; /** * Thrown to indicate that the requested operation is not supported */ class UnsupportedOperationException extends PhpLogicException implements UuidExceptionInterface { } ================================================ FILE: src/Exception/UuidExceptionInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Exception; use Throwable; interface UuidExceptionInterface extends Throwable { } ================================================ FILE: src/FeatureSet.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use Ramsey\Uuid\Builder\FallbackBuilder; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Codec\GuidStringCodec; use Ramsey\Uuid\Codec\StringCodec; use Ramsey\Uuid\Converter\Number\GenericNumberConverter; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\Time\GenericTimeConverter; use Ramsey\Uuid\Converter\Time\PhpTimeConverter; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Generator\DceSecurityGenerator; use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface; use Ramsey\Uuid\Generator\NameGeneratorFactory; use Ramsey\Uuid\Generator\NameGeneratorInterface; use Ramsey\Uuid\Generator\PeclUuidNameGenerator; use Ramsey\Uuid\Generator\PeclUuidRandomGenerator; use Ramsey\Uuid\Generator\PeclUuidTimeGenerator; use Ramsey\Uuid\Generator\RandomGeneratorFactory; use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorFactory; use Ramsey\Uuid\Generator\TimeGeneratorInterface; use Ramsey\Uuid\Generator\UnixTimeGenerator; use Ramsey\Uuid\Guid\GuidBuilder; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Math\CalculatorInterface; use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder; use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider; use Ramsey\Uuid\Provider\DceSecurityProviderInterface; use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Provider\Node\SystemNodeProvider; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\Time\SystemTimeProvider; use Ramsey\Uuid\Provider\TimeProviderInterface; use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder; use Ramsey\Uuid\Validator\GenericValidator; use Ramsey\Uuid\Validator\ValidatorInterface; use const PHP_INT_SIZE; /** * FeatureSet detects and exposes available features in the current environment * * A feature set is used by UuidFactory to determine the available features and capabilities of the environment. */ class FeatureSet { private ?TimeProviderInterface $timeProvider = null; private CalculatorInterface $calculator; private CodecInterface $codec; private DceSecurityGeneratorInterface $dceSecurityGenerator; private NameGeneratorInterface $nameGenerator; private NodeProviderInterface $nodeProvider; private NumberConverterInterface $numberConverter; private RandomGeneratorInterface $randomGenerator; private TimeConverterInterface $timeConverter; private TimeGeneratorInterface $timeGenerator; private TimeGeneratorInterface $unixTimeGenerator; private UuidBuilderInterface $builder; private ValidatorInterface $validator; /** * @param bool $useGuids True build UUIDs using the GuidStringCodec * @param bool $force32Bit True to force the use of 32-bit functionality (primarily for testing purposes) * @param bool $forceNoBigNumber (obsolete) * @param bool $ignoreSystemNode True to disable attempts to check for the system node ID (primarily for testing purposes) * @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator to generate version 1 UUIDs * * @phpstan-ignore constructor.unusedParameter ($forceNoBigNumber is deprecated) */ public function __construct( bool $useGuids = false, private bool $force32Bit = false, bool $forceNoBigNumber = false, private bool $ignoreSystemNode = false, private bool $enablePecl = false, ) { $this->randomGenerator = $this->buildRandomGenerator(); $this->setCalculator(new BrickMathCalculator()); $this->builder = $this->buildUuidBuilder($useGuids); $this->codec = $this->buildCodec($useGuids); $this->nodeProvider = $this->buildNodeProvider(); $this->nameGenerator = $this->buildNameGenerator(); $this->setTimeProvider(new SystemTimeProvider()); $this->setDceSecurityProvider(new SystemDceSecurityProvider()); $this->validator = new GenericValidator(); assert($this->timeProvider !== null); $this->unixTimeGenerator = $this->buildUnixTimeGenerator(); } /** * Returns the builder configured for this environment */ public function getBuilder(): UuidBuilderInterface { return $this->builder; } /** * Returns the calculator configured for this environment */ public function getCalculator(): CalculatorInterface { return $this->calculator; } /** * Returns the codec configured for this environment */ public function getCodec(): CodecInterface { return $this->codec; } /** * Returns the DCE Security generator configured for this environment */ public function getDceSecurityGenerator(): DceSecurityGeneratorInterface { return $this->dceSecurityGenerator; } /** * Returns the name generator configured for this environment */ public function getNameGenerator(): NameGeneratorInterface { return $this->nameGenerator; } /** * Returns the node provider configured for this environment */ public function getNodeProvider(): NodeProviderInterface { return $this->nodeProvider; } /** * Returns the number converter configured for this environment */ public function getNumberConverter(): NumberConverterInterface { return $this->numberConverter; } /** * Returns the random generator configured for this environment */ public function getRandomGenerator(): RandomGeneratorInterface { return $this->randomGenerator; } /** * Returns the time converter configured for this environment */ public function getTimeConverter(): TimeConverterInterface { return $this->timeConverter; } /** * Returns the time generator configured for this environment */ public function getTimeGenerator(): TimeGeneratorInterface { return $this->timeGenerator; } /** * Returns the Unix Epoch time generator configured for this environment */ public function getUnixTimeGenerator(): TimeGeneratorInterface { return $this->unixTimeGenerator; } /** * Returns the validator configured for this environment */ public function getValidator(): ValidatorInterface { return $this->validator; } /** * Sets the calculator to use in this environment */ public function setCalculator(CalculatorInterface $calculator): void { $this->calculator = $calculator; $this->numberConverter = $this->buildNumberConverter($calculator); $this->timeConverter = $this->buildTimeConverter($calculator); if (isset($this->timeProvider)) { $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); } } /** * Sets the DCE Security provider to use in this environment */ public function setDceSecurityProvider(DceSecurityProviderInterface $dceSecurityProvider): void { $this->dceSecurityGenerator = $this->buildDceSecurityGenerator($dceSecurityProvider); } /** * Sets the node provider to use in this environment */ public function setNodeProvider(NodeProviderInterface $nodeProvider): void { $this->nodeProvider = $nodeProvider; if (isset($this->timeProvider)) { $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); } } /** * Sets the time provider to use in this environment */ public function setTimeProvider(TimeProviderInterface $timeProvider): void { $this->timeProvider = $timeProvider; $this->timeGenerator = $this->buildTimeGenerator($timeProvider); } /** * Set the validator to use in this environment */ public function setValidator(ValidatorInterface $validator): void { $this->validator = $validator; } /** * Returns a codec configured for this environment * * @param bool $useGuids Whether to build UUIDs using the GuidStringCodec */ private function buildCodec(bool $useGuids = false): CodecInterface { if ($useGuids) { return new GuidStringCodec($this->builder); } return new StringCodec($this->builder); } /** * Returns a DCE Security generator configured for this environment */ private function buildDceSecurityGenerator( DceSecurityProviderInterface $dceSecurityProvider, ): DceSecurityGeneratorInterface { return new DceSecurityGenerator($this->numberConverter, $this->timeGenerator, $dceSecurityProvider); } /** * Returns a node provider configured for this environment */ private function buildNodeProvider(): NodeProviderInterface { if ($this->ignoreSystemNode) { return new RandomNodeProvider(); } return new FallbackNodeProvider([new SystemNodeProvider(), new RandomNodeProvider()]); } /** * Returns a number converter configured for this environment */ private function buildNumberConverter(CalculatorInterface $calculator): NumberConverterInterface { return new GenericNumberConverter($calculator); } /** * Returns a random generator configured for this environment */ private function buildRandomGenerator(): RandomGeneratorInterface { if ($this->enablePecl) { return new PeclUuidRandomGenerator(); } return (new RandomGeneratorFactory())->getGenerator(); } /** * Returns a time generator configured for this environment * * @param TimeProviderInterface $timeProvider The time provider to use with * the time generator */ private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface { if ($this->enablePecl) { return new PeclUuidTimeGenerator(); } return (new TimeGeneratorFactory($this->nodeProvider, $this->timeConverter, $timeProvider))->getGenerator(); } /** * Returns a Unix Epoch time generator configured for this environment */ private function buildUnixTimeGenerator(): TimeGeneratorInterface { return new UnixTimeGenerator($this->randomGenerator); } /** * Returns a name generator configured for this environment */ private function buildNameGenerator(): NameGeneratorInterface { if ($this->enablePecl) { return new PeclUuidNameGenerator(); } return (new NameGeneratorFactory())->getGenerator(); } /** * Returns a time converter configured for this environment */ private function buildTimeConverter(CalculatorInterface $calculator): TimeConverterInterface { $genericConverter = new GenericTimeConverter($calculator); if ($this->is64BitSystem()) { return new PhpTimeConverter($calculator, $genericConverter); } return $genericConverter; } /** * Returns a UUID builder configured for this environment * * @param bool $useGuids Whether to build UUIDs using the GuidStringCodec */ private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface { if ($useGuids) { return new GuidBuilder($this->numberConverter, $this->timeConverter); } return new FallbackBuilder([ new Rfc4122UuidBuilder($this->numberConverter, $this->timeConverter), new NonstandardUuidBuilder($this->numberConverter, $this->timeConverter), ]); } /** * Returns true if the PHP build is 64-bit */ private function is64BitSystem(): bool { return PHP_INT_SIZE === 8 && !$this->force32Bit; } } ================================================ FILE: src/Fields/FieldsInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Fields; use Serializable; /** * UUIDs consist of unsigned integers, the bytes of which are separated into fields and arranged in a particular layout * defined by the specification for the variant * * @immutable */ interface FieldsInterface extends Serializable { /** * Returns the bytes that comprise the fields * * @pure */ public function getBytes(): string; } ================================================ FILE: src/Fields/SerializableFieldsTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Fields; use ValueError; use function base64_decode; use function sprintf; use function strlen; /** * Provides common serialization functionality to fields * * @immutable */ trait SerializableFieldsTrait { /** * @param string $bytes The bytes that comprise the fields */ abstract public function __construct(string $bytes); /** * Returns the bytes that comprise the fields */ abstract public function getBytes(): string; /** * Returns a string representation of the object */ public function serialize(): string { return $this->getBytes(); } /** * @return array{bytes: string} */ public function __serialize(): array { return ['bytes' => $this->getBytes()]; } /** * Constructs the object from a serialized string representation * * @param string $data The serialized string representation of the object */ public function unserialize(string $data): void { if (strlen($data) === 16) { $this->__construct($data); } else { $this->__construct(base64_decode($data)); } } /** * @param array{bytes?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['bytes'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['bytes']); } } ================================================ FILE: src/Generator/CombGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use function bin2hex; use function explode; use function hex2bin; use function microtime; use function str_pad; use function substr; use const STR_PAD_LEFT; /** * CombGenerator generates COMBs (combined UUID/timestamp) * * The CombGenerator, when used with the StringCodec (and, by proxy, the TimestampLastCombCodec) or the * TimestampFirstCombCodec, combines the current timestamp with a UUID (hence the name "COMB"). The timestamp either * appears as the first or last 48 bits of the COMB, depending on the codec used. * * By default, COMBs will have the timestamp set as the last 48 bits of the identifier. * * ``` * $factory = new UuidFactory(); * * $factory->setRandomGenerator(new CombGenerator( * $factory->getRandomGenerator(), * $factory->getNumberConverter(), * )); * * $comb = $factory->uuid4(); * ``` * * To generate a COMB with the timestamp as the first 48 bits, set the TimestampFirstCombCodec as the codec. * * ``` * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); * ``` * * @deprecated Please migrate to {@link https://uuid.ramsey.dev/en/stable/rfc4122/version7.html Version 7, Unix Epoch Time UUIDs}. * * @link https://web.archive.org/web/20240118030355/https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys */ class CombGenerator implements RandomGeneratorInterface { public const TIMESTAMP_BYTES = 6; public function __construct( private RandomGeneratorInterface $generator, private NumberConverterInterface $numberConverter ) { } /** * @throws InvalidArgumentException if $length is not a positive integer greater than or equal to CombGenerator::TIMESTAMP_BYTES * * @inheritDoc */ public function generate(int $length): string { if ($length < self::TIMESTAMP_BYTES) { throw new InvalidArgumentException( 'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES ); } if ($length % 2 !== 0) { throw new InvalidArgumentException('Length must be an even number'); } $hash = ''; /** @phpstan-ignore greater.alwaysTrue (TIMESTAMP_BYTES constant could change in child classes) */ if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) { $hash = $this->generator->generate($length - self::TIMESTAMP_BYTES); } $lsbTime = str_pad( $this->numberConverter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT, ); return (string) hex2bin(str_pad(bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime); } /** * Returns the current timestamp as a string integer, precise to 0.00001 seconds */ private function timestamp(): string { $time = explode(' ', microtime(false)); return $time[1] . substr($time[0], 2, 5); } } ================================================ FILE: src/Generator/DceSecurityGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Exception\DceSecurityException; use Ramsey\Uuid\Provider\DceSecurityProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Uuid; use function hex2bin; use function in_array; use function pack; use function str_pad; use function strlen; use function substr_replace; use const STR_PAD_LEFT; /** * DceSecurityGenerator generates strings of binary data based on a local domain, local identifier, node ID, clock * sequence, and the current time */ class DceSecurityGenerator implements DceSecurityGeneratorInterface { private const DOMAINS = [ Uuid::DCE_DOMAIN_PERSON, Uuid::DCE_DOMAIN_GROUP, Uuid::DCE_DOMAIN_ORG, ]; /** * Upper bounds for the clock sequence in DCE Security UUIDs. */ private const CLOCK_SEQ_HIGH = 63; /** * Lower bounds for the clock sequence in DCE Security UUIDs. */ private const CLOCK_SEQ_LOW = 0; public function __construct( private NumberConverterInterface $numberConverter, private TimeGeneratorInterface $timeGenerator, private DceSecurityProviderInterface $dceSecurityProvider, ) { } public function generate( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null, ): string { if (!in_array($localDomain, self::DOMAINS)) { throw new DceSecurityException('Local domain must be a valid DCE Security domain'); } if ($localIdentifier && $localIdentifier->isNegative()) { throw new DceSecurityException( 'Local identifier out of bounds; it must be a value between 0 and 4294967295', ); } if ($clockSeq > self::CLOCK_SEQ_HIGH || $clockSeq < self::CLOCK_SEQ_LOW) { throw new DceSecurityException('Clock sequence out of bounds; it must be a value between 0 and 63'); } switch ($localDomain) { case Uuid::DCE_DOMAIN_ORG: if ($localIdentifier === null) { throw new DceSecurityException('A local identifier must be provided for the org domain'); } break; case Uuid::DCE_DOMAIN_PERSON: if ($localIdentifier === null) { $localIdentifier = $this->dceSecurityProvider->getUid(); } break; case Uuid::DCE_DOMAIN_GROUP: default: if ($localIdentifier === null) { $localIdentifier = $this->dceSecurityProvider->getGid(); } break; } $identifierHex = $this->numberConverter->toHex($localIdentifier->toString()); // The maximum value for the local identifier is 0xffffffff, or 4,294,967,295. This is 8 hexadecimal digits, so // if the length of hexadecimal digits is greater than 8, we know the value is greater than 0xffffffff. if (strlen($identifierHex) > 8) { throw new DceSecurityException( 'Local identifier out of bounds; it must be a value between 0 and 4294967295', ); } $domainByte = pack('n', $localDomain)[1]; $identifierBytes = (string) hex2bin(str_pad($identifierHex, 8, '0', STR_PAD_LEFT)); if ($node instanceof Hexadecimal) { $node = $node->toString(); } // Shift the clock sequence 8 bits to the left, so it matches 0x3f00. if ($clockSeq !== null) { $clockSeq = $clockSeq << 8; } $bytes = $this->timeGenerator->generate($node, $clockSeq); // Replace bytes in the time-based UUID with DCE Security values. $bytes = substr_replace($bytes, $identifierBytes, 0, 4); return substr_replace($bytes, $domainByte, 9, 1); } } ================================================ FILE: src/Generator/DceSecurityGeneratorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Rfc4122\UuidV2; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; /** * A DCE Security generator generates strings of binary data based on a local domain, local identifier, node ID, clock * sequence, and the current time * * @see UuidV2 */ interface DceSecurityGeneratorInterface { /** * Generate a binary string from a local domain, local identifier, node ID, clock sequence, and current time * * @param int $localDomain The local domain to use when generating bytes, according to DCE Security * @param IntegerObject | null $localIdentifier The local identifier for the given domain; this may be a UID or GID * on POSIX systems if the local domain is "person" or "group," or it may be a site-defined identifier if the * local domain is "org" * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return string A binary string */ public function generate( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null, ): string; } ================================================ FILE: src/Generator/DefaultNameGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Exception\NameException; use Ramsey\Uuid\UuidInterface; use ValueError; use function hash; /** * DefaultNameGenerator generates strings of binary data based on a namespace, name, and hashing algorithm */ class DefaultNameGenerator implements NameGeneratorInterface { /** * @pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string { try { return hash($hashAlgorithm, $ns->getBytes() . $name, true); } catch (ValueError $e) { throw new NameException( message: sprintf('Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm), previous: $e, ); } } } ================================================ FILE: src/Generator/DefaultTimeGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Exception\RandomSourceException; use Ramsey\Uuid\Exception\TimeSourceException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\TimeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; use Throwable; use function dechex; use function hex2bin; use function is_int; use function pack; use function preg_match; use function sprintf; use function str_pad; use function strlen; use const STR_PAD_LEFT; /** * DefaultTimeGenerator generates strings of binary data based on a node ID, clock sequence, and the current time */ class DefaultTimeGenerator implements TimeGeneratorInterface { public function __construct( private NodeProviderInterface $nodeProvider, private TimeConverterInterface $timeConverter, private TimeProviderInterface $timeProvider, ) { } /** * @throws InvalidArgumentException if the parameters contain invalid values * @throws RandomSourceException if random_int() throws an exception/error * * @inheritDoc */ public function generate($node = null, ?int $clockSeq = null): string { if ($node instanceof Hexadecimal) { $node = $node->toString(); } $node = $this->getValidNode($node); if ($clockSeq === null) { try { // This does not use "stable storage"; see RFC 9562, section 6.3. $clockSeq = random_int(0, 0x3fff); } catch (Throwable $exception) { throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception); } } $time = $this->timeProvider->getTime(); $uuidTime = $this->timeConverter->calculateTime( $time->getSeconds()->toString(), $time->getMicroseconds()->toString() ); $timeHex = str_pad($uuidTime->toString(), 16, '0', STR_PAD_LEFT); if (strlen($timeHex) !== 16) { throw new TimeSourceException(sprintf('The generated time of \'%s\' is larger than expected', $timeHex)); } $timeBytes = (string) hex2bin($timeHex); return $timeBytes[4] . $timeBytes[5] . $timeBytes[6] . $timeBytes[7] . $timeBytes[2] . $timeBytes[3] . $timeBytes[0] . $timeBytes[1] . pack('n*', $clockSeq) . $node; } /** * Uses the node provider given when constructing this instance to get the node ID (usually a MAC address) * * @param int | string | null $node A node value that may be used to override the node provider * * @return string 6-byte binary string representation of the node * * @throws InvalidArgumentException */ private function getValidNode(int | string | null $node): string { if ($node === null) { $node = $this->nodeProvider->getNode(); } // Convert the node to hex if it is still an integer. if (is_int($node)) { $node = dechex($node); } if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) { throw new InvalidArgumentException('Invalid node value'); } return (string) hex2bin(str_pad((string) $node, 12, '0', STR_PAD_LEFT)); } } ================================================ FILE: src/Generator/NameGeneratorFactory.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; /** * NameGeneratorFactory retrieves a default name generator, based on the environment */ class NameGeneratorFactory { /** * Returns a default name generator, based on the current environment */ public function getGenerator(): NameGeneratorInterface { return new DefaultNameGenerator(); } } ================================================ FILE: src/Generator/NameGeneratorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\UuidInterface; /** * A name generator generates strings of binary data created by hashing together a namespace with a name, according to a * hashing algorithm */ interface NameGeneratorInterface { /** * Generate a binary string from a namespace and name hashed together with the specified hashing algorithm * * @param UuidInterface $ns The namespace * @param string $name The name to use for creating a UUID * @param string $hashAlgorithm The hashing algorithm to use * * @return string A binary string * * @pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string; } ================================================ FILE: src/Generator/PeclUuidNameGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Exception\NameException; use Ramsey\Uuid\UuidInterface; use function sprintf; use function uuid_generate_md5; use function uuid_generate_sha1; use function uuid_parse; /** * PeclUuidNameGenerator generates strings of binary data from a namespace and a name, using ext-uuid * * @link https://pecl.php.net/package/uuid ext-uuid */ class PeclUuidNameGenerator implements NameGeneratorInterface { /** * @pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string { $uuid = match ($hashAlgorithm) { 'md5' => uuid_generate_md5($ns->toString(), $name), /** @phpstan-ignore possiblyImpure.functionCall */ 'sha1' => uuid_generate_sha1($ns->toString(), $name), /** @phpstan-ignore possiblyImpure.functionCall */ default => throw new NameException( sprintf('Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm), ), }; /** @phpstan-ignore possiblyImpure.functionCall */ return (string) uuid_parse($uuid); } } ================================================ FILE: src/Generator/PeclUuidRandomGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use function uuid_create; use function uuid_parse; use const UUID_TYPE_RANDOM; /** * PeclUuidRandomGenerator generates strings of random binary data using ext-uuid * * @link https://pecl.php.net/package/uuid ext-uuid */ class PeclUuidRandomGenerator implements RandomGeneratorInterface { public function generate(int $length): string { $uuid = uuid_create(UUID_TYPE_RANDOM); return (string) uuid_parse($uuid); } } ================================================ FILE: src/Generator/PeclUuidTimeGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use function uuid_create; use function uuid_parse; use const UUID_TYPE_TIME; /** * PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs, using ext-uuid * * @link https://pecl.php.net/package/uuid ext-uuid */ class PeclUuidTimeGenerator implements TimeGeneratorInterface { /** * @inheritDoc */ public function generate($node = null, ?int $clockSeq = null): string { $uuid = uuid_create(UUID_TYPE_TIME); return (string) uuid_parse($uuid); } } ================================================ FILE: src/Generator/RandomBytesGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Exception\RandomSourceException; use Throwable; /** * RandomBytesGenerator generates strings of random binary data using the built-in `random_bytes()` PHP function * * @link http://php.net/random_bytes random_bytes() */ class RandomBytesGenerator implements RandomGeneratorInterface { /** * @throws RandomSourceException if random_bytes() throws an exception/error * * @inheritDoc */ public function generate(int $length): string { try { return random_bytes($length); } catch (Throwable $exception) { throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception); } } } ================================================ FILE: src/Generator/RandomGeneratorFactory.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; /** * RandomGeneratorFactory retrieves a default random generator, based on the environment */ class RandomGeneratorFactory { /** * Returns a default random generator, based on the current environment */ public function getGenerator(): RandomGeneratorInterface { return new RandomBytesGenerator(); } } ================================================ FILE: src/Generator/RandomGeneratorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; /** * A random generator generates strings of random binary data */ interface RandomGeneratorInterface { /** * Generates a string of randomized binary data * * @param int<1, max> $length The number of bytes to generate of random binary data * * @return string A binary string */ public function generate(int $length): string; } ================================================ FILE: src/Generator/RandomLibAdapter.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use RandomLib\Factory; use RandomLib\Generator; /** * RandomLibAdapter generates strings of random binary data using the paragonie/random-lib library * * @deprecated This class will be removed in 5.0.0. Use the default RandomBytesGenerator or implement your own generator * that implements RandomGeneratorInterface. * * @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib */ class RandomLibAdapter implements RandomGeneratorInterface { private Generator $generator; /** * Constructs a RandomLibAdapter * * By default, if no Generator is passed in, this creates a high-strength generator to use when generating random * binary data. * * @param Generator | null $generator The generator to use when generating binary data */ public function __construct(?Generator $generator = null) { if ($generator === null) { $factory = new Factory(); $generator = $factory->getHighStrengthGenerator(); } $this->generator = $generator; } public function generate(int $length): string { return $this->generator->generate($length); } } ================================================ FILE: src/Generator/TimeGeneratorFactory.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\TimeProviderInterface; /** * TimeGeneratorFactory retrieves a default time generator, based on the environment */ class TimeGeneratorFactory { public function __construct( private NodeProviderInterface $nodeProvider, private TimeConverterInterface $timeConverter, private TimeProviderInterface $timeProvider, ) { } /** * Returns a default time generator, based on the current environment */ public function getGenerator(): TimeGeneratorInterface { return new DefaultTimeGenerator($this->nodeProvider, $this->timeConverter, $this->timeProvider); } } ================================================ FILE: src/Generator/TimeGeneratorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Type\Hexadecimal; /** * A time generator generates strings of binary data based on a node ID, clock sequence, and the current time */ interface TimeGeneratorInterface { /** * Generate a binary string from a node ID, clock sequence, and current time * * @param Hexadecimal | int | string | null $node A 48-bit number representing the hardware address; this number may * be represented as an integer or a hexadecimal string * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return string A binary string */ public function generate($node = null, ?int $clockSeq = null): string; } ================================================ FILE: src/Generator/UnixTimeGenerator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Generator; use Brick\Math\BigInteger; use DateTimeInterface; use Ramsey\Uuid\Type\Hexadecimal; use function assert; use function hash; use function pack; use function str_pad; use function strlen; use function substr; use function substr_replace; use function unpack; use const PHP_INT_SIZE; use const STR_PAD_LEFT; /** * UnixTimeGenerator generates bytes, combining a 48-bit timestamp in milliseconds since the Unix Epoch with 80 random bits * * Code and concepts within this class are borrowed from the symfony/uid package and are used under the terms of the MIT * license distributed with symfony/uid. * * symfony/uid is copyright (c) Fabien Potencier. * * @link https://symfony.com/components/Uid Symfony Uid component * @link https://github.com/symfony/uid/blob/4f9f537e57261519808a7ce1d941490736522bbc/UuidV7.php Symfony UuidV7 class * @link https://github.com/symfony/uid/blob/6.2/LICENSE MIT License */ class UnixTimeGenerator implements TimeGeneratorInterface { private static string $time = ''; private static ?string $seed = null; private static int $seedIndex = 0; /** @var int[] */ private static array $rand = []; /** @var int[] */ private static array $seedParts; public function __construct( private RandomGeneratorInterface $randomGenerator, private int $intSize = PHP_INT_SIZE, ) { } /** * @param Hexadecimal | int | string | null $node Unused in this generator * @param int | null $clockSeq Unused in this generator * @param DateTimeInterface | null $dateTime A date-time instance to use when generating bytes */ public function generate($node = null, ?int $clockSeq = null, ?DateTimeInterface $dateTime = null): string { if ($dateTime === null) { $time = microtime(false); $time = substr($time, 11) . substr($time, 2, 3); } else { $time = $dateTime->format('Uv'); } if ($time > self::$time || ($dateTime !== null && $time !== self::$time)) { $this->randomize($time); } else { $time = $this->increment(); } if ($this->intSize >= 8) { $time = substr(pack('J', (int) $time), -6); } else { $time = str_pad(BigInteger::of($time)->toBytes(false), 6, "\x00", STR_PAD_LEFT); } assert(strlen($time) === 6); return $time . pack('n*', self::$rand[1], self::$rand[2], self::$rand[3], self::$rand[4], self::$rand[5]); } private function randomize(string $time): void { if (self::$seed === null) { $seed = $this->randomGenerator->generate(16); self::$seed = $seed; } else { $seed = $this->randomGenerator->generate(10); } /** @var int[] $rand */ $rand = unpack('n*', $seed); $rand[1] &= 0x03ff; self::$rand = $rand; self::$time = $time; } /** * Special thanks to Nicolas Grekas () for sharing the following information: * * Within the same ms, we increment the rand part by a random 24-bit number. * * Instead of getting this number from random_bytes(), which is slow, we get it by sha512-hashing self::$seed. This * produces 64 bytes of entropy, which we need to split in a list of 24-bit numbers. `unpack()` first splits them * into 16 x 32-bit numbers; we take the first byte of each number to get 5 extra 24-bit numbers. Then, we consume * each number one-by-one and run this logic every 21 iterations. * * `self::$rand` holds the random part of the UUID, split into 5 x 16-bit numbers for x86 portability. We increment * this random part by the next 24-bit number in the `self::$seedParts` list and decrement `self::$seedIndex`. */ private function increment(): string { if (self::$seedIndex === 0 && self::$seed !== null) { self::$seed = hash('sha512', self::$seed, true); /** @var int[] $s */ $s = unpack('l*', self::$seed); $s[] = ($s[1] >> 8 & 0xff0000) | ($s[2] >> 16 & 0xff00) | ($s[3] >> 24 & 0xff); $s[] = ($s[4] >> 8 & 0xff0000) | ($s[5] >> 16 & 0xff00) | ($s[6] >> 24 & 0xff); $s[] = ($s[7] >> 8 & 0xff0000) | ($s[8] >> 16 & 0xff00) | ($s[9] >> 24 & 0xff); $s[] = ($s[10] >> 8 & 0xff0000) | ($s[11] >> 16 & 0xff00) | ($s[12] >> 24 & 0xff); $s[] = ($s[13] >> 8 & 0xff0000) | ($s[14] >> 16 & 0xff00) | ($s[15] >> 24 & 0xff); self::$seedParts = $s; self::$seedIndex = 21; } self::$rand[5] = 0xffff & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xffffff); self::$rand[4] = 0xffff & $carry = self::$rand[4] + ($carry >> 16); self::$rand[3] = 0xffff & $carry = self::$rand[3] + ($carry >> 16); self::$rand[2] = 0xffff & $carry = self::$rand[2] + ($carry >> 16); self::$rand[1] += $carry >> 16; if (0xfc00 & self::$rand[1]) { $time = self::$time; $mtime = (int) substr($time, -9); if ($this->intSize >= 8 || strlen($time) < 10) { $time = (string) ((int) $time + 1); } elseif ($mtime === 999999999) { $time = (1 + (int) substr($time, 0, -9)) . '000000000'; } else { $mtime++; $time = substr_replace($time, str_pad((string) $mtime, 9, '0', STR_PAD_LEFT), -9); } $this->randomize($time); } return self::$time; } } ================================================ FILE: src/Guid/Fields.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Guid; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Fields\SerializableFieldsTrait; use Ramsey\Uuid\Rfc4122\FieldsInterface; use Ramsey\Uuid\Rfc4122\MaxTrait; use Ramsey\Uuid\Rfc4122\NilTrait; use Ramsey\Uuid\Rfc4122\VariantTrait; use Ramsey\Uuid\Rfc4122\VersionTrait; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Uuid; use function bin2hex; use function dechex; use function hexdec; use function pack; use function sprintf; use function str_pad; use function strlen; use function substr; use function unpack; use const STR_PAD_LEFT; /** * GUIDs consist of a set of named fields, according to RFC 9562 (formerly RFC 4122) * * @see Guid * * @immutable */ final class Fields implements FieldsInterface { use MaxTrait; use NilTrait; use SerializableFieldsTrait; use VariantTrait; use VersionTrait; /** * @param string $bytes A 16-byte binary string representation of a UUID * * @throws InvalidArgumentException if the byte string is not exactly 16 bytes * @throws InvalidArgumentException if the byte string does not represent a GUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ public function __construct(private string $bytes) { if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; received ' . strlen($this->bytes) . ' bytes', ); } if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) ' . 'or Microsoft Corporation variants', ); } if (!$this->isCorrectVersion()) { throw new InvalidArgumentException('The byte string received does not contain a valid version'); } } public function getBytes(): string { return $this->bytes; } public function getTimeLow(): Hexadecimal { // Swap the bytes from little endian to network byte order. /** @var string[] $hex */ $hex = unpack( 'H*', pack( 'v*', hexdec(bin2hex(substr($this->bytes, 2, 2))), hexdec(bin2hex(substr($this->bytes, 0, 2))), ), ); return new Hexadecimal($hex[1] ?? ''); } public function getTimeMid(): Hexadecimal { // Swap the bytes from little endian to network byte order. /** @var string[] $hex */ $hex = unpack('H*', pack('v', hexdec(bin2hex(substr($this->bytes, 4, 2))))); return new Hexadecimal($hex[1] ?? ''); } public function getTimeHiAndVersion(): Hexadecimal { // Swap the bytes from little endian to network byte order. /** @var string[] $hex */ $hex = unpack('H*', pack('v', hexdec(bin2hex(substr($this->bytes, 6, 2))))); return new Hexadecimal($hex[1] ?? ''); } public function getTimestamp(): Hexadecimal { return new Hexadecimal(sprintf( '%03x%04s%08s', hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, $this->getTimeMid()->toString(), $this->getTimeLow()->toString() )); } public function getClockSeq(): Hexadecimal { if ($this->isMax()) { $clockSeq = 0xffff; } elseif ($this->isNil()) { $clockSeq = 0x0000; } else { $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; } return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); } public function getClockSeqHiAndReserved(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); } public function getClockSeqLow(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); } public function getNode(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 10))); } public function getVersion(): ?int { if ($this->isNil() || $this->isMax()) { return null; } /** @var int[] $parts */ $parts = unpack('n*', $this->bytes); return ($parts[4] >> 4) & 0x00f; } private function isCorrectVariant(): bool { if ($this->isNil() || $this->isMax()) { return true; } $variant = $this->getVariant(); return $variant === Uuid::RFC_4122 || $variant === Uuid::RESERVED_MICROSOFT; } } ================================================ FILE: src/Guid/Guid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Guid; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Uuid; /** * Guid represents a UUID with "native" (little-endian) byte order * * From Wikipedia: * * > The first three fields are unsigned 32- and 16-bit integers and are subject to swapping, while the last two fields * > consist of uninterpreted bytes, not subject to swapping. This byte swapping applies even for versions 3, 4, and 5, * > where the canonical fields do not correspond to the content of the UUID. * * The first three fields of a GUID are encoded in little-endian byte order, while the last three fields are in network * (big-endian) byte order. This is according to the history of the Microsoft GUID definition. * * According to the .NET Guid.ToByteArray method documentation: * * > Note that the order of bytes in the returned byte array is different from the string representation of a Guid value. * > The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the * > last two-byte group and the closing six-byte group is the same. * * @link https://en.wikipedia.org/wiki/Universally_unique_identifier#Variants UUID Variants on Wikipedia * @link https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid Windows GUID structure * @link https://docs.microsoft.com/en-us/dotnet/api/system.guid .NET Guid Struct * @link https://docs.microsoft.com/en-us/dotnet/api/system.guid.tobytearray .NET Guid.ToByteArray Method * * @immutable */ final class Guid extends Uuid { public function __construct( Fields $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Guid/GuidBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Guid; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\UnableToBuildUuidException; use Ramsey\Uuid\UuidInterface; use Throwable; /** * GuidBuilder builds instances of Guid * * @see Guid * * @immutable */ class GuidBuilder implements UuidBuilderInterface { /** * @param NumberConverterInterface $numberConverter The number converter to use when constructing the Guid * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to Unix timestamps */ public function __construct( private NumberConverterInterface $numberConverter, private TimeConverterInterface $timeConverter, ) { } /** * Builds and returns a Guid * * @param CodecInterface $codec The codec to use for building this Guid instance * @param string $bytes The byte string from which to construct a UUID * * @return Guid The GuidBuilder returns an instance of Ramsey\Uuid\Guid\Guid * * @pure */ public function build(CodecInterface $codec, string $bytes): UuidInterface { try { /** @phpstan-ignore possiblyImpure.new */ return new Guid($this->buildFields($bytes), $this->numberConverter, $codec, $this->timeConverter); } catch (Throwable $e) { /** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); } } /** * Proxy method to allow injecting a mock for testing * * @pure */ protected function buildFields(string $bytes): Fields { /** @phpstan-ignore possiblyImpure.new */ return new Fields($bytes); } } ================================================ FILE: src/Lazy/LazyUuidFromString.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Lazy; use DateTimeInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Fields\FieldsInterface; use Ramsey\Uuid\Rfc4122\UuidV1; use Ramsey\Uuid\Rfc4122\UuidV6; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidInterface; use ValueError; use function assert; use function bin2hex; use function hex2bin; use function sprintf; use function str_replace; use function substr; /** * Lazy version of a UUID: its format has not been determined yet, so it is mostly only usable for string/bytes * conversion. This object optimizes instantiation, serialization and string conversion time, at the cost of increased * overhead for more advanced UUID operations. * * > [!NOTE] * > The {@see FieldsInterface} does not declare methods that deprecated API relies upon: the API has been ported from * > the {@see \Ramsey\Uuid\Uuid} definition, and is deprecated anyway. * * > [!NOTE] * > The deprecated API from {@see \Ramsey\Uuid\Uuid} is in use here (on purpose): it will be removed once the * > deprecated API is gone from this class too. * * @internal this type is used internally for performance reasons and is not supposed to be directly referenced in consumer libraries. */ final class LazyUuidFromString implements UuidInterface { public const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms'; private ?UuidInterface $unwrapped = null; /** * @param non-empty-string $uuid */ public function __construct(private string $uuid) { } public static function fromBytes(string $bytes): self { $base16Uuid = bin2hex($bytes); return new self( substr($base16Uuid, 0, 8) . '-' . substr($base16Uuid, 8, 4) . '-' . substr($base16Uuid, 12, 4) . '-' . substr($base16Uuid, 16, 4) . '-' . substr($base16Uuid, 20, 12) ); } public function serialize(): string { return $this->uuid; } /** * @return array{string: non-empty-string} */ public function __serialize(): array { return ['string' => $this->uuid]; } /** * {@inheritDoc} * * @param non-empty-string $data */ public function unserialize(string $data): void { $this->uuid = $data; } /** * @param array{string?: non-empty-string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['string'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['string']); } public function getNumberConverter(): NumberConverterInterface { return ($this->unwrapped ?? $this->unwrap())->getNumberConverter(); } /** * @inheritDoc */ public function getFieldsHex(): array { return ($this->unwrapped ?? $this->unwrap())->getFieldsHex(); } public function getClockSeqHiAndReservedHex(): string { return ($this->unwrapped ?? $this->unwrap())->getClockSeqHiAndReservedHex(); } public function getClockSeqLowHex(): string { return ($this->unwrapped ?? $this->unwrap())->getClockSeqLowHex(); } public function getClockSequenceHex(): string { return ($this->unwrapped ?? $this->unwrap())->getClockSequenceHex(); } public function getDateTime(): DateTimeInterface { return ($this->unwrapped ?? $this->unwrap())->getDateTime(); } public function getLeastSignificantBitsHex(): string { return ($this->unwrapped ?? $this->unwrap())->getLeastSignificantBitsHex(); } public function getMostSignificantBitsHex(): string { return ($this->unwrapped ?? $this->unwrap())->getMostSignificantBitsHex(); } public function getNodeHex(): string { return ($this->unwrapped ?? $this->unwrap())->getNodeHex(); } public function getTimeHiAndVersionHex(): string { return ($this->unwrapped ?? $this->unwrap())->getTimeHiAndVersionHex(); } public function getTimeLowHex(): string { return ($this->unwrapped ?? $this->unwrap())->getTimeLowHex(); } public function getTimeMidHex(): string { return ($this->unwrapped ?? $this->unwrap())->getTimeMidHex(); } public function getTimestampHex(): string { return ($this->unwrapped ?? $this->unwrap())->getTimestampHex(); } public function getUrn(): string { return ($this->unwrapped ?? $this->unwrap())->getUrn(); } public function getVariant(): ?int { return ($this->unwrapped ?? $this->unwrap())->getVariant(); } public function getVersion(): ?int { return ($this->unwrapped ?? $this->unwrap())->getVersion(); } public function compareTo(UuidInterface $other): int { return ($this->unwrapped ?? $this->unwrap())->compareTo($other); } public function equals(?object $other): bool { if (!$other instanceof UuidInterface) { return false; } return $this->uuid === $other->toString(); } public function getBytes(): string { /** * @var non-empty-string * @phpstan-ignore possiblyImpure.functionCall, possiblyImpure.functionCall */ return (string) hex2bin(str_replace('-', '', $this->uuid)); } public function getFields(): FieldsInterface { return ($this->unwrapped ?? $this->unwrap())->getFields(); } public function getHex(): Hexadecimal { return ($this->unwrapped ?? $this->unwrap())->getHex(); } public function getInteger(): IntegerObject { return ($this->unwrapped ?? $this->unwrap())->getInteger(); } public function toString(): string { return $this->uuid; } public function __toString(): string { return $this->uuid; } public function jsonSerialize(): string { return $this->uuid; } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeqHiAndReserved()} * and use the arbitrary-precision math library of your choice to convert it to a string integer. */ public function getClockSeqHiAndReserved(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getClockSeqHiAndReserved()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeqLow()} and use * the arbitrary-precision math library of your choice to convert it to a string integer. */ public function getClockSeqLow(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getClockSeqLow()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeq()} and use the * arbitrary-precision math library of your choice to convert it to a string integer. */ public function getClockSequence(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getClockSeq()->toString()); } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getLeastSignificantBits(): string { $instance = ($this->unwrapped ?? $this->unwrap()); return $instance->getNumberConverter()->fromHex(substr($instance->getHex()->toString(), 16)); } /** * @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be * obtained by splitting in half the value returned by {@see UuidInterface::getHex()}. */ public function getMostSignificantBits(): string { $instance = ($this->unwrapped ?? $this->unwrap()); return $instance->getNumberConverter()->fromHex(substr($instance->getHex()->toString(), 0, 16)); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getNode()} and use the * arbitrary-precision math library of your choice to convert it to a string integer. */ public function getNode(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getNode()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeHiAndVersion()} and * use the arbitrary-precision math library of your choice to convert it to a string integer. */ public function getTimeHiAndVersion(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getTimeHiAndVersion()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeLow()} and use the * arbitrary-precision math library of your choice to convert it to a string integer. */ public function getTimeLow(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getTimeLow()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeMid()} and use the * arbitrary-precision math library of your choice to convert it to a string integer. */ public function getTimeMid(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); return $instance->getNumberConverter()->fromHex($fields->getTimeMid()->toString()); } /** * @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a * {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimestamp()} and use * the arbitrary-precision math library of your choice to convert it to a string integer. */ public function getTimestamp(): string { $instance = ($this->unwrapped ?? $this->unwrap()); $fields = $instance->getFields(); assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface); if ($fields->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } return $instance->getNumberConverter()->fromHex($fields->getTimestamp()->toString()); } public function toUuidV1(): UuidV1 { $instance = ($this->unwrapped ?? $this->unwrap()); if ($instance instanceof UuidV1) { return $instance; } assert($instance instanceof UuidV6); return $instance->toUuidV1(); } public function toUuidV6(): UuidV6 { $instance = ($this->unwrapped ?? $this->unwrap()); assert($instance instanceof UuidV6); return $instance; } private function unwrap(): UuidInterface { return $this->unwrapped = (new UuidFactory())->fromString($this->uuid); } } ================================================ FILE: src/Math/BrickMathCalculator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Math; use Brick\Math\BigDecimal; use Brick\Math\BigInteger; use Brick\Math\Exception\MathException; use Brick\Math\RoundingMode as BrickMathRounding; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Type\Decimal; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\NumberInterface; /** * A calculator using the brick/math library for arbitrary-precision arithmetic * * @immutable */ final class BrickMathCalculator implements CalculatorInterface { private const ROUNDING_MODE_MAP = [ RoundingMode::UNNECESSARY => BrickMathRounding::UNNECESSARY, RoundingMode::UP => BrickMathRounding::UP, RoundingMode::DOWN => BrickMathRounding::DOWN, RoundingMode::CEILING => BrickMathRounding::CEILING, RoundingMode::FLOOR => BrickMathRounding::FLOOR, RoundingMode::HALF_UP => BrickMathRounding::HALF_UP, RoundingMode::HALF_DOWN => BrickMathRounding::HALF_DOWN, RoundingMode::HALF_CEILING => BrickMathRounding::HALF_CEILING, RoundingMode::HALF_FLOOR => BrickMathRounding::HALF_FLOOR, RoundingMode::HALF_EVEN => BrickMathRounding::HALF_EVEN, ]; public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface { $sum = BigInteger::of($augend->toString()); foreach ($addends as $addend) { $sum = $sum->plus($addend->toString()); } /** @phpstan-ignore possiblyImpure.new */ return new IntegerObject((string) $sum); } public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface { $difference = BigInteger::of($minuend->toString()); foreach ($subtrahends as $subtrahend) { $difference = $difference->minus($subtrahend->toString()); } /** @phpstan-ignore possiblyImpure.new */ return new IntegerObject((string) $difference); } public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface { $product = BigInteger::of($multiplicand->toString()); foreach ($multipliers as $multiplier) { $product = $product->multipliedBy($multiplier->toString()); } /** @phpstan-ignore possiblyImpure.new */ return new IntegerObject((string) $product); } public function divide( int $roundingMode, int $scale, NumberInterface $dividend, NumberInterface ...$divisors, ): NumberInterface { /** @phpstan-ignore possiblyImpure.methodCall */ $brickRounding = $this->getBrickRoundingMode($roundingMode); $quotient = BigDecimal::of($dividend->toString()); foreach ($divisors as $divisor) { $quotient = $quotient->dividedBy($divisor->toString(), $scale, $brickRounding); } if ($scale === 0) { /** @phpstan-ignore possiblyImpure.new */ return new IntegerObject((string) $quotient->toBigInteger()); } /** @phpstan-ignore possiblyImpure.new */ return new Decimal((string) $quotient); } public function fromBase(string $value, int $base): IntegerObject { try { /** @phpstan-ignore possiblyImpure.new */ return new IntegerObject((string) BigInteger::fromBase($value, $base)); } catch (MathException | \InvalidArgumentException $exception) { throw new InvalidArgumentException( $exception->getMessage(), (int) $exception->getCode(), $exception ); } } public function toBase(IntegerObject $value, int $base): string { try { return BigInteger::of($value->toString())->toBase($base); } catch (MathException | \InvalidArgumentException $exception) { throw new InvalidArgumentException( $exception->getMessage(), (int) $exception->getCode(), $exception ); } } public function toHexadecimal(IntegerObject $value): Hexadecimal { /** @phpstan-ignore possiblyImpure.new */ return new Hexadecimal($this->toBase($value, 16)); } public function toInteger(Hexadecimal $value): IntegerObject { return $this->fromBase($value->toString(), 16); } /** * Maps ramsey/uuid rounding modes to those used by brick/math * * @return BrickMathRounding::* */ private function getBrickRoundingMode(int $roundingMode) { return self::ROUNDING_MODE_MAP[$roundingMode] ?? BrickMathRounding::UNNECESSARY; } } ================================================ FILE: src/Math/CalculatorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Math; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\NumberInterface; /** * A calculator performs arithmetic operations on numbers * * @immutable */ interface CalculatorInterface { /** * Returns the sum of all the provided parameters * * @param NumberInterface $augend The first addend (the integer being added to) * @param NumberInterface ...$addends The additional integers to a add to the augend * * @return NumberInterface The sum of all the parameters * * @pure */ public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface; /** * Returns the difference of all the provided parameters * * @param NumberInterface $minuend The integer being subtracted from * @param NumberInterface ...$subtrahends The integers to subtract from the minuend * * @return NumberInterface The difference after subtracting all parameters * * @pure */ public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface; /** * Returns the product of all the provided parameters * * @param NumberInterface $multiplicand The integer to be multiplied * @param NumberInterface ...$multipliers The factors by which to multiply the multiplicand * * @return NumberInterface The product of multiplying all the provided parameters * * @pure */ public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface; /** * Returns the quotient of the provided parameters divided left-to-right * * @param int $roundingMode The RoundingMode constant to use for this operation * @param int $scale The scale to use for this operation * @param NumberInterface $dividend The integer to be divided * @param NumberInterface ...$divisors The integers to divide $dividend by, in the order in which the division * operations should take place (left-to-right) * * @return NumberInterface The quotient of dividing the provided parameters left-to-right * * @pure */ public function divide( int $roundingMode, int $scale, NumberInterface $dividend, NumberInterface ...$divisors, ): NumberInterface; /** * Converts a value from an arbitrary base to a base-10 integer value * * @param string $value The value to convert * @param int $base The base to convert from (i.e., 2, 16, 32, etc.) * * @return IntegerObject The base-10 integer value of the converted value * * @pure */ public function fromBase(string $value, int $base): IntegerObject; /** * Converts a base-10 integer value to an arbitrary base * * @param IntegerObject $value The integer value to convert * @param int $base The base to convert to (i.e., 2, 16, 32, etc.) * * @return string The value represented in the specified base * * @pure */ public function toBase(IntegerObject $value, int $base): string; /** * Converts an Integer instance to a Hexadecimal instance * * @pure */ public function toHexadecimal(IntegerObject $value): Hexadecimal; /** * Converts a Hexadecimal instance to an Integer instance * * @pure */ public function toInteger(Hexadecimal $value): IntegerObject; } ================================================ FILE: src/Math/RoundingMode.php ================================================ = 0.5; otherwise, behaves as for DOWN. Note that this is the * rounding mode commonly taught at school. */ public const HALF_UP = 5; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. * * Behaves as for UP if the discarded fraction is > 0.5; otherwise, behaves as for DOWN. */ public const HALF_DOWN = 6; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity. * * If the result is positive, behaves as for HALF_UP; if negative, behaves as for HALF_DOWN. */ public const HALF_CEILING = 7; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity. * * If the result is positive, behaves as for HALF_DOWN; if negative, behaves as for HALF_UP. */ public const HALF_FLOOR = 8; /** * Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor. * * Behaves as for HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for HALF_DOWN if it's even. * * Note that this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a * sequence of calculations. It is sometimes known as "Banker's rounding", and is chiefly used in the USA. */ public const HALF_EVEN = 9; /** * Private constructor. This class is not instantiable. * * @codeCoverageIgnore */ private function __construct() { } } ================================================ FILE: src/Nonstandard/Fields.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Nonstandard; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Fields\SerializableFieldsTrait; use Ramsey\Uuid\Rfc4122\FieldsInterface; use Ramsey\Uuid\Rfc4122\VariantTrait; use Ramsey\Uuid\Type\Hexadecimal; use function bin2hex; use function dechex; use function hexdec; use function sprintf; use function str_pad; use function strlen; use function substr; use const STR_PAD_LEFT; /** * Nonstandard UUID fields do not conform to the RFC 9562 (formerly RFC 4122) standard * * Since some systems may create nonstandard UUIDs, this implements the {@see FieldsInterface}, so that functionality of * a nonstandard UUID is not degraded, in the event these UUIDs are expected to contain RFC 9562 (formerly RFC 4122) fields. * * Internally, this class represents the fields together as a 16-byte binary string. * * @immutable */ final class Fields implements FieldsInterface { use SerializableFieldsTrait; use VariantTrait; /** * @param string $bytes A 16-byte binary string representation of a UUID * * @throws InvalidArgumentException if the byte string is not exactly 16 bytes */ public function __construct(private string $bytes) { if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; received ' . strlen($this->bytes) . ' bytes', ); } } public function getBytes(): string { return $this->bytes; } public function getClockSeq(): Hexadecimal { $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); } public function getClockSeqHiAndReserved(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); } public function getClockSeqLow(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); } public function getNode(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 10))); } public function getTimeHiAndVersion(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2))); } public function getTimeLow(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4))); } public function getTimeMid(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2))); } public function getTimestamp(): Hexadecimal { return new Hexadecimal(sprintf( '%03x%04s%08s', hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, $this->getTimeMid()->toString(), $this->getTimeLow()->toString() )); } public function getVersion(): ?int { return null; } public function isNil(): bool { return false; } public function isMax(): bool { return false; } } ================================================ FILE: src/Nonstandard/Uuid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Nonstandard; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Uuid as BaseUuid; /** * Nonstandard\Uuid is a UUID that doesn't conform to RFC 9562 (formerly RFC 4122) * * @immutable * @pure */ final class Uuid extends BaseUuid { public function __construct( Fields $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Nonstandard/UuidBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Nonstandard; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\UnableToBuildUuidException; use Ramsey\Uuid\UuidInterface; use Throwable; /** * Nonstandard\UuidBuilder builds instances of Nonstandard\Uuid * * @immutable */ class UuidBuilder implements UuidBuilderInterface { /** * @param NumberConverterInterface $numberConverter The number converter to use when constructing the Nonstandard\Uuid * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to Unix timestamps */ public function __construct( private NumberConverterInterface $numberConverter, private TimeConverterInterface $timeConverter, ) { } /** * Builds and returns a Nonstandard\Uuid * * @param CodecInterface $codec The codec to use for building this instance * @param string $bytes The byte string from which to construct a UUID * * @return Uuid The Nonstandard\UuidBuilder returns an instance of Nonstandard\Uuid * * @pure */ public function build(CodecInterface $codec, string $bytes): UuidInterface { try { /** @phpstan-ignore possiblyImpure.new */ return new Uuid($this->buildFields($bytes), $this->numberConverter, $codec, $this->timeConverter); } catch (Throwable $e) { /** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); } } /** * Proxy method to allow injecting a mock for testing * * @pure */ protected function buildFields(string $bytes): Fields { /** @phpstan-ignore possiblyImpure.new */ return new Fields($bytes); } } ================================================ FILE: src/Nonstandard/UuidV6.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Nonstandard; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Rfc4122\TimeTrait; use Ramsey\Uuid\Rfc4122\UuidInterface; use Ramsey\Uuid\Rfc4122\UuidV1; use Ramsey\Uuid\Uuid as BaseUuid; /** * Reordered time, or version 6, UUIDs include timestamp, clock sequence, and node values that are combined into a * 128-bit unsigned integer * * @deprecated Use {@see \Ramsey\Uuid\Rfc4122\UuidV6} instead. * * @link https://github.com/uuid6/uuid6-ietf-draft UUID version 6 IETF draft * @link http://gh.peabody.io/uuidv6/ "Version 6" UUIDs * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.6 RFC 9562, 5.6. UUID Version 6 * * @immutable */ class UuidV6 extends BaseUuid implements UuidInterface { use TimeTrait; /** * Creates a version 6 (reordered Gregorian time) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== BaseUuid::UUID_TYPE_REORDERED_TIME) { throw new InvalidArgumentException( 'Fields used to create a UuidV6 must represent a version 6 (reordered time) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } /** * Converts this UUID into an instance of a version 1 UUID */ public function toUuidV1(): UuidV1 { $hex = $this->getHex()->toString(); $hex = substr($hex, 7, 5) . substr($hex, 13, 3) . substr($hex, 3, 4) . '1' . substr($hex, 0, 3) . substr($hex, 16); /** @var LazyUuidFromString $uuid */ $uuid = BaseUuid::fromBytes((string) hex2bin($hex)); return $uuid->toUuidV1(); } /** * Converts a version 1 UUID into an instance of a version 6 UUID */ public static function fromUuidV1(UuidV1 $uuidV1): \Ramsey\Uuid\Rfc4122\UuidV6 { $hex = $uuidV1->getHex()->toString(); $hex = substr($hex, 13, 3) . substr($hex, 8, 4) . substr($hex, 0, 5) . '6' . substr($hex, 5, 3) . substr($hex, 16); /** @var LazyUuidFromString $uuid */ $uuid = BaseUuid::fromBytes((string) hex2bin($hex)); return $uuid->toUuidV6(); } } ================================================ FILE: src/Provider/Dce/SystemDceSecurityProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Dce; use Ramsey\Uuid\Exception\DceSecurityException; use Ramsey\Uuid\Provider\DceSecurityProviderInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; use function escapeshellarg; use function preg_split; use function str_getcsv; use function strrpos; use function strtolower; use function strtoupper; use function substr; use function trim; use const PREG_SPLIT_NO_EMPTY; /** * SystemDceSecurityProvider retrieves the user or group identifiers from the system */ class SystemDceSecurityProvider implements DceSecurityProviderInterface { /** * @throws DceSecurityException if unable to get a user identifier * * @inheritDoc */ public function getUid(): IntegerObject { /** @var IntegerObject | int | float | string | null $uid */ static $uid = null; if ($uid instanceof IntegerObject) { return $uid; } if ($uid === null) { $uid = $this->getSystemUid(); } if ($uid === '') { throw new DceSecurityException( 'Unable to get a user identifier using the system DCE Security provider; please provide a custom ' . 'identifier or use a different provider', ); } $uid = new IntegerObject($uid); return $uid; } /** * @throws DceSecurityException if unable to get a group identifier * * @inheritDoc */ public function getGid(): IntegerObject { /** @var IntegerObject | int | float | string | null $gid */ static $gid = null; if ($gid instanceof IntegerObject) { return $gid; } if ($gid === null) { $gid = $this->getSystemGid(); } if ($gid === '') { throw new DceSecurityException( 'Unable to get a group identifier using the system DCE Security provider; please provide a custom ' . 'identifier or use a different provider', ); } $gid = new IntegerObject($gid); return $gid; } /** * Returns the UID from the system */ private function getSystemUid(): string { if (!$this->hasShellExec()) { return ''; } return match ($this->getOs()) { 'WIN' => $this->getWindowsUid(), default => trim((string) shell_exec('id -u')), }; } /** * Returns the GID from the system */ private function getSystemGid(): string { if (!$this->hasShellExec()) { return ''; } return match ($this->getOs()) { 'WIN' => $this->getWindowsGid(), default => trim((string) shell_exec('id -g')), }; } /** * Returns true if shell_exec() is available for use */ private function hasShellExec(): bool { return !str_contains(strtolower((string) ini_get('disable_functions')), 'shell_exec'); } /** * Returns the PHP_OS string */ private function getOs(): string { /** @var string $phpOs */ $phpOs = constant('PHP_OS'); return strtoupper(substr($phpOs, 0, 3)); } /** * Returns the user identifier for a user on a Windows system * * Windows does not have the same concept as an effective POSIX UID for the running script. Instead, each user is * uniquely identified by an SID (security identifier). The SID includes three 32-bit unsigned integers that make up * a unique domain identifier, followed by an RID (relative identifier) that we will use as the UID. The primary * caveat is that this UID may not be unique to the system, since it is, instead, unique to the domain. * * @link https://www.lifewire.com/what-is-an-sid-number-2626005 What Is an SID Number? * @link https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/81d92bba-d22b-4a8c-908a-554ab29148ab Well-known SID Structures * @link https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers#well-known-sids Well-known SIDs * @link https://www.windows-commandline.com/get-sid-of-user/ Get SID of user */ private function getWindowsUid(): string { $response = shell_exec('whoami /user /fo csv /nh'); if ($response === null) { return ''; } $sid = str_getcsv(trim((string) $response), escape: '\\')[1] ?? ''; if (($lastHyphen = strrpos($sid, '-')) === false) { return ''; } return trim(substr($sid, $lastHyphen + 1)); } /** * Returns a group identifier for a user on a Windows system * * Since Windows does not have the same concept as an effective POSIX GID for the running script, we will get the * local group memberships for the user running the script. Then, we will get the SID (security identifier) for the * first group that appears in that list. Finally, we will return the RID (relative identifier) for the group and * use that as the GID. * * @link https://www.windows-commandline.com/list-of-user-groups-command-line/ List of user groups command line */ private function getWindowsGid(): string { $response = shell_exec('net user %username% | findstr /b /i "Local Group Memberships"'); if ($response === null) { return ''; } $userGroups = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); $firstGroup = trim($userGroups[1] ?? '', "* \t\n\r\0\x0B"); if ($firstGroup === '') { return ''; } $response = shell_exec('wmic group get name,sid | findstr /b /i ' . escapeshellarg($firstGroup)); if ($response === null) { return ''; } $userGroup = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); $sid = $userGroup[1] ?? ''; if (($lastHyphen = strrpos($sid, '-')) === false) { return ''; } return trim(substr($sid, $lastHyphen + 1)); } } ================================================ FILE: src/Provider/DceSecurityProviderInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider; use Ramsey\Uuid\Rfc4122\UuidV2; use Ramsey\Uuid\Type\Integer as IntegerObject; /** * A DCE provider provides access to local domain identifiers for version 2, DCE Security, UUIDs * * @see UuidV2 */ interface DceSecurityProviderInterface { /** * Returns a user identifier for the system * * @link https://en.wikipedia.org/wiki/User_identifier User identifier */ public function getUid(): IntegerObject; /** * Returns a group identifier for the system * * @link https://en.wikipedia.org/wiki/Group_identifier Group identifier */ public function getGid(): IntegerObject; } ================================================ FILE: src/Provider/Node/FallbackNodeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Exception\NodeException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; /** * FallbackNodeProvider retrieves the system node ID by stepping through a list of providers until a node ID can be obtained */ class FallbackNodeProvider implements NodeProviderInterface { /** * @param iterable $providers Array of node providers */ public function __construct(private iterable $providers) { } public function getNode(): Hexadecimal { $lastProviderException = null; foreach ($this->providers as $provider) { try { return $provider->getNode(); } catch (NodeException $exception) { $lastProviderException = $exception; continue; } } throw new NodeException(message: 'Unable to find a suitable node provider', previous: $lastProviderException); } } ================================================ FILE: src/Provider/Node/NodeProviderCollection.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Node; use Ramsey\Collection\AbstractCollection; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; /** * A collection of NodeProviderInterface objects * * @deprecated this class has been deprecated and will be removed in 5.0.0. The use-case for this class comes from a * pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced at runtime: * that is no longer necessary, now that you can safely verify your code to be correct and use more generic types * like `iterable` instead. * * @extends AbstractCollection */ class NodeProviderCollection extends AbstractCollection { public function getType(): string { return NodeProviderInterface::class; } /** * Re-constructs the object from its serialized form * * @param string $serialized The serialized PHP string to unserialize into a UuidInterface instance */ public function unserialize($serialized): void { /** @var array $data */ $data = unserialize($serialized, [ 'allowed_classes' => [ Hexadecimal::class, RandomNodeProvider::class, StaticNodeProvider::class, SystemNodeProvider::class, ], ]); /** @phpstan-ignore-next-line */ $this->data = array_filter($data, fn ($unserialized): bool => $unserialized instanceof NodeProviderInterface); } } ================================================ FILE: src/Provider/Node/RandomNodeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Exception\RandomSourceException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; use Throwable; use function bin2hex; use function dechex; use function hex2bin; use function hexdec; use function str_pad; use function substr; use const STR_PAD_LEFT; /** * RandomNodeProvider generates a random node ID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.10 RFC 9562, 6.10. UUIDs That Do Not Identify the Host */ class RandomNodeProvider implements NodeProviderInterface { public function getNode(): Hexadecimal { try { $nodeBytes = random_bytes(6); } catch (Throwable $exception) { throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception); } // Split the node bytes for math on 32-bit systems. $nodeMsb = substr($nodeBytes, 0, 3); $nodeLsb = substr($nodeBytes, 3); // Set the multicast bit; see RFC 9562, section 6.10. $nodeMsb = hex2bin(str_pad(dechex(hexdec(bin2hex($nodeMsb)) | 0x010000), 6, '0', STR_PAD_LEFT)); return new Hexadecimal(str_pad(bin2hex($nodeMsb . $nodeLsb), 12, '0', STR_PAD_LEFT)); } } ================================================ FILE: src/Provider/Node/StaticNodeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; use function dechex; use function hexdec; use function str_pad; use function substr; use const STR_PAD_LEFT; /** * StaticNodeProvider provides a static node value with the multicast bit set * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.10 RFC 9562, 6.10. UUIDs That Do Not Identify the Host */ class StaticNodeProvider implements NodeProviderInterface { private Hexadecimal $node; /** * @param Hexadecimal $node The static node value to use */ public function __construct(Hexadecimal $node) { if (strlen($node->toString()) > 12) { throw new InvalidArgumentException('Static node value cannot be greater than 12 hexadecimal characters'); } $this->node = $this->setMulticastBit($node); } public function getNode(): Hexadecimal { return $this->node; } /** * Set the multicast bit for the static node value */ private function setMulticastBit(Hexadecimal $node): Hexadecimal { $nodeHex = str_pad($node->toString(), 12, '0', STR_PAD_LEFT); $firstOctet = substr($nodeHex, 0, 2); $firstOctet = str_pad(dechex(hexdec($firstOctet) | 0x01), 2, '0', STR_PAD_LEFT); return new Hexadecimal($firstOctet . substr($nodeHex, 2)); } } ================================================ FILE: src/Provider/Node/SystemNodeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Exception\NodeException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; use function array_filter; use function array_map; use function array_walk; use function count; use function ob_get_clean; use function ob_start; use function preg_match; use function preg_match_all; use function reset; use function str_contains; use function str_replace; use function strtolower; use function strtoupper; use function substr; use const GLOB_NOSORT; use const PREG_PATTERN_ORDER; /** * SystemNodeProvider retrieves the system node ID, if possible * * The system node ID, or host ID, is often the same as the MAC address for a network interface on the host. */ class SystemNodeProvider implements NodeProviderInterface { /** * Pattern to match nodes in `ifconfig` and `ipconfig` output. */ private const IFCONFIG_PATTERN = '/[^:]([0-9a-f]{2}([:-])[0-9a-f]{2}(\2[0-9a-f]{2}){4})[^:]/i'; /** * Pattern to match nodes in sysfs stream output. */ private const SYSFS_PATTERN = '/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i'; public function getNode(): Hexadecimal { $node = $this->getNodeFromSystem(); if ($node === '') { throw new NodeException('Unable to fetch a node for this system'); } return new Hexadecimal($node); } /** * Returns the system node if found */ protected function getNodeFromSystem(): string { /** @var string | null $node */ static $node = null; if ($node !== null) { return $node; } // First, try a Linux-specific approach. $node = $this->getSysfs(); if ($node === '') { // Search ifconfig output for MAC addresses & return the first one. $node = $this->getIfconfig(); } $node = str_replace([':', '-'], '', $node); return $node; } /** * Returns the network interface configuration for the system * * @codeCoverageIgnore */ protected function getIfconfig(): string { if (str_contains(strtolower((string) ini_get('disable_functions')), 'passthru')) { return ''; } /** @var string $phpOs */ $phpOs = constant('PHP_OS'); ob_start(); switch (strtoupper(substr($phpOs, 0, 3))) { case 'WIN': passthru('ipconfig /all 2>&1'); break; case 'DAR': passthru('ifconfig 2>&1'); break; case 'FRE': passthru('netstat -i -f link 2>&1'); break; case 'LIN': default: passthru('netstat -ie 2>&1'); break; } $ifconfig = (string) ob_get_clean(); if (preg_match_all(self::IFCONFIG_PATTERN, $ifconfig, $matches, PREG_PATTERN_ORDER)) { foreach ($matches[1] as $iface) { if ($iface !== '00:00:00:00:00:00' && $iface !== '00-00-00-00-00-00') { return $iface; } } } return ''; } /** * Returns MAC address from the first system interface via the sysfs interface */ protected function getSysfs(): string { /** @var string $phpOs */ $phpOs = constant('PHP_OS'); if (strtoupper($phpOs) !== 'LINUX') { return ''; } $addressPaths = glob('/sys/class/net/*/address', GLOB_NOSORT); if ($addressPaths === false || count($addressPaths) === 0) { return ''; } /** @var array $macs */ $macs = []; array_walk($addressPaths, function (string $addressPath) use (&$macs): void { if (is_readable($addressPath)) { $macs[] = file_get_contents($addressPath); } }); /** @var callable $trim */ $trim = 'trim'; $macs = array_map($trim, $macs); // Remove invalid entries. $macs = array_filter($macs, function (mixed $address): bool { assert(is_string($address)); return $address !== '00:00:00:00:00:00' && preg_match(self::SYSFS_PATTERN, $address); }); /** @var bool | string $mac */ $mac = reset($macs); return (string) $mac; } } ================================================ FILE: src/Provider/NodeProviderInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider; use Ramsey\Uuid\Type\Hexadecimal; /** * A node provider retrieves or generates a node ID */ interface NodeProviderInterface { /** * Returns a node ID * * @return Hexadecimal The node ID as a hexadecimal string */ public function getNode(): Hexadecimal; } ================================================ FILE: src/Provider/Time/FixedTimeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Time; use Ramsey\Uuid\Provider\TimeProviderInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\Time; /** * FixedTimeProvider uses a known time to provide the time * * This provider allows the use of a previously generated, or known, time when generating time-based UUIDs. */ class FixedTimeProvider implements TimeProviderInterface { public function __construct(private Time $time) { } /** * Sets the `usec` component of the time * * @param IntegerObject | int | string $value The `usec` value to set */ public function setUsec($value): void { $this->time = new Time($this->time->getSeconds(), $value); } /** * Sets the `sec` component of the time * * @param IntegerObject | int | string $value The `sec` value to set */ public function setSec($value): void { $this->time = new Time($value, $this->time->getMicroseconds()); } public function getTime(): Time { return $this->time; } } ================================================ FILE: src/Provider/Time/SystemTimeProvider.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider\Time; use Ramsey\Uuid\Provider\TimeProviderInterface; use Ramsey\Uuid\Type\Time; use function gettimeofday; /** * SystemTimeProvider retrieves the current time using built-in PHP functions */ class SystemTimeProvider implements TimeProviderInterface { public function getTime(): Time { $time = gettimeofday(); return new Time($time['sec'], $time['usec']); } } ================================================ FILE: src/Provider/TimeProviderInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Provider; use Ramsey\Uuid\Type\Time; /** * A time provider retrieves the current time */ interface TimeProviderInterface { /** * Returns a time object */ public function getTime(): Time; } ================================================ FILE: src/Rfc4122/Fields.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Fields\SerializableFieldsTrait; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Uuid; use function bin2hex; use function dechex; use function hexdec; use function sprintf; use function str_pad; use function strlen; use function substr; use function unpack; use const STR_PAD_LEFT; /** * RFC 9562 (formerly RFC 4122) variant UUIDs consist of a set of named fields * * Internally, this class represents the fields together as a 16-byte binary string. * * @immutable */ final class Fields implements FieldsInterface { use MaxTrait; use NilTrait; use SerializableFieldsTrait; use VariantTrait; use VersionTrait; /** * @param string $bytes A 16-byte binary string representation of a UUID * * @throws InvalidArgumentException if the byte string is not exactly 16 bytes * @throws InvalidArgumentException if the byte string does not represent an RFC 9562 (formerly RFC 4122) UUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ public function __construct(private string $bytes) { if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' . 'received ' . strlen($this->bytes) . ' bytes', ); } if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant', ); } if (!$this->isCorrectVersion()) { throw new InvalidArgumentException( 'The byte string received does not contain a valid RFC 9562 (formerly RFC 4122) version', ); } } /** * @pure */ public function getBytes(): string { return $this->bytes; } public function getClockSeq(): Hexadecimal { if ($this->isMax()) { $clockSeq = 0xffff; } elseif ($this->isNil()) { $clockSeq = 0x0000; } else { $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; } return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); } public function getClockSeqHiAndReserved(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1))); } public function getClockSeqLow(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1))); } public function getNode(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 10))); } public function getTimeHiAndVersion(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2))); } public function getTimeLow(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4))); } public function getTimeMid(): Hexadecimal { return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2))); } /** * Returns the full 60-bit timestamp, without the version * * For version 2 UUIDs, the time_low field is the local identifier and should not be returned as part of the time. * For this reason, we set the bottom 32 bits of the timestamp to 0's. As a result, there is some loss of timestamp * fidelity, for version 2 UUIDs. The timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 minutes, 9 * seconds, and 496,730 microseconds). * * For version 6 UUIDs, the timestamp order is reversed from the typical RFC 9562 (formerly RFC 4122) order (the * time bits are in the correct bit order, so that it is monotonically increasing). In returning the timestamp * value, we put the bits in the order: time_low + time_mid + time_hi. */ public function getTimestamp(): Hexadecimal { return new Hexadecimal(match ($this->getVersion()) { Uuid::UUID_TYPE_DCE_SECURITY => sprintf( '%03x%04s%08s', hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, $this->getTimeMid()->toString(), '' ), Uuid::UUID_TYPE_REORDERED_TIME => sprintf( '%08s%04s%03x', $this->getTimeLow()->toString(), $this->getTimeMid()->toString(), hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff ), // The Unix timestamp in version 7 UUIDs is a 48-bit number, but for consistency, we will return a 60-bit // number, padded to the left with zeros. Uuid::UUID_TYPE_UNIX_TIME => sprintf( '%011s%04s', $this->getTimeLow()->toString(), $this->getTimeMid()->toString(), ), default => sprintf( '%03x%04s%08s', hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, $this->getTimeMid()->toString(), $this->getTimeLow()->toString() ), }); } public function getVersion(): ?int { if ($this->isNil() || $this->isMax()) { return null; } /** @var int[] $parts */ $parts = unpack('n*', $this->bytes); return $parts[4] >> 12; } private function isCorrectVariant(): bool { if ($this->isNil() || $this->isMax()) { return true; } return $this->getVariant() === Uuid::RFC_4122; } } ================================================ FILE: src/Rfc4122/FieldsInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Fields\FieldsInterface as BaseFieldsInterface; use Ramsey\Uuid\Type\Hexadecimal; /** * UUID fields, as defined by RFC 4122 * * This interface defines the fields of an RFC 4122 variant UUID. Since RFC 9562 removed the concept of fields and * instead defined layouts that are specific to a given version, this interface is a legacy artifact of the earlier, and * now obsolete, RFC 4122. * * The fields of an RFC 4122 variant UUID are: * * * **time_low**: The low field of the timestamp, an unsigned 32-bit integer * * **time_mid**: The middle field of the timestamp, an unsigned 16-bit integer * * **time_hi_and_version**: The high field of the timestamp multiplexed with the version number, an unsigned 16-bit integer * * **clock_seq_hi_and_reserved**: The high field of the clock sequence multiplexed with the variant, an unsigned 8-bit integer * * **clock_seq_low**: The low field of the clock sequence, an unsigned 8-bit integer * * **node**: The spatially unique node identifier, an unsigned 48-bit integer * * @link https://www.rfc-editor.org/rfc/rfc4122#section-4.1 RFC 4122, 4.1. Format * @link https://www.rfc-editor.org/rfc/rfc9562#section-4 RFC 9562, 4. UUID Format * * @immutable */ interface FieldsInterface extends BaseFieldsInterface { /** * Returns the full 16-bit clock sequence, with the variant bits (two most significant bits) masked out */ public function getClockSeq(): Hexadecimal; /** * Returns the high field of the clock sequence multiplexed with the variant */ public function getClockSeqHiAndReserved(): Hexadecimal; /** * Returns the low field of the clock sequence */ public function getClockSeqLow(): Hexadecimal; /** * Returns the node field */ public function getNode(): Hexadecimal; /** * Returns the high field of the timestamp multiplexed with the version */ public function getTimeHiAndVersion(): Hexadecimal; /** * Returns the low field of the timestamp */ public function getTimeLow(): Hexadecimal; /** * Returns the middle field of the timestamp */ public function getTimeMid(): Hexadecimal; /** * Returns the full 60-bit timestamp, without the version */ public function getTimestamp(): Hexadecimal; /** * Returns the variant * * The variant number describes the layout of the UUID. The variant number has the following meaning: * * - 0 - Reserved for NCS backward compatibility * - 2 - The RFC 9562 (formerly RFC 4122) variant * - 6 - Reserved, Microsoft Corporation backward compatibility * - 7 - Reserved for future definition * * For RFC 9562 (formerly RFC 4122) variant UUIDs, this value should always be the integer `2`. * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public function getVariant(): int; /** * Returns the UUID version * * The version number describes how the UUID was generated and has the following meaning: * * 1. Gregorian time UUID * 2. DCE security UUID * 3. Name-based UUID hashed with MD5 * 4. Randomly generated UUID * 5. Name-based UUID hashed with SHA-1 * 6. Reordered Gregorian time UUID * 7. Unix Epoch time UUID * 8. Custom format UUID * * This returns `null` if the UUID is not an RFC 9562 (formerly RFC 4122) variant, since the version is only * meaningful for this variant. * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field * * @pure */ public function getVersion(): ?int; /** * Returns true if these fields represent a nil UUID * * The nil UUID is a special form of UUID that is specified to have all 128 bits set to zero. * * @pure */ public function isNil(): bool; } ================================================ FILE: src/Rfc4122/MaxTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; /** * Provides common functionality for max UUIDs * * @immutable */ trait MaxTrait { /** * Returns the bytes that comprise the fields * * @pure */ abstract public function getBytes(): string; /** * Returns true if the byte string represents a max UUID * * @pure */ public function isMax(): bool { return $this->getBytes() === "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; } } ================================================ FILE: src/Rfc4122/MaxUuid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Uuid; /** * The max UUID is a special form of UUID that has all 128 bits set to one (`1`) * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.10 RFC 9562, 5.10. Max UUID * * @immutable */ final class MaxUuid extends Uuid implements UuidInterface { } ================================================ FILE: src/Rfc4122/NilTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; /** * Provides common functionality for nil UUIDs * * @immutable */ trait NilTrait { /** * Returns the bytes that comprise the fields * * @pure */ abstract public function getBytes(): string; /** * Returns true if the byte string represents a nil UUID */ public function isNil(): bool { return $this->getBytes() === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; } } ================================================ FILE: src/Rfc4122/NilUuid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Uuid; /** * The nil UUID is a special form of UUID that has all 128 bits set to zero (`0`) * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.9 RFC 9562, 5.9. Nil UUID * * @immutable */ final class NilUuid extends Uuid implements UuidInterface { } ================================================ FILE: src/Rfc4122/TimeTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use DateTimeImmutable; use DateTimeInterface; use Ramsey\Uuid\Exception\DateTimeException; use Throwable; use function str_pad; use const STR_PAD_LEFT; /** * Provides common functionality for getting the time from a time-based UUID * * @immutable */ trait TimeTrait { /** * Returns a DateTimeInterface object representing the timestamp associated with the UUID * * @return DateTimeImmutable A PHP DateTimeImmutable instance representing the timestamp of a time-based UUID */ public function getDateTime(): DateTimeInterface { $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); try { return new DateTimeImmutable( '@' . $time->getSeconds()->toString() . '.' . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) ); } catch (Throwable $e) { throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); } } } ================================================ FILE: src/Rfc4122/UuidBuilder.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\Time\UnixTimeConverter; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\UnableToBuildUuidException; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Rfc4122\UuidInterface as Rfc4122UuidInterface; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Throwable; /** * UuidBuilder builds instances of RFC 9562 (formerly 4122) UUIDs * * @immutable */ class UuidBuilder implements UuidBuilderInterface { private TimeConverterInterface $unixTimeConverter; /** * Constructs the DefaultUuidBuilder * * @param NumberConverterInterface $numberConverter The number converter to use when constructing the Uuid * @param TimeConverterInterface $timeConverter The time converter to use for converting Gregorian time extracted * from version 1, 2, and 6 UUIDs to Unix timestamps * @param TimeConverterInterface | null $unixTimeConverter The time converter to use for converter Unix Epoch time * extracted from version 7 UUIDs to Unix timestamps */ public function __construct( private NumberConverterInterface $numberConverter, private TimeConverterInterface $timeConverter, ?TimeConverterInterface $unixTimeConverter = null, ) { $this->unixTimeConverter = $unixTimeConverter ?? new UnixTimeConverter(new BrickMathCalculator()); } /** * Builds and returns a Uuid * * @param CodecInterface $codec The codec to use for building this Uuid instance * @param string $bytes The byte string from which to construct a UUID * * @return Rfc4122UuidInterface UuidBuilder returns instances of Rfc4122UuidInterface * * @pure */ public function build(CodecInterface $codec, string $bytes): UuidInterface { try { /** @var Fields $fields */ $fields = $this->buildFields($bytes); if ($fields->isNil()) { /** @phpstan-ignore possiblyImpure.new */ return new NilUuid($fields, $this->numberConverter, $codec, $this->timeConverter); } if ($fields->isMax()) { /** @phpstan-ignore possiblyImpure.new */ return new MaxUuid($fields, $this->numberConverter, $codec, $this->timeConverter); } return match ($fields->getVersion()) { /** @phpstan-ignore possiblyImpure.new */ Uuid::UUID_TYPE_TIME => new UuidV1($fields, $this->numberConverter, $codec, $this->timeConverter), Uuid::UUID_TYPE_DCE_SECURITY /** @phpstan-ignore possiblyImpure.new */ => new UuidV2($fields, $this->numberConverter, $codec, $this->timeConverter), /** @phpstan-ignore possiblyImpure.new */ Uuid::UUID_TYPE_HASH_MD5 => new UuidV3($fields, $this->numberConverter, $codec, $this->timeConverter), /** @phpstan-ignore possiblyImpure.new */ Uuid::UUID_TYPE_RANDOM => new UuidV4($fields, $this->numberConverter, $codec, $this->timeConverter), /** @phpstan-ignore possiblyImpure.new */ Uuid::UUID_TYPE_HASH_SHA1 => new UuidV5($fields, $this->numberConverter, $codec, $this->timeConverter), Uuid::UUID_TYPE_REORDERED_TIME /** @phpstan-ignore possiblyImpure.new */ => new UuidV6($fields, $this->numberConverter, $codec, $this->timeConverter), Uuid::UUID_TYPE_UNIX_TIME /** @phpstan-ignore possiblyImpure.new */ => new UuidV7($fields, $this->numberConverter, $codec, $this->unixTimeConverter), /** @phpstan-ignore possiblyImpure.new */ Uuid::UUID_TYPE_CUSTOM => new UuidV8($fields, $this->numberConverter, $codec, $this->timeConverter), default => throw new UnsupportedOperationException( 'The UUID version in the given fields is not supported by this UUID builder', ), }; } catch (Throwable $e) { /** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); } } /** * Proxy method to allow injecting a mock for testing * * @pure */ protected function buildFields(string $bytes): FieldsInterface { /** @phpstan-ignore possiblyImpure.new */ return new Fields($bytes); } } ================================================ FILE: src/Rfc4122/UuidInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\UuidInterface as BaseUuidInterface; /** * A universally unique identifier (UUID), as defined in RFC 9562 (formerly RFC 4122) * * @link https://www.rfc-editor.org/rfc/rfc9562 RFC 9562 * * @immutable */ interface UuidInterface extends BaseUuidInterface { } ================================================ FILE: src/Rfc4122/UuidV1.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Gregorian time, or version 1, UUIDs include timestamp, clock sequence, and node values, combined into a 128-bit unsigned integer * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.1 RFC 9562, 5.1. UUID Version 1 * * @immutable */ final class UuidV1 extends Uuid implements UuidInterface { use TimeTrait; /** * Creates a version 1 (Gregorian time) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_TIME) { throw new InvalidArgumentException( 'Fields used to create a UuidV1 must represent a version 1 (time-based) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/UuidV2.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Uuid; use function hexdec; /** * DCE Security version, or version 2, UUIDs include local domain identifier, local ID for the specified domain, and * node values that are combined into a 128-bit unsigned integer * * It is important to note that a version 2 UUID suffers from some loss of timestamp fidelity, due to replacing the * time_low field with the local identifier. When constructing the timestamp value for date purposes, we replace the * local identifier bits with zeros. As a result, the timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 * minutes, 9 seconds, and 496,730 microseconds). * * Astute observers might note this value directly corresponds to `2^32-1`, or `0xffffffff`. The local identifier is * 32-bits, and we have set each of these bits to `0`, so the maximum range of timestamp drift is `0x00000000` to * `0xffffffff` (counted in 100-nanosecond intervals). * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.2 RFC 9562, 5.2. UUID Version 2 * @link https://publications.opengroup.org/c311 DCE 1.1: Authentication and Security Services * @link https://publications.opengroup.org/c706 DCE 1.1: Remote Procedure Call * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01 DCE 1.1: Auth & Sec, §5.2.1.1 * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1: Auth & Sec, §11.5.1.1 * @link https://pubs.opengroup.org/onlinepubs/9629399/apdxa.htm DCE 1.1: RPC, Appendix A * @link https://github.com/google/uuid Go package for UUIDs (includes DCE implementation) * * @immutable */ final class UuidV2 extends Uuid implements UuidInterface { use TimeTrait; /** * Creates a version 2 (DCE Security) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_DCE_SECURITY) { throw new InvalidArgumentException( 'Fields used to create a UuidV2 must represent a version 2 (DCE Security) UUID' ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } /** * Returns the local domain used to create this version 2 UUID */ public function getLocalDomain(): int { /** @var Rfc4122FieldsInterface $fields */ $fields = $this->getFields(); return (int) hexdec($fields->getClockSeqLow()->toString()); } /** * Returns the string name of the local domain */ public function getLocalDomainName(): string { return Uuid::DCE_DOMAIN_NAMES[$this->getLocalDomain()]; } /** * Returns the local identifier for the domain used to create this version 2 UUID */ public function getLocalIdentifier(): IntegerObject { /** @var Rfc4122FieldsInterface $fields */ $fields = $this->getFields(); return new IntegerObject($this->numberConverter->fromHex($fields->getTimeLow()->toString())); } } ================================================ FILE: src/Rfc4122/UuidV3.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Version 3 UUIDs are named-based, using a combination of a namespace and name that are hashed into a 128-bit unsigned * integer using the MD5 hashing algorithm * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.3 RFC 9562, 5.3. UUID Version 3 * * @immutable */ final class UuidV3 extends Uuid implements UuidInterface { /** * Creates a version 3 (name-based, MD5-hashed) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_MD5) { throw new InvalidArgumentException( 'Fields used to create a UuidV3 must represent a version 3 (name-based, MD5-hashed) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/UuidV4.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Random, or version 4, UUIDs are randomly or pseudo-randomly generated 128-bit integers * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.4 RFC 9562, 5.4. UUID Version 4 * * @immutable */ final class UuidV4 extends Uuid implements UuidInterface { /** * Creates a version 4 (random) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_RANDOM) { throw new InvalidArgumentException( 'Fields used to create a UuidV4 must represent a version 4 (random) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/UuidV5.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Version 5 UUIDs are named-based, using a combination of a namespace and name that are hashed into a 128-bit unsigned * integer using the SHA1 hashing algorithm * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.5 RFC 9562, 5.5. UUID Version 5 * * @immutable */ final class UuidV5 extends Uuid implements UuidInterface { /** * Creates a version 5 (name-based, SHA1-hashed) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_SHA1) { throw new InvalidArgumentException( 'Fields used to create a UuidV5 must represent a version 5 (named-based, SHA1-hashed) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/UuidV6.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Nonstandard\UuidV6 as NonstandardUuidV6; /** * Reordered Gregorian time, or version 6, UUIDs include timestamp, clock sequence, and node values that are combined * into a 128-bit unsigned integer * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.6 RFC 9562, 5.6. UUID Version 6 * * @immutable */ final class UuidV6 extends NonstandardUuidV6 implements UuidInterface { } ================================================ FILE: src/Rfc4122/UuidV7.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Unix Epoch time, or version 7, UUIDs include a timestamp in milliseconds since the Unix Epoch, along with random bytes * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.7 RFC 9562, 5.7. UUID Version 7 * * @immutable */ final class UuidV7 extends Uuid implements UuidInterface { use TimeTrait; /** * Creates a version 7 (Unix Epoch time) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_UNIX_TIME) { throw new InvalidArgumentException( 'Fields used to create a UuidV7 must represent a version 7 (Unix Epoch time) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/UuidV8.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; /** * Custom format, or version 8, UUIDs provide an RFC-compatible format for experimental or vendor-specific uses * * The only requirement for version 8 UUIDs is that the version and variant bits must be set. Otherwise, implementations * are free to set the other bits according to their needs. As a result, the uniqueness of version 8 UUIDs is * implementation-specific and should not be assumed. * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.8 RFC 9562, 5.8. UUID Version 8 * * @immutable */ final class UuidV8 extends Uuid implements UuidInterface { /** * Creates a version 8 (custom format) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { if ($fields->getVersion() !== Uuid::UUID_TYPE_CUSTOM) { throw new InvalidArgumentException( 'Fields used to create a UuidV8 must represent a version 8 (custom format) UUID', ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } } ================================================ FILE: src/Rfc4122/Validator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Validator\ValidatorInterface; use function preg_match; use function str_replace; /** * Rfc4122\Validator validates strings as UUIDs of the RFC 9562 (formerly RFC 4122) variant * * @immutable */ final class Validator implements ValidatorInterface { private const VALID_PATTERN = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-' . '[1-8][0-9A-Fa-f]{3}-[ABab89][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z'; /** * @return non-empty-string */ public function getPattern(): string { return self::VALID_PATTERN; } public function validate(string $uuid): bool { /** @phpstan-ignore possiblyImpure.functionCall */ $uuid = strtolower(str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid)); /** @phpstan-ignore possiblyImpure.functionCall */ return $uuid === Uuid::NIL || $uuid === Uuid::MAX || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); } } ================================================ FILE: src/Rfc4122/VariantTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Exception\InvalidBytesException; use Ramsey\Uuid\Uuid; use function decbin; use function str_pad; use function str_starts_with; use function strlen; use function substr; use function unpack; use const STR_PAD_LEFT; /** * Provides common functionality for handling the variant, as defined by RFC 9562 (formerly RFC 4122) * * @immutable */ trait VariantTrait { /** * Returns the bytes that comprise the fields */ abstract public function getBytes(): string; /** * Returns the variant * * The variant number describes the layout of the UUID. The variant number has the following meaning: * * - 0 - Reserved for NCS backward compatibility * - 2 - The RFC 9562 (formerly RFC 4122) variant * - 6 - Reserved, Microsoft Corporation backward compatibility * - 7 - Reserved for future definition * * For RFC 9562 (formerly RFC 4122) variant UUIDs, this value should always be the integer `2`. * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public function getVariant(): int { if (strlen($this->getBytes()) !== 16) { throw new InvalidBytesException('Invalid number of bytes'); } // According to RFC 9562, sections {@link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 4.1} and // {@link https://www.rfc-editor.org/rfc/rfc9562#section-5.10 5.10}, the Max UUID falls within the range // of the future variant. if ($this->isMax()) { return Uuid::RESERVED_FUTURE; } // According to RFC 9562, sections {@link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 4.1} and // {@link https://www.rfc-editor.org/rfc/rfc9562#section-5.9 5.9}, the Nil UUID falls within the range // of the Apollo NCS variant. if ($this->isNil()) { return Uuid::RESERVED_NCS; } /** @var int[] $parts */ $parts = unpack('n*', $this->getBytes()); // $parts[5] is a 16-bit, unsigned integer containing the variant bits of the UUID. We convert this integer into // a string containing a binary representation, padded to 16 characters. We analyze the first three characters // (three most-significant bits) to determine the variant. $msb = substr(str_pad(decbin($parts[5]), 16, '0', STR_PAD_LEFT), 0, 3); if ($msb === '111') { return Uuid::RESERVED_FUTURE; } elseif ($msb === '110') { return Uuid::RESERVED_MICROSOFT; } elseif (str_starts_with($msb, '10')) { return Uuid::RFC_4122; } return Uuid::RESERVED_NCS; } } ================================================ FILE: src/Rfc4122/VersionTrait.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Rfc4122; use Ramsey\Uuid\Uuid; /** * Provides common functionality for handling the version, as defined by RFC 9562 (formerly RFC 4122) * * @immutable */ trait VersionTrait { /** * Returns the UUID version * * The version number describes how the UUID was generated and has the following meaning: * * 1. Gregorian time UUID * 2. DCE security UUID * 3. Name-based UUID hashed with MD5 * 4. Randomly generated UUID * 5. Name-based UUID hashed with SHA-1 * 6. Reordered Gregorian time UUID * 7. Unix Epoch time UUID * 8. Custom format UUID * * This returns `null` if the UUID is not an RFC 9562 (formerly RFC 4122) variant, since the version is only * meaningful for this variant. * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field * * @pure */ abstract public function getVersion(): ?int; /** * Returns true if these fields represent a max UUID */ abstract public function isMax(): bool; /** * Returns true if these fields represent a nil UUID */ abstract public function isNil(): bool; /** * Returns true if the version matches one of those defined by RFC 9562 (formerly RFC 4122) * * @return bool True if the UUID version is valid, false otherwise */ private function isCorrectVersion(): bool { if ($this->isNil() || $this->isMax()) { return true; } return match ($this->getVersion()) { Uuid::UUID_TYPE_TIME, Uuid::UUID_TYPE_DCE_SECURITY, Uuid::UUID_TYPE_HASH_MD5, Uuid::UUID_TYPE_RANDOM, Uuid::UUID_TYPE_HASH_SHA1, Uuid::UUID_TYPE_REORDERED_TIME, Uuid::UUID_TYPE_UNIX_TIME, Uuid::UUID_TYPE_CUSTOM => true, default => false, }; } } ================================================ FILE: src/Type/Decimal.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; use ValueError; use function is_numeric; use function sprintf; use function str_starts_with; /** * A value object representing a decimal * * This class exists for type-safety purposes, to ensure that decimals returned from ramsey/uuid methods as strings are * truly decimals and not some other kind of string. * * To support values as true decimals and not as floats or doubles, we store the decimals as strings. * * @immutable */ final class Decimal implements NumberInterface { private string $value; private bool $isNegative; public function __construct(float | int | string | self $value) { $value = (string) $value; if (!is_numeric($value)) { throw new InvalidArgumentException( 'Value must be a signed decimal or a string containing only ' . 'digits 0-9 and, optionally, a decimal point or sign (+ or -)' ); } // Remove the leading +-symbol. if (str_starts_with($value, '+')) { $value = substr($value, 1); } // For cases like `-0` or `-0.0000`, convert the value to `0`. if (abs((float) $value) === 0.0) { $value = '0'; } if (str_starts_with($value, '-')) { $this->isNegative = true; } else { $this->isNegative = false; } $this->value = $value; } public function isNegative(): bool { return $this->isNegative; } public function toString(): string { return $this->value; } public function __toString(): string { return $this->toString(); } public function jsonSerialize(): string { return $this->toString(); } public function serialize(): string { return $this->toString(); } /** * @return array{string: string} */ public function __serialize(): array { return ['string' => $this->toString()]; } /** * Constructs the object from a serialized string representation * * @param string $data The serialized string representation of the object */ public function unserialize(string $data): void { $this->__construct($data); } /** * @param array{string?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['string'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['string']); } } ================================================ FILE: src/Type/Hexadecimal.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; use ValueError; use function preg_match; use function sprintf; use function substr; /** * A value object representing a hexadecimal number * * This class exists for type-safety purposes, to ensure that hexadecimal numbers returned from ramsey/uuid methods as * strings are truly hexadecimal and not some other kind of string. * * @immutable */ final class Hexadecimal implements TypeInterface { /** * @var non-empty-string */ private string $value; /** * @param self | string $value The hexadecimal value to store */ public function __construct(self | string $value) { $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); } /** * @return non-empty-string * * @pure */ public function toString(): string { return $this->value; } /** * @return non-empty-string */ public function __toString(): string { return $this->toString(); } /** * @return non-empty-string */ public function jsonSerialize(): string { return $this->toString(); } /** * @return non-empty-string */ public function serialize(): string { return $this->toString(); } /** * @return array{string: string} */ public function __serialize(): array { return ['string' => $this->toString()]; } /** * Constructs the object from a serialized string representation * * @param string $data The serialized string representation of the object */ public function unserialize(string $data): void { $this->__construct($data); } /** * @param array{string?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['string'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['string']); } /** * @return non-empty-string */ private function prepareValue(string $value): string { $value = strtolower($value); if (str_starts_with($value, '0x')) { $value = substr($value, 2); } if (!preg_match('/^[A-Fa-f0-9]+$/', $value)) { throw new InvalidArgumentException('Value must be a hexadecimal number'); } /** @var non-empty-string */ return $value; } } ================================================ FILE: src/Type/Integer.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; use ValueError; use function assert; use function is_numeric; use function preg_match; use function sprintf; use function substr; /** * A value object representing an integer * * This class exists for type-safety purposes, to ensure that integers returned from ramsey/uuid methods as strings are * truly integers and not some other kind of string. * * To support large integers beyond PHP_INT_MAX and PHP_INT_MIN on both 64-bit and 32-bit systems, we store the integers * as strings. * * @immutable */ final class Integer implements NumberInterface { /** * @var numeric-string */ private string $value; /** * @phpstan-ignore property.readOnlyByPhpDocDefaultValue */ private bool $isNegative = false; public function __construct(self | float | int | string $value) { $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); } public function isNegative(): bool { return $this->isNegative; } /** * @return numeric-string * * @pure */ public function toString(): string { return $this->value; } /** * @return numeric-string */ public function __toString(): string { return $this->toString(); } public function jsonSerialize(): string { return $this->toString(); } public function serialize(): string { return $this->toString(); } /** * @return array{string: string} */ public function __serialize(): array { return ['string' => $this->toString()]; } /** * Constructs the object from a serialized string representation * * @param string $data The serialized string representation of the object */ public function unserialize(string $data): void { $this->__construct($data); } /** * @param array{string?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['string'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['string']); } /** * @return numeric-string */ private function prepareValue(float | int | string $value): string { $value = (string) $value; $sign = '+'; // If the value contains a sign, remove it for the digit pattern check. if (str_starts_with($value, '-') || str_starts_with($value, '+')) { $sign = substr($value, 0, 1); $value = substr($value, 1); } if (!preg_match('/^\d+$/', $value)) { throw new InvalidArgumentException( 'Value must be a signed integer or a string containing only ' . 'digits 0-9 and, optionally, a sign (+ or -)' ); } // Trim any leading zeros. $value = ltrim($value, '0'); // Set to zero if the string is empty after trimming zeros. if ($value === '') { $value = '0'; } // Add the negative sign back to the value. if ($sign === '-' && $value !== '0') { $value = $sign . $value; /** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */ $this->isNegative = true; } assert(is_numeric($value)); return $value; } } ================================================ FILE: src/Type/NumberInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; /** * NumberInterface ensures consistency in numeric values returned by ramsey/uuid * * @immutable */ interface NumberInterface extends TypeInterface { /** * Returns true if this number is less than zero */ public function isNegative(): bool; } ================================================ FILE: src/Type/Time.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Type\Integer as IntegerObject; use ValueError; use function json_decode; use function json_encode; use function sprintf; /** * A value object representing a timestamp * * This class exists for type-safety purposes, to ensure that timestamps used by ramsey/uuid are truly timestamp * integers and not some other kind of string or integer. * * @immutable */ final class Time implements TypeInterface { private IntegerObject $seconds; private IntegerObject $microseconds; public function __construct( IntegerObject | float | int | string $seconds, IntegerObject | float | int | string $microseconds = 0, ) { $this->seconds = new IntegerObject($seconds); $this->microseconds = new IntegerObject($microseconds); } /** * @pure */ public function getSeconds(): IntegerObject { return $this->seconds; } /** * @pure */ public function getMicroseconds(): IntegerObject { return $this->microseconds; } public function toString(): string { return $this->seconds->toString() . '.' . sprintf('%06s', $this->microseconds->toString()); } public function __toString(): string { return $this->toString(); } /** * @return string[] */ public function jsonSerialize(): array { return [ 'seconds' => $this->getSeconds()->toString(), 'microseconds' => $this->getMicroseconds()->toString(), ]; } public function serialize(): string { return (string) json_encode($this); } /** * @return array{seconds: string, microseconds: string} */ public function __serialize(): array { return [ 'seconds' => $this->getSeconds()->toString(), 'microseconds' => $this->getMicroseconds()->toString(), ]; } /** * Constructs the object from a serialized string representation * * @param string $data The serialized string representation of the object */ public function unserialize(string $data): void { /** @var array{seconds?: float | int | string, microseconds?: float | int | string} $time */ $time = json_decode($data, true); if (!isset($time['seconds']) || !isset($time['microseconds'])) { throw new UnsupportedOperationException('Attempted to unserialize an invalid value'); } $this->__construct($time['seconds'], $time['microseconds']); } /** * @param array{seconds?: string, microseconds?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['seconds']) || !isset($data['microseconds'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->__construct($data['seconds'], $data['microseconds']); } } ================================================ FILE: src/Type/TypeInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Type; use JsonSerializable; use Serializable; /** * TypeInterface ensures consistency in typed values returned by ramsey/uuid * * @immutable */ interface TypeInterface extends JsonSerializable, Serializable { /** * @pure */ public function toString(): string; /** * @pure */ public function __toString(): string; } ================================================ FILE: src/Uuid.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use BadMethodCallException; use DateTimeInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Fields\FieldsInterface; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use ValueError; use function assert; use function bin2hex; use function method_exists; use function preg_match; use function sprintf; use function str_replace; use function strcmp; use function strlen; use function strtolower; use function substr; /** * Uuid provides constants and static methods for working with and generating UUIDs * * @immutable */ class Uuid implements UuidInterface { use DeprecatedUuidMethodsTrait; /** * When this namespace is specified, the name string is a fully qualified domain name * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.6 RFC 9562, 6.6. Namespace ID Usage and Allocation */ public const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; /** * When this namespace is specified, the name string is a URL * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.6 RFC 9562, 6.6. Namespace ID Usage and Allocation */ public const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; /** * When this namespace is specified, the name string is an ISO OID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.6 RFC 9562, 6.6. Namespace ID Usage and Allocation */ public const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'; /** * When this namespace is specified, the name string is an X.500 DN (in DER or a text output format) * * @link https://www.rfc-editor.org/rfc/rfc9562#section-6.6 RFC 9562, 6.6. Namespace ID Usage and Allocation */ public const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; /** * The Nil UUID is a special form of UUID that is specified to have all 128 bits set to zero * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.9 RFC 9562, 5.9. Nil UUID */ public const NIL = '00000000-0000-0000-0000-000000000000'; /** * The Max UUID is a special form of UUID that is specified to have all 128 bits set to one * * @link https://www.rfc-editor.org/rfc/rfc9562#section-5.10 RFC 9562, 5.10. Max UUID */ public const MAX = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; /** * Variant: reserved, NCS backward compatibility * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public const RESERVED_NCS = 0; /** * Variant: the UUID layout specified in RFC 9562 (formerly RFC 4122) * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field * @see Uuid::RFC_9562 */ public const RFC_4122 = 2; /** * Variant: the UUID layout specified in RFC 9562 (formerly RFC 4122) * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public const RFC_9562 = 2; /** * Variant: reserved, Microsoft Corporation backward compatibility * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public const RESERVED_MICROSOFT = 6; /** * Variant: reserved for future definition * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field */ public const RESERVED_FUTURE = 7; /** * @deprecated Use {@see ValidatorInterface::getPattern()} instead. */ public const VALID_PATTERN = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'; /** * Version 1 (Gregorian time) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_TIME = 1; /** * Version 2 (DCE Security) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_DCE_SECURITY = 2; /** * @deprecated Use {@see Uuid::UUID_TYPE_DCE_SECURITY} instead. */ public const UUID_TYPE_IDENTIFIER = 2; /** * Version 3 (name-based and hashed with MD5) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_HASH_MD5 = 3; /** * Version 4 (random) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_RANDOM = 4; /** * Version 5 (name-based and hashed with SHA1) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_HASH_SHA1 = 5; /** * @deprecated Use {@see Uuid::UUID_TYPE_REORDERED_TIME} instead. */ public const UUID_TYPE_PEABODY = 6; /** * Version 6 (reordered Gregorian time) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_REORDERED_TIME = 6; /** * Version 7 (Unix Epoch time) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_UNIX_TIME = 7; /** * Version 8 (custom format) UUID * * @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field */ public const UUID_TYPE_CUSTOM = 8; /** * DCE Security principal domain * * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 */ public const DCE_DOMAIN_PERSON = 0; /** * DCE Security group domain * * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 */ public const DCE_DOMAIN_GROUP = 1; /** * DCE Security organization domain * * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 */ public const DCE_DOMAIN_ORG = 2; /** * DCE Security domain string names * * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1, §11.5.1.1 */ public const DCE_DOMAIN_NAMES = [ self::DCE_DOMAIN_PERSON => 'person', self::DCE_DOMAIN_GROUP => 'group', self::DCE_DOMAIN_ORG => 'org', ]; /** * @phpstan-ignore property.readOnlyByPhpDocDefaultValue */ private static ?UuidFactoryInterface $factory = null; /** * @var bool flag to detect if the UUID factory was replaced internally, which disables all optimizations for the * default/happy path internal scenarios * @phpstan-ignore property.readOnlyByPhpDocDefaultValue */ private static bool $factoryReplaced = false; protected CodecInterface $codec; protected NumberConverterInterface $numberConverter; protected Rfc4122FieldsInterface $fields; protected TimeConverterInterface $timeConverter; /** * Creates a universally unique identifier (UUID) from an array of fields * * Unless you're making advanced use of this library to generate identifiers that deviate from RFC 9562 (formerly * RFC 4122), you probably do not want to instantiate a UUID directly. Use the static methods, instead: * * ``` * use Ramsey\Uuid\Uuid; * * $timeBasedUuid = Uuid::uuid1(); * $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/'); * $randomUuid = Uuid::uuid4(); * $namespaceSha1Uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'http://php.net/'); * ``` * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding UUID strings * @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a * UUID to unix timestamps */ public function __construct( Rfc4122FieldsInterface $fields, NumberConverterInterface $numberConverter, CodecInterface $codec, TimeConverterInterface $timeConverter, ) { $this->fields = $fields; $this->codec = $codec; $this->numberConverter = $numberConverter; $this->timeConverter = $timeConverter; } /** * @return non-empty-string */ public function __toString(): string { return $this->toString(); } /** * Converts the UUID to a string for JSON serialization */ public function jsonSerialize(): string { return $this->toString(); } /** * Converts the UUID to a string for PHP serialization */ public function serialize(): string { return $this->codec->encode($this); } /** * @return array{bytes: string} */ public function __serialize(): array { return ['bytes' => $this->serialize()]; } /** * Re-constructs the object from its serialized form * * @param string $data The serialized PHP string to unserialize into a UuidInterface instance */ public function unserialize(string $data): void { if (strlen($data) === 16) { /** @var Uuid $uuid */ $uuid = self::getFactory()->fromBytes($data); } else { /** @var Uuid $uuid */ $uuid = self::getFactory()->fromString($data); } /** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */ $this->codec = $uuid->codec; /** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */ $this->numberConverter = $uuid->numberConverter; /** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */ $this->fields = $uuid->fields; /** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */ $this->timeConverter = $uuid->timeConverter; } /** * @param array{bytes?: string} $data */ public function __unserialize(array $data): void { // @codeCoverageIgnoreStart if (!isset($data['bytes'])) { throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); } // @codeCoverageIgnoreEnd $this->unserialize($data['bytes']); } public function compareTo(UuidInterface $other): int { $compare = strcmp($this->toString(), $other->toString()); if ($compare < 0) { return -1; } if ($compare > 0) { return 1; } return 0; } public function equals(?object $other): bool { if (!$other instanceof UuidInterface) { return false; } return $this->compareTo($other) === 0; } /** * @return non-empty-string */ public function getBytes(): string { return $this->codec->encodeBinary($this); } public function getFields(): FieldsInterface { return $this->fields; } public function getHex(): Hexadecimal { return new Hexadecimal(str_replace('-', '', $this->toString())); } public function getInteger(): IntegerObject { return new IntegerObject($this->numberConverter->fromHex($this->getHex()->toString())); } public function getUrn(): string { return 'urn:uuid:' . $this->toString(); } /** * @return non-empty-string */ public function toString(): string { return $this->codec->encode($this); } /** * Returns the factory used to create UUIDs */ public static function getFactory(): UuidFactoryInterface { if (self::$factory === null) { self::$factory = new UuidFactory(); } return self::$factory; } /** * Sets the factory used to create UUIDs * * @param UuidFactoryInterface $factory A factory that will be used by this class to create UUIDs */ public static function setFactory(UuidFactoryInterface $factory): void { // Note: non-strict equality is intentional here. If the factory is configured differently, every assumption // around purity is broken, and we have to internally decide everything differently. // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedNotEqualOperator self::$factoryReplaced = ($factory != new UuidFactory()); self::$factory = $factory; } /** * Creates a UUID from a byte string * * @param string $bytes A binary string * * @return UuidInterface A UuidInterface instance created from a binary string representation * * @throws InvalidArgumentException * * @pure */ public static function fromBytes(string $bytes): UuidInterface { /** @phpstan-ignore impure.staticPropertyAccess */ if (!self::$factoryReplaced && strlen($bytes) === 16) { $base16Uuid = bin2hex($bytes); // Note: we are calling `fromString` internally because we don't know if the given `$bytes` is a valid UUID return self::fromString( substr($base16Uuid, 0, 8) . '-' . substr($base16Uuid, 8, 4) . '-' . substr($base16Uuid, 12, 4) . '-' . substr($base16Uuid, 16, 4) . '-' . substr($base16Uuid, 20, 12), ); } /** @phpstan-ignore possiblyImpure.methodCall */ return self::getFactory()->fromBytes($bytes); } /** * Creates a UUID from the string standard representation * * @param string $uuid A hexadecimal string * * @return UuidInterface A UuidInterface instance created from a hexadecimal string representation * * @throws InvalidArgumentException * * @pure */ public static function fromString(string $uuid): UuidInterface { $uuid = strtolower($uuid); /** @phpstan-ignore impure.staticPropertyAccess, possiblyImpure.functionCall */ if (!self::$factoryReplaced && preg_match(LazyUuidFromString::VALID_REGEX, $uuid) === 1) { /** @phpstan-ignore possiblyImpure.functionCall */ assert($uuid !== ''); /** @phpstan-ignore possiblyImpure.new */ return new LazyUuidFromString($uuid); } /** @phpstan-ignore possiblyImpure.methodCall */ return self::getFactory()->fromString($uuid); } /** * Creates a UUID from a DateTimeInterface instance * * @param DateTimeInterface $dateTime The date and time * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 1 UUID created from a DateTimeInterface instance */ public static function fromDateTime( DateTimeInterface $dateTime, ?Hexadecimal $node = null, ?int $clockSeq = null ): UuidInterface { return self::getFactory()->fromDateTime($dateTime, $node, $clockSeq); } /** * Creates a UUID from the Hexadecimal object * * @param Hexadecimal $hex Hexadecimal object representing a hexadecimal number * * @return UuidInterface A UuidInterface instance created from the Hexadecimal object representing a hexadecimal number * * @throws InvalidArgumentException * * @pure */ public static function fromHexadecimal(Hexadecimal $hex): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ $factory = self::getFactory(); if (method_exists($factory, 'fromHexadecimal')) { /** @phpstan-ignore possiblyImpure.methodCall */ $uuid = $factory->fromHexadecimal($hex); /** @phpstan-ignore possiblyImpure.functionCall */ assert($uuid instanceof UuidInterface); return $uuid; } throw new BadMethodCallException('The method fromHexadecimal() does not exist on the provided factory'); } /** * Creates a UUID from a 128-bit integer string * * @param string $integer String representation of 128-bit integer * * @return UuidInterface A UuidInterface instance created from the string representation of a 128-bit integer * * @throws InvalidArgumentException * * @pure */ public static function fromInteger(string $integer): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return self::getFactory()->fromInteger($integer); } /** * Returns true if the provided string is a valid UUID * * @param string $uuid A string to validate as a UUID * * @return bool True if the string is a valid UUID, false otherwise * * @phpstan-assert-if-true =non-empty-string $uuid * * @pure */ public static function isValid(string $uuid): bool { /** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ return self::getFactory()->getValidator()->validate($uuid); } /** * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | int | string | null $node A 48-bit number representing the hardware address; this number may * be represented as an integer or a hexadecimal string * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 1 UUID */ public static function uuid1($node = null, ?int $clockSeq = null): UuidInterface { return self::getFactory()->uuid1($node, $clockSeq); } /** * Returns a version 2 (DCE Security) UUID from a local domain, local identifier, host ID, clock sequence, and the current time * * @param int $localDomain The local domain to use when generating bytes, according to DCE Security * @param IntegerObject | null $localIdentifier The local identifier for the given domain; this may be a UID or GID * on POSIX systems, if the local domain is "person" or "group," or it may be a site-defined identifier if the * local domain is "org" * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes (in a version 2 UUID, the lower 8 bits of this number are * replaced with the domain). * * @return UuidInterface A UuidInterface instance that represents a version 2 UUID */ public static function uuid2( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null ): UuidInterface { return self::getFactory()->uuid2($localDomain, $localIdentifier, $node, $clockSeq); } /** * Returns a version 3 (name-based) UUID based on the MD5 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * @param string $name The name to use for creating a UUID * * @return UuidInterface A UuidInterface instance that represents a version 3 UUID * * @pure */ public static function uuid3($ns, string $name): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return self::getFactory()->uuid3($ns, $name); } /** * Returns a version 4 (random) UUID * * @return UuidInterface A UuidInterface instance that represents a version 4 UUID */ public static function uuid4(): UuidInterface { return self::getFactory()->uuid4(); } /** * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * @param string $name The name to use for creating a UUID * * @return UuidInterface A UuidInterface instance that represents a version 5 UUID * * @pure */ public static function uuid5($ns, string $name): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return self::getFactory()->uuid5($ns, $name); } /** * Returns a version 6 (reordered Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 6 UUID */ public static function uuid6( ?Hexadecimal $node = null, ?int $clockSeq = null ): UuidInterface { return self::getFactory()->uuid6($node, $clockSeq); } /** * Returns a version 7 (Unix Epoch time) UUID * * @param DateTimeInterface | null $dateTime An optional date/time from which to create the version 7 UUID. If not * provided, the UUID is generated using the current date/time. * * @return UuidInterface A UuidInterface instance that represents a version 7 UUID */ public static function uuid7(?DateTimeInterface $dateTime = null): UuidInterface { $factory = self::getFactory(); if (method_exists($factory, 'uuid7')) { /** @var UuidInterface */ return $factory->uuid7($dateTime); } throw new UnsupportedOperationException('The provided factory does not support the uuid7() method'); } /** * Returns a version 8 (custom format) UUID * * The bytes provided may contain any value according to your application's needs. Be aware, however, that other * applications may not understand the semantics of the value. * * @param string $bytes A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of * information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 * and 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs. * * @return UuidInterface A UuidInterface instance that represents a version 8 UUID * * @pure */ public static function uuid8(string $bytes): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ $factory = self::getFactory(); if (method_exists($factory, 'uuid8')) { /** * @var UuidInterface * @phpstan-ignore possiblyImpure.methodCall */ return $factory->uuid8($bytes); } throw new UnsupportedOperationException('The provided factory does not support the uuid8() method'); } } ================================================ FILE: src/UuidFactory.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use DateTimeInterface; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface; use Ramsey\Uuid\Generator\DefaultTimeGenerator; use Ramsey\Uuid\Generator\NameGeneratorInterface; use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorInterface; use Ramsey\Uuid\Generator\UnixTimeGenerator; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\Time\FixedTimeProvider; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Type\Time; use Ramsey\Uuid\Validator\ValidatorInterface; use function bin2hex; use function hex2bin; use function pack; use function str_pad; use function strtolower; use function substr; use function substr_replace; use function unpack; use const STR_PAD_LEFT; class UuidFactory implements UuidFactoryInterface { private CodecInterface $codec; private DceSecurityGeneratorInterface $dceSecurityGenerator; private NameGeneratorInterface $nameGenerator; private NodeProviderInterface $nodeProvider; private NumberConverterInterface $numberConverter; private RandomGeneratorInterface $randomGenerator; private TimeConverterInterface $timeConverter; private TimeGeneratorInterface $timeGenerator; private TimeGeneratorInterface $unixTimeGenerator; private UuidBuilderInterface $uuidBuilder; private ValidatorInterface $validator; /** * @var bool whether the feature set was provided from outside, or we can operate under "default" assumptions */ private bool $isDefaultFeatureSet; /** * @param FeatureSet | null $features A set of available features in the current environment */ public function __construct(?FeatureSet $features = null) { $this->isDefaultFeatureSet = $features === null; $features = $features ?: new FeatureSet(); $this->codec = $features->getCodec(); $this->dceSecurityGenerator = $features->getDceSecurityGenerator(); $this->nameGenerator = $features->getNameGenerator(); $this->nodeProvider = $features->getNodeProvider(); $this->numberConverter = $features->getNumberConverter(); $this->randomGenerator = $features->getRandomGenerator(); $this->timeConverter = $features->getTimeConverter(); $this->timeGenerator = $features->getTimeGenerator(); $this->uuidBuilder = $features->getBuilder(); $this->validator = $features->getValidator(); $this->unixTimeGenerator = $features->getUnixTimeGenerator(); } /** * Returns the codec used by this factory */ public function getCodec(): CodecInterface { return $this->codec; } /** * Sets the codec to use for this factory * * @param CodecInterface $codec A UUID encoder-decoder */ public function setCodec(CodecInterface $codec): void { $this->isDefaultFeatureSet = false; $this->codec = $codec; } /** * Returns the name generator used by this factory */ public function getNameGenerator(): NameGeneratorInterface { return $this->nameGenerator; } /** * Sets the name generator to use for this factory * * @param NameGeneratorInterface $nameGenerator A generator to generate binary data, based on a namespace and name */ public function setNameGenerator(NameGeneratorInterface $nameGenerator): void { $this->isDefaultFeatureSet = false; $this->nameGenerator = $nameGenerator; } /** * Returns the node provider used by this factory */ public function getNodeProvider(): NodeProviderInterface { return $this->nodeProvider; } /** * Returns the random generator used by this factory */ public function getRandomGenerator(): RandomGeneratorInterface { return $this->randomGenerator; } /** * Returns the time generator used by this factory */ public function getTimeGenerator(): TimeGeneratorInterface { return $this->timeGenerator; } /** * Sets the time generator to use for this factory * * @param TimeGeneratorInterface $generator A generator to generate binary data, based on the time */ public function setTimeGenerator(TimeGeneratorInterface $generator): void { $this->isDefaultFeatureSet = false; $this->timeGenerator = $generator; } /** * Returns the DCE Security generator used by this factory */ public function getDceSecurityGenerator(): DceSecurityGeneratorInterface { return $this->dceSecurityGenerator; } /** * Sets the DCE Security generator to use for this factory * * @param DceSecurityGeneratorInterface $generator A generator to generate binary data, based on a local domain and * local identifier */ public function setDceSecurityGenerator(DceSecurityGeneratorInterface $generator): void { $this->isDefaultFeatureSet = false; $this->dceSecurityGenerator = $generator; } /** * Returns the number converter used by this factory */ public function getNumberConverter(): NumberConverterInterface { return $this->numberConverter; } /** * Sets the random generator to use for this factory * * @param RandomGeneratorInterface $generator A generator to generate binary data, based on some random input */ public function setRandomGenerator(RandomGeneratorInterface $generator): void { $this->isDefaultFeatureSet = false; $this->randomGenerator = $generator; } /** * Sets the number converter to use for this factory * * @param NumberConverterInterface $converter A converter to use for working with large integers (i.e., integers * greater than PHP_INT_MAX) */ public function setNumberConverter(NumberConverterInterface $converter): void { $this->isDefaultFeatureSet = false; $this->numberConverter = $converter; } /** * Returns the UUID builder used by this factory */ public function getUuidBuilder(): UuidBuilderInterface { return $this->uuidBuilder; } /** * Sets the UUID builder to use for this factory * * @param UuidBuilderInterface $builder A builder for constructing instances of UuidInterface */ public function setUuidBuilder(UuidBuilderInterface $builder): void { $this->isDefaultFeatureSet = false; $this->uuidBuilder = $builder; } public function getValidator(): ValidatorInterface { return $this->validator; } /** * Sets the validator to use for this factory * * @param ValidatorInterface $validator A validator to use for validating whether a string is a valid UUID */ public function setValidator(ValidatorInterface $validator): void { $this->isDefaultFeatureSet = false; $this->validator = $validator; } /** * @pure */ public function fromBytes(string $bytes): UuidInterface { return $this->codec->decodeBytes($bytes); } /** * @pure */ public function fromString(string $uuid): UuidInterface { $uuid = strtolower($uuid); return $this->codec->decode($uuid); } /** * @pure */ public function fromInteger(string $integer): UuidInterface { $hex = $this->numberConverter->toHex($integer); $hex = str_pad($hex, 32, '0', STR_PAD_LEFT); return $this->fromString($hex); } public function fromDateTime( DateTimeInterface $dateTime, ?Hexadecimal $node = null, ?int $clockSeq = null, ): UuidInterface { $timeProvider = new FixedTimeProvider(new Time($dateTime->format('U'), $dateTime->format('u'))); $timeGenerator = new DefaultTimeGenerator($this->nodeProvider, $this->timeConverter, $timeProvider); $bytes = $timeGenerator->generate($node?->toString(), $clockSeq); return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); } /** * @pure */ public function fromHexadecimal(Hexadecimal $hex): UuidInterface { return $this->codec->decode($hex->__toString()); } /** * @inheritDoc */ public function uuid1($node = null, ?int $clockSeq = null): UuidInterface { $bytes = $this->timeGenerator->generate($node, $clockSeq); return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); } public function uuid2( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null, ): UuidInterface { $bytes = $this->dceSecurityGenerator->generate($localDomain, $localIdentifier, $node, $clockSeq); return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_DCE_SECURITY); } /** * @inheritDoc * @pure */ public function uuid3($ns, string $name): UuidInterface { return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_MD5, 'md5'); } public function uuid4(): UuidInterface { $bytes = $this->randomGenerator->generate(16); return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_RANDOM); } /** * @inheritDoc * @pure */ public function uuid5($ns, string $name): UuidInterface { return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_SHA1, 'sha1'); } public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface { $bytes = $this->timeGenerator->generate($node?->toString(), $clockSeq); // Rearrange the bytes, according to the UUID version 6 specification. $v6 = $bytes[6] . $bytes[7] . $bytes[4] . $bytes[5] . $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3]; $v6 = bin2hex($v6); // Drop the first four bits, while adding an empty four bits for the version field. This allows us to // reconstruct the correct time from the bytes of this UUID. $v6Bytes = hex2bin(substr($v6, 1, 12) . '0' . substr($v6, -3)); $v6Bytes .= substr($bytes, 8); return $this->uuidFromBytesAndVersion($v6Bytes, Uuid::UUID_TYPE_REORDERED_TIME); } /** * Returns a version 7 (Unix Epoch time) UUID * * @param DateTimeInterface | null $dateTime An optional date/time from which to create the version 7 UUID. If not * provided, the UUID is generated using the current date/time. * * @return UuidInterface A UuidInterface instance that represents a version 7 UUID */ public function uuid7(?DateTimeInterface $dateTime = null): UuidInterface { assert($this->unixTimeGenerator instanceof UnixTimeGenerator); $bytes = $this->unixTimeGenerator->generate(null, null, $dateTime); return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_UNIX_TIME); } /** * Returns a version 8 (custom format) UUID * * The bytes provided may contain any value according to your application's needs. Be aware, however, that other * applications may not understand the semantics of the value. * * @param string $bytes A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of * information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 * and 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs. * * @return UuidInterface A UuidInterface instance that represents a version 8 UUID * * @pure */ public function uuid8(string $bytes): UuidInterface { /** @phpstan-ignore possiblyImpure.methodCall */ return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_CUSTOM); } /** * Returns a Uuid created from the provided byte string * * Uses the configured builder and codec and the provided byte string to construct a Uuid object. * * @param string $bytes The byte string from which to construct a UUID * * @return UuidInterface An instance of UuidInterface, created from the provided bytes * * @pure */ public function uuid(string $bytes): UuidInterface { return $this->uuidBuilder->build($this->codec, $bytes); } /** * Returns a version 3 or 5 namespaced Uuid * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * @param string $name The name to hash together with the namespace * @param int $version The version of UUID to create (3 or 5) * @param string $hashAlgorithm The hashing algorithm to use when hashing together the namespace and name * * @return UuidInterface An instance of UuidInterface, created by hashing together the provided namespace and name * * @pure */ private function uuidFromNsAndName( UuidInterface | string $ns, string $name, int $version, string $hashAlgorithm, ): UuidInterface { if (!($ns instanceof UuidInterface)) { $ns = $this->fromString($ns); } $bytes = $this->nameGenerator->generate($ns, $name, $hashAlgorithm); /** @phpstan-ignore possiblyImpure.methodCall */ return $this->uuidFromBytesAndVersion(substr($bytes, 0, 16), $version); } /** * Returns a Uuid created from the provided bytes and version * * @param string $bytes The byte string to convert to a UUID * @param int $version The version to apply to the UUID * * @return UuidInterface An instance of UuidInterface, created from the byte string and version */ private function uuidFromBytesAndVersion(string $bytes, int $version): UuidInterface { /** @var int[] $unpackedTime */ $unpackedTime = unpack('n*', substr($bytes, 6, 2)); $timeHi = $unpackedTime[1]; $timeHiAndVersion = pack('n*', BinaryUtils::applyVersion($timeHi, $version)); /** @var int[] $unpackedClockSeq */ $unpackedClockSeq = unpack('n*', substr($bytes, 8, 2)); $clockSeqHi = $unpackedClockSeq[1]; $clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi)); $bytes = substr_replace($bytes, $timeHiAndVersion, 6, 2); $bytes = substr_replace($bytes, $clockSeqHiAndReserved, 8, 2); if ($this->isDefaultFeatureSet) { return LazyUuidFromString::fromBytes($bytes); } return $this->uuid($bytes); } } ================================================ FILE: src/UuidFactoryInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use DateTimeInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Validator\ValidatorInterface; /** * UuidFactoryInterface defines the common functionality all `UuidFactory` instances must implement */ interface UuidFactoryInterface { /** * Creates a UUID from a byte string * * @param string $bytes A binary string * * @return UuidInterface A UuidInterface instance created from a binary string representation * * @pure */ public function fromBytes(string $bytes): UuidInterface; /** * Creates a UUID from a DateTimeInterface instance * * @param DateTimeInterface $dateTime The date and time * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 1 UUID created from a DateTimeInterface instance */ public function fromDateTime( DateTimeInterface $dateTime, ?Hexadecimal $node = null, ?int $clockSeq = null, ): UuidInterface; /** * Creates a UUID from a 128-bit integer string * * @param string $integer String representation of 128-bit integer * * @return UuidInterface A UuidInterface instance created from the string representation of a 128-bit integer * * @pure */ public function fromInteger(string $integer): UuidInterface; /** * Creates a UUID from the string standard representation * * @param string $uuid A hexadecimal string * * @return UuidInterface A UuidInterface instance created from a hexadecimal string representation * * @pure */ public function fromString(string $uuid): UuidInterface; /** * Returns the validator used by the factory */ public function getValidator(): ValidatorInterface; /** * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | int | string | null $node A 48-bit number representing the hardware address; this number may * be represented as an integer or a hexadecimal string * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 1 UUID */ public function uuid1($node = null, ?int $clockSeq = null): UuidInterface; /** * Returns a version 2 (DCE Security) UUID from a local domain, local identifier, host ID, clock sequence, and the * current time * * @param int $localDomain The local domain to use when generating bytes, according to DCE Security * @param IntegerObject | null $localIdentifier The local identifier for the given domain; this may be a UID or GID * on POSIX systems, if the local domain is a person or group, or it may be a site-defined identifier if the * local domain is org * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 2 UUID */ public function uuid2( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null, ): UuidInterface; /** * Returns a version 3 (name-based) UUID based on the MD5 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * @param string $name The name to use for creating a UUID * * @return UuidInterface A UuidInterface instance that represents a version 3 UUID * * @pure */ public function uuid3($ns, string $name): UuidInterface; /** * Returns a version 4 (random) UUID * * @return UuidInterface A UuidInterface instance that represents a version 4 UUID */ public function uuid4(): UuidInterface; /** * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * @param string $name The name to use for creating a UUID * * @return UuidInterface A UuidInterface instance that represents a version 5 UUID * * @pure */ public function uuid5($ns, string $name): UuidInterface; /** * Returns a version 6 (reordered Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return UuidInterface A UuidInterface instance that represents a version 6 UUID */ public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface; } ================================================ FILE: src/UuidInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid; use JsonSerializable; use Ramsey\Uuid\Fields\FieldsInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Serializable; use Stringable; /** * A UUID is a universally unique identifier adhering to an agreed-upon representation format and standard for generation * * @immutable */ interface UuidInterface extends DeprecatedUuidInterface, JsonSerializable, Serializable, Stringable { /** * Returns -1, 0, or 1 if the UUID is less than, equal to, or greater than the other UUID * * The first of two UUIDs is greater than the second if the most significant field in which the UUIDs differ is * greater for the first UUID. * * @param UuidInterface $other The UUID to compare * * @return int<-1,1> -1, 0, or 1 if the UUID is less than, equal to, or greater than $other */ public function compareTo(UuidInterface $other): int; /** * Returns true if the UUID is equal to the provided object * * The result is true if and only if the argument is not null, is a UUID object, has the same variant, and contains * the same value, bit-for-bit, as the UUID. * * @param object | null $other An object to test for equality with this UUID * * @return bool True if the other object is equal to this UUID */ public function equals(?object $other): bool; /** * Returns the binary string representation of the UUID * * @return non-empty-string * * @pure */ public function getBytes(): string; /** * Returns the fields that comprise this UUID */ public function getFields(): FieldsInterface; /** * Returns the hexadecimal representation of the UUID */ public function getHex(): Hexadecimal; /** * Returns the integer representation of the UUID */ public function getInteger(): IntegerObject; /** * Returns the string standard representation of the UUID as a URN * * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name Uniform Resource Name * @link https://www.rfc-editor.org/rfc/rfc9562.html#section-4 RFC 9562, 4. UUID Format * @link https://www.rfc-editor.org/rfc/rfc9562.html#section-7 RFC 9562, 7. IANA Considerations * @link https://www.rfc-editor.org/rfc/rfc4122.html#section-3 RFC 4122, 3. Namespace Registration Template */ public function getUrn(): string; /** * Returns the string standard representation of the UUID * * @return non-empty-string * * @pure */ public function toString(): string; /** * Casts the UUID to the string standard representation * * @return non-empty-string * * @pure */ public function __toString(): string; } ================================================ FILE: src/Validator/GenericValidator.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Validator; use Ramsey\Uuid\Uuid; use function preg_match; use function str_replace; /** * GenericValidator validates strings as UUIDs of any variant * * @immutable */ final class GenericValidator implements ValidatorInterface { /** * Regular expression pattern for matching a UUID of any variant. */ private const VALID_PATTERN = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\z'; /** * @return non-empty-string */ public function getPattern(): string { return self::VALID_PATTERN; } public function validate(string $uuid): bool { /** @phpstan-ignore possiblyImpure.functionCall */ $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid); /** @phpstan-ignore possiblyImpure.functionCall */ return $uuid === Uuid::NIL || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); } } ================================================ FILE: src/Validator/ValidatorInterface.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Validator; /** * A validator validates a string as a proper UUID * * @immutable */ interface ValidatorInterface { /** * Returns the regular expression pattern used by this validator * * @return non-empty-string The regular expression pattern this validator uses */ public function getPattern(): string; /** * Returns true if the provided string represents a UUID * * @param string $uuid The string to validate as a UUID * * @return bool True if the string is a valid UUID, false otherwise * * @pure */ public function validate(string $uuid): bool; } ================================================ FILE: src/functions.php ================================================ * @license http://opensource.org/licenses/MIT MIT * phpcs:disable Squiz.Functions.GlobalFunction */ declare(strict_types=1); namespace Ramsey\Uuid; use DateTimeInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; /** * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | int | string | null $node A 48-bit number representing the hardware address; this number may be * represented as an integer or a hexadecimal string * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return non-empty-string Version 1 UUID as a string */ function v1($node = null, ?int $clockSeq = null): string { return Uuid::uuid1($node, $clockSeq)->toString(); } /** * Returns a version 2 (DCE Security) UUID from a local domain, local identifier, host ID, clock sequence, and the current time * * @param int $localDomain The local domain to use when generating bytes, according to DCE Security * @param IntegerObject | null $localIdentifier The local identifier for the given domain; this may be a UID or GID on * POSIX systems, if the local domain is a person or group, or it may be a site-defined identifier if the local * domain is org * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return non-empty-string Version 2 UUID as a string */ function v2( int $localDomain, ?IntegerObject $localIdentifier = null, ?Hexadecimal $node = null, ?int $clockSeq = null, ): string { return Uuid::uuid2($localDomain, $localIdentifier, $node, $clockSeq)->toString(); } /** * Returns a version 3 (name-based) UUID based on the MD5 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * * @return non-empty-string Version 3 UUID as a string * * @pure */ function v3($ns, string $name): string { return Uuid::uuid3($ns, $name)->toString(); } /** * Returns a version 4 (random) UUID * * @return non-empty-string Version 4 UUID as a string */ function v4(): string { return Uuid::uuid4()->toString(); } /** * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a namespace ID and a name * * @param UuidInterface | string $ns The namespace (must be a valid UUID) * * @return non-empty-string Version 5 UUID as a string * * @pure */ function v5($ns, string $name): string { return Uuid::uuid5($ns, $name)->toString(); } /** * Returns a version 6 (reordered Gregorian time) UUID from a host ID, sequence number, and the current time * * @param Hexadecimal | null $node A 48-bit number representing the hardware address * @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set * backwards in time or if the node ID changes * * @return non-empty-string Version 6 UUID as a string */ function v6(?Hexadecimal $node = null, ?int $clockSeq = null): string { return Uuid::uuid6($node, $clockSeq)->toString(); } /** * Returns a version 7 (Unix Epoch time) UUID * * @param DateTimeInterface|null $dateTime An optional date/time from which to create the version 7 UUID. If not * provided, the UUID is generated using the current date/time. * * @return non-empty-string Version 7 UUID as a string */ function v7(?DateTimeInterface $dateTime = null): string { return Uuid::uuid7($dateTime)->toString(); } /** * Returns a version 8 (custom format) UUID * * The bytes provided may contain any value according to your application's needs. Be aware, however, that other * applications may not understand the semantics of the value. * * @param string $bytes A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of * information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 and * 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs. * * @return non-empty-string Version 8 UUID as a string * * @pure */ function v8(string $bytes): string { return Uuid::uuid8($bytes)->toString(); } ================================================ FILE: tests/BinaryUtilsTest.php ================================================ assertSame($expectedInt, BinaryUtils::applyVersion($timeHi, $version)); $this->assertSame($expectedHex, dechex(BinaryUtils::applyVersion($timeHi, $version))); } /** * @dataProvider provideVariantTestValues */ public function testApplyVariant(int $clockSeq, int $expectedInt, string $expectedHex): void { $this->assertSame($expectedInt, BinaryUtils::applyVariant($clockSeq)); $this->assertSame($expectedHex, dechex(BinaryUtils::applyVariant($clockSeq))); } /** * @return array */ public function provideVersionTestValues(): array { return [ [ 'timeHi' => 1001, 'version' => 1, 'expectedInt' => 5097, 'expectedHex' => '13e9', ], [ 'timeHi' => 1001, 'version' => 2, 'expectedInt' => 9193, 'expectedHex' => '23e9', ], [ 'timeHi' => 1001, 'version' => 3, 'expectedInt' => 13289, 'expectedHex' => '33e9', ], [ 'timeHi' => 1001, 'version' => 4, 'expectedInt' => 17385, 'expectedHex' => '43e9', ], [ 'timeHi' => 1001, 'version' => 5, 'expectedInt' => 21481, 'expectedHex' => '53e9', ], [ 'timeHi' => 65535, 'version' => 1, 'expectedInt' => 8191, 'expectedHex' => '1fff', ], [ 'timeHi' => 65535, 'version' => 2, 'expectedInt' => 12287, 'expectedHex' => '2fff', ], [ 'timeHi' => 65535, 'version' => 3, 'expectedInt' => 16383, 'expectedHex' => '3fff', ], [ 'timeHi' => 65535, 'version' => 4, 'expectedInt' => 20479, 'expectedHex' => '4fff', ], [ 'timeHi' => 65535, 'version' => 5, 'expectedInt' => 24575, 'expectedHex' => '5fff', ], [ 'timeHi' => 0, 'version' => 1, 'expectedInt' => 4096, 'expectedHex' => '1000', ], [ 'timeHi' => 0, 'version' => 2, 'expectedInt' => 8192, 'expectedHex' => '2000', ], [ 'timeHi' => 0, 'version' => 3, 'expectedInt' => 12288, 'expectedHex' => '3000', ], [ 'timeHi' => 0, 'version' => 4, 'expectedInt' => 16384, 'expectedHex' => '4000', ], [ 'timeHi' => 0, 'version' => 5, 'expectedInt' => 20480, 'expectedHex' => '5000', ], ]; } /** * @return array */ public function provideVariantTestValues(): array { return [ [ 'clockSeq' => 0, 'expectedInt' => 32768, 'expectedHex' => '8000', ], [ 'clockSeq' => 4096, 'expectedInt' => 36864, 'expectedHex' => '9000', ], [ 'clockSeq' => 8192, 'expectedInt' => 40960, 'expectedHex' => 'a000', ], [ 'clockSeq' => 12288, 'expectedInt' => 45056, 'expectedHex' => 'b000', ], [ 'clockSeq' => 4095, 'expectedInt' => 36863, 'expectedHex' => '8fff', ], [ 'clockSeq' => 8191, 'expectedInt' => 40959, 'expectedHex' => '9fff', ], [ 'clockSeq' => 12287, 'expectedInt' => 45055, 'expectedHex' => 'afff', ], [ 'clockSeq' => 16383, 'expectedInt' => 49151, 'expectedHex' => 'bfff', ], [ 'clockSeq' => 16384, 'expectedInt' => 32768, 'expectedHex' => '8000', ], [ 'clockSeq' => 20480, 'expectedInt' => 36864, 'expectedHex' => '9000', ], [ 'clockSeq' => 24576, 'expectedInt' => 40960, 'expectedHex' => 'a000', ], [ 'clockSeq' => 28672, 'expectedInt' => 45056, 'expectedHex' => 'b000', ], [ 'clockSeq' => 32768, 'expectedInt' => 32768, 'expectedHex' => '8000', ], [ 'clockSeq' => 36864, 'expectedInt' => 36864, 'expectedHex' => '9000', ], [ 'clockSeq' => 40960, 'expectedInt' => 40960, 'expectedHex' => 'a000', ], [ 'clockSeq' => 45056, 'expectedInt' => 45056, 'expectedHex' => 'b000', ], [ 'clockSeq' => 36863, 'expectedInt' => 36863, 'expectedHex' => '8fff', ], [ 'clockSeq' => 40959, 'expectedInt' => 40959, 'expectedHex' => '9fff', ], [ 'clockSeq' => 45055, 'expectedInt' => 45055, 'expectedHex' => 'afff', ], [ 'clockSeq' => 49151, 'expectedInt' => 49151, 'expectedHex' => 'bfff', ], ]; } } ================================================ FILE: tests/Builder/DefaultUuidBuilderTest.php ================================================ '754cd475', 'time_mid' => '7e58', 'time_hi_and_version' => '4411', 'clock_seq_hi_and_reserved' => '93', 'clock_seq_low' => '22', 'node' => 'be0725c8ce01', ]; $bytes = (string) hex2bin(implode('', $fields)); $result = $builder->build($codec, $bytes); $this->assertInstanceOf(Uuid::class, $result); } } ================================================ FILE: tests/Builder/FallbackBuilderTest.php ================================================ shouldReceive('build') ->once() ->with($codec, $bytes) ->andThrow(UnableToBuildUuidException::class); $builder2 = Mockery::mock(UuidBuilderInterface::class); $builder2 ->shouldReceive('build') ->once() ->with($codec, $bytes) ->andThrow(UnableToBuildUuidException::class); $builder3 = Mockery::mock(UuidBuilderInterface::class); $builder3 ->shouldReceive('build') ->once() ->with($codec, $bytes) ->andThrow(UnableToBuildUuidException::class); $fallbackBuilder = new FallbackBuilder([$builder1, $builder2, $builder3]); $this->expectException(BuilderNotFoundException::class); $this->expectExceptionMessage( 'Could not find a suitable builder for the provided codec and fields' ); $fallbackBuilder->build($codec, $bytes); } /** * @dataProvider provideBytes */ public function testSerializationOfBuilderCollection(string $bytes): void { $calculator = new BrickMathCalculator(); $genericNumberConverter = new GenericNumberConverter($calculator); $genericTimeConverter = new GenericTimeConverter($calculator); $phpTimeConverter = new PhpTimeConverter($calculator, $genericTimeConverter); // Use the GenericTimeConverter. $guidBuilder = new GuidBuilder($genericNumberConverter, $genericTimeConverter); $rfc4122Builder = new Rfc4122UuidBuilder($genericNumberConverter, $genericTimeConverter); $nonstandardBuilder = new NonstandardUuidBuilder($genericNumberConverter, $genericTimeConverter); // Use the PhpTimeConverter. $guidBuilder2 = new GuidBuilder($genericNumberConverter, $phpTimeConverter); $rfc4122Builder2 = new Rfc4122UuidBuilder($genericNumberConverter, $phpTimeConverter); $nonstandardBuilder2 = new NonstandardUuidBuilder($genericNumberConverter, $phpTimeConverter); /** @var list $unserializedBuilderCollection */ $unserializedBuilderCollection = unserialize(serialize([ $guidBuilder, $guidBuilder2, $rfc4122Builder, $rfc4122Builder2, $nonstandardBuilder, $nonstandardBuilder2, ])); foreach ($unserializedBuilderCollection as $builder) { $codec = new StringCodec($builder); $this->assertInstanceOf(UuidBuilderInterface::class, $builder); try { $uuid = $builder->build($codec, $bytes); if (($uuid instanceof UuidV1) || ($uuid instanceof UuidV2) || ($uuid instanceof UuidV6)) { $this->assertNotEmpty($uuid->getDateTime()->format('r')); } } catch (UnableToBuildUuidException $exception) { switch ($exception->getMessage()) { case 'The byte string received does not contain a valid version': case 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant': case 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) ' . 'or Microsoft Corporation variants': // This is expected; ignoring. break; default: throw $exception; } } } } /** * @return array */ public function provideBytes(): array { return [ [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1110b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1111b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1112b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1113b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1114b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1115b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1116b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e1117b210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e111eb210800200c9a66'), ], [ // GUID bytes 'bytes' => (string) hex2bin('b08c6fff7dc5e111fb210800200c9a66'), ], [ // Version 1 bytes 'bytes' => (string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66'), ], [ // Version 2 bytes 'bytes' => (string) hex2bin('000001f55cde21ea84000242ac130003'), ], [ // Version 3 bytes 'bytes' => (string) hex2bin('ff6f8cb0c57d31e1bb210800200c9a66'), ], [ // Version 4 bytes 'bytes' => (string) hex2bin('ff6f8cb0c57d41e1ab210800200c9a66'), ], [ // Version 5 bytes 'bytes' => (string) hex2bin('ff6f8cb0c57d51e18b210800200c9a66'), ], [ // Version 6 bytes 'bytes' => (string) hex2bin('ff6f8cb0c57d61e18b210800200c9a66'), ], [ // NIL bytes 'bytes' => (string) hex2bin('00000000000000000000000000000000'), ], ]; } } ================================================ FILE: tests/Codec/GuidStringCodecTest.php ================================================ builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock(); $this->fields = new Fields((string) hex2bin('785634123412cd4babef1234abcd4321')); } protected function tearDown(): void { parent::tearDown(); unset($this->builder, $this->fields, $this->uuid); } public function testEncodeUsesFieldsArray(): void { $this->uuid->expects($this->once()) ->method('getFields') ->willReturn($this->fields); $codec = new GuidStringCodec($this->builder); $codec->encode($this->uuid); } public function testEncodeReturnsFormattedString(): void { $this->uuid->method('getFields') ->willReturn($this->fields); $codec = new GuidStringCodec($this->builder); $result = $codec->encode($this->uuid); $this->assertSame('12345678-1234-4bcd-abef-1234abcd4321', $result); } public function testEncodeBinary(): void { $expectedBytes = (string) hex2bin('785634123412cd4babef1234abcd4321'); $fields = new Fields($expectedBytes); $codec = new GuidStringCodec($this->builder); $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $uuid = new Guid($fields, $numberConverter, $codec, $timeConverter); $bytes = $codec->encodeBinary($uuid); $this->assertSame($expectedBytes, $bytes); } public function testDecodeReturnsGuid(): void { $string = 'uuid:12345678-1234-4bcd-abef-1234abcd4321'; $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new GuidBuilder($numberConverter, $timeConverter); $codec = new GuidStringCodec($builder); $guid = $codec->decode($string); $this->assertInstanceOf(Guid::class, $guid); $this->assertSame('12345678-1234-4bcd-abef-1234abcd4321', $guid->toString()); } public function testDecodeReturnsUuidFromBuilder(): void { $string = 'uuid:78563412-3412-cd4b-abef-1234abcd4321'; $this->builder->method('build') ->willReturn($this->uuid); $codec = new GuidStringCodec($this->builder); $result = $codec->decode($string); $this->assertSame($this->uuid, $result); } public function testDecodeBytesReturnsUuid(): void { $string = '1234567812344bcd4bef1234abcd4321'; $bytes = pack('H*', $string); $codec = new GuidStringCodec($this->builder); $this->builder->method('build') ->willReturn($this->uuid); $result = $codec->decodeBytes($bytes); $this->assertSame($this->uuid, $result); } } ================================================ FILE: tests/Codec/OrderedTimeCodecTest.php ================================================ builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock(); $this->fields = new Fields((string) hex2bin('58e0a7d7eebc11d896690800200c9a66')); } protected function tearDown(): void { parent::tearDown(); unset($this->builder, $this->uuid, $this->fields); } public function testEncodeUsesFieldsArray(): void { $this->uuid->expects($this->once()) ->method('getFields') ->willReturn($this->fields); $codec = new OrderedTimeCodec($this->builder); $codec->encode($this->uuid); } public function testEncodeReturnsFormattedString(): void { $this->uuid->method('getFields') ->willReturn($this->fields); $codec = new OrderedTimeCodec($this->builder); $result = $codec->encode($this->uuid); $this->assertSame($this->uuidString, $result); } public function testEncodeBinary(): void { $expected = hex2bin($this->optimizedHex); $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $factory = new UuidFactory(); $factory->setCodec($codec); $uuid = $factory->fromString($this->uuidString); $this->assertSame($expected, $codec->encodeBinary($uuid)); } public function testDecodeBytesThrowsExceptionWhenBytesStringNotSixteenCharacters(): void { $string = '61'; $bytes = pack('H*', $string); $codec = new OrderedTimeCodec($this->builder); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('$bytes string should contain 16 characters.'); $codec->decodeBytes($bytes); } public function testDecodeReturnsUuidFromBuilder(): void { $string = 'uuid:58e0a7d7-eebc-11d8-9669-0800200c9a66'; $this->builder->method('build') ->willReturn($this->uuid); $codec = new OrderedTimeCodec($this->builder); $result = $codec->decode($string); $this->assertSame($this->uuid, $result); } public function testDecodeBytesRearrangesFields(): void { $bytes = (string) hex2bin($this->optimizedHex); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $factory = new UuidFactory(); $factory->setCodec($codec); $expectedUuid = $factory->fromString($this->uuidString); $uuidReturned = $codec->decodeBytes($bytes); $this->assertTrue($uuidReturned->equals($expectedUuid)); } public function testEncodeBinaryThrowsExceptionForNonRfc4122Uuid(): void { $nonRfc4122Uuid = '58e0a7d7-eebc-11d8-d669-0800200c9a66'; $fields = new NonstandardFields((string) hex2bin(str_replace('-', '', $nonRfc4122Uuid))); $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $uuid = Mockery::mock(UuidInterface::class, [ 'getVariant' => 0, 'toString' => $nonRfc4122Uuid, 'getFields' => $fields, ]); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected version 1 (time-based) UUID'); $codec->encodeBinary($uuid); } public function testEncodeBinaryThrowsExceptionForNonTimeBasedUuid(): void { $nonTimeBasedUuid = '58e0a7d7-eebc-41d8-9669-0800200c9a66'; $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $factory = new UuidFactory(); $factory->setCodec($codec); $uuid = $factory->fromString($nonTimeBasedUuid); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected version 1 (time-based) UUID'); $codec->encodeBinary($uuid); } public function testDecodeBytesThrowsExceptionsForNonRfc4122Uuid(): void { $nonRfc4122OptimizedHex = '11d8eebc58e0a7d716690800200c9a66'; $bytes = (string) hex2bin($nonRfc4122OptimizedHex); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = new GenericTimeConverter($calculator); $builder = new UuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage( 'Attempting to decode a non-time-based UUID using OrderedTimeCodec' ); $codec->decodeBytes($bytes); } public function testDecodeBytesThrowsExceptionsForNonTimeBasedUuid(): void { $nonTimeBasedOptimizedHex = '41d8eebc58e0a7d796690800200c9a66'; $bytes = (string) hex2bin($nonTimeBasedOptimizedHex); $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new OrderedTimeCodec($builder); $factory = new UuidFactory(); $factory->setCodec($codec); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage( 'Attempting to decode a non-time-based UUID using OrderedTimeCodec' ); $codec->decodeBytes($bytes); } public function testSerializationDoesNotUseOrderedTimeCodec(): void { $expected = '9ec692cc-67c8-11eb-ae93-0242ac130002'; $codec = new OrderedTimeCodec( (new UuidFactory())->getUuidBuilder() ); $decoded = $codec->decode($expected); $serialized = serialize($decoded); /** @var UuidInterface $unserializedUuid */ $unserializedUuid = unserialize($serialized); $expectedUuid = Uuid::fromString($expected); $this->assertSame($expectedUuid->getVersion(), $unserializedUuid->getVersion()); $this->assertTrue($expectedUuid->equals($unserializedUuid)); } } ================================================ FILE: tests/Codec/StringCodecTest.php ================================================ builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock(); $this->fields = new Fields((string) hex2bin('1234567812344bcdabef1234abcd4321')); } protected function tearDown(): void { parent::tearDown(); unset($this->builder, $this->uuid, $this->fields); } public function testEncodeUsesFieldsArray(): void { $this->uuid->expects($this->once()) ->method('getFields') ->willReturn($this->fields); $codec = new StringCodec($this->builder); $codec->encode($this->uuid); } public function testEncodeReturnsFormattedString(): void { $this->uuid->method('getFields') ->willReturn($this->fields); $codec = new StringCodec($this->builder); $result = $codec->encode($this->uuid); $this->assertSame($this->uuidString, $result); } public function testEncodeBinaryReturnsBinaryString(): void { $expected = hex2bin('123456781234abcdabef1234abcd4321'); $fields = Mockery::mock(FieldsInterface::class, [ 'getBytes' => hex2bin('123456781234abcdabef1234abcd4321'), ]); $this->uuid->method('getFields')->willReturn($fields); $codec = new StringCodec($this->builder); $result = $codec->encodeBinary($this->uuid); $this->assertSame($expected, $result); } public function testDecodeUsesBuilderOnFields(): void { $fields = [ 'time_low' => $this->fields->getTimeLow()->toString(), 'time_mid' => $this->fields->getTimeMid()->toString(), 'time_hi_and_version' => $this->fields->getTimeHiAndVersion()->toString(), 'clock_seq_hi_and_reserved' => $this->fields->getClockSeqHiAndReserved()->toString(), 'clock_seq_low' => $this->fields->getClockSeqLow()->toString(), 'node' => $this->fields->getNode()->toString(), ]; $bytes = hex2bin(implode('', $fields)); $string = 'uuid:12345678-1234-4bcd-abef-1234abcd4321'; $this->builder->expects($this->once()) ->method('build') ->with($this->isInstanceOf(StringCodec::class), $bytes); $codec = new StringCodec($this->builder); $codec->decode($string); } public function testDecodeThrowsExceptionOnInvalidUuid(): void { $string = 'invalid-uuid'; $codec = new StringCodec($this->builder); $this->expectException(InvalidArgumentException::class); $codec->decode($string); } public function testDecodeReturnsUuidFromBuilder(): void { $string = 'uuid:12345678-1234-abcd-abef-1234abcd4321'; $this->builder->method('build') ->willReturn($this->uuid); $codec = new StringCodec($this->builder); $result = $codec->decode($string); $this->assertSame($this->uuid, $result); } public function testDecodeBytesThrowsExceptionWhenBytesStringNotSixteenCharacters(): void { $string = '61'; $bytes = pack('H*', $string); $codec = new StringCodec($this->builder); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('$bytes string should contain 16 characters.'); $codec->decodeBytes($bytes); } public function testDecodeBytesReturnsUuid(): void { $string = '123456781234abcdabef1234abcd4321'; $bytes = pack('H*', $string); $codec = new StringCodec($this->builder); $this->builder->method('build') ->willReturn($this->uuid); $result = $codec->decodeBytes($bytes); $this->assertSame($this->uuid, $result); } } ================================================ FILE: tests/Converter/Number/BigNumberConverterTest.php ================================================ expectException(InvalidArgumentException::class); $this->expectExceptionMessage('"." is not a valid character in base 16'); $converter->fromHex('123.34'); } public function testToHexThrowsExceptionWhenStringDoesNotContainOnlyDigits(): void { $converter = new BigNumberConverter(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only digits ' . '0-9 and, optionally, a sign (+ or -)' ); $converter->toHex('123.34'); } public function testFromHex(): void { $converter = new BigNumberConverter(); $this->assertSame('65535', $converter->fromHex('ffff')); } public function testToHex(): void { $converter = new BigNumberConverter(); $this->assertSame('ffff', $converter->toHex('65535')); } } ================================================ FILE: tests/Converter/Number/GenericNumberConverterTest.php ================================================ assertSame('65535', $converter->fromHex('ffff')); } public function testToHex(): void { $calculator = new BrickMathCalculator(); $converter = new GenericNumberConverter($calculator); $this->assertSame('ffff', $converter->toHex('65535')); } } ================================================ FILE: tests/Converter/Time/BigNumberTimeConverterTest.php ================================================ plus($seconds->multipliedBy(10000000)) ->plus($microseconds->multipliedBy(10)) ->plus(BigInteger::fromBase('01b21dd213814000', 16)); $maskLow = BigInteger::fromBase('ffffffff', 16); $maskMid = BigInteger::fromBase('ffff', 16); $maskHi = BigInteger::fromBase('0fff', 16); $expected = sprintf('%04s', $calculatedTime->shiftedRight(48)->and($maskHi)->toBase(16)); $expected .= sprintf('%04s', $calculatedTime->shiftedRight(32)->and($maskMid)->toBase(16)); $expected .= sprintf('%08s', $calculatedTime->and($maskLow)->toBase(16)); $converter = new BigNumberTimeConverter(); $returned = $converter->calculateTime((string) $seconds, (string) $microseconds); $this->assertSame($expected, $returned->toString()); } public function testConvertTime(): void { $converter = new BigNumberTimeConverter(); $returned = $converter->convertTime(new Hexadecimal('1e1c57dff6f8cb0')); $this->assertSame('1341368074', $returned->getSeconds()->toString()); } public function testCalculateTimeThrowsExceptionWhenSecondsIsNotOnlyDigits(): void { $converter = new BigNumberTimeConverter(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only digits ' . '0-9 and, optionally, a sign (+ or -)' ); $converter->calculateTime('12.34', '5678'); } public function testCalculateTimeThrowsExceptionWhenMicrosecondsIsNotOnlyDigits(): void { $converter = new BigNumberTimeConverter(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only digits ' . '0-9 and, optionally, a sign (+ or -)' ); $converter->calculateTime('1234', '56.78'); } } ================================================ FILE: tests/Converter/Time/GenericTimeConverterTest.php ================================================ calculateTime($seconds, $microseconds); $this->assertSame($expected, $result->toString()); } /** * @return array */ public function provideCalculateTime(): array { return [ [ 'seconds' => '-12219146756', 'microseconds' => '0', 'expected' => '000001540901e600', ], [ 'seconds' => '103072857659', 'microseconds' => '999999', 'expected' => '0fffffffff9785f6', ], [ 'seconds' => '1578612359', 'microseconds' => '521023', 'expected' => '01ea333764c71df6', ], // This is the earliest possible date supported by v1 UUIDs: // 1582-10-15 00:00:00.000000 [ 'seconds' => '-12219292800', 'microseconds' => '0', 'expected' => '0000000000000000', ], // This is the last possible time supported by the GenericTimeConverter: // 60038-03-11 05:36:10.955161 // When a UUID is created from this time, however, the highest 4 bits // are replaced with the version (1), so we lose fidelity and cannot // accurately decompose the date from the UUID. [ 'seconds' => '1832455114570', 'microseconds' => '955161', 'expected' => 'fffffffffffffffa', ], // This is technically the last possible time supported by v1 UUIDs: // 5236-03-31 21:21:00.684697 // All dates above this will lose fidelity, since the highest 4 bits // are replaced with the UUID version (1). As a result, we cannot // accurately decompose the date from UUIDs created from dates // greater than this one. [ 'seconds' => '103072857660', 'microseconds' => '684697', 'expected' => '0ffffffffffffffa', ], ]; } /** * @param numeric-string $unixTimestamp * @param numeric-string $microseconds * * @dataProvider provideConvertTime */ public function testConvertTime(Hexadecimal $uuidTimestamp, string $unixTimestamp, string $microseconds): void { $calculator = new BrickMathCalculator(); $converter = new GenericTimeConverter($calculator); $result = $converter->convertTime($uuidTimestamp); $this->assertSame($unixTimestamp, $result->getSeconds()->toString()); $this->assertSame($microseconds, $result->getMicroseconds()->toString()); } /** * @return array */ public function provideConvertTime(): array { return [ [ 'uuidTimestamp' => new Hexadecimal('1e1c57dff6f8cb0'), 'unixTimestamp' => '1341368074', 'microseconds' => '491000', ], [ 'uuidTimestamp' => new Hexadecimal('1ea333764c71df6'), 'unixTimestamp' => '1578612359', 'microseconds' => '521023', ], [ 'uuidTimestamp' => new Hexadecimal('fffffffff9785f6'), 'unixTimestamp' => '103072857659', 'microseconds' => '999999', ], // This is the last possible time supported by v1 UUIDs. When // converted to a Unix timestamp, the microseconds are lost. // 60038-03-11 05:36:10.955161 [ 'uuidTimestamp' => new Hexadecimal('fffffffffffffffa'), 'unixTimestamp' => '1832455114570', 'microseconds' => '955161', ], // This is the earliest possible date supported by v1 UUIDs: // 1582-10-15 00:00:00.000000 [ 'uuidTimestamp' => new Hexadecimal('000000000000'), 'unixTimestamp' => '-12219292800', 'microseconds' => '0', ], // This is the Unix epoch: // 1970-01-01 00:00:00.000000 [ 'uuidTimestamp' => new Hexadecimal('1b21dd213814000'), 'unixTimestamp' => '0', 'microseconds' => '0', ], ]; } } ================================================ FILE: tests/Converter/Time/PhpTimeConverterTest.php ================================================ plus($seconds->multipliedBy(10000000)) ->plus($microseconds->multipliedBy(10)) ->plus(BigInteger::fromBase('01b21dd213814000', 16)); $maskLow = BigInteger::fromBase('ffffffff', 16); $maskMid = BigInteger::fromBase('ffff', 16); $maskHi = BigInteger::fromBase('0fff', 16); $expected = sprintf('%04s', $calculatedTime->shiftedRight(48)->and($maskHi)->toBase(16)); $expected .= sprintf('%04s', $calculatedTime->shiftedRight(32)->and($maskMid)->toBase(16)); $expected .= sprintf('%08s', $calculatedTime->and($maskLow)->toBase(16)); $converter = new PhpTimeConverter(); $returned = $converter->calculateTime((string) $seconds, (string) $microseconds); $this->assertSame($expected, $returned->toString()); } public function testCalculateTimeThrowsExceptionWhenSecondsIsNotOnlyDigits(): void { /** @var Mockery\MockInterface & PhpTimeConverter $converter */ $converter = Mockery::mock(PhpTimeConverter::class)->makePartial(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only digits ' . '0-9 and, optionally, a sign (+ or -)' ); $converter->calculateTime('12.34', '5678'); } public function testCalculateTimeThrowsExceptionWhenMicrosecondsIsNotOnlyDigits(): void { /** @var Mockery\MockInterface & PhpTimeConverter $converter */ $converter = Mockery::mock(PhpTimeConverter::class)->makePartial(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only digits ' . '0-9 and, optionally, a sign (+ or -)' ); $converter->calculateTime('1234', '56.78'); } /** * @param numeric-string $unixTimestamp * @param numeric-string $microseconds * * @dataProvider provideConvertTime */ public function testConvertTime(Hexadecimal $uuidTimestamp, string $unixTimestamp, string $microseconds): void { $calculator = new BrickMathCalculator(); $fallbackConverter = new GenericTimeConverter($calculator); $converter = new PhpTimeConverter($calculator, $fallbackConverter); $result = $converter->convertTime($uuidTimestamp); $this->assertSame($unixTimestamp, $result->getSeconds()->toString()); $this->assertSame($microseconds, $result->getMicroseconds()->toString()); } /** * @return array */ public function provideConvertTime(): array { return [ [ 'uuidTimestamp' => new Hexadecimal('1e1c57dff6f8cb0'), 'unixTimestamp' => '1341368074', 'microseconds' => '491000', ], [ 'uuidTimestamp' => new Hexadecimal('1ea333764c71df6'), 'unixTimestamp' => '1578612359', 'microseconds' => '521023', ], [ 'uuidTimestamp' => new Hexadecimal('fffffffff9785f6'), 'unixTimestamp' => '103072857659', 'microseconds' => '999999', ], // This is the last possible time supported by v1 UUIDs. When // converted to a Unix timestamp, the microseconds are lost. // 60038-03-11 05:36:10.955161 [ 'uuidTimestamp' => new Hexadecimal('fffffffffffffffa'), 'unixTimestamp' => '1832455114570', 'microseconds' => '955161', ], // This is the earliest possible date supported by v1 UUIDs: // 1582-10-15 00:00:00.000000 [ 'uuidTimestamp' => new Hexadecimal('000000000000'), 'unixTimestamp' => '-12219292800', 'microseconds' => '0', ], // This is the Unix epoch: // 1970-01-01 00:00:00.000000 [ 'uuidTimestamp' => new Hexadecimal('1b21dd213814000'), 'unixTimestamp' => '0', 'microseconds' => '0', ], ]; } /** * @param non-empty-string $seconds * @param non-empty-string $microseconds * @param non-empty-string $expected * * @dataProvider provideCalculateTime */ public function testCalculateTime(string $seconds, string $microseconds, string $expected): void { $calculator = new BrickMathCalculator(); $fallbackConverter = new GenericTimeConverter($calculator); $converter = new PhpTimeConverter($calculator, $fallbackConverter); $result = $converter->calculateTime($seconds, $microseconds); $this->assertSame($expected, $result->toString()); } /** * @return array */ public function provideCalculateTime(): array { return [ [ 'seconds' => '-12219146756', 'microseconds' => '0', 'expected' => '000001540901e600', ], [ 'seconds' => '103072857659', 'microseconds' => '999999', 'expected' => '0fffffffff9785f6', ], [ 'seconds' => '1578612359', 'microseconds' => '521023', 'expected' => '01ea333764c71df6', ], // This is the earliest possible date supported by v1 UUIDs: // 1582-10-15 00:00:00.000000 [ 'seconds' => '-12219292800', 'microseconds' => '0', 'expected' => '0000000000000000', ], // This is the last possible time supported by v1 UUIDs: // 60038-03-11 05:36:10.955161 [ 'seconds' => '1832455114570', 'microseconds' => '955161', 'expected' => 'fffffffffffffffa', ], ]; } } ================================================ FILE: tests/Converter/Time/UnixTimeConverterTest.php ================================================ convertTime($uuidTimestamp); $this->assertSame($unixTimestamp, $result->getSeconds()->toString()); $this->assertSame($microseconds, $result->getMicroseconds()->toString()); } /** * @return array */ public function provideConvertTime(): array { return [ [ 'uuidTimestamp' => new Hexadecimal('017F22E279B0'), 'unixTimestamp' => '1645557742', 'microseconds' => '0', ], [ 'uuidTimestamp' => new Hexadecimal('01384fc480fb'), 'unixTimestamp' => '1341368074', 'microseconds' => '491000', ], [ 'uuidTimestamp' => new Hexadecimal('016f8ca10161'), 'unixTimestamp' => '1578612359', 'microseconds' => '521000', ], [ 'uuidTimestamp' => new Hexadecimal('5dbe85111a5f'), 'unixTimestamp' => '103072857659', 'microseconds' => '999000', ], // This is the last possible time supported by v7 UUIDs (2 ^ 48 - 1). // 10889-08-02 05:31:50.655 +00:00 [ 'uuidTimestamp' => new Hexadecimal('ffffffffffff'), 'unixTimestamp' => '281474976710', 'microseconds' => '655000', ], // This is the earliest possible date supported by v7 UUIDs. // It is the Unix Epoch (big surprise!). // 1970-01-01 00:00:00.0 +00:00 [ 'uuidTimestamp' => new Hexadecimal('000000000000'), 'unixTimestamp' => '0', 'microseconds' => '0', ], [ 'uuidTimestamp' => new Hexadecimal('000000000001'), 'unixTimestamp' => '0', 'microseconds' => '1000', ], [ 'uuidTimestamp' => new Hexadecimal('00000000000f'), 'unixTimestamp' => '0', 'microseconds' => '15000', ], [ 'uuidTimestamp' => new Hexadecimal('000000000064'), 'unixTimestamp' => '0', 'microseconds' => '100000', ], [ 'uuidTimestamp' => new Hexadecimal('0000000003e7'), 'unixTimestamp' => '0', 'microseconds' => '999000', ], [ 'uuidTimestamp' => new Hexadecimal('0000000003e8'), 'unixTimestamp' => '1', 'microseconds' => '0', ], [ 'uuidTimestamp' => new Hexadecimal('0000000003e9'), 'unixTimestamp' => '1', 'microseconds' => '1000', ], ]; } /** * @dataProvider provideCalculateTime */ public function testCalculateTime(string $seconds, string $microseconds, string $expected): void { $calculator = new BrickMathCalculator(); $converter = new UnixTimeConverter($calculator); $result = $converter->calculateTime($seconds, $microseconds); $this->assertSame($expected, $result->toString()); } /** * @return array */ public function provideCalculateTime(): array { return [ [ 'seconds' => '1645557742', 'microseconds' => '0', 'expected' => '017f22e279b0', ], [ 'seconds' => '1341368074', 'microseconds' => '491000', 'expected' => '01384fc480fb', ], [ 'seconds' => '1578612359', 'microseconds' => '521023', 'expected' => '016f8ca10161', ], [ 'seconds' => '103072857659', 'microseconds' => '999499', 'expected' => '5dbe85111a5f', ], [ 'seconds' => '103072857659', 'microseconds' => '999999', 'expected' => '5dbe85111a5f', ], // This is the earliest possible date supported by v7 UUIDs. // It is the Unix Epoch (big surprise!): 1970-01-01 00:00:00.0 +00:00 [ 'seconds' => '0', 'microseconds' => '0', 'expected' => '000000000000', ], // This is the last possible time supported by v7 UUIDs (2 ^ 48 - 1): // 10889-08-02 05:31:50.655 +00:00 [ 'seconds' => '281474976710', 'microseconds' => '655000', 'expected' => 'ffffffffffff', ], [ 'seconds' => '0', 'microseconds' => '1000', 'expected' => '000000000001', ], [ 'seconds' => '0', 'microseconds' => '15000', 'expected' => '00000000000f', ], [ 'seconds' => '0', 'microseconds' => '100000', 'expected' => '000000000064', ], [ 'seconds' => '0', 'microseconds' => '999000', 'expected' => '0000000003e7', ], [ 'seconds' => '1', 'microseconds' => '0', 'expected' => '0000000003e8', ], [ 'seconds' => '1', 'microseconds' => '1000', 'expected' => '0000000003e9', ], ]; } } ================================================ FILE: tests/DeprecatedUuidMethodsTraitTest.php ================================================ assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u')); } public function testGetDateTimeThrowsException(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 1, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new Uuid($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } } ================================================ FILE: tests/Encoder/TimestampFirstCombCodecTest.php ================================================ builderMock = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $this->codec = new TimestampFirstCombCodec($this->builderMock); } public function testEncoding(): void { $fields = new Fields((string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66')); $uuidMock = Mockery::mock(UuidInterface::class, [ 'getFields' => $fields, ]); $encodedUuid = $this->codec->encode($uuidMock); $this->assertSame('0800200c-9a66-11e1-9b21-ff6f8cb0c57d', $encodedUuid); } public function testBinaryEncoding(): void { $fields = new Fields((string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66')); $uuidMock = Mockery::mock(UuidInterface::class, [ 'getFields' => $fields, ]); $encodedUuid = $this->codec->encodeBinary($uuidMock); $this->assertSame(hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'), $encodedUuid); } public function testDecoding(): void { $this->builderMock->expects($this->exactly(1)) ->method('build') ->with( $this->codec, hex2bin(implode('', [ 'time_low' => 'ff6f8cb0', 'time_mid' => 'c57d', 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', 'node' => '0800200c9a66', ])) ); $this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d'); } public function testBinaryDecoding(): void { $this->builderMock->expects($this->exactly(1)) ->method('build') ->with( $this->codec, hex2bin(implode('', [ 'time_low' => 'ff6f8cb0', 'time_mid' => 'c57d', 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', 'node' => '0800200c9a66', ])) ); $this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d')); } } ================================================ FILE: tests/Encoder/TimestampLastCombCodecTest.php ================================================ builderMock = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $this->codec = new TimestampLastCombCodec($this->builderMock); } public function testEncoding(): void { $fields = new Fields((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d')); $uuidMock = Mockery::mock(UuidInterface::class, [ 'getFields' => $fields, ]); $encodedUuid = $this->codec->encode($uuidMock); $this->assertSame('0800200c-9a66-11e1-9b21-ff6f8cb0c57d', $encodedUuid); } public function testBinaryEncoding(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getBytes' => hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'), ]); /** @var MockObject & UuidInterface $uuidMock */ $uuidMock = $this->getMockBuilder(UuidInterface::class)->getMock(); $uuidMock->expects($this->any())->method('getFields')->willReturn($fields); $encodedUuid = $this->codec->encodeBinary($uuidMock); $this->assertSame(hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'), $encodedUuid); } public function testDecoding(): void { $this->builderMock->expects($this->exactly(1)) ->method('build') ->with( $this->codec, hex2bin(implode('', [ 'time_low' => '0800200c', 'time_mid' => '9a66', 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', 'node' => 'ff6f8cb0c57d', ])) ); $this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d'); } public function testBinaryDecoding(): void { $this->builderMock->expects($this->exactly(1)) ->method('build') ->with( $this->codec, hex2bin(implode('', [ 'time_low' => '0800200c', 'time_mid' => '9a66', 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', 'node' => 'ff6f8cb0c57d', ])) ); $this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d')); } } ================================================ FILE: tests/ExpectedBehaviorTest.php ================================================ assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertIsInt($uuid->compareTo(Uuid::uuid1())); $this->assertNotSame(0, $uuid->compareTo(Uuid::uuid4())); $this->assertSame(0, $uuid->compareTo(clone $uuid)); $this->assertFalse($uuid->equals(new stdClass())); $this->assertTrue($uuid->equals(clone $uuid)); $this->assertIsString($uuid->getBytes()); $this->assertInstanceOf('Ramsey\Uuid\Converter\NumberConverterInterface', $uuid->getNumberConverter()); $this->assertIsString((string) $uuid->getHex()); $this->assertIsArray($uuid->getFieldsHex()); $this->assertArrayHasKey('time_low', $uuid->getFieldsHex()); $this->assertArrayHasKey('time_mid', $uuid->getFieldsHex()); $this->assertArrayHasKey('time_hi_and_version', $uuid->getFieldsHex()); $this->assertArrayHasKey('clock_seq_hi_and_reserved', $uuid->getFieldsHex()); $this->assertArrayHasKey('clock_seq_low', $uuid->getFieldsHex()); $this->assertArrayHasKey('node', $uuid->getFieldsHex()); $this->assertIsString($uuid->getTimeLowHex()); $this->assertIsString($uuid->getTimeMidHex()); $this->assertIsString($uuid->getTimeHiAndVersionHex()); $this->assertIsString($uuid->getClockSeqHiAndReservedHex()); $this->assertIsString($uuid->getClockSeqLowHex()); $this->assertIsString($uuid->getNodeHex()); $this->assertSame($uuid->getFieldsHex()['time_low'], $uuid->getTimeLowHex()); $this->assertSame($uuid->getFieldsHex()['time_mid'], $uuid->getTimeMidHex()); $this->assertSame($uuid->getFieldsHex()['time_hi_and_version'], $uuid->getTimeHiAndVersionHex()); $this->assertSame($uuid->getFieldsHex()['clock_seq_hi_and_reserved'], $uuid->getClockSeqHiAndReservedHex()); $this->assertSame($uuid->getFieldsHex()['clock_seq_low'], $uuid->getClockSeqLowHex()); $this->assertSame($uuid->getFieldsHex()['node'], $uuid->getNodeHex()); $this->assertSame(substr((string) $uuid->getHex(), 16), $uuid->getLeastSignificantBitsHex()); $this->assertSame(substr((string) $uuid->getHex(), 0, 16), $uuid->getMostSignificantBitsHex()); $this->assertSame( (string) $uuid->getHex(), $uuid->getTimeLowHex() . $uuid->getTimeMidHex() . $uuid->getTimeHiAndVersionHex() . $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex() . $uuid->getNodeHex() ); $this->assertSame( (string) $uuid->getHex(), $uuid->getFieldsHex()['time_low'] . $uuid->getFieldsHex()['time_mid'] . $uuid->getFieldsHex()['time_hi_and_version'] . $uuid->getFieldsHex()['clock_seq_hi_and_reserved'] . $uuid->getFieldsHex()['clock_seq_low'] . $uuid->getFieldsHex()['node'] ); $this->assertIsString($uuid->getUrn()); $this->assertStringStartsWith('urn:uuid:', $uuid->getUrn()); $this->assertSame('urn:uuid:' . (string) $uuid->getHex(), str_replace('-', '', $uuid->getUrn())); $this->assertSame((string) $uuid->getHex(), str_replace('-', '', $uuid->toString())); $this->assertSame((string) $uuid->getHex(), str_replace('-', '', (string) $uuid)); $this->assertSame( $uuid->toString(), $uuid->getTimeLowHex() . '-' . $uuid->getTimeMidHex() . '-' . $uuid->getTimeHiAndVersionHex() . '-' . $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex() . '-' . $uuid->getNodeHex() ); $this->assertSame( (string) $uuid, $uuid->getTimeLowHex() . '-' . $uuid->getTimeMidHex() . '-' . $uuid->getTimeHiAndVersionHex() . '-' . $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex() . '-' . $uuid->getNodeHex() ); $this->assertSame(2, $uuid->getVariant()); $this->assertSame((int) substr($method, -1), $uuid->getVersion()); $this->assertSame(1, preg_match('/^\d+$/', (string) $uuid->getInteger())); } public function provideStaticCreationMethods() { return [ ['uuid1', []], ['uuid1', ['00000fffffff']], ['uuid1', [null, 1234]], ['uuid1', ['00000fffffff', 1234]], ['uuid1', ['00000fffffff', null]], ['uuid1', [268435455]], ['uuid1', [268435455, 1234]], ['uuid1', [268435455, null]], ['uuid3', [Uuid::NAMESPACE_URL, 'https://example.com/foo']], ['uuid4', []], ['uuid5', [Uuid::NAMESPACE_URL, 'https://example.com/foo']], ]; } public function testUuidVersion1MethodBehavior() { $uuid = Uuid::uuid1('00000fffffff', 0xffff); $this->assertInstanceOf('DateTimeInterface', $uuid->getDateTime()); $this->assertSame('00000fffffff', $uuid->getNodeHex()); $this->assertSame('3fff', $uuid->getClockSequenceHex()); $this->assertSame('16383', (string) $uuid->getClockSequence()); } public function testUuidVersion1MethodBehavior64Bit() { $uuid = Uuid::uuid1('ffffffffffff', 0xffff); $this->assertInstanceOf('DateTimeInterface', $uuid->getDateTime()); $this->assertSame('ffffffffffff', $uuid->getNodeHex()); $this->assertSame('281474976710655', (string) $uuid->getNode()); $this->assertSame('3fff', $uuid->getClockSequenceHex()); $this->assertSame('16383', (string) $uuid->getClockSequence()); $this->assertSame(1, preg_match('/^\d+$/', (string) $uuid->getTimestamp())); } /** * @dataProvider provideIsValid */ public function testIsValid($uuid, $expected) { $this->assertSame($expected, Uuid::isValid($uuid), "{$uuid} is not a valid UUID"); $this->assertSame($expected, Uuid::isValid(strtoupper($uuid)), strtoupper($uuid) . ' is not a valid UUID'); } public function provideIsValid() { return [ // RFC 4122 UUIDs ['00000000-0000-0000-0000-000000000000', true], ['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', true], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', true], ['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', true], ['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', true], ['ff6f8cb0-c57d-21e1-8b21-0800200c9a66', true], ['ff6f8cb0-c57d-21e1-9b21-0800200c9a66', true], ['ff6f8cb0-c57d-21e1-ab21-0800200c9a66', true], ['ff6f8cb0-c57d-21e1-bb21-0800200c9a66', true], ['ff6f8cb0-c57d-31e1-8b21-0800200c9a66', true], ['ff6f8cb0-c57d-31e1-9b21-0800200c9a66', true], ['ff6f8cb0-c57d-31e1-ab21-0800200c9a66', true], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', true], ['ff6f8cb0-c57d-41e1-8b21-0800200c9a66', true], ['ff6f8cb0-c57d-41e1-9b21-0800200c9a66', true], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', true], ['ff6f8cb0-c57d-41e1-bb21-0800200c9a66', true], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', true], ['ff6f8cb0-c57d-51e1-9b21-0800200c9a66', true], ['ff6f8cb0-c57d-51e1-ab21-0800200c9a66', true], ['ff6f8cb0-c57d-51e1-bb21-0800200c9a66', true], // Non RFC 4122 UUIDs ['ffffffff-ffff-ffff-ffff-ffffffffffff', true], ['00000000-0000-0000-0000-000000000000', true], ['ff6f8cb0-c57d-01e1-0b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-1b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-2b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-3b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-4b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-5b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-6b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-7b21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-db21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-eb21-0800200c9a66', true], ['ff6f8cb0-c57d-01e1-fb21-0800200c9a66', true], // Other valid patterns ['{ff6f8cb0-c57d-01e1-fb21-0800200c9a66}', true], ['urn:uuid:ff6f8cb0-c57d-01e1-fb21-0800200c9a66', true], // Invalid UUIDs ['ffffffffffffffffffffffffffffffff', false], ['00000000000000000000000000000000', false], [0, false], ['foobar', false], ['ff6f8cb0c57d51e1bb210800200c9a66', false], ['gf6f8cb0-c57d-51e1-bb21-0800200c9a66', false], ]; } /** * @dataProvider provideFromStringInteger */ public function testSerialization($string) { $uuid = Uuid::fromString($string); $serialized = serialize($uuid); $unserialized = unserialize($serialized); $this->assertSame(0, $uuid->compareTo($unserialized)); $this->assertTrue($uuid->equals($unserialized)); $this->assertSame("\"{$string}\"", json_encode($uuid)); } /** * @dataProvider provideFromStringInteger */ public function testSerializationWithOrderedTimeCodec($string) { $factory = new UuidFactory(); $factory->setCodec(new OrderedTimeCodec( $factory->getUuidBuilder() )); $previousFactory = Uuid::getFactory(); Uuid::setFactory($factory); $uuid = Uuid::fromString($string); $serialized = serialize($uuid); $unserialized = unserialize($serialized); Uuid::setFactory($previousFactory); $this->assertSame(0, $uuid->compareTo($unserialized)); $this->assertTrue($uuid->equals($unserialized)); $this->assertSame("\"{$string}\"", json_encode($uuid)); } /** * @dataProvider provideFromStringInteger */ public function testNumericReturnValues($string) { $leastSignificantBitsHex = substr(str_replace('-', '', $string), 16); $mostSignificantBitsHex = substr(str_replace('-', '', $string), 0, 16); $leastSignificantBits = BigInteger::fromBase($leastSignificantBitsHex, 16)->__toString(); $mostSignificantBits = BigInteger::fromBase($mostSignificantBitsHex, 16)->__toString(); $components = explode('-', $string); array_walk($components, function (&$value) { $value = BigInteger::fromBase($value, 16)->__toString(); }); if (strtolower($string) === Uuid::MAX) { $clockSeq = (int) $components[3]; } else { $clockSeq = (int) $components[3] & 0x3fff; } $clockSeqHiAndReserved = (int) $components[3] >> 8; $clockSeqLow = (int) $components[3] & 0x00ff; $uuid = Uuid::fromString($string); $this->assertSame($components[0], (string) $uuid->getTimeLow()); $this->assertSame($components[1], (string) $uuid->getTimeMid()); $this->assertSame($components[2], (string) $uuid->getTimeHiAndVersion()); $this->assertSame((string) $clockSeq, (string) $uuid->getClockSequence()); $this->assertSame((string) $clockSeqHiAndReserved, (string) $uuid->getClockSeqHiAndReserved()); $this->assertSame((string) $clockSeqLow, (string) $uuid->getClockSeqLow()); $this->assertSame($components[4], (string) $uuid->getNode()); $this->assertSame($leastSignificantBits, (string) $uuid->getLeastSignificantBits()); $this->assertSame($mostSignificantBits, (string) $uuid->getMostSignificantBits()); } /** * @dataProvider provideFromStringInteger */ public function testFromBytes($string, $version, $variant, $integer) { $bytes = hex2bin(str_replace('-', '', $string)); $uuid = Uuid::fromBytes($bytes); $this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertSame($string, $uuid->toString()); $this->assertSame($version, $uuid->getVersion()); $this->assertSame($variant, $uuid->getVariant()); $components = explode('-', $string); $this->assertSame($components[0], $uuid->getTimeLowHex()); $this->assertSame($components[1], $uuid->getTimeMidHex()); $this->assertSame($components[2], $uuid->getTimeHiAndVersionHex()); $this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex()); $this->assertSame($components[4], $uuid->getNodeHex()); $this->assertSame($integer, (string) $uuid->getInteger()); $this->assertSame($bytes, $uuid->getBytes()); } /** * @dataProvider provideFromStringInteger */ public function testFromInteger($string, $version, $variant, $integer) { $bytes = hex2bin(str_replace('-', '', $string)); $uuid = Uuid::fromInteger($integer); $this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertSame($string, $uuid->toString()); $this->assertSame($version, $uuid->getVersion()); $this->assertSame($variant, $uuid->getVariant()); $components = explode('-', $string); $this->assertSame($components[0], $uuid->getTimeLowHex()); $this->assertSame($components[1], $uuid->getTimeMidHex()); $this->assertSame($components[2], $uuid->getTimeHiAndVersionHex()); $this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex()); $this->assertSame($components[4], $uuid->getNodeHex()); $this->assertSame($integer, (string) $uuid->getInteger()); $this->assertSame($bytes, $uuid->getBytes()); } /** * @dataProvider provideFromStringInteger */ public function testFromString($string, $version, $variant, $integer) { $bytes = hex2bin(str_replace('-', '', $string)); $uuid = Uuid::fromString($string); $this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertSame($string, $uuid->toString()); $this->assertSame($version, $uuid->getVersion()); $this->assertSame($variant, $uuid->getVariant()); $components = explode('-', $string); $this->assertSame($components[0], $uuid->getTimeLowHex()); $this->assertSame($components[1], $uuid->getTimeMidHex()); $this->assertSame($components[2], $uuid->getTimeHiAndVersionHex()); $this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex()); $this->assertSame($components[4], $uuid->getNodeHex()); $this->assertSame($integer, (string) $uuid->getInteger()); $this->assertSame($bytes, $uuid->getBytes()); } public function provideFromStringInteger() { return [ ['00000000-0000-0000-0000-000000000000', null, 0, '0'], ['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', 1, 2, '339532337419071774304650190139318639206'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 1, 2, '339532337419071774305803111643925486182'], ['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', 1, 2, '339532337419071774306956033148532333158'], ['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', 1, 2, '339532337419071774308108954653139180134'], ['ff6f8cb0-c57d-21e1-8b21-0800200c9a66', 2, 2, '339532337419071849862513916053642058342'], ['ff6f8cb0-c57d-21e1-9b21-0800200c9a66', 2, 2, '339532337419071849863666837558248905318'], ['ff6f8cb0-c57d-21e1-ab21-0800200c9a66', 2, 2, '339532337419071849864819759062855752294'], ['ff6f8cb0-c57d-21e1-bb21-0800200c9a66', 2, 2, '339532337419071849865972680567462599270'], ['ff6f8cb0-c57d-31e1-8b21-0800200c9a66', 3, 2, '339532337419071925420377641967965477478'], ['ff6f8cb0-c57d-31e1-9b21-0800200c9a66', 3, 2, '339532337419071925421530563472572324454'], ['ff6f8cb0-c57d-31e1-ab21-0800200c9a66', 3, 2, '339532337419071925422683484977179171430'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 3, 2, '339532337419071925423836406481786018406'], ['ff6f8cb0-c57d-41e1-8b21-0800200c9a66', 4, 2, '339532337419072000978241367882288896614'], ['ff6f8cb0-c57d-41e1-9b21-0800200c9a66', 4, 2, '339532337419072000979394289386895743590'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 4, 2, '339532337419072000980547210891502590566'], ['ff6f8cb0-c57d-41e1-bb21-0800200c9a66', 4, 2, '339532337419072000981700132396109437542'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 5, 2, '339532337419072076536105093796612315750'], ['ff6f8cb0-c57d-51e1-9b21-0800200c9a66', 5, 2, '339532337419072076537258015301219162726'], ['ff6f8cb0-c57d-51e1-ab21-0800200c9a66', 5, 2, '339532337419072076538410936805826009702'], ['ff6f8cb0-c57d-51e1-bb21-0800200c9a66', 5, 2, '339532337419072076539563858310432856678'], ['ff6f8cb0-c57d-01e1-0b21-0800200c9a66', null, 0, '339532337419071698737563092188140444262'], ['ff6f8cb0-c57d-01e1-1b21-0800200c9a66', null, 0, '339532337419071698738716013692747291238'], ['ff6f8cb0-c57d-01e1-2b21-0800200c9a66', null, 0, '339532337419071698739868935197354138214'], ['ff6f8cb0-c57d-01e1-3b21-0800200c9a66', null, 0, '339532337419071698741021856701960985190'], ['ff6f8cb0-c57d-01e1-4b21-0800200c9a66', null, 0, '339532337419071698742174778206567832166'], ['ff6f8cb0-c57d-01e1-5b21-0800200c9a66', null, 0, '339532337419071698743327699711174679142'], ['ff6f8cb0-c57d-01e1-6b21-0800200c9a66', null, 0, '339532337419071698744480621215781526118'], ['ff6f8cb0-c57d-01e1-7b21-0800200c9a66', null, 0, '339532337419071698745633542720388373094'], ['ff6f8cb0-c57d-01e1-cb21-0800200c9a66', null, 6, '339532337419071698751398150243422607974'], ['ff6f8cb0-c57d-01e1-db21-0800200c9a66', null, 6, '339532337419071698752551071748029454950'], ['ff6f8cb0-c57d-01e1-eb21-0800200c9a66', null, 7, '339532337419071698753703993252636301926'], ['ff6f8cb0-c57d-01e1-fb21-0800200c9a66', null, 7, '339532337419071698754856914757243148902'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', null, 7, '340282366920938463463374607431768211455'], ]; } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetSetFactory() { $this->assertInstanceOf('Ramsey\Uuid\UuidFactory', Uuid::getFactory()); $factory = \Mockery::mock('Ramsey\Uuid\UuidFactory'); Uuid::setFactory($factory); $this->assertSame($factory, Uuid::getFactory()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testFactoryProvidesFunctionality() { $uuid = \Mockery::mock('Ramsey\Uuid\UuidInterface'); $factory = \Mockery::mock('Ramsey\Uuid\UuidFactoryInterface', [ 'uuid1' => $uuid, 'uuid3' => $uuid, 'uuid4' => $uuid, 'uuid5' => $uuid, 'fromBytes' => $uuid, 'fromString' => $uuid, 'fromInteger' => $uuid, ]); Uuid::setFactory($factory); $this->assertSame($uuid, Uuid::uuid1('ffffffffffff', 0xffff)); $this->assertSame($uuid, Uuid::uuid3(Uuid::NAMESPACE_URL, 'https://example.com/foo')); $this->assertSame($uuid, Uuid::uuid4()); $this->assertSame($uuid, Uuid::uuid5(Uuid::NAMESPACE_URL, 'https://example.com/foo')); $this->assertSame($uuid, Uuid::fromBytes(hex2bin('ffffffffffffffffffffffffffffffff'))); $this->assertSame($uuid, Uuid::fromString('ffffffff-ffff-ffff-ffff-ffffffffffff')); $this->assertSame($uuid, Uuid::fromInteger('340282366920938463463374607431768211455')); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testUsingDegradedFeatures() { $numberConverter = new DegradedNumberConverter(); $builder = new DegradedUuidBuilder($numberConverter); $factory = new UuidFactory(); $factory->setNumberConverter($numberConverter); $factory->setUuidBuilder($builder); Uuid::setFactory($factory); $uuid = Uuid::uuid1(); $this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertInstanceOf('Ramsey\Uuid\DegradedUuid', $uuid); $this->assertInstanceOf('Ramsey\Uuid\Converter\Number\DegradedNumberConverter', $uuid->getNumberConverter()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testUsingCustomCodec() { $mockUuid = \Mockery::mock('Ramsey\Uuid\UuidInterface'); $codec = \Mockery::mock('Ramsey\Uuid\Codec\CodecInterface', [ 'encode' => 'abcd1234', 'encodeBinary' => hex2bin('abcd1234'), 'decode' => $mockUuid, 'decodeBytes' => $mockUuid, ]); $factory = new UuidFactory(); $factory->setCodec($codec); Uuid::setFactory($factory); $uuid = Uuid::uuid4(); $this->assertSame('abcd1234', $uuid->toString()); $this->assertSame(hex2bin('abcd1234'), $uuid->getBytes()); $this->assertSame($mockUuid, Uuid::fromString('f00ba2')); $this->assertSame($mockUuid, Uuid::fromBytes(hex2bin('f00ba2'))); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testUsingCustomRandomGenerator() { $generator = \Mockery::mock('Ramsey\Uuid\Generator\RandomGeneratorInterface', [ 'generate' => hex2bin('01234567abcd5432dcba0123456789ab'), ]); $factory = new UuidFactory(); $factory->setRandomGenerator($generator); Uuid::setFactory($factory); $uuid = Uuid::uuid4(); $this->assertSame('01234567-abcd-4432-9cba-0123456789ab', $uuid->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testUsingCustomTimeGenerator() { $generator = \Mockery::mock('Ramsey\Uuid\Generator\TimeGeneratorInterface', [ 'generate' => hex2bin('01234567abcd5432dcba0123456789ab'), ]); $factory = new UuidFactory(); $factory->setTimeGenerator($generator); Uuid::setFactory($factory); $uuid = Uuid::uuid1(); $this->assertSame('01234567-abcd-1432-9cba-0123456789ab', $uuid->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testUsingDefaultTimeGeneratorWithCustomProviders() { $nodeProvider = \Mockery::mock('Ramsey\Uuid\Provider\NodeProviderInterface', [ 'getNode' => new Hexadecimal('0123456789ab'), ]); $timeConverter = \Mockery::mock('Ramsey\Uuid\Converter\TimeConverterInterface'); $timeConverter ->shouldReceive('calculateTime') ->andReturnUsing(function ($seconds, $microseconds) { return new Hexadecimal('abcd' . dechex($microseconds) . dechex($seconds)); }); $timeProvider = \Mockery::mock('Ramsey\Uuid\Provider\TimeProviderInterface', [ 'currentTime' => [ 'sec' => 1578522046, 'usec' => 10000, ], 'getTime' => new Time(1578522046, 10000), ]); $generator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider); $factory = new UuidFactory(); $factory->setTimeGenerator($generator); Uuid::setFactory($factory); $uuid = Uuid::uuid1(null, 4095); $this->assertSame('5e1655be-2710-1bcd-8fff-0123456789ab', $uuid->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testHelperFunctions() { $uuid1 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [ 'toString' => 'aVersion1Uuid', ]); $uuid3 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [ 'toString' => 'aVersion3Uuid', ]); $uuid4 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [ 'toString' => 'aVersion4Uuid', ]); $uuid5 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [ 'toString' => 'aVersion5Uuid', ]); $factory = \Mockery::mock('Ramsey\Uuid\UuidFactoryInterface', [ 'uuid1' => $uuid1, 'uuid3' => $uuid3, 'uuid4' => $uuid4, 'uuid5' => $uuid5, ]); Uuid::setFactory($factory); $this->assertSame('aVersion1Uuid', \Ramsey\Uuid\v1('ffffffffffff', 0xffff)); $this->assertSame('aVersion3Uuid', \Ramsey\Uuid\v3(Uuid::NAMESPACE_URL, 'https://example.com/foo')); $this->assertSame('aVersion4Uuid', \Ramsey\Uuid\v4()); $this->assertSame('aVersion5Uuid', \Ramsey\Uuid\v5(Uuid::NAMESPACE_URL, 'https://example.com/foo')); } /** * @link https://git.io/JvJZo Use of TimestampFirstCombCodec in laravel/framework */ public function testUseOfTimestampFirstCombCodec() { $factory = new UuidFactory(); $factory->setRandomGenerator(new CombGenerator( $factory->getRandomGenerator(), $factory->getNumberConverter() )); $factory->setCodec(new TimestampFirstCombCodec( $factory->getUuidBuilder() )); $uuid = $factory->uuid4(); // Swap fields according to the rules for TimestampFirstCombCodec. $fields = array_values($uuid->getFieldsHex()); $last48Bits = $fields[5]; $fields[5] = $fields[0] . $fields[1]; $fields[0] = substr($last48Bits, 0, 8); $fields[1] = substr($last48Bits, 8, 4); $expectedHex = implode('', $fields); $expectedBytes = hex2bin($expectedHex); $this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(4, $uuid->getVersion()); $this->assertSame($expectedBytes, $uuid->getBytes()); $this->assertSame($expectedHex, (string) $uuid->getHex()); } /** * @dataProvider provideUuidConstantTests */ public function testUuidConstants($constantName, $expected) { $this->assertSame($expected, constant("Ramsey\\Uuid\\Uuid::{$constantName}")); } public function provideUuidConstantTests() { return [ ['NAMESPACE_DNS', '6ba7b810-9dad-11d1-80b4-00c04fd430c8'], ['NAMESPACE_URL', '6ba7b811-9dad-11d1-80b4-00c04fd430c8'], ['NAMESPACE_OID', '6ba7b812-9dad-11d1-80b4-00c04fd430c8'], ['NAMESPACE_X500', '6ba7b814-9dad-11d1-80b4-00c04fd430c8'], ['NIL', '00000000-0000-0000-0000-000000000000'], ['MAX', 'ffffffff-ffff-ffff-ffff-ffffffffffff'], ['RESERVED_NCS', 0], ['RFC_4122', 2], ['RESERVED_MICROSOFT', 6], ['RESERVED_FUTURE', 7], ['VALID_PATTERN', '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'], ['UUID_TYPE_TIME', 1], ['UUID_TYPE_IDENTIFIER', 2], ['UUID_TYPE_HASH_MD5', 3], ['UUID_TYPE_RANDOM', 4], ['UUID_TYPE_HASH_SHA1', 5], ['UUID_TYPE_REORDERED_TIME', 6], ['UUID_TYPE_UNIX_TIME', 7], ]; } } ================================================ FILE: tests/FeatureSetTest.php ================================================ assertInstanceOf(GuidBuilder::class, $featureSet->getBuilder()); } public function testFallbackBuilderIsSelected(): void { $featureSet = new FeatureSet(false, true); $this->assertInstanceOf(FallbackBuilder::class, $featureSet->getBuilder()); } public function testSetValidatorSetsTheProvidedValidator(): void { $validator = Mockery::mock(ValidatorInterface::class); $featureSet = new FeatureSet(); $featureSet->setValidator($validator); $this->assertSame($validator, $featureSet->getValidator()); } public function testGetTimeConverter(): void { $featureSet = new FeatureSet(); /** @phpstan-ignore method.alreadyNarrowedType */ $this->assertInstanceOf(TimeConverterInterface::class, $featureSet->getTimeConverter()); } public function testDefaultNameGeneratorIsSelected(): void { $featureSet = new FeatureSet(); $this->assertInstanceOf(DefaultNameGenerator::class, $featureSet->getNameGenerator()); } public function testPeclUuidTimeGeneratorIsSelected(): void { $featureSet = new FeatureSet(false, false, false, false, true); $this->assertInstanceOf(PeclUuidTimeGenerator::class, $featureSet->getTimeGenerator()); } public function testGetCalculator(): void { $featureSet = new FeatureSet(); $this->assertInstanceOf(BrickMathCalculator::class, $featureSet->getCalculator()); } public function testSetNodeProvider(): void { $nodeProvider = Mockery::mock(NodeProviderInterface::class); $featureSet = new FeatureSet(); $featureSet->setNodeProvider($nodeProvider); $this->assertSame($nodeProvider, $featureSet->getNodeProvider()); } public function testGetUnixTimeGenerator(): void { $featureSet = new FeatureSet(); $this->assertInstanceOf(UnixTimeGenerator::class, $featureSet->getUnixTimeGenerator()); } } ================================================ FILE: tests/FunctionsTest.php ================================================ assertIsString($v1); $this->assertSame(Uuid::UUID_TYPE_TIME, Uuid::fromString($v1)->getVersion()); } public function testV2ReturnsVersion2UuidString(): void { $v2 = v2( Uuid::DCE_DOMAIN_PERSON, new IntegerObject('1004'), new Hexadecimal('aabbccdd0011'), 63 ); /** @var FieldsInterface $fields */ $fields = Uuid::fromString($v2)->getFields(); $this->assertIsString($v2); $this->assertSame(Uuid::UUID_TYPE_DCE_SECURITY, $fields->getVersion()); } public function testV3ReturnsVersion3UuidString(): void { $ns = Uuid::fromString(Uuid::NAMESPACE_URL); $v3 = v3($ns, 'https://example.com/foo'); $this->assertIsString($v3); $this->assertSame(Uuid::UUID_TYPE_HASH_MD5, Uuid::fromString($v3)->getVersion()); } public function testV4ReturnsVersion4UuidString(): void { $v4 = v4(); $this->assertIsString($v4); $this->assertSame(Uuid::UUID_TYPE_RANDOM, Uuid::fromString($v4)->getVersion()); } public function testV5ReturnsVersion5UuidString(): void { $ns = Uuid::fromString(Uuid::NAMESPACE_URL); $v5 = v5($ns, 'https://example.com/foo'); $this->assertIsString($v5); $this->assertSame(Uuid::UUID_TYPE_HASH_SHA1, Uuid::fromString($v5)->getVersion()); } public function testV6ReturnsVersion6UuidString(): void { $v6 = v6( new Hexadecimal('aabbccdd0011'), 1234 ); /** @var FieldsInterface $fields */ $fields = Uuid::fromString($v6)->getFields(); $this->assertIsString($v6); $this->assertSame(Uuid::UUID_TYPE_REORDERED_TIME, $fields->getVersion()); } public function testV7ReturnsVersion7UuidString(): void { $v7 = v7(); /** @var UuidV7 $uuid */ $uuid = Uuid::fromString($v7); /** @var FieldsInterface $fields */ $fields = $uuid->getFields(); $this->assertIsString($v7); $this->assertSame(Uuid::UUID_TYPE_UNIX_TIME, $fields->getVersion()); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); } public function testV7WithCustomDateTimeReturnsVersion7UuidString(): void { $dateTime = new DateTimeImmutable('2022-09-14T22:44:33+00:00'); $v7 = v7($dateTime); /** @var UuidV7 $uuid */ $uuid = Uuid::fromString($v7); /** @var FieldsInterface $fields */ $fields = $uuid->getFields(); $this->assertIsString($v7); $this->assertSame(Uuid::UUID_TYPE_UNIX_TIME, $fields->getVersion()); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(1663195473, $uuid->getDateTime()->getTimestamp()); } public function testV8ReturnsVersion8UuidString(): void { $v8 = v8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"); /** @var UuidV8 $uuid */ $uuid = Uuid::fromString($v8); /** @var FieldsInterface $fields */ $fields = $uuid->getFields(); $this->assertIsString($v8); $this->assertSame(Uuid::UUID_TYPE_CUSTOM, $fields->getVersion()); } } ================================================ FILE: tests/Generator/CombGeneratorTest.php ================================================ timestampBytes; /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); $randomGenerator->expects($this->once()) ->method('generate') ->with($expectedLength); /** @var MockObject & NumberConverterInterface $converter */ $converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $generator = new CombGenerator($randomGenerator, $converter); $generator->generate($length); } public function testGenerateCalculatesPaddedHexStringFromCurrentTimestamp(): void { /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); /** @var MockObject & NumberConverterInterface $converter */ $converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $converter->expects($this->once()) ->method('toHex') ->with($this->isType('string')); $generator = new CombGenerator($randomGenerator, $converter); $generator->generate(10); } public function testGenerateReturnsBinaryStringCreatedFromGeneratorAndConverter(): void { $length = 20; $hash = dechex(1234567891); $timeHash = dechex(1458147405); /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); $randomGenerator->method('generate') ->with($length - $this->timestampBytes) ->willReturn($hash); /** @var MockObject & NumberConverterInterface $converter */ $converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $converter->method('toHex') ->with($this->isType('string')) ->willReturn($timeHash); $time = str_pad($timeHash, 12, '0', STR_PAD_LEFT); $expected = hex2bin(str_pad(bin2hex($hash), $length - $this->timestampBytes, '0')) . hex2bin($time); $generator = new CombGenerator($randomGenerator, $converter); $returned = $generator->generate($length); $this->assertIsString($returned); $this->assertSame($expected, $returned); } /** * @return array */ public function lengthLessThanSix(): array { return [[0], [1], [2], [3], [4], [5]]; } /** * @param int<1, max> $length * * @dataProvider lengthLessThanSix */ public function testGenerateWithLessThanTimestampBytesThrowsException(int $length): void { /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); /** @var MockObject & NumberConverterInterface $converter */ $converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $generator = new CombGenerator($randomGenerator, $converter); $this->expectException(InvalidArgumentException::class); $generator->generate($length); } public function testGenerateWithOddNumberOverTimestampBytesCausesError(): void { /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); /** @var MockObject & NumberConverterInterface $converter */ $converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $generator = new CombGenerator($randomGenerator, $converter); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Length must be an even number'); $generator->generate(7); } } ================================================ FILE: tests/Generator/DceSecurityGeneratorTest.php ================================================ new IntegerObject($uid), 'getGid' => new IntegerObject($gid), ]); /** @var NodeProviderInterface $nodeProvider */ $nodeProvider = Mockery::mock(NodeProviderInterface::class, [ 'getNode' => new Hexadecimal($node), ]); $timeProvider = new FixedTimeProvider(new Time($seconds, $microseconds)); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = new GenericTimeConverter($calculator); $timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $bytes = $dceSecurityGenerator->generate($providedDomain, $providedId, $providedNode); $this->assertSame($expectedId, bin2hex(substr($bytes, 0, 4))); $this->assertSame($expectedDomain, bin2hex(substr($bytes, 9, 1))); $this->assertSame($expectedNode, bin2hex(substr($bytes, 10))); $this->assertSame($expectedTimeMidHi, bin2hex(substr($bytes, 4, 4))); } /** * @return array */ public function provideValuesForDceSecurityGenerator(): array { return [ [ 'uid' => '1001', 'gid' => '2001', 'node' => '001122334455', 'seconds' => 1579132397, 'microseconds' => 500000, 'providedDomain' => Uuid::DCE_DOMAIN_PERSON, 'providedId' => null, 'providedNode' => null, 'expectedId' => '000003e9', 'expectedDomain' => '00', 'expectedNode' => '001122334455', 'expectedTimeMidHi' => '37f201ea', ], [ 'uid' => '1001', 'gid' => '2001', 'node' => '001122334455', 'seconds' => 1579132397, 'microseconds' => 500000, 'providedDomain' => Uuid::DCE_DOMAIN_GROUP, 'providedId' => null, 'providedNode' => null, 'expectedId' => '000007d1', 'expectedDomain' => '01', 'expectedNode' => '001122334455', 'expectedTimeMidHi' => '37f201ea', ], [ 'uid' => 0, 'gid' => 0, 'node' => '001122334455', 'seconds' => 1579132397, 'microseconds' => 500000, 'providedDomain' => Uuid::DCE_DOMAIN_ORG, 'providedId' => new IntegerObject('4294967295'), 'providedNode' => null, 'expectedId' => 'ffffffff', 'expectedDomain' => '02', 'expectedNode' => '001122334455', 'expectedTimeMidHi' => '37f201ea', ], ]; } public function testGenerateThrowsExceptionForInvalidDomain(): void { $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $generator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage('Local domain must be a valid DCE Security domain'); $generator->generate(42); } public function testGenerateThrowsExceptionForOrgWithoutIdentifier(): void { $numberConverter = Mockery::mock(NumberConverterInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $generator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage('A local identifier must be provided for the org domain'); $generator->generate(Uuid::DCE_DOMAIN_ORG); } public function testClockSequenceLowerBounds(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $nodeProvider = Mockery::mock(NodeProviderInterface::class); $timeProvider = new FixedTimeProvider(new Time(1583527677, 111984)); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = new GenericTimeConverter($calculator); $timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $bytes = $dceSecurityGenerator->generate( Uuid::DCE_DOMAIN_ORG, new IntegerObject(1001), new Hexadecimal('0123456789ab'), 0 ); $hex = bin2hex($bytes); $this->assertSame('000003e9', substr($hex, 0, 8)); $this->assertSame('5feb01ea', substr($hex, 8, 8)); $this->assertSame('00', substr($hex, 16, 2)); $this->assertSame('02', substr($hex, 18, 2)); $this->assertSame('0123456789ab', substr($hex, 20)); } public function testClockSequenceUpperBounds(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $nodeProvider = Mockery::mock(NodeProviderInterface::class); $timeProvider = new FixedTimeProvider(new Time(1583527677, 111984)); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = new GenericTimeConverter($calculator); $timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $bytes = $dceSecurityGenerator->generate( Uuid::DCE_DOMAIN_ORG, new IntegerObject(1001), new Hexadecimal('0123456789ab'), 63 ); $hex = bin2hex($bytes); $this->assertSame('000003e9', substr($hex, 0, 8)); $this->assertSame('5feb01ea', substr($hex, 8, 8)); $this->assertSame('3f', substr($hex, 16, 2)); $this->assertSame('02', substr($hex, 18, 2)); $this->assertSame('0123456789ab', substr($hex, 20)); } public function testExceptionThrownWhenClockSequenceTooLow(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $numberConverter = Mockery::mock(NumberConverterInterface::class); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Clock sequence out of bounds; it must be a value between 0 and 63' ); $dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, null, null, -1); } public function testExceptionThrownWhenClockSequenceTooHigh(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $numberConverter = Mockery::mock(NumberConverterInterface::class); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Clock sequence out of bounds; it must be a value between 0 and 63' ); $dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, null, null, 64); } public function testExceptionThrownWhenLocalIdTooLow(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $numberConverter = Mockery::mock(NumberConverterInterface::class); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Local identifier out of bounds; it must be a value between 0 and 4294967295' ); $dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, new IntegerObject(-1)); } public function testExceptionThrownWhenLocalIdTooHigh(): void { $dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Local identifier out of bounds; it must be a value between 0 and 4294967295' ); $dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, new IntegerObject('4294967296')); } } ================================================ FILE: tests/Generator/DefaultNameGeneratorTest.php ================================================ getBytes() . $name, true); $generator = new DefaultNameGenerator(); $this->assertSame($expectedBytes, $generator->generate($namespace, $name, $algorithm)); } /** * @return array */ public function provideNamesForHashingTest(): array { return [ [ 'ns' => Uuid::NAMESPACE_URL, 'name' => 'https://example.com/foobar', 'algorithm' => 'md5', ], [ 'ns' => Uuid::NAMESPACE_URL, 'name' => 'https://example.com/foobar', 'algorithm' => 'sha1', ], [ 'ns' => Uuid::NAMESPACE_URL, 'name' => 'https://example.com/foobar', 'algorithm' => 'sha256', ], [ 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1.4.1.343', 'algorithm' => 'sha1', ], [ 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1.4.1.52627', 'algorithm' => 'md5', ], [ 'ns' => 'd988ae29-674e-48e7-b93c-2825e2a96fbe', 'name' => 'foobar', 'algorithm' => 'sha1', ], ]; } public function testGenerateThrowsException(): void { $namespace = Uuid::fromString('cd998804-c661-4264-822c-00cada75a87b'); $generator = new DefaultNameGenerator(); $this->expectException(NameException::class); $this->expectExceptionMessage( 'Unable to hash namespace and name with algorithm \'aBadAlgorithm\'' ); $generator->generate($namespace, 'a test name', 'aBadAlgorithm'); } } ================================================ FILE: tests/Generator/DefaultTimeGeneratorTest.php ================================================ nodeProvider = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $this->timeConverter = $this->getMockBuilder(TimeConverterInterface::class)->getMock(); $this->currentTime = ['sec' => 1458733431, 'usec' => 877449]; $this->calculatedTime = new Hexadecimal('03cb98e083cb98e0'); $time = new Time($this->currentTime['sec'], $this->currentTime['usec']); $this->timeProvider = Mockery::mock(TimeProviderInterface::class, [ 'getTime' => $time, ]); } protected function tearDown(): void { parent::tearDown(); unset($this->timeProvider, $this->nodeProvider, $this->timeConverter); Mockery::close(); } public function testGenerateUsesNodeProviderWhenNodeIsNull(): void { $this->nodeProvider->expects($this->once()) ->method('getNode') ->willReturn(new Hexadecimal('122f80ca9e06')); $this->timeConverter->expects($this->once()) ->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $defaultTimeGenerator->generate(null, $this->clockSeq); } public function testGenerateUsesTimeProvidersCurrentTime(): void { $this->timeConverter->expects($this->once()) ->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $defaultTimeGenerator->generate($this->nodeId, $this->clockSeq); } public function testGenerateCalculatesTimeWithConverter(): void { $this->timeConverter->expects($this->once()) ->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $defaultTimeGenerator->generate($this->nodeId, $this->clockSeq); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGenerateDoesNotApplyVersionAndVariant(): void { $expectedBytes = hex2bin('83cb98e098e003cb0fe2122f80ca9e06'); $this->timeConverter->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); $binaryUtils = Mockery::mock('alias:' . BinaryUtils::class); $binaryUtils->shouldNotReceive('applyVersion'); $binaryUtils->shouldNotReceive('applyVariant'); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $this->assertSame($expectedBytes, $defaultTimeGenerator->generate($this->nodeId, $this->clockSeq)); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGenerateUsesRandomSequenceWhenClockSeqNull(): void { PHPMockery::mock('Ramsey\Uuid\Generator', 'random_int') ->once() ->with(0, 0x3fff) ->andReturn(9622); $this->timeConverter->expects($this->once()) ->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $defaultTimeGenerator->generate($this->nodeId); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGenerateThrowsExceptionWhenExceptionThrownByRandomint(): void { PHPMockery::mock('Ramsey\Uuid\Generator', 'random_int') ->once() ->andThrow(new Exception('Could not gather sufficient random data')); $defaultTimeGenerator = new DefaultTimeGenerator( $this->nodeProvider, $this->timeConverter, $this->timeProvider ); $this->expectException(RandomSourceException::class); $this->expectExceptionMessage('Could not gather sufficient random data'); $defaultTimeGenerator->generate($this->nodeId); } public function testDefaultTimeGeneratorThrowsExceptionForLargeGeneratedValue(): void { $timeProvider = new FixedTimeProvider(new Time('1832455114570', '955162')); $featureSet = new FeatureSet(); $timeGenerator = new DefaultTimeGenerator( $featureSet->getNodeProvider(), $featureSet->getTimeConverter(), $timeProvider ); $this->expectException(TimeSourceException::class); $this->expectExceptionMessage( 'The generated time of \'10000000000000004\' is larger than expected' ); $timeGenerator->generate(); } } ================================================ FILE: tests/Generator/NameGeneratorFactoryTest.php ================================================ assertInstanceOf(DefaultNameGenerator::class, $factory->getGenerator()); } } ================================================ FILE: tests/Generator/PeclUuidNameGeneratorTest.php ================================================ getBytes() . $name, true), 0, 16); // Need to add the version and variant, since ext-uuid already includes // these in the values returned. /** @var int[] $unpackedTime */ $unpackedTime = unpack('n*', substr($expectedBytes, 6, 2)); $timeHi = $unpackedTime[1]; $timeHiAndVersion = pack('n*', BinaryUtils::applyVersion($timeHi, $version)); /** @var int[] $unpackedClockSeq */ $unpackedClockSeq = unpack('n*', substr($expectedBytes, 8, 2)); $clockSeqHi = $unpackedClockSeq[1]; $clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi)); $expectedBytes = substr_replace($expectedBytes, $timeHiAndVersion, 6, 2); $expectedBytes = substr_replace($expectedBytes, $clockSeqHiAndReserved, 8, 2); $generator = new PeclUuidNameGenerator(); $generatedBytes = $generator->generate($namespace, $name, $algorithm); $this->assertSame( $expectedBytes, $generatedBytes, 'Expected: ' . bin2hex($expectedBytes) . '; Received: ' . bin2hex($generatedBytes) ); } /** * @return array */ public function provideNamesForHashingTest(): array { return [ [ 'ns' => Uuid::NAMESPACE_URL, 'name' => 'https://example.com/foobar', 'algorithm' => 'md5', ], [ 'ns' => Uuid::NAMESPACE_URL, 'name' => 'https://example.com/foobar', 'algorithm' => 'sha1', ], [ 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1.4.1.343', 'algorithm' => 'sha1', ], [ 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1.4.1.52627', 'algorithm' => 'md5', ], [ 'ns' => 'd988ae29-674e-48e7-b93c-2825e2a96fbe', 'name' => 'foobar', 'algorithm' => 'sha1', ], ]; } public function testGenerateThrowsException(): void { $namespace = Uuid::fromString('cd998804-c661-4264-822c-00cada75a87b'); $generator = new PeclUuidNameGenerator(); $this->expectException(NameException::class); $this->expectExceptionMessage( 'Unable to hash namespace and name with algorithm \'aBadAlgorithm\'' ); $generator->generate($namespace, 'a test name', 'aBadAlgorithm'); } } ================================================ FILE: tests/Generator/PeclUuidRandomGeneratorTest.php ================================================ generate(10); $uuid = Uuid::fromBytes($bytes); /** @var Fields $fields */ $fields = $uuid->getFields(); $this->assertSame(16, strlen($bytes)); $this->assertSame(Uuid::UUID_TYPE_RANDOM, $fields->getVersion()); } } ================================================ FILE: tests/Generator/PeclUuidTimeGeneratorTest.php ================================================ generate(); $uuid = Uuid::fromBytes($bytes); /** @var Fields $fields */ $fields = $uuid->getFields(); $this->assertSame(16, strlen($bytes)); $this->assertSame(Uuid::UUID_TYPE_TIME, $fields->getVersion()); } } ================================================ FILE: tests/Generator/RandomBytesGeneratorTest.php ================================================ */ public function lengthAndHexDataProvider(): array { return [ [6, '4f17dd046fb8'], [10, '4d25f6fe5327cb04267a'], [12, '1ea89f83bd49cacfdf119e24'], ]; } /** * @param positive-int $length * @param non-empty-string $hex * * @throws Exception * * @dataProvider lengthAndHexDataProvider * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGenerateReturnsRandomBytes(int $length, string $hex): void { $bytes = hex2bin($hex); PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes') ->once() ->with($length) ->andReturn($bytes); $generator = new RandomBytesGenerator(); $this->assertSame($bytes, $generator->generate($length)); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGenerateThrowsExceptionWhenExceptionThrownByRandomBytes(): void { PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes') ->once() ->with(16) ->andThrow(new Exception('Could not gather sufficient random data')); $generator = new RandomBytesGenerator(); $this->expectException(RandomSourceException::class); $this->expectExceptionMessage('Could not gather sufficient random data'); $generator->generate(16); } } ================================================ FILE: tests/Generator/RandomGeneratorFactoryTest.php ================================================ getGenerator(); $this->assertInstanceOf(RandomBytesGenerator::class, $generator); } } ================================================ FILE: tests/Generator/RandomLibAdapterTest.php ================================================ shouldNotReceive('getHighStrengthGenerator'); $generator = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->getMock(); /** @phpstan-ignore method.alreadyNarrowedType */ $this->assertInstanceOf(RandomLibAdapter::class, new RandomLibAdapter($generator)); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testAdapterWithoutGeneratorCreatesGenerator(): void { $generator = Mockery::mock(Generator::class); /** @var RandomLibFactory&MockInterface $factory */ $factory = Mockery::mock('overload:' . RandomLibFactory::class); $factory->expects()->getHighStrengthGenerator()->andReturns($generator); /** @phpstan-ignore method.alreadyNarrowedType */ $this->assertInstanceOf(RandomLibAdapter::class, new RandomLibAdapter()); } public function testGenerateUsesGenerator(): void { $length = 10; $generator = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->getMock(); $generator->expects($this->once()) ->method('generate') ->with($length) ->willReturn('foo'); $adapter = new RandomLibAdapter($generator); $adapter->generate($length); } public function testGenerateReturnsString(): void { $generator = $this->getMockBuilder(Generator::class) ->disableOriginalConstructor() ->getMock(); $generator->expects($this->once()) ->method('generate') ->willReturn('random-string'); $adapter = new RandomLibAdapter($generator); $result = $adapter->generate(1); $this->assertSame('random-string', $result); } } ================================================ FILE: tests/Generator/TimeGeneratorFactoryTest.php ================================================ getMockBuilder(TimeProviderInterface::class)->getMock(); /** @var MockObject & NodeProviderInterface $nodeProvider */ $nodeProvider = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); /** @var MockObject & TimeConverterInterface $timeConverter */ $timeConverter = $this->getMockBuilder(TimeConverterInterface::class)->getMock(); $factory = new TimeGeneratorFactory($nodeProvider, $timeConverter, $timeProvider); $generator = $factory->getGenerator(); /** @phpstan-ignore method.alreadyNarrowedType */ $this->assertInstanceOf(TimeGeneratorInterface::class, $generator); } } ================================================ FILE: tests/Generator/UnixTimeGeneratorTest.php ================================================ expects()->generate(16)->andReturns( "\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00", ); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator); $bytes = $unixTimeGenerator->generate(null, null, $dateTime); $this->assertSame( $expectedBytes, $bytes, 'Failed asserting that "' . bin2hex($bytes) . '" is equal to "' . bin2hex($expectedBytes) . '"', ); } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResults(): void { $randomGenerator = new RandomBytesGenerator(); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResultsWithSameDate(): void { $dateTime = new DateTimeImmutable('now'); $randomGenerator = new RandomBytesGenerator(); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(null, null, $dateTime); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResultsFor32BitPath(): void { $randomGenerator = new RandomBytesGenerator(); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResultsWithSameDateFor32BitPath(): void { $dateTime = new DateTimeImmutable('now'); $randomGenerator = new RandomBytesGenerator(); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(null, null, $dateTime); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResultsStartingWithAllBitsSet(): void { /** @var RandomGeneratorInterface&MockInterface $randomGenerator */ $randomGenerator = Mockery::mock(RandomGeneratorInterface::class); $randomGenerator->expects()->generate(16)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $randomGenerator->allows()->generate(10)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateRollsOverWithAllBitsSetWithSameDate(): void { $dateTime = new DateTimeImmutable('now'); /** @var RandomGeneratorInterface&MockInterface $randomGenerator */ $randomGenerator = Mockery::mock(RandomGeneratorInterface::class); $randomGenerator->expects()->generate(16)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $randomGenerator->allows()->generate(10)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator); // We can only call this twice before the overflow kicks in, "randomizing" all the bits back to 1's, according to // our mocked random generator. As a result, we can't run this in a loop like with the other monotonicity tests // in this class; it starts failing at the third loop. This is okay, since our goal is to test the overflow. $first = $unixTimeGenerator->generate(null, null, $dateTime); $second = $unixTimeGenerator->generate(null, null, $dateTime); $this->assertTrue($second > $first); } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateProducesMonotonicResultsStartingWithAllBitsSetFor32BitPath(): void { /** @var RandomGeneratorInterface&MockInterface $randomGenerator */ $randomGenerator = Mockery::mock(RandomGeneratorInterface::class); $randomGenerator->expects()->generate(16)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $randomGenerator->allows()->generate(10)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4); $previous = ''; for ($i = 0; $i < self::ITERATIONS; $i++) { $bytes = $unixTimeGenerator->generate(); $this->assertTrue( $bytes > $previous, 'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous), ); $previous = $bytes; } } /** * @runInSeparateProcess since values are stored statically on the class * @preserveGlobalState disabled */ public function testGenerateRollsOverWithAllBitsSetWithSameDateFor32BitPath(): void { $dateTime = new DateTimeImmutable('now'); /** @var RandomGeneratorInterface&MockInterface $randomGenerator */ $randomGenerator = Mockery::mock(RandomGeneratorInterface::class); $randomGenerator->expects()->generate(16)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $randomGenerator->allows()->generate(10)->andReturns( "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", ); $unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4); // We can only call this twice before the overflow kicks in, "randomizing" all the bits back to 1's, according to // our mocked random generator. As a result, we can't run this in a loop like with the other monotonicity tests // in this class; it starts failing at the third loop. This is okay, since our goal is to test the overflow. $first = $unixTimeGenerator->generate(null, null, $dateTime); $second = $unixTimeGenerator->generate(null, null, $dateTime); $this->assertTrue($second > $first); } } ================================================ FILE: tests/Guid/FieldsTest.php ================================================ expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string must be 16 bytes long; received 6 bytes' ); new Fields('foobar'); } /** * @param non-empty-string $guid * * @dataProvider nonRfc4122GuidVariantProvider */ public function testConstructorThrowsExceptionIfNotRfc4122Variant(string $guid): void { $bytes = (string) hex2bin($guid); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) or ' . 'Microsoft Corporation variants' ); new Fields($bytes); } /** * These values are already in GUID byte order, for easy testing. * * @return array */ public function nonRfc4122GuidVariantProvider(): array { // In string representation, the following IDs would begin as: // ff6f8cb0-c57d-11e1-... return [ ['b08c6fff7dc5e1110b210800200c9a66'], ['b08c6fff7dc5e1111b210800200c9a66'], ['b08c6fff7dc5e1112b210800200c9a66'], ['b08c6fff7dc5e1113b210800200c9a66'], ['b08c6fff7dc5e1114b210800200c9a66'], ['b08c6fff7dc5e1115b210800200c9a66'], ['b08c6fff7dc5e1116b210800200c9a66'], ['b08c6fff7dc5e1117b210800200c9a66'], ['b08c6fff7dc5e111eb210800200c9a66'], ['b08c6fff7dc5e111fb210800200c9a66'], ]; } /** * @param non-empty-string $guid * * @dataProvider invalidVersionProvider */ public function testConstructorThrowsExceptionIfInvalidVersion(string $guid): void { $bytes = (string) hex2bin($guid); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string received does not contain a valid version' ); new Fields($bytes); } /** * @return array */ public function invalidVersionProvider(): array { // The following UUIDs are in GUID byte order. Dashes have // been removed in the tests to distinguish these from string // representations, which are never in GUID byte order. return [ ['b08c6fff7dc5e1018b210800200c9a66'], ['b08c6fff7dc5e191bb210800200c9a66'], ['b08c6fff7dc5e1a19b210800200c9a66'], ['b08c6fff7dc5e1b1ab210800200c9a66'], ['b08c6fff7dc5e1c1ab210800200c9a66'], ['b08c6fff7dc5e1d1ab210800200c9a66'], ['b08c6fff7dc5e1e1ab210800200c9a66'], ['b08c6fff7dc5e1f1ab210800200c9a66'], ]; } /** * @param non-empty-string $bytes * @param non-empty-string $methodName * @param non-empty-string | bool | int | null $expectedValue * * @dataProvider fieldGetterMethodProvider */ public function testFieldGetterMethods( string $bytes, string $methodName, bool | int | string | null $expectedValue, ): void { $bytes = (string) hex2bin($bytes); $fields = new Fields($bytes); $result = $fields->$methodName(); if ($result instanceof Hexadecimal) { $this->assertSame($expectedValue, $result->toString()); } else { $this->assertSame($expectedValue, $result); } } /** * @return array */ public function fieldGetterMethodProvider(): array { // The following UUIDs are in GUID byte order. Dashes have // been removed in the tests to distinguish these from string // representations, which are never in GUID byte order. return [ // For ff6f8cb0-c57d-11e1-cb21-0800200c9a66 ['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeq', '0b21'], ['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeqHiAndReserved', 'cb'], ['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeqLow', '21'], ['b08c6fff7dc5e111cb210800200c9a66', 'getNode', '0800200c9a66'], ['b08c6fff7dc5e111cb210800200c9a66', 'getTimeHiAndVersion', '11e1'], ['b08c6fff7dc5e111cb210800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['b08c6fff7dc5e111cb210800200c9a66', 'getTimeMid', 'c57d'], ['b08c6fff7dc5e111cb210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['b08c6fff7dc5e111cb210800200c9a66', 'getVariant', 6], ['b08c6fff7dc5e111cb210800200c9a66', 'getVersion', 1], ['b08c6fff7dc5e111cb210800200c9a66', 'isNil', false], ['b08c6fff7dc5e111cb210800200c9a66', 'isMax', false], // For ff6f8cb0-c57d-41e1-db21-0800200c9a66 ['b08c6fff7dc5e141db210800200c9a66', 'getClockSeq', '1b21'], ['b08c6fff7dc5e141db210800200c9a66', 'getClockSeqHiAndReserved', 'db'], ['b08c6fff7dc5e141db210800200c9a66', 'getClockSeqLow', '21'], ['b08c6fff7dc5e141db210800200c9a66', 'getNode', '0800200c9a66'], ['b08c6fff7dc5e141db210800200c9a66', 'getTimeHiAndVersion', '41e1'], ['b08c6fff7dc5e141db210800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['b08c6fff7dc5e141db210800200c9a66', 'getTimeMid', 'c57d'], ['b08c6fff7dc5e141db210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['b08c6fff7dc5e141db210800200c9a66', 'getVariant', 6], ['b08c6fff7dc5e141db210800200c9a66', 'getVersion', 4], ['b08c6fff7dc5e141db210800200c9a66', 'isNil', false], ['b08c6fff7dc5e141db210800200c9a66', 'isMax', false], // For ff6f8cb0-c57d-31e1-8b21-0800200c9a66 ['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeq', '0b21'], ['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeqHiAndReserved', '8b'], ['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeqLow', '21'], ['b08c6fff7dc5e1318b210800200c9a66', 'getNode', '0800200c9a66'], ['b08c6fff7dc5e1318b210800200c9a66', 'getTimeHiAndVersion', '31e1'], ['b08c6fff7dc5e1318b210800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['b08c6fff7dc5e1318b210800200c9a66', 'getTimeMid', 'c57d'], ['b08c6fff7dc5e1318b210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['b08c6fff7dc5e1318b210800200c9a66', 'getVariant', 2], ['b08c6fff7dc5e1318b210800200c9a66', 'getVersion', 3], ['b08c6fff7dc5e1318b210800200c9a66', 'isNil', false], ['b08c6fff7dc5e1318b210800200c9a66', 'isMax', false], // For ff6f8cb0-c57d-51e1-9b21-0800200c9a66 ['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeq', '1b21'], ['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeqHiAndReserved', '9b'], ['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeqLow', '21'], ['b08c6fff7dc5e1519b210800200c9a66', 'getNode', '0800200c9a66'], ['b08c6fff7dc5e1519b210800200c9a66', 'getTimeHiAndVersion', '51e1'], ['b08c6fff7dc5e1519b210800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['b08c6fff7dc5e1519b210800200c9a66', 'getTimeMid', 'c57d'], ['b08c6fff7dc5e1519b210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['b08c6fff7dc5e1519b210800200c9a66', 'getVariant', 2], ['b08c6fff7dc5e1519b210800200c9a66', 'getVersion', 5], ['b08c6fff7dc5e1519b210800200c9a66', 'isNil', false], ['b08c6fff7dc5e1519b210800200c9a66', 'isMax', false], // For 00000000-0000-0000-0000-000000000000 ['00000000000000000000000000000000', 'getClockSeq', '0000'], ['00000000000000000000000000000000', 'getClockSeqHiAndReserved', '00'], ['00000000000000000000000000000000', 'getClockSeqLow', '00'], ['00000000000000000000000000000000', 'getNode', '000000000000'], ['00000000000000000000000000000000', 'getTimeHiAndVersion', '0000'], ['00000000000000000000000000000000', 'getTimeLow', '00000000'], ['00000000000000000000000000000000', 'getTimeMid', '0000'], ['00000000000000000000000000000000', 'getTimestamp', '000000000000000'], ['00000000000000000000000000000000', 'getVariant', 0], ['00000000000000000000000000000000', 'getVersion', null], ['00000000000000000000000000000000', 'isNil', true], ['00000000000000000000000000000000', 'isMax', false], // For ffffffff-ffff-ffff-ffff-ffffffffffff ['ffffffffffffffffffffffffffffffff', 'getClockSeq', 'ffff'], ['ffffffffffffffffffffffffffffffff', 'getClockSeqHiAndReserved', 'ff'], ['ffffffffffffffffffffffffffffffff', 'getClockSeqLow', 'ff'], ['ffffffffffffffffffffffffffffffff', 'getNode', 'ffffffffffff'], ['ffffffffffffffffffffffffffffffff', 'getTimeHiAndVersion', 'ffff'], ['ffffffffffffffffffffffffffffffff', 'getTimeLow', 'ffffffff'], ['ffffffffffffffffffffffffffffffff', 'getTimeMid', 'ffff'], ['ffffffffffffffffffffffffffffffff', 'getTimestamp', 'fffffffffffffff'], ['ffffffffffffffffffffffffffffffff', 'getVariant', 7], ['ffffffffffffffffffffffffffffffff', 'getVersion', null], ['ffffffffffffffffffffffffffffffff', 'isNil', false], ['ffffffffffffffffffffffffffffffff', 'isMax', true], ]; } public function testSerializingFields(): void { $bytes = (string) hex2bin('b08c6fff7dc5e111cb210800200c9a66'); $fields = new Fields($bytes); $serializedFields = serialize($fields); /** @var Fields $unserializedFields */ $unserializedFields = unserialize($serializedFields); $this->assertSame($fields->getBytes(), $unserializedFields->getBytes()); } } ================================================ FILE: tests/Guid/GuidBuilderTest.php ================================================ shouldAllowMockingProtectedMethods(); $builder->shouldReceive('buildFields')->andThrow( RuntimeException::class, 'exception thrown' ); $builder->shouldReceive('build')->passthru(); $this->expectException(UnableToBuildUuidException::class); $this->expectExceptionMessage('exception thrown'); $builder->build($codec, 'foobar'); } } ================================================ FILE: tests/Math/BrickMathCalculatorTest.php ================================================ add($int1, $int2, $int3); $this->assertSame('18', $result->toString()); } public function testSubtract(): void { $int1 = new IntegerObject(5); $int2 = new IntegerObject(6); $int3 = new IntegerObject(7); $calculator = new BrickMathCalculator(); $result = $calculator->subtract($int1, $int2, $int3); $this->assertSame('-8', $result->toString()); } public function testMultiply(): void { $int1 = new IntegerObject(5); $int2 = new IntegerObject(6); $int3 = new IntegerObject(7); $calculator = new BrickMathCalculator(); $result = $calculator->multiply($int1, $int2, $int3); $this->assertSame('210', $result->toString()); } public function testDivide(): void { $int1 = new IntegerObject(1023); $int2 = new IntegerObject(6); $int3 = new IntegerObject(7); $calculator = new BrickMathCalculator(); $result = $calculator->divide(RoundingMode::HALF_UP, 0, $int1, $int2, $int3); $this->assertSame('24', $result->toString()); } public function testFromBase(): void { $calculator = new BrickMathCalculator(); $result = $calculator->fromBase('ffffffffffffffffffff', 16); $this->assertSame('1208925819614629174706175', $result->toString()); } public function testToBase(): void { $intValue = new IntegerObject('1208925819614629174706175'); $calculator = new BrickMathCalculator(); $this->assertSame('ffffffffffffffffffff', $calculator->toBase($intValue, 16)); } public function testToHexadecimal(): void { $intValue = new IntegerObject('1208925819614629174706175'); $calculator = new BrickMathCalculator(); $result = $calculator->toHexadecimal($intValue); $this->assertSame('ffffffffffffffffffff', $result->toString()); } public function testFromBaseThrowsException(): void { $calculator = new BrickMathCalculator(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('"o" is not a valid character in base 16'); $calculator->fromBase('foobar', 16); } public function testToBaseThrowsException(): void { $calculator = new BrickMathCalculator(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Base 1024 is out of range [2, 36]'); $calculator->toBase(new IntegerObject(42), 1024); } } ================================================ FILE: tests/Nonstandard/FieldsTest.php ================================================ expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string must be 16 bytes long; received 6 bytes' ); new Fields('foobar'); } /** * @param non-empty-string $uuid * @param non-empty-string $methodName * @param non-empty-string | int | bool | null $expectedValue * * @dataProvider fieldGetterMethodProvider */ public function testFieldGetterMethods( string $uuid, string $methodName, bool | int | string | null $expectedValue, ): void { $bytes = (string) hex2bin(str_replace('-', '', $uuid)); $fields = new Fields($bytes); $result = $fields->$methodName(); if ($result instanceof Hexadecimal) { $this->assertSame($expectedValue, $result->toString()); } else { $this->assertSame($expectedValue, $result); } } /** * @return array */ public function fieldGetterMethodProvider(): array { return [ ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeq', '0b21'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeqHiAndReserved', '0b'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeHiAndVersion', '91e1'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getVariant', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getVersion', null], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'isMax', false], ]; } public function testSerializingFields(): void { $bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-91e1-0b21-0800200c9a66')); $fields = new Fields($bytes); $serializedFields = serialize($fields); /** @var Fields $unserializedFields */ $unserializedFields = unserialize($serializedFields); $this->assertSame($fields->getBytes(), $unserializedFields->getBytes()); } } ================================================ FILE: tests/Nonstandard/UuidBuilderTest.php ================================================ shouldAllowMockingProtectedMethods(); $builder->shouldReceive('buildFields')->andThrow( RuntimeException::class, 'exception thrown' ); $builder->shouldReceive('build')->passthru(); $this->expectException(UnableToBuildUuidException::class); $this->expectExceptionMessage('exception thrown'); $builder->build($codec, 'foobar'); } } ================================================ FILE: tests/Nonstandard/UuidV6Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV6 must represent a ' . 'version 6 (reordered time) UUID' ); new UuidV6($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 7], ['version' => 8], ['version' => 9], ]; } /** * @param non-empty-string $uuid * * @dataProvider provideUuidV6WithOddMicroseconds */ public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void { /** @var UuidV6 $object */ $object = Uuid::fromString($uuid); $date = $object->getDateTime(); $this->assertInstanceOf(DateTimeImmutable::class, $date); $this->assertSame($expected, $date->format('U.u')); } /** * @return array */ public function provideUuidV6WithOddMicroseconds(): array { return [ [ 'uuid' => '1b21dd21-4814-6000-9669-00007ffffffe', 'expected' => '1.677722', ], [ 'uuid' => '1b21dd21-3714-6000-9669-00007ffffffe', 'expected' => '0.104858', ], [ 'uuid' => '1b21dd21-3713-6000-9669-00007ffffffe', 'expected' => '0.105267', ], [ 'uuid' => '1b21dd21-2e8a-6980-8d4f-acde48001122', 'expected' => '-1.000000', ], ]; } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider provideUuidV1UuidV6Equivalents */ public function testToUuidV1(string $uuidv6, string $uuidv1): void { /** @var UuidV6 $uuid6 */ $uuid6 = Uuid::fromString($uuidv6); $uuid1 = $uuid6->toUuidV1(); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame( $uuid6->getDateTime()->format('U.u'), $uuid1->getDateTime()->format('U.u') ); } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider provideUuidV1UuidV6Equivalents */ public function testFromUuidV1(string $uuidv6, string $uuidv1): void { /** @var LazyUuidFromString $uuid */ $uuid = Uuid::fromString($uuidv1); $uuid1 = $uuid->toUuidV1(); $uuid6 = UuidV6::fromUuidV1($uuid1); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame( $uuid1->getDateTime()->format('U.u'), $uuid6->getDateTime()->format('U.u') ); } /** * @return array */ public function provideUuidV1UuidV6Equivalents(): array { return [ [ 'uuidv6' => '1b21dd21-4814-6000-9669-00007ffffffe', 'uuidv1' => '14814000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-3714-6000-9669-00007ffffffe', 'uuidv1' => '13714000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-3713-6000-9669-00007ffffffe', 'uuidv1' => '13713000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-2e8a-6980-8d4f-acde48001122', 'uuidv1' => '12e8a980-1dd2-11b2-8d4f-acde48001122', ], ]; } public function testGetDateTimeThrowsException(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 6, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new UuidV6($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } } ================================================ FILE: tests/Provider/Dce/SystemDceSecurityProviderTest.php ================================================ with('disable_functions')->once()->andReturn('foo bar shell_exec baz'); $provider = new SystemDceSecurityProvider(); // Test that we catch the exception multiple times, but the ini_get() // function is called only once. $caughtException = 0; for ($i = 1; $i <= 5; $i++) { try { $provider->getUid(); } catch (DceSecurityException $e) { $caughtException++; $this->assertSame( 'Unable to get a user identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider', $e->getMessage() ); } } $this->assertSame(5, $caughtException); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetUidForPosixThrowsExceptionIfShellExecReturnsNull(): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Linux'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('id -u')->once()->andReturnNull(); $provider = new SystemDceSecurityProvider(); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Unable to get a user identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider' ); $provider->getUid(); } /** * @param mixed $value * * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideWindowsBadValues */ public function testGetUidForWindowsThrowsExceptionIfShellExecForWhoAmIReturnsBadValues($value): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Windows_NT'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('whoami /user /fo csv /nh')->once()->andReturn($value); $provider = new SystemDceSecurityProvider(); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Unable to get a user identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider' ); $provider->getUid(); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideWindowsGoodWhoAmIValues */ public function testGetUidForWindowsWhenShellExecForWhoAmIReturnsGoodValues( string $value, string $expectedId ): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Windows_NT'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('whoami /user /fo csv /nh')->once()->andReturn($value); $provider = new SystemDceSecurityProvider(); $uid = $provider->getUid(); $this->assertSame($expectedId, $uid->toString()); $this->assertSame($uid, $provider->getUid()); } /** * @return array */ public function provideWindowsGoodWhoAmIValues(): array { return [ [ 'value' => '"Melilot Sackville","S-1-5-21-7375663-6890924511-1272660413-2944159"', 'expectedId' => '2944159', ], [ 'value' => '"Brutus Sandheaver","S-1-3-12-1234525106-3567804255-30012867-1437"', 'expectedId' => '1437', ], [ 'value' => '"Cora Rumble","S-345"', 'expectedId' => '345', ], ]; } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider providePosixTestValues */ public function testGetUidForPosixSystems(string $os, string $id): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn($os); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('id -u')->once()->andReturn($id); $provider = new SystemDceSecurityProvider(); $uid = $provider->getUid(); $this->assertSame($id, $uid->toString()); $this->assertSame($uid, $provider->getUid()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetGidThrowsExceptionIfShellExecDisabled(): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('foo bar shell_exec baz'); $provider = new SystemDceSecurityProvider(); // Test that we catch the exception multiple times, but the ini_get() // function is called only once. $caughtException = 0; for ($i = 1; $i <= 5; $i++) { try { $provider->getGid(); } catch (DceSecurityException $e) { $caughtException++; $this->assertSame( 'Unable to get a group identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider', $e->getMessage() ); } } $this->assertSame(5, $caughtException); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetGidForPosixThrowsExceptionIfShellExecReturnsNull(): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Linux'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('id -g')->once()->andReturnNull(); $provider = new SystemDceSecurityProvider(); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Unable to get a group identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider' ); $provider->getGid(); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider providePosixTestValues */ public function testGetGidForPosixSystems(string $os, string $id): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn($os); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('id -g')->once()->andReturn($id); $provider = new SystemDceSecurityProvider(); $gid = $provider->getGid(); $this->assertSame($id, $gid->toString()); $this->assertSame($gid, $provider->getGid()); } /** * @param mixed $value * * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideWindowsBadValues */ public function testGetGidForWindowsThrowsExceptionWhenShellExecForNetUserReturnsBadValues($value): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Windows_NT'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'shell_exec' )->with('net user %username% | findstr /b /i "Local Group Memberships"')->once()->andReturn($value); $provider = new SystemDceSecurityProvider(); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Unable to get a group identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider' ); $provider->getGid(); } /** * @param mixed $value * * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideWindowsBadGroupValues */ public function testGetGidForWindowsThrowsExceptionWhenShellExecForWmicGroupGetReturnsBadValues($value): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Windows_NT'); $shellExec = PHPMockery::mock('Ramsey\Uuid\Provider\Dce', 'shell_exec'); $shellExec ->with('net user %username% | findstr /b /i "Local Group Memberships"') ->once() ->andReturn('Local Group Memberships *Users'); $shellExec ->with(Mockery::pattern("/^wmic group get name,sid \| findstr \/b \/i (\"|\')Users(\"|\')$/")) ->once() ->andReturn($value); $provider = new SystemDceSecurityProvider(); $this->expectException(DceSecurityException::class); $this->expectExceptionMessage( 'Unable to get a group identifier using the system DCE ' . 'Security provider; please provide a custom identifier or ' . 'use a different provider' ); $provider->getGid(); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideWindowsGoodNetUserAndWmicGroupValues */ public function testGetGidForWindowsSucceeds( string $netUserResponse, string $wmicGroupResponse, string $expectedGroup, string $expectedId ): void { PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'ini_get' )->with('disable_functions')->once()->andReturn('nothing'); PHPMockery::mock( 'Ramsey\Uuid\Provider\Dce', 'constant' )->with('PHP_OS')->once()->andReturn('Windows_NT'); $shellExec = PHPMockery::mock('Ramsey\Uuid\Provider\Dce', 'shell_exec'); $shellExec ->with('net user %username% | findstr /b /i "Local Group Memberships"') ->once() ->andReturn($netUserResponse); $shellExec ->with(Mockery::pattern("/^wmic group get name,sid \| findstr \/b \/i (\"|\'){$expectedGroup}(\"|\')$/")) ->once() ->andReturn($wmicGroupResponse); $provider = new SystemDceSecurityProvider(); $gid = $provider->getGid(); $this->assertSame($expectedId, $gid->toString()); $this->assertSame($gid, $provider->getGid()); } /** * @return array */ public function provideWindowsGoodNetUserAndWmicGroupValues(): array { return [ [ 'netUserResponse' => 'Local Group Memberships *Administrators *Users', 'wmicGroupResponse' => 'Administrators S-1-5-32-544', 'expectedGroup' => 'Administrators', 'expectedId' => '544', ], [ 'netUserResponse' => 'Local Group Memberships Users', 'wmicGroupResponse' => 'Users S-1-5-32-545', 'expectedGroup' => 'Users', 'expectedId' => '545', ], [ 'netUserResponse' => 'Local Group Memberships Guests Nobody', 'wmicGroupResponse' => 'Guests S-1-5-32-546', 'expectedGroup' => 'Guests', 'expectedId' => '546', ], [ 'netUserResponse' => 'Local Group Memberships Some Group Another Group', 'wmicGroupResponse' => 'Some Group S-1-5-80-19088743-1985229328-4294967295-1324', 'expectedGroup' => 'Some Group', 'expectedId' => '1324', ], ]; } /** * @return array */ public function providePosixTestValues(): array { return [ ['os' => 'Darwin', 'id' => '1042'], ['os' => 'FreeBSD', 'id' => '672'], ['os' => 'GNU', 'id' => '1008'], ['os' => 'Linux', 'id' => '567'], ['os' => 'NetBSD', 'id' => '7234'], ['os' => 'OpenBSD', 'id' => '2347'], ['os' => 'OS400', 'id' => '1234'], ]; } /** * @return array */ public function provideWindowsBadValues(): array { return [ ['value' => null], ['value' => 'foobar'], ['value' => 'foo,bar,baz'], ['value' => ''], ['value' => '1234'], ['value' => 'Local Group Memberships'], ['value' => 'Local Group Memberships **** Foo'], ]; } /** * @return array */ public function provideWindowsBadGroupValues(): array { return array_merge( $this->provideWindowsBadValues(), [ ['value' => 'Users Not a valid SID string'], ['value' => 'Users 344aab9758bb0d018b93739e7893fb3a'], ] ); } } ================================================ FILE: tests/Provider/Node/FallbackNodeProviderTest.php ================================================ getMockBuilder(NodeProviderInterface::class)->getMock(); $providerWithNode->expects($this->once()) ->method('getNode') ->willReturn(new Hexadecimal('57764a07f756')); $providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $providerWithoutNode->expects($this->once()) ->method('getNode') ->willThrowException(new NodeException()); $provider = new FallbackNodeProvider([$providerWithoutNode, $providerWithNode]); $provider->getNode(); } public function testGetNodeReturnsNodeFromFirstProviderWithNode(): void { $providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $providerWithoutNode->expects($this->once()) ->method('getNode') ->willThrowException(new NodeException()); $providerWithNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $providerWithNode->expects($this->once()) ->method('getNode') ->willReturn(new Hexadecimal('57764a07f756')); $anotherProviderWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $anotherProviderWithoutNode->expects($this->never()) ->method('getNode'); $provider = new FallbackNodeProvider([$providerWithoutNode, $providerWithNode, $anotherProviderWithoutNode]); $node = $provider->getNode(); $this->assertSame('57764a07f756', $node->toString()); } public function testGetNodeThrowsExceptionWhenNoNodesFound(): void { $providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock(); $providerWithoutNode->method('getNode') ->willThrowException(new NodeException()); $provider = new FallbackNodeProvider([$providerWithoutNode]); $this->expectException(NodeException::class); $this->expectExceptionMessage( 'Unable to find a suitable node provider' ); $provider->getNode(); } public function testSerializationOfNodeProviderCollection(): void { $staticNodeProvider = new StaticNodeProvider(new Hexadecimal('aabbccddeeff')); $randomNodeProvider = new RandomNodeProvider(); $systemNodeProvider = new SystemNodeProvider(); /** @var list $unserializedNodeProviderCollection */ $unserializedNodeProviderCollection = unserialize(serialize([ $staticNodeProvider, $randomNodeProvider, $systemNodeProvider, ])); foreach ($unserializedNodeProviderCollection as $nodeProvider) { $this->assertInstanceOf(NodeProviderInterface::class, $nodeProvider); } } } ================================================ FILE: tests/Provider/Node/RandomNodeProviderTest.php ================================================ once() ->with(6) ->andReturn($bytes); $provider = new RandomNodeProvider(); $node = $provider->getNode(); $this->assertSame($expectedNode, $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeAlreadyHasMulticastBit(): void { $bytesHex = '4161a1ff5d50'; $bytes = hex2bin($bytesHex); // We expect the same hex value for the node. $expectedNode = $bytesHex; PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes') ->once() ->with(6) ->andReturn($bytes); $provider = new RandomNodeProvider(); $this->assertSame($expectedNode, $provider->getNode()->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeSetsMulticastBitForLowNodeValue(): void { $bytes = hex2bin('100000000001'); $expectedNode = '110000000001'; PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes') ->once() ->with(6) ->andReturn($bytes); $provider = new RandomNodeProvider(); $this->assertSame($expectedNode, $provider->getNode()->toString()); } public function testGetNodeAlwaysSetsMulticastBit(): void { $provider = new RandomNodeProvider(); $nodeHex = $provider->getNode(); // Convert what we got into bytes so that we can mask out everything // except the multicast bit. If the multicast bit doesn't exist, this // test will fail appropriately. $nodeBytes = (string) hex2bin((string) $nodeHex); // Split the node bytes for math on 32-bit systems. $nodeMsb = substr($nodeBytes, 0, 3); $nodeLsb = substr($nodeBytes, 3); // Only set bits that match the mask so we can see that the multicast // bit is always set. $nodeMsb = sprintf('%06x', hexdec(bin2hex($nodeMsb)) & 0x010000); $nodeLsb = sprintf('%06x', hexdec(bin2hex($nodeLsb)) & 0x000000); // Recombine the node bytes. $node = $nodeMsb . $nodeLsb; $this->assertSame('010000000000', $node); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeThrowsExceptionWhenExceptionThrownByRandombytes(): void { PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes') ->once() ->andThrow(new Exception('Could not gather sufficient random data')); $provider = new RandomNodeProvider(); $this->expectException(RandomSourceException::class); $this->expectExceptionMessage('Could not gather sufficient random data'); $provider->getNode(); } } ================================================ FILE: tests/Provider/Node/StaticNodeProviderTest.php ================================================ assertSame($expectedNode, $staticNode->getNode()->toString()); } /** * @return array */ public function provideNodeForTest(): array { return [ [ 'node' => new Hexadecimal('0'), 'expectedNode' => '010000000000', ], [ 'node' => new Hexadecimal('1'), 'expectedNode' => '010000000001', ], [ 'node' => new Hexadecimal('f2ffffffffff'), 'expectedNode' => 'f3ffffffffff', ], [ 'node' => new Hexadecimal('ffffffffffff'), 'expectedNode' => 'ffffffffffff', ], ]; } public function testStaticNodeThrowsExceptionForTooLongNode(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Static node value cannot be greater than 12 hexadecimal characters' ); new StaticNodeProvider(new Hexadecimal('1000000000000')); } } ================================================ FILE: tests/Provider/Node/SystemNodeProviderTest.php ================================================ arrangeMockFunctions( null, null, function () use ($netstatOutput): void { echo $netstatOutput; }, 'NOT LINUX', 'nothing disabled' ); /* Act upon the system under test */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert the result match expectations */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame($expected, $node->toString()); $message = vsprintf( 'Node should be a hexadecimal string of 12 characters. Actual node: %s (length: %s)', [$node->toString(), strlen($node->toString()),] ); $this->assertMatchesRegularExpression('/^[A-Fa-f0-9]{12}$/', $node->toString(), $message); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideInvalidNetStatOutput */ public function testGetNodeShouldNotReturnsSystemNodeForInvalidMacAddress(string $netstatOutput): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function () use ($netstatOutput): void { echo $netstatOutput; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $exception = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception) { // do nothing } /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertInstanceOf(NodeException::class, $exception); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideNotationalFormats */ public function testGetNodeReturnsNodeStrippedOfNotationalFormatting(string $formatted, string $expected): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function () use ($formatted): void { echo "\n{$formatted}\n"; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame($expected, $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideInvalidNotationalFormats */ public function testGetNodeDoesNotAcceptIncorrectNotationalFormatting(string $formatted): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function () use ($formatted): void { echo "\n{$formatted}\n"; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $exception = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception) { // do nothing } /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertInstanceOf(NodeException::class, $exception); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeReturnsFirstMacAddressFound(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function (): void { echo "\nAA-BB-CC-DD-EE-FF\n00-11-22-33-44-55\nFF-11-EE-22-DD-33\n"; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame('aabbccddeeff', $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeReturnsFalseWhenNodeIsNotFound(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function (): void { echo 'some string that does not match the mac address'; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $exception = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception) { // do nothing } /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertInstanceOf(NodeException::class, $exception); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeWillNotExecuteSystemCallIfFailedFirstTime(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function (): void { echo 'some string that does not match the mac address'; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $exception1 = null; $exception2 = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception1) { // do nothing } try { $provider->getNode(); } catch (NodeException $exception2) { // do nothing } /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertInstanceOf(NodeException::class, $exception1); $this->assertInstanceOf(NodeException::class, $exception2); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideCommandPerOs */ public function testGetNodeGetsNetworkInterfaceConfig(string $os, string $command): void { /* Arrange */ $this->arrangeMockFunctions( 'whatever', ['mock address path'], 'whatever', $os, 'nothing disabled', true ); /* Act */ $exception = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception) { // do nothing } /* Assert */ $globBodyAssert = null; $fileGetContentsAssert = null; $isReadableAssert = null; if ($os === 'Linux') { $globBodyAssert = [['/sys/class/net/*/address', GLOB_NOSORT]]; $fileGetContentsAssert = ['mock address path']; $isReadableAssert = $fileGetContentsAssert; } $this->assertMockFunctions( $fileGetContentsAssert, $globBodyAssert, [$command], ['PHP_OS'], ['disable_functions'], $isReadableAssert ); $this->assertInstanceOf(NodeException::class, $exception); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeReturnsSameNodeUponSubsequentCalls(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function (): void { echo "\nAA-BB-CC-DD-EE-FF\n"; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); $node2 = $provider->getNode(); /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame($node->toString(), $node2->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testSubsequentCallsToGetNodeDoNotRecallIfconfig(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, function (): void { echo "\nAA-BB-CC-DD-EE-FF\n"; }, 'NOT LINUX', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); $node2 = $provider->getNode(); /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame($node->toString(), $node2->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled * @dataProvider provideCommandPerOs */ public function testCallGetsysfsOnLinux(string $os, string $command): void { /* Arrange */ $this->arrangeMockFunctions( function () { /** @var non-empty-list $macs */ static $macs = ["00:00:00:00:00:00\n", "01:02:03:04:05:06\n"]; return array_shift($macs); }, ['mock address path 1', 'mock address path 2'], function (): void { echo "\n01-02-03-04-05-06\n"; }, $os, 'nothing disabled', true ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $fileGetContentsAssert = null; $globBodyAssert = null; $passthruBodyAssert = [$command]; $constantBodyAssert = ['PHP_OS']; $iniGetDisableFunctionsAssert = ['disable_functions']; $isReadableAssert = null; if ($os === 'Linux') { $fileGetContentsAssert = [['mock address path 1'], ['mock address path 2']]; $globBodyAssert = [['/sys/class/net/*/address', GLOB_NOSORT]]; $passthruBodyAssert = null; $constantBodyAssert = ['PHP_OS']; $iniGetDisableFunctionsAssert = null; $isReadableAssert = $fileGetContentsAssert; } $this->assertMockFunctions( $fileGetContentsAssert, $globBodyAssert, $passthruBodyAssert, $constantBodyAssert, $iniGetDisableFunctionsAssert, $isReadableAssert ); $this->assertSame('010203040506', $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testCallGetsysfsOnLinuxWhenGlobReturnsFalse(): void { /* Arrange */ $this->arrangeMockFunctions( null, false, function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $this->assertMockFunctions( null, [['/sys/class/net/*/address', GLOB_NOSORT]], ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions'] ); $this->assertSame('010203040506', $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testCallGetsysfsOnLinuxWhenGlobReturnsEmptyArray(): void { /* Arrange */ $this->arrangeMockFunctions( null, [], function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', 'nothing disabled' ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $this->assertMockFunctions( null, [['/sys/class/net/*/address', GLOB_NOSORT]], ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions'] ); $this->assertSame('010203040506', $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testCallGetsysfsOnLinuxWhenGlobFilesAreNotReadable(): void { /* Arrange */ $this->arrangeMockFunctions( null, ['mock address path 1', 'mock address path 2'], function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', 'nothing disabled', false ); /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); /* Assert */ $this->assertMockFunctions( null, [['/sys/class/net/*/address', GLOB_NOSORT]], ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions'], ['mock address path 1', 'mock address path 2'] ); $this->assertSame('010203040506', $node->toString()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeReturnsFalseWhenPassthruIsDisabled(): void { /* Arrange */ $this->arrangeMockFunctions( null, null, null, 'NOT LINUX', 'PASSTHRU,some_other_function' ); /* Act */ $exception = null; $provider = new SystemNodeProvider(); try { $provider->getNode(); } catch (NodeException $exception) { // do nothing } /* Assert */ $this->assertMockFunctions( null, null, null, ['PHP_OS'], ['disable_functions'] ); $this->assertInstanceOf(NodeException::class, $exception); } /** * Replaces the return value for functions with the given value or callback. * * @param callback|mixed|null $fileGetContentsBody * @param callback|mixed|null $globBody * @param callback|mixed|null $passthruBody * @param callback|mixed|null $constantBody * @param callback|mixed|null $iniGetDisableFunctionsBody * @param callback|mixed|null $isReadableBody */ private function arrangeMockFunctions( $fileGetContentsBody, $globBody, $passthruBody, $constantBody, $iniGetDisableFunctionsBody, $isReadableBody = true ): void { $mockFunction = [ self::MOCK_FILE_GET_CONTENTS => $fileGetContentsBody, self::MOCK_GLOB => $globBody, self::MOCK_PASSTHRU => $passthruBody, self::MOCK_CONSTANT => $constantBody, self::MOCK_INI_GET => $iniGetDisableFunctionsBody, self::MOCK_IS_READABLE => $isReadableBody, ]; array_walk($mockFunction, function ($body, $key): void { if (!is_callable($body)) { $body = function () use ($body) { return $body; }; } $spy = new Spy(self::PROVIDER_NAMESPACE, $key, $body); $spy->enable(); $this->functionProxies[$key] = $spy; }); } /** * Verifies that each function was called exactly once for each assert given. * * Provide a NULL to assert a function is never called. * * @param array|array>|null $fileGetContentsAssert * @param array>|null $globBodyAssert * @param array|array>|null $passthruBodyAssert * @param array|array>|null $constantBodyAssert * @param array|array>|null $iniGetDisableFunctionsAssert * @param array|array>|null $isReadableAssert */ private function assertMockFunctions( ?array $fileGetContentsAssert, ?array $globBodyAssert, ?array $passthruBodyAssert, ?array $constantBodyAssert, ?array $iniGetDisableFunctionsAssert, ?array $isReadableAssert = null ): void { $mockFunctionAsserts = [ self::MOCK_FILE_GET_CONTENTS => $fileGetContentsAssert, self::MOCK_GLOB => $globBodyAssert, self::MOCK_PASSTHRU => $passthruBodyAssert, self::MOCK_CONSTANT => $constantBodyAssert, self::MOCK_INI_GET => $iniGetDisableFunctionsAssert, self::MOCK_IS_READABLE => $isReadableAssert, ]; array_walk($mockFunctionAsserts, function (mixed $asserts, string $key): void { if ($asserts === null) { // Assert the function was never invoked. $this->assertEmpty($this->functionProxies[$key]->getInvocations()); } elseif (is_array($asserts)) { /** @phpstan-ignore function.alreadyNarrowedType */ // Assert there was at least one invocation for this function. $this->assertNotEmpty($this->functionProxies[$key]->getInvocations()); $invokedArgs = []; foreach ($this->functionProxies[$key]->getInvocations() as $invocation) { $invokedArgs[] = $invocation->getArguments(); } foreach ($asserts as $assert) { // Assert these args were used to invoke the function. $assert = is_array($assert) ? $assert : [$assert]; $this->assertContains($assert, $invokedArgs); } } else { $error = vsprintf( 'Given parameter for %s must be an array or NULL, "%s" given.', [$key, gettype($asserts)] ); throw new InvalidArgumentException($error); } }); } /** * Provides the command that should be executed per supported OS * * @return array */ public function provideCommandPerOs(): array { return [ 'windows' => ['Windows', 'ipconfig /all 2>&1'], 'mac' => ['Darwhat', 'ifconfig 2>&1'], 'linux' => ['Linux', 'netstat -ie 2>&1'], 'freebsd' => ['FreeBSD', 'netstat -i -f link 2>&1'], 'anything_else' => ['someotherxyz', 'netstat -ie 2>&1'], 'Linux when `glob` fails' => ['LIN', 'netstat -ie 2>&1'], ]; } /** * Values that are NOT parsed to a mac address by the class under test * * @return array */ public function provideInvalidNetStatOutput(): array { return [ 'Not an octal value' => [ "The program 'netstat' is currently not installed. " . "You can install it by typing:\nsudo apt install net-tools\n", ], 'One character too short' => ["\nA-BB-CC-DD-EE-FF\n"], 'One tuple too short' => ["\nBB-CC-DD-EE-FF\n"], 'With colon, with linebreak, without space' => ["\n:AA-BB-CC-DD-EE-FF\n"], 'With colon, without linebreak, with space' => [' : AA-BB-CC-DD-EE-FF'], 'With colon, without linebreak, without space' => [':AA-BB-CC-DD-EE-FF'], 'Without colon, without linebreak, without space' => ['AA-BB-CC-DD-EE-FF'], 'Without leading linebreak' => ["AA-BB-CC-DD-EE-FF\n"], 'Without leading whitespace' => ['AA-BB-CC-DD-EE-FF '], 'Without trailing linebreak' => ["\nAA-BB-CC-DD-EE-FF"], 'Without trailing whitespace' => [' AA-BB-CC-DD-EE-FF'], 'All zero MAC address' => ['00-00-00-00-00-00'], ]; } /** * Provides notations that the class under test should NOT attempt to strip * * @return array */ public function provideInvalidNotationalFormats(): array { return [ ['01:23-45-67-89-ab'], ['01:23:45-67-89-ab'], ['01:23:45:67-89-ab'], ['01:23:45:67:89-ab'], ['01-23:45:67:89:ab'], ['01-23-45:67:89:ab'], ['01-23-45-67:89:ab'], ['01-23-45-67-89:ab'], ['00:00:00:00:00:00'], ]; } /** * Provides mac addresses that the class under test should strip notational format from * * @return array */ public function provideNotationalFormats(): array { return [ ['01-23-45-67-89-ab', '0123456789ab'], ['01:23:45:67:89:ab', '0123456789ab'], ]; } /** * Values that are parsed to a mac address by the class under test * * @return array */ public function provideValidNetStatOutput(): array { return [ /* Full output of related command */ 'Full output - Linux' => [ <<<'TXT' Kernel Interface table docker0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) enp3s0 Link encap:Ethernet HWaddr fe:dc:ba:98:76:54 inet addr:10.0.0.1 Bcast:10.0.0.255 Mask:255.255.255.0 inet6 addr: ffee::ddcc:bbaa:9988:7766/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:943077 errors:0 dropped:0 overruns:0 frame:0 TX packets:2168039 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:748596414 (748.5 MB) TX bytes:2930448282 (2.9 GB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:8302 errors:0 dropped:0 overruns:0 frame:0 TX packets:8302 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1094983 (1.0 MB) TX bytes:1094983 (1.0 MB) TXT, '0123456789ab', ], 'Full output - MacOS' => [ <<<'TXT' lo0: flags=8049 mtu 16384 options=1203 inet 127.0.0.1 netmask 0xff000000 inet6 ::1 prefixlen 128 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 nd6 options=201 gif0: flags=8010 mtu 1280 stf0: flags=0<> mtu 1280 EHC29: flags=0<> mtu 0 XHC20: flags=0<> mtu 0 EHC26: flags=0<> mtu 0 aa0: flags=8863 mtu 1500 options=10b ether 00:00:00:00:00:00 status: active en0: flags=8863 mtu 1500 options=10b ether 10:dd:b1:b4:e4:8e inet6 fe80::c70:76f5:aa1:5db1%en0 prefixlen 64 secured scopeid 0x7 inet 10.53.8.112 netmask 0xfffffc00 broadcast 10.53.11.255 nd6 options=201 media: autoselect (1000baseT ) status: active en1: flags=8863 mtu 1500 ether ec:35:86:38:c8:c2 inet6 fe80::aa:d44f:5f5f:7fd4%en1 prefixlen 64 secured scopeid 0x8 inet 10.53.17.196 netmask 0xfffffc00 broadcast 10.53.19.255 nd6 options=201 media: autoselect status: active p2p0: flags=8843 mtu 2304 ether 0e:35:86:38:c8:c2 media: autoselect status: inactive awdl0: flags=8943 mtu 1484 ether ea:ab:ae:25:f5:d0 inet6 fe80::e8ab:aeff:fe25:f5d0%awdl0 prefixlen 64 scopeid 0xa nd6 options=201 media: autoselect status: active en2: flags=8963 mtu 1500 options=60 ether 32:00:18:9b:dc:60 media: autoselect status: inactive en3: flags=8963 mtu 1500 options=60 ether 32:00:18:9b:dc:61 media: autoselect status: inactive bridge0: flags=8822 mtu 1500 options=63 ether 32:00:18:9b:dc:60 Configuration: id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0 maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200 root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0 ipfilter disabled flags 0x2 member: en2 flags=3 ifmaxaddr 0 port 11 priority 0 path cost 0 member: en3 flags=3 ifmaxaddr 0 port 12 priority 0 path cost 0 media: status: inactive utun0: flags=8051 mtu 2000 options=6403 inet6 fe80::57c6:d692:9d41:d28f%utun0 prefixlen 64 scopeid 0xe nd6 options=201 TXT, '10ddb1b4e48e', ], 'Full output - Window' => [ <<<'TXT' Windows IP Configuration Host Name . . . . . . . . . . . . : MSEDGEWIN10 Primary Dns Suffix . . . . . . . : Node Type . . . . . . . . . . . . : Hybrid IP Routing Enabled. . . . . . . . : No WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : network.lan Some kind of adapter: Connection-specific DNS Suffix . : network.foo Description . . . . . . . . . . . : Some Adapter Physical Address. . . . . . . . . : 00-00-00-00-00-00 Ethernet adapter Ethernet: Connection-specific DNS Suffix . : network.lan Description . . . . . . . . . . . : Intel(R) PRO/1000 MT Desktop Adapter Physical Address. . . . . . . . . : 08-00-27-B8-42-C6 DHCP Enabled. . . . . . . . . . . : Yes Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::606a:ae33:7ce1:b5e9%3(Preferred) IPv4 Address. . . . . . . . . . . : 10.0.2.15(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Lease Obtained. . . . . . . . . . : Tuesday, January 30, 2018 11:25:31 PM Lease Expires . . . . . . . . . . : Wednesday, January 31, 2018 11:25:27 PM Default Gateway . . . . . . . . . : 10.0.2.2 DHCP Server . . . . . . . . . . . : 10.0.2.2 DHCPv6 IAID . . . . . . . . . . . : 34078759 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-21-40-72-3F-08-00-27-B8-42-C6 DNS Servers . . . . . . . . . . . : 10.0.2.3 NetBIOS over Tcpip. . . . . . . . : Enabled Tunnel adapter isatap.network.lan: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : network.lan Description . . . . . . . . . . . : Microsoft ISATAP Adapter Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0 DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes TXT, '080027b842c6', ], 'Full output - FreeBSD' => [ <<<'TXT' Name Mtu Network Address Ipkts Ierrs Idrop Opkts Oerrs Coll aa0 0 00:00:00:00:00:00 0 0 0 0 0 0 em0 1500 08:00:27:71:a1:00 65514 0 0 42918 0 0 em1 1500 08:00:27:d0:60:a0 1199 0 0 535 0 0 lo0 16384 lo0 4 0 0 4 0 0 TXT, '08002771a100', ], /* The single line that is relevant */ 'Linux - single line' => ["\ndocker0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab\n", '0123456789ab'], 'MacOS - Single line ' => ["\nether 10:dd:b1:b4:e4:8e\n", '10ddb1b4e48e'], 'Window - single line' => ["\nPhysical Address. . . . . . . . . : 08-00-27-B8-42-C6\n", '080027b842c6'], /* Minimal subsets of the single line to show the differences */ 'with colon, with linebreak, with space' => ["\n : AA-BB-CC-DD-EE-FF\n", 'aabbccddeeff'], 'without colon, with linebreak, with space' => ["\n AA-BB-CC-DD-EE-FF \n", 'aabbccddeeff'], 'without colon, with linebreak, without space' => ["\nAA-BB-CC-DD-EE-FF\n", 'aabbccddeeff'], 'without colon, without linebreak, with space' => [' AA-BB-CC-DD-EE-FF ', 'aabbccddeeff'], /* Other accepted variations */ 'Actual mac - 1' => ["\n52:54:00:14:91:69\n", '525400149169'], 'Actual mac - 2' => ["\n00:16:3e:a9:73:f0\n", '00163ea973f0'], 'FF:FF:FF:FF:FF:FF' => ["\nFF:FF:FF:FF:FF:FF\n", 'ffffffffffff'], /* Incorrect variations that are also accepted */ 'Too long -- extra character' => ["\nABC-01-23-45-67-89\n", 'bc0123456789'], 'Too long -- extra tuple' => ["\n01-AA-BB-CC-DD-EE-FF\n", '01aabbccddee'], ]; } } ================================================ FILE: tests/Provider/Time/FixedTimeProviderTest.php ================================================ assertSame($time, $provider->getTime()); } public function testGetTimeReturnsTimeAfterChange(): void { $time = new Time(1458844556, 200997); $provider = new FixedTimeProvider($time); $this->assertSame('1458844556', $provider->getTime()->getSeconds()->toString()); $this->assertSame('200997', $provider->getTime()->getMicroseconds()->toString()); $provider->setSec(1050804050); $this->assertSame('1050804050', $provider->getTime()->getSeconds()->toString()); $this->assertSame('200997', $provider->getTime()->getMicroseconds()->toString()); $provider->setUsec(30192); $this->assertSame('1050804050', $provider->getTime()->getSeconds()->toString()); $this->assertSame('30192', $provider->getTime()->getMicroseconds()->toString()); $this->assertNotSame($time, $provider->getTime()); } } ================================================ FILE: tests/Provider/Time/SystemTimeProviderTest.php ================================================ getTime(); /** @phpstan-ignore method.alreadyNarrowedType */ $this->assertInstanceOf(Time::class, $time); } } ================================================ FILE: tests/Rfc4122/FieldsTest.php ================================================ expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string must be 16 bytes long; received 6 bytes' ); new Fields('foobar'); } /** * @param non-empty-string $uuid * * @dataProvider nonRfc4122VariantProvider */ public function testConstructorThrowsExceptionIfNotRfc4122Variant(string $uuid): void { $bytes = (string) hex2bin(str_replace('-', '', $uuid)); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant' ); new Fields($bytes); } /** * @return array */ public function nonRfc4122VariantProvider(): array { return [ ['ff6f8cb0-c57d-11e1-0b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-1b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-2b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-3b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-4b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-5b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-6b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-7b21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-cb21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-db21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-eb21-0800200c9a66'], ['ff6f8cb0-c57d-11e1-fb21-0800200c9a66'], ]; } /** * @param non-empty-string $uuid * * @dataProvider invalidVersionProvider */ public function testConstructorThrowsExceptionIfInvalidVersion(string $uuid): void { $bytes = (string) hex2bin(str_replace('-', '', $uuid)); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'The byte string received does not contain a valid RFC 9562 (formerly RFC 4122) version' ); new Fields($bytes); } /** * @return array */ public function invalidVersionProvider(): array { return [ ['ff6f8cb0-c57d-01e1-8b21-0800200c9a66'], ['ff6f8cb0-c57d-91e1-bb21-0800200c9a66'], ['ff6f8cb0-c57d-a1e1-9b21-0800200c9a66'], ['ff6f8cb0-c57d-b1e1-ab21-0800200c9a66'], ['ff6f8cb0-c57d-c1e1-ab21-0800200c9a66'], ['ff6f8cb0-c57d-d1e1-ab21-0800200c9a66'], ['ff6f8cb0-c57d-e1e1-ab21-0800200c9a66'], ['ff6f8cb0-c57d-f1e1-ab21-0800200c9a66'], ]; } /** * @param non-empty-string $uuid * @param non-empty-string $methodName * @param non-empty-string | int | bool | null $expectedValue * * @dataProvider fieldGetterMethodProvider */ public function testFieldGetterMethods( string $uuid, string $methodName, bool | int | string | null $expectedValue, ): void { $bytes = (string) hex2bin(str_replace('-', '', $uuid)); $fields = new Fields($bytes); $result = $fields->$methodName(); if ($result instanceof Hexadecimal) { $this->assertSame($expectedValue, $result->toString()); } else { $this->assertSame($expectedValue, $result); } } /** * @return array */ public function fieldGetterMethodProvider(): array { return [ ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeq', '1b21'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeqHiAndReserved', '9b'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeHiAndVersion', '11e1'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getVariant', 2], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getVersion', 1], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'isMax', false], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeq', '2b21'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeqHiAndReserved', 'ab'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeHiAndVersion', '41e1'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getVariant', 2], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getVersion', 4], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'isMax', false], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeq', '3b21'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeqHiAndReserved', 'bb'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeHiAndVersion', '31e1'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getVariant', 2], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getVersion', 3], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'isMax', false], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeq', '0b21'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeqHiAndReserved', '8b'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeHiAndVersion', '51e1'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getVariant', 2], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getVersion', 5], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'isMax', false], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeq', '0b21'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeqHiAndReserved', '8b'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeqLow', '21'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getNode', '0800200c9a66'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeHiAndVersion', '61e1'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeMid', 'c57d'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimestamp', 'ff6f8cb0c57d1e1'], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getVariant', 2], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getVersion', 6], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'isNil', false], ['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'isMax', false], ['00000000-0000-0000-0000-000000000000', 'getClockSeq', '0000'], ['00000000-0000-0000-0000-000000000000', 'getClockSeqHiAndReserved', '00'], ['00000000-0000-0000-0000-000000000000', 'getClockSeqLow', '00'], ['00000000-0000-0000-0000-000000000000', 'getNode', '000000000000'], ['00000000-0000-0000-0000-000000000000', 'getTimeHiAndVersion', '0000'], ['00000000-0000-0000-0000-000000000000', 'getTimeLow', '00000000'], ['00000000-0000-0000-0000-000000000000', 'getTimeMid', '0000'], ['00000000-0000-0000-0000-000000000000', 'getTimestamp', '000000000000000'], ['00000000-0000-0000-0000-000000000000', 'getVariant', 0], ['00000000-0000-0000-0000-000000000000', 'getVersion', null], ['00000000-0000-0000-0000-000000000000', 'isNil', true], ['00000000-0000-0000-0000-000000000000', 'isMax', false], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeq', 'ffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeqHiAndReserved', 'ff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeqLow', 'ff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getNode', 'ffffffffffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeHiAndVersion', 'ffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeLow', 'ffffffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeMid', 'ffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimestamp', 'fffffffffffffff'], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getVariant', 7], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getVersion', null], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'isNil', false], ['ffffffff-ffff-ffff-ffff-ffffffffffff', 'isMax', true], ['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeq', '0400'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeqHiAndReserved', '84'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeqLow', '00'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getNode', '0242ac130003'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeHiAndVersion', '21ea'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeLow', '000001f5'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeMid', '5cde'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getTimestamp', '1ea5cde00000000'], ['000001f5-5cde-21ea-8400-0242ac130003', 'getVariant', 2], ['000001f5-5cde-21ea-8400-0242ac130003', 'getVersion', 2], ['000001f5-5cde-21ea-8400-0242ac130003', 'isNil', false], ['000001f5-5cde-21ea-8400-0242ac130003', 'isMax', false], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeq', '1b21'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeqHiAndReserved', '9b'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeqLow', '21'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getNode', '0800200c9a66'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeHiAndVersion', '71e1'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeLow', '018339f0'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeMid', '1b83'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimestamp', '000018339f01b83'], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getVariant', 2], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'getVersion', 7], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'isNil', false], ['018339f0-1b83-71e1-9b21-0800200c9a66', 'isMax', false], ]; } public function testSerializingFields(): void { $bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66')); $fields = new Fields($bytes); $serializedFields = serialize($fields); /** @var Fields $unserializedFields */ $unserializedFields = unserialize($serializedFields); $this->assertSame($fields->getBytes(), $unserializedFields->getBytes()); } public function testSerializingFieldsWithOldFormat(): void { $fields = new Fields("\xb3\xcd\x58\x6a\xe3\xca\x44\xf3\x98\x8c\xf4\xd6\x66\xc1\xbf\x4d"); $serializedFields = 'C:26:"Ramsey\Uuid\Rfc4122\Fields":24:{s81YauPKRPOYjPTWZsG/TQ==}'; /** @var Fields $unserializedFields */ $unserializedFields = unserialize($serializedFields); $this->assertSame($fields->getBytes(), $unserializedFields->getBytes()); } } ================================================ FILE: tests/Rfc4122/UuidBuilderTest.php ================================================ build($codec, $bytes); /** @var Fields $fields */ $fields = $result->getFields(); $this->assertInstanceOf($expectedClass, $result); $this->assertSame($expectedVersion, $fields->getVersion()); } /** * @return array */ public function provideBuildTestValues(): array { return [ [ 'uuid' => '00000000-0000-0000-0000-000000000000', 'expectedClass' => NilUuid::class, 'expectedVersion' => null, ], [ 'uuid' => 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'expectedClass' => MaxUuid::class, 'expectedVersion' => null, ], [ 'uuid' => 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'expectedClass' => UuidV1::class, 'expectedVersion' => 1, ], [ 'uuid' => 'ff6f8cb0-c57d-21e1-9b21-0800200c9a66', 'expectedClass' => UuidV2::class, 'expectedVersion' => 2, ], [ 'uuid' => 'ff6f8cb0-c57d-31e1-9b21-0800200c9a66', 'expectedClass' => UuidV3::class, 'expectedVersion' => 3, ], [ 'uuid' => 'ff6f8cb0-c57d-41e1-9b21-0800200c9a66', 'expectedClass' => UuidV4::class, 'expectedVersion' => 4, ], [ 'uuid' => 'ff6f8cb0-c57d-51e1-9b21-0800200c9a66', 'expectedClass' => UuidV5::class, 'expectedVersion' => 5, ], [ 'uuid' => 'ff6f8cb0-c57d-61e1-9b21-0800200c9a66', 'expectedClass' => UuidV6::class, 'expectedVersion' => 6, ], // The same UUIDv6 will also be of the expected class type // \Ramsey\Uuid\Nonstandard\UuidV6. [ 'uuid' => 'ff6f8cb0-c57d-61e1-9b21-0800200c9a66', 'expectedClass' => NonstandardUuidV6::class, 'expectedVersion' => 6, ], [ 'uuid' => 'ff6f8cb0-c57d-71e1-9b21-0800200c9a66', 'expectedClass' => UuidV7::class, 'expectedVersion' => 7, ], [ 'uuid' => 'ff6f8cb0-c57d-81e1-9b21-0800200c9a66', 'expectedClass' => UuidV8::class, 'expectedVersion' => 8, ], ]; } public function testBuildThrowsUnableToBuildException(): void { $bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-51e1-9b21-0800200c9a')); $calculator = new BrickMathCalculator(); $numberConverter = new GenericNumberConverter($calculator); $timeConverter = new GenericTimeConverter($calculator); $builder = new UuidBuilder($numberConverter, $timeConverter); $codec = new StringCodec($builder); $this->expectException(UnableToBuildUuidException::class); $this->expectExceptionMessage( 'The byte string must be 16 bytes long; received 15 bytes' ); $builder->build($codec, $bytes); } public function testBuildThrowsUnableToBuildExceptionForIncorrectVersionFields(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'isNil' => false, 'isMax' => false, 'getVersion' => 255, ]); $builder = Mockery::mock(UuidBuilder::class); $builder->shouldAllowMockingProtectedMethods(); $builder->shouldReceive('buildFields')->andReturn($fields); $builder->shouldReceive('build')->passthru(); $codec = Mockery::mock(StringCodec::class); $this->expectException(UnableToBuildUuidException::class); $this->expectExceptionMessage( 'The UUID version in the given fields is not supported by this UUID builder' ); $builder->build($codec, 'foobar'); } } ================================================ FILE: tests/Rfc4122/UuidV1Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV1 must represent a ' . 'version 1 (time-based) UUID' ); new UuidV1($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 6], ['version' => 7], ['version' => 8], ['version' => 9], ]; } /** * @param non-empty-string $uuid * @param numeric-string $expected * * @dataProvider provideUuidV1WithOddMicroseconds */ public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void { /** @var UuidV1 $object */ $object = Uuid::fromString($uuid); $date = $object->getDateTime(); $this->assertInstanceOf(DateTimeImmutable::class, $date); $this->assertSame($expected, $date->format('U.u')); } /** * @return array */ public function provideUuidV1WithOddMicroseconds(): array { return [ [ 'uuid' => '14814000-1dd2-11b2-9669-00007ffffffe', 'expected' => '1.677722', ], [ 'uuid' => '13714000-1dd2-11b2-9669-00007ffffffe', 'expected' => '0.104858', ], [ 'uuid' => '13713000-1dd2-11b2-9669-00007ffffffe', 'expected' => '0.105267', ], [ 'uuid' => '12e8a980-1dd2-11b2-8d4f-acde48001122', 'expected' => '-1.000000', ], ]; } public function testGetDateTimeThrowsException(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 1, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new UuidV1($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } } ================================================ FILE: tests/Rfc4122/UuidV2Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV2 must represent a ' . 'version 2 (DCE Security) UUID' ); new UuidV2($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 6], ['version' => 7], ['version' => 8], ['version' => 9], ]; } /** * @dataProvider provideLocalDomainAndIdentifierForTests */ public function testGetLocalDomainAndIdentifier( int $domain, IntegerObject $identifier, Time $time, int $expectedDomain, string $expectedDomainName, string $expectedIdentifier, string $expectedTimestamp, string $expectedTime ): void { $calculator = new BrickMathCalculator(); $genericConverter = new GenericTimeConverter($calculator); $numberConverter = new GenericNumberConverter($calculator); $nodeProvider = new StaticNodeProvider(new Hexadecimal('1234567890ab')); $timeProvider = new FixedTimeProvider($time); $timeGenerator = new DefaultTimeGenerator($nodeProvider, $genericConverter, $timeProvider); $dceProvider = new SystemDceSecurityProvider(); $dceGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceProvider); $factory = new UuidFactory(); $factory->setTimeGenerator($timeGenerator); $factory->setDceSecurityGenerator($dceGenerator); /** @var UuidV2 $uuid */ $uuid = $factory->uuid2($domain, $identifier); /** @var FieldsInterface $fields */ $fields = $uuid->getFields(); $this->assertSame($expectedDomain, $uuid->getLocalDomain()); $this->assertSame($expectedDomainName, $uuid->getLocalDomainName()); $this->assertInstanceOf(IntegerObject::class, $uuid->getLocalIdentifier()); $this->assertSame($expectedIdentifier, $uuid->getLocalIdentifier()->toString()); $this->assertSame($expectedTimestamp, $fields->getTimestamp()->toString()); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame($expectedTime, $uuid->getDateTime()->format('U.u')); $this->assertSame('1334567890ab', $fields->getNode()->toString()); } /** * @return array */ public function provideLocalDomainAndIdentifierForTests(): array { // https://github.com/php/php-src/issues/7758 $isGH7758Fixed = PHP_VERSION_ID >= 80107; return [ [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('12345678'), 'time' => new Time(0, 0), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '12345678', 'expectedTimestamp' => '1b21dd200000000', 'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763', ], [ 'domain' => Uuid::DCE_DOMAIN_GROUP, 'identifier' => new IntegerObject('87654321'), 'time' => new Time(0, 0), 'expectedDomain' => 1, 'expectedDomainName' => 'group', 'expectedIdentifier' => '87654321', 'expectedTimestamp' => '1b21dd200000000', 'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763', ], [ 'domain' => Uuid::DCE_DOMAIN_ORG, 'identifier' => new IntegerObject('1'), 'time' => new Time(0, 0), 'expectedDomain' => 2, 'expectedDomainName' => 'org', 'expectedIdentifier' => '1', 'expectedTimestamp' => '1b21dd200000000', 'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763', ], [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('0'), 'time' => new Time(1583208664, 444109), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '0', 'expectedTimestamp' => '1ea5d0500000000', 'expectedTime' => '1583208664.444109', ], [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('2147483647'), 'time' => new Time(1583208879, 500000), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '2147483647', // This time is the same as in the previous test because of the // loss of precision by setting the lowest 32 bits to zeros. 'expectedTimestamp' => '1ea5d0500000000', 'expectedTime' => '1583208664.444109', ], [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('4294967295'), 'time' => new Time(1583208879, 500000), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '4294967295', // This time is the same as in the previous test because of the // loss of precision by setting the lowest 32 bits to zeros. 'expectedTimestamp' => '1ea5d0500000000', 'expectedTime' => '1583208664.444109', ], [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('4294967295'), 'time' => new Time(1583209093, 940838), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '4294967295', // This time is the same as in the previous test because of the // loss of precision by setting the lowest 32 bits to zeros. 'expectedTimestamp' => '1ea5d0500000000', 'expectedTime' => '1583208664.444109', ], [ 'domain' => Uuid::DCE_DOMAIN_PERSON, 'identifier' => new IntegerObject('4294967295'), 'time' => new Time(1583209093, 940839), 'expectedDomain' => 0, 'expectedDomainName' => 'person', 'expectedIdentifier' => '4294967295', 'expectedTimestamp' => '1ea5d0600000000', 'expectedTime' => '1583209093.940838', ], ]; } } ================================================ FILE: tests/Rfc4122/UuidV3Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV3 must represent a ' . 'version 3 (name-based, MD5-hashed) UUID' ); new UuidV3($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 4], ['version' => 5], ['version' => 6], ['version' => 7], ['version' => 8], ['version' => 9], ]; } } ================================================ FILE: tests/Rfc4122/UuidV4Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV4 must represent a ' . 'version 4 (random) UUID' ); new UuidV4($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 5], ['version' => 6], ['version' => 7], ['version' => 8], ['version' => 9], ]; } } ================================================ FILE: tests/Rfc4122/UuidV5Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV5 must represent a ' . 'version 5 (named-based, SHA1-hashed) UUID' ); new UuidV5($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 6], ['version' => 7], ['version' => 8], ['version' => 9], ]; } } ================================================ FILE: tests/Rfc4122/UuidV6Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV6 must represent a ' . 'version 6 (reordered time) UUID' ); new UuidV6($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 7], ['version' => 8], ['version' => 9], ]; } /** * @param non-empty-string $uuid * @param non-empty-string $expected * * @dataProvider provideUuidV6WithOddMicroseconds */ public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void { /** @var UuidV6 $object */ $object = Uuid::fromString($uuid); $date = $object->getDateTime(); $this->assertInstanceOf(DateTimeImmutable::class, $date); $this->assertSame($expected, $date->format('U.u')); } /** * @return array */ public function provideUuidV6WithOddMicroseconds(): array { return [ [ 'uuid' => '1b21dd21-4814-6000-9669-00007ffffffe', 'expected' => '1.677722', ], [ 'uuid' => '1b21dd21-3714-6000-9669-00007ffffffe', 'expected' => '0.104858', ], [ 'uuid' => '1b21dd21-3713-6000-9669-00007ffffffe', 'expected' => '0.105267', ], [ 'uuid' => '1b21dd21-2e8a-6980-8d4f-acde48001122', 'expected' => '-1.000000', ], ]; } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider provideUuidV1UuidV6Equivalents */ public function testToUuidV1(string $uuidv6, string $uuidv1): void { /** @var UuidV6 $uuid6 */ $uuid6 = Uuid::fromString($uuidv6); $uuid1 = $uuid6->toUuidV1(); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame( $uuid6->getDateTime()->format('U.u'), $uuid1->getDateTime()->format('U.u') ); } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider provideUuidV1UuidV6Equivalents */ public function testFromUuidV1(string $uuidv6, string $uuidv1): void { /** @var LazyUuidFromString $uuid */ $uuid = Uuid::fromString($uuidv1); $uuid1 = $uuid->toUuidV1(); $uuid6 = UuidV6::fromUuidV1($uuid1); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame( $uuid1->getDateTime()->format('U.u'), $uuid6->getDateTime()->format('U.u') ); } /** * @return array */ public function provideUuidV1UuidV6Equivalents(): array { return [ [ 'uuidv6' => '1b21dd21-4814-6000-9669-00007ffffffe', 'uuidv1' => '14814000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-3714-6000-9669-00007ffffffe', 'uuidv1' => '13714000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-3713-6000-9669-00007ffffffe', 'uuidv1' => '13713000-1dd2-11b2-9669-00007ffffffe', ], [ 'uuidv6' => '1b21dd21-2e8a-6980-8d4f-acde48001122', 'uuidv1' => '12e8a980-1dd2-11b2-8d4f-acde48001122', ], ]; } public function testGetDateTimeThrowsException(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 6, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new UuidV6($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } /** * @link https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#appendix-B.1 */ public function testUsingDraftPeabodyUuidV6TestVector(): void { $testVector = '1EC9414C-232A-6B00-B3C8-9E6BDECED846'; /** @var UuidV6 $uuidv6 */ $uuidv6 = Uuid::fromString($testVector); $uuidv1 = $uuidv6->toUuidV1(); /** @var FieldsInterface $fields */ $fields = $uuidv6->getFields(); $this->assertSame('1ec9414c', $fields->getTimeLow()->toString()); $this->assertSame('232a', $fields->getTimeMid()->toString()); $this->assertSame('6b00', $fields->getTimeHiAndVersion()->toString()); $this->assertSame('b3', $fields->getClockSeqHiAndReserved()->toString()); $this->assertSame('c8', $fields->getClockSeqLow()->toString()); $this->assertSame('9e6bdeced846', $fields->getNode()->toString()); $this->assertSame(1645557742, $uuidv6->getDateTime()->getTimestamp()); $this->assertSame( 'c232ab00-9414-11ec-b3c8-9e6bdeced846', $uuidv1->toString(), ); } } ================================================ FILE: tests/Rfc4122/UuidV7Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Fields used to create a UuidV7 must represent a ' . 'version 7 (Unix Epoch time) UUID' ); new UuidV7($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 6], ['version' => 8], ['version' => 9], ]; } /** * @param non-empty-string $uuid * * @dataProvider provideUuidV7WithMicroseconds */ public function testGetDateTimeProperlyHandlesMicroseconds(string $uuid, string $expected): void { /** @var UuidV7 $object */ $object = Uuid::fromString($uuid); $date = $object->getDateTime(); $this->assertInstanceOf(DateTimeImmutable::class, $date); $this->assertSame($expected, $date->format('U.u')); } /** * @return array */ public function provideUuidV7WithMicroseconds(): array { return [ [ 'uuid' => '00000000-0001-71b2-9669-00007ffffffe', 'expected' => '0.001000', ], [ 'uuid' => '00000000-000f-71b2-9669-00007ffffffe', 'expected' => '0.015000', ], [ 'uuid' => '00000000-0064-71b2-9669-00007ffffffe', 'expected' => '0.100000', ], [ 'uuid' => '00000000-03e7-71b2-9669-00007ffffffe', 'expected' => '0.999000', ], [ 'uuid' => '00000000-03e8-71b2-9669-00007ffffffe', 'expected' => '1.000000', ], [ 'uuid' => '00000000-03e9-71b2-9669-00007ffffffe', 'expected' => '1.001000', ], ]; } public function testGetDateTimeThrowsException(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 7, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new UuidV7($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } } ================================================ FILE: tests/Rfc4122/UuidV8Test.php ================================================ $version, ]); $numberConverter = Mockery::mock(NumberConverterInterface::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Fields used to create a UuidV8 must represent a version 8 (custom format) UUID'); new UuidV8($fields, $numberConverter, $codec, $timeConverter); } /** * @return array */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 6], ['version' => 7], ['version' => 9], ]; } } ================================================ FILE: tests/Rfc4122/ValidatorTest.php ================================================ assertSame( $expected, $validator->validate($variation), sprintf( 'Expected "%s" to be %s', $variation, $expected ? 'valid' : 'not valid', ), ); } } /** * @return array */ public function provideValuesForValidation(): array { $hexMutations = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']; $trueVersions = [1, 2, 3, 4, 5, 6, 7, 8]; $trueVariants = [8, 9, 'a', 'b']; $testValues = []; foreach ($hexMutations as $version) { foreach ($hexMutations as $variant) { $testValues[] = [ 'value' => "ff6f8cb0-c57d-{$version}1e1-{$variant}b21-0800200c9a66", 'expected' => in_array($variant, $trueVariants, true) && in_array($version, $trueVersions, true), ]; } } return array_merge($testValues, [ [ 'value' => 'zf6f8cb0-c57d-11e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => '3f6f8cb0-c57d-11e1-9b21-0800200c9a6', 'expected' => false, ], [ 'value' => 'af6f8cb-c57d-11e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => 'af6f8cb0c57d11e19b210800200c9a66', 'expected' => false, ], [ 'value' => 'ff6f8cb0-c57da-51e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => "ff6f8cb0-c57d-11e1-1b21-0800200c9a66\n", 'expected' => false, ], [ 'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66", 'expected' => false, ], [ 'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66\n", 'expected' => false, ], [ 'value' => '00000000-0000-0000-0000-000000000000', 'expected' => true, ], [ 'value' => 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'expected' => true, ], [ 'value' => 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF', 'expected' => true, ], ]); } public function testGetPattern(): void { $expectedPattern = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-' . '[1-8][0-9A-Fa-f]{3}-[ABab89][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z'; $validator = new Validator(); $this->assertSame($expectedPattern, $validator->getPattern()); } } ================================================ FILE: tests/Rfc4122/VariantTraitTest.php ================================================ $bytes, 'isMax' => false, 'isNil' => false, ]); $this->expectException(InvalidBytesException::class); $this->expectExceptionMessage('Invalid number of bytes'); $trait->getVariant(); } /** * @return array */ public function invalidBytesProvider(): array { return [ ['not16Bytes_abcd'], ['not16Bytes_abcdef'], ]; } /** * @dataProvider uuidVariantProvider */ public function testGetVariant(string $uuid, int $expectedVariant): void { $bytes = (string) hex2bin(str_replace('-', '', $uuid)); /** @var Fields $trait */ $trait = Mockery::mock(VariantTrait::class, [ 'getBytes' => $bytes, 'isMax' => false, 'isNil' => false, ]); $this->assertSame($expectedVariant, $trait->getVariant()); } /** * @return array */ public function uuidVariantProvider(): array { return [ ['ff6f8cb0-c57d-11e1-0b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-1b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-2b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-3b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-4b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-5b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-6b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-7b21-0800200c9a66', 0], ['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', 2], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 2], ['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', 2], ['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', 2], ['ff6f8cb0-c57d-11e1-cb21-0800200c9a66', 6], ['ff6f8cb0-c57d-11e1-db21-0800200c9a66', 6], ['ff6f8cb0-c57d-11e1-eb21-0800200c9a66', 7], ['ff6f8cb0-c57d-11e1-fb21-0800200c9a66', 7], // The following are the same UUIDs in GUID byte order. Dashes have // been removed in the tests to distinguish these from string // representations, which are never in GUID byte order. ['b08c6fff7dc5e1110b210800200c9a66', 0], ['b08c6fff7dc5e1111b210800200c9a66', 0], ['b08c6fff7dc5e1112b210800200c9a66', 0], ['b08c6fff7dc5e1113b210800200c9a66', 0], ['b08c6fff7dc5e1114b210800200c9a66', 0], ['b08c6fff7dc5e1115b210800200c9a66', 0], ['b08c6fff7dc5e1116b210800200c9a66', 0], ['b08c6fff7dc5e1117b210800200c9a66', 0], ['b08c6fff7dc5e1118b210800200c9a66', 2], ['b08c6fff7dc5e1119b210800200c9a66', 2], ['b08c6fff7dc5e111ab210800200c9a66', 2], ['b08c6fff7dc5e111bb210800200c9a66', 2], ['b08c6fff7dc5e111cb210800200c9a66', 6], ['b08c6fff7dc5e111db210800200c9a66', 6], ['b08c6fff7dc5e111eb210800200c9a66', 7], ['b08c6fff7dc5e111fb210800200c9a66', 7], ]; } } ================================================ FILE: tests/TestCase.php ================================================ assertSame($expected, $decimal->toString()); $this->assertSame($expected, (string) $decimal); $this->assertSame($expectedIsNegative, $decimal->isNegative()); } /** * @return array */ public function provideDecimal(): array { return [ [ 'value' => '-11386878954224802805705605120', 'expected' => '-11386878954224802805705605120', 'expectedIsNegative' => true, ], [ 'value' => '-9223372036854775808', 'expected' => '-9223372036854775808', 'expectedIsNegative' => true, ], [ 'value' => -99986838650880, 'expected' => '-99986838650880', 'expectedIsNegative' => true, ], [ 'value' => -4294967296, 'expected' => '-4294967296', 'expectedIsNegative' => true, ], [ 'value' => -2147483649, 'expected' => '-2147483649', 'expectedIsNegative' => true, ], [ 'value' => -123456.0, 'expected' => '-123456', 'expectedIsNegative' => true, ], [ 'value' => -1.00000000000001, 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => -1, 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => '-1', 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => 0, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => -0, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '-0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '+0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => 1, 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => '1', 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => '+1', 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => 1.00000000000001, 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => 123456.0, 'expected' => '123456', 'expectedIsNegative' => false, ], [ 'value' => 2147483648, 'expected' => '2147483648', 'expectedIsNegative' => false, ], [ 'value' => 4294967294, 'expected' => '4294967294', 'expectedIsNegative' => false, ], [ 'value' => 99965363767850, 'expected' => '99965363767850', 'expectedIsNegative' => false, ], [ 'value' => '9223372036854775808', 'expected' => '9223372036854775808', 'expectedIsNegative' => false, ], [ 'value' => '11386878954224802805705605120', 'expected' => '11386878954224802805705605120', 'expectedIsNegative' => false, ], [ 'value' => -9223372036854775809, 'expected' => '-9.2233720368548E+18', 'expectedIsNegative' => true, ], [ 'value' => 9223372036854775808, 'expected' => '9.2233720368548E+18', 'expectedIsNegative' => false, ], [ 'value' => -123456.789, 'expected' => '-123456.789', 'expectedIsNegative' => true, ], [ 'value' => -1.0000000000001, 'expected' => '-1.0000000000001', 'expectedIsNegative' => true, ], [ 'value' => -0.5, 'expected' => '-0.5', 'expectedIsNegative' => true, ], [ 'value' => 0.5, 'expected' => '0.5', 'expectedIsNegative' => false, ], [ 'value' => 1.0000000000001, 'expected' => '1.0000000000001', 'expectedIsNegative' => false, ], [ 'value' => 123456.789, 'expected' => '123456.789', 'expectedIsNegative' => false, ], [ 'value' => '-0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '+0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => -0.00000000, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => 0.00000000, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => -0.0001, 'expected' => '-0.0001', 'expectedIsNegative' => true, ], [ 'value' => 0.0001, 'expected' => '0.0001', 'expectedIsNegative' => false, ], [ 'value' => -0.00001, 'expected' => '-1.0E-5', 'expectedIsNegative' => true, ], [ 'value' => 0.00001, 'expected' => '1.0E-5', 'expectedIsNegative' => false, ], [ 'value' => '+1234.56', 'expected' => '1234.56', 'expectedIsNegative' => false, ], ]; } /** * @param int|float|string $value * * @dataProvider provideDecimalBadValues */ public function testDecimalTypeThrowsExceptionForBadValues($value): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed decimal or a string containing only ' . 'digits 0-9 and, optionally, a decimal point or sign (+ or -)' ); new Decimal($value); } /** * @return array */ public function provideDecimalBadValues(): array { return [ ['123abc'], ['abc123'], ['foobar'], ['123.456a'], ['+abcd'], ['-0012.a'], ]; } /** * @param float|int|string|Decimal $value * * @dataProvider provideDecimal */ public function testSerializeUnserializeDecimal($value, string $expected): void { $decimal = new Decimal($value); $serializedDecimal = serialize($decimal); /** @var Decimal $unserializedDecimal */ $unserializedDecimal = unserialize($serializedDecimal); $this->assertSame($expected, $unserializedDecimal->toString()); } /** * @param float|int|string|Decimal $value * * @dataProvider provideDecimal */ public function testJsonSerialize($value, string $expected): void { $decimal = new Decimal($value); $expectedJson = sprintf('"%s"', $expected); $this->assertSame($expectedJson, json_encode($decimal)); } } ================================================ FILE: tests/Type/HexadecimalTest.php ================================================ assertSame($expected, $hexadecimal->toString()); $this->assertSame($expected, (string) $hexadecimal); } /** * @return array */ public function provideHex(): array { return [ [ 'value' => '0xFFFF', 'expected' => 'ffff', ], [ 'value' => '0123456789abcdef', 'expected' => '0123456789abcdef', ], [ 'value' => 'ABCDEF', 'expected' => 'abcdef', ], ]; } /** * @dataProvider provideHexBadValues */ public function testHexadecimalTypeThrowsExceptionForBadValues(string $value): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a hexadecimal number' ); new Hexadecimal($value); } /** * @return array */ public function provideHexBadValues(): array { return [ ['-123456.789'], ['123456.789'], ['foobar'], ['0xfoobar'], ]; } /** * @dataProvider provideHex */ public function testSerializeUnserializeHexadecimal(string $value, string $expected): void { $hexadecimal = new Hexadecimal($value); $serializedHexadecimal = serialize($hexadecimal); /** @var Hexadecimal $unserializedHexadecimal */ $unserializedHexadecimal = unserialize($serializedHexadecimal); $this->assertSame($expected, $unserializedHexadecimal->toString()); } /** * @dataProvider provideHex */ public function testJsonSerialize(string $value, string $expected): void { $hexadecimal = new Hexadecimal($value); $expectedJson = sprintf('"%s"', $expected); $this->assertSame($expectedJson, json_encode($hexadecimal)); } } ================================================ FILE: tests/Type/IntegerTest.php ================================================ assertSame($expected, $integer->toString()); $this->assertSame($expected, (string) $integer); $this->assertSame($expectedIsNegative, $integer->isNegative()); } /** * @return array */ public function provideInteger(): array { return [ [ 'value' => '-11386878954224802805705605120', 'expected' => '-11386878954224802805705605120', 'expectedIsNegative' => true, ], [ 'value' => '-9223372036854775808', 'expected' => '-9223372036854775808', 'expectedIsNegative' => true, ], [ 'value' => -99986838650880, 'expected' => '-99986838650880', 'expectedIsNegative' => true, ], [ 'value' => -4294967296, 'expected' => '-4294967296', 'expectedIsNegative' => true, ], [ 'value' => -2147483649, 'expected' => '-2147483649', 'expectedIsNegative' => true, ], [ 'value' => -123456.0, 'expected' => '-123456', 'expectedIsNegative' => true, ], [ 'value' => -1.00000000000001, 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => -1, 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => '-1', 'expected' => '-1', 'expectedIsNegative' => true, ], [ 'value' => 0, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => -0, 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '-0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => '+0', 'expected' => '0', 'expectedIsNegative' => false, ], [ 'value' => 1, 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => '1', 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => '+1', 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => 1.00000000000001, 'expected' => '1', 'expectedIsNegative' => false, ], [ 'value' => 123456.0, 'expected' => '123456', 'expectedIsNegative' => false, ], [ 'value' => 2147483648, 'expected' => '2147483648', 'expectedIsNegative' => false, ], [ 'value' => 4294967294, 'expected' => '4294967294', 'expectedIsNegative' => false, ], [ 'value' => 99965363767850, 'expected' => '99965363767850', 'expectedIsNegative' => false, ], [ 'value' => '9223372036854775808', 'expected' => '9223372036854775808', 'expectedIsNegative' => false, ], [ 'value' => '11386878954224802805705605120', 'expected' => '11386878954224802805705605120', 'expectedIsNegative' => false, ], ]; } /** * @param int|float|string $value * * @dataProvider provideIntegerBadValues */ public function testIntegerTypeThrowsExceptionForBadValues($value): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Value must be a signed integer or a string containing only ' . 'digits 0-9 and, optionally, a sign (+ or -)' ); new IntegerObject($value); } /** * @return array */ public function provideIntegerBadValues(): array { return [ [-9223372036854775809], // String value is "-9.2233720368548E+18" [-123456.789], [-1.0000000000001], [-0.5], [0.5], [1.0000000000001], [123456.789], [9223372036854775808], // String value is "9.2233720368548E+18" ['123abc'], ['abc123'], ['foobar'], ]; } /** * @param int|float|string|IntegerObject $value * * @dataProvider provideInteger */ public function testSerializeUnserializeInteger($value, string $expected): void { $integer = new IntegerObject($value); $serializedInteger = serialize($integer); /** @var IntegerObject $unserializedInteger */ $unserializedInteger = unserialize($serializedInteger); $this->assertSame($expected, $unserializedInteger->toString()); } /** * @param int|float|string|IntegerObject $value * * @dataProvider provideInteger */ public function testJsonSerialize($value, string $expected): void { $integer = new IntegerObject($value); $expectedJson = sprintf('"%s"', $expected); $this->assertSame($expectedJson, json_encode($integer)); } } ================================================ FILE: tests/Type/TimeTest.php ================================================ assertSame((string) $seconds, $time->getSeconds()->toString()); $this->assertSame( (string) $microseconds ?: '0', $time->getMicroseconds()->toString() ); $this->assertSame($timeString, (string) $time); } /** * @return array */ public function provideTimeValues(): array { return [ [ 'seconds' => 103072857659, 'microseconds' => null, ], [ 'seconds' => -12219292800, 'microseconds' => 1234, ], ]; } /** * @param int|float|string|IntegerObject $seconds * @param int|float|string|IntegerObject|null $microseconds * * @dataProvider provideTimeValues */ public function testSerializeUnserializeTime($seconds, $microseconds): void { $params = [$seconds]; if ($microseconds !== null) { $params[] = $microseconds; } $time = new Time(...$params); $serializedTime = serialize($time); /** @var Time $unserializedTime */ $unserializedTime = unserialize($serializedTime); $this->assertSame((string) $seconds, $unserializedTime->getSeconds()->toString()); $this->assertSame( (string) $microseconds ?: '0', $unserializedTime->getMicroseconds()->toString() ); } public function testUnserializeOfInvalidValueException(): void { $invalidSerialization = 'C:21:"Ramsey\\Uuid\\Type\\Time":13:{{"foo":"bar"}}'; $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('Attempted to unserialize an invalid value'); unserialize($invalidSerialization); } /** * @param int|float|string|IntegerObject $seconds * @param int|float|string|IntegerObject|null $microseconds * * @dataProvider provideTimeValues */ public function testJsonSerialize($seconds, $microseconds): void { $time = [ 'seconds' => (string) $seconds, 'microseconds' => (string) $microseconds ?: '0', ]; $expectedJson = json_encode($time); $params = [$seconds]; if ($microseconds !== null) { $params[] = $microseconds; } $time = new Time(...$params); $this->assertSame($expectedJson, json_encode($time)); } } ================================================ FILE: tests/UuidFactoryTest.php ================================================ fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); $this->assertSame(hex2bin('ff6f8cb0c57d11e19b210800200c9a66'), $uuid->getBytes()); } public function testParsesGuidCorrectly(): void { $factory = new UuidFactory(new FeatureSet(true)); $uuid = $factory->fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); $this->assertSame(hex2bin('b08c6fff7dc5e1119b210800200c9a66'), $uuid->getBytes()); } public function testFromStringParsesUuidInLowercase(): void { $uuidString = 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66'; $uuidUpper = strtoupper($uuidString); $factory = new UuidFactory(new FeatureSet(true)); $uuid = $factory->fromString($uuidUpper); $this->assertSame($uuidString, $uuid->toString()); } public function testGettersReturnValueFromFeatureSet(): void { $codec = Mockery::mock(CodecInterface::class); $nodeProvider = Mockery::mock(NodeProviderInterface::class); $randomGenerator = Mockery::mock(RandomGeneratorInterface::class); $timeConverter = Mockery::mock(TimeConverterInterface::class); $timeGenerator = Mockery::mock(TimeGeneratorInterface::class); $unixTimeGenerator = Mockery::mock(TimeGeneratorInterface::class); $nameGenerator = Mockery::mock(NameGeneratorInterface::class); $dceSecurityGenerator = Mockery::mock(DceSecurityGeneratorInterface::class); $numberConverter = Mockery::mock(NumberConverterInterface::class); $builder = Mockery::mock(UuidBuilderInterface::class); $validator = Mockery::mock(ValidatorInterface::class); $featureSet = Mockery::mock(FeatureSet::class, [ 'getCodec' => $codec, 'getNodeProvider' => $nodeProvider, 'getRandomGenerator' => $randomGenerator, 'getTimeConverter' => $timeConverter, 'getTimeGenerator' => $timeGenerator, 'getNameGenerator' => $nameGenerator, 'getDceSecurityGenerator' => $dceSecurityGenerator, 'getNumberConverter' => $numberConverter, 'getBuilder' => $builder, 'getValidator' => $validator, 'getUnixTimeGenerator' => $unixTimeGenerator, ]); $uuidFactory = new UuidFactory($featureSet); $this->assertSame( $codec, $uuidFactory->getCodec(), 'getCodec did not return CodecInterface from FeatureSet' ); $this->assertSame( $nodeProvider, $uuidFactory->getNodeProvider(), 'getNodeProvider did not return NodeProviderInterface from FeatureSet' ); $this->assertSame( $randomGenerator, $uuidFactory->getRandomGenerator(), 'getRandomGenerator did not return RandomGeneratorInterface from FeatureSet' ); $this->assertSame( $timeGenerator, $uuidFactory->getTimeGenerator(), 'getTimeGenerator did not return TimeGeneratorInterface from FeatureSet' ); } public function testSettersSetValueForGetters(): void { $uuidFactory = new UuidFactory(); /** @var MockObject & CodecInterface $codec */ $codec = $this->getMockBuilder(CodecInterface::class)->getMock(); $uuidFactory->setCodec($codec); $this->assertSame($codec, $uuidFactory->getCodec()); /** @var MockObject & TimeGeneratorInterface $timeGenerator */ $timeGenerator = $this->getMockBuilder(TimeGeneratorInterface::class)->getMock(); $uuidFactory->setTimeGenerator($timeGenerator); $this->assertSame($timeGenerator, $uuidFactory->getTimeGenerator()); /** @var MockObject & NumberConverterInterface $numberConverter */ $numberConverter = $this->getMockBuilder(NumberConverterInterface::class)->getMock(); $uuidFactory->setNumberConverter($numberConverter); $this->assertSame($numberConverter, $uuidFactory->getNumberConverter()); /** @var MockObject & UuidBuilderInterface $uuidBuilder */ $uuidBuilder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock(); $uuidFactory->setUuidBuilder($uuidBuilder); $this->assertSame($uuidBuilder, $uuidFactory->getUuidBuilder()); } /** * @dataProvider provideDateTime */ public function testFromDateTime( DateTimeInterface $dateTime, ?Hexadecimal $node, ?int $clockSeq, string $expectedUuidFormat, string $expectedTime ): void { $factory = new UuidFactory(); $uuid = $factory->fromDateTime($dateTime, $node, $clockSeq); $this->assertStringMatchesFormat($expectedUuidFormat, $uuid->toString()); $this->assertSame($expectedTime, $uuid->getDateTime()->format('U.u')); } /** * @return array */ public function provideDateTime(): array { return [ [ new DateTimeImmutable('2012-07-04 02:14:34.491000'), null, null, 'ff6f8cb0-c57d-11e1-%s', '1341368074.491000', ], [ new DateTimeImmutable('1582-10-16 16:34:04'), new Hexadecimal('0800200c9a66'), 15137, '0901e600-0154-1000-%cb21-0800200c9a66', '-12219146756.000000', ], [ new DateTime('5236-03-31 21:20:59.999999'), new Hexadecimal('00007ffffffe'), 1641, 'ff9785f6-ffff-1fff-%c669-00007ffffffe', '103072857659.999999', ], [ new DateTime('1582-10-15 00:00:00'), new Hexadecimal('00007ffffffe'), 1641, '00000000-0000-1000-%c669-00007ffffffe', '-12219292800.000000', ], [ new DateTimeImmutable('@103072857660.684697'), new Hexadecimal('0'), 0, 'fffffffa-ffff-1fff-%c000-000000000000', '103072857660.684697', ], [ new DateTimeImmutable('5236-03-31 21:21:00.684697'), null, null, 'fffffffa-ffff-1fff-%s', '103072857660.684697', ], ]; } public function testFactoryReturnsDefaultNameGenerator(): void { $factory = new UuidFactory(); $this->assertInstanceOf(DefaultNameGenerator::class, $factory->getNameGenerator()); } public function testFactoryReturnsSetNameGenerator(): void { $factory = new UuidFactory(); $this->assertInstanceOf(DefaultNameGenerator::class, $factory->getNameGenerator()); $nameGenerator = Mockery::mock(NameGeneratorInterface::class); $factory->setNameGenerator($nameGenerator); $this->assertSame($nameGenerator, $factory->getNameGenerator()); } } ================================================ FILE: tests/UuidTest.php ================================================ assertSame( 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66', Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66') ->toString() ); } public function testFromHexadecimal(): void { $hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A025041000001'); $uuid = Uuid::fromHexadecimal($hex); $this->assertInstanceOf(Uuid::class, $uuid); $this->assertEquals('1ea78deb-37ce-625e-8f1a-025041000001', $uuid->toString()); } public function testFromHexadecimalShort(): void { $hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A0250410000'); $this->expectException(InvalidUuidStringException::class); $this->expectExceptionMessage('Invalid UUID string:'); Uuid::fromHexadecimal($hex); } public function testFromHexadecimalThrowsWhenMethodDoesNotExist(): void { $factory = Mockery::mock(UuidFactoryInterface::class); Uuid::setFactory($factory); $hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A025041000001'); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('The method fromHexadecimal() does not exist on the provided factory'); Uuid::fromHexadecimal($hex); } /** * Tests that UUID and GUID's have the same textual representation but not * the same binary representation. */ public function testFromGuidString(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); Uuid::setFactory(new UuidFactory(new FeatureSet(true))); $guid = Guid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); // UUID's and GUID's share the same textual representation. $this->assertSame($uuid->toString(), $guid->toString()); // But not the same binary representation. $this->assertNotSame($uuid->getBytes(), $guid->getBytes()); } public function testFromStringWithCurlyBraces(): void { $uuid = Uuid::fromString('{ff6f8cb0-c57d-11e1-9b21-0800200c9a66}'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); } public function testFromStringWithInvalidUuidString(): void { $this->expectException(InvalidUuidStringException::class); $this->expectExceptionMessage('Invalid UUID string:'); Uuid::fromString('ff6f8cb0-c57d-11e1-9b21'); } public function testFromStringWithLeadingNewLine(): void { $this->expectException(InvalidUuidStringException::class); $this->expectExceptionMessage('Invalid UUID string:'); Uuid::fromString("\nd0d5f586-21d1-470c-8088-55c8857728dc"); } public function testFromStringWithTrailingNewLine(): void { $this->expectException(InvalidUuidStringException::class); $this->expectExceptionMessage('Invalid UUID string:'); Uuid::fromString("d0d5f586-21d1-470c-8088-55c8857728dc\n"); } public function testFromStringWithUrn(): void { $uuid = Uuid::fromString('urn:uuid:ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); } public function testFromStringWithEmptyString(): void { $this->expectException(InvalidUuidStringException::class); $this->expectExceptionMessage('Invalid UUID string: '); Uuid::fromString(''); } public function testFromStringUppercase(): void { $uuid = Uuid::fromString('FF6F8CB0-C57D-11E1-9B21-0800200C9A66'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); } public function testFromStringLazyUuidFromUppercase(): void { $this->assertInstanceOf(LazyUuidFromString::class, Uuid::fromString('FF6F8CB0-C57D-11E1-9B21-0800200C9A66')); } public function testFromStringWithNilUuid(): void { $uuid = Uuid::fromString(Uuid::NIL); /** @var Fields $fields */ $fields = $uuid->getFields(); $this->assertSame('00000000-0000-0000-0000-000000000000', $uuid->toString()); $this->assertTrue($fields->isNil()); $this->assertFalse($fields->isMax()); } public function testFromStringWithMaxUuid(): void { $uuid = Uuid::fromString(Uuid::MAX); /** @var Fields $fields */ $fields = $uuid->getFields(); $this->assertSame('ffffffff-ffff-ffff-ffff-ffffffffffff', $uuid->toString()); $this->assertFalse($fields->isNil()); $this->assertTrue($fields->isMax()); } public function testGetBytes(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame(16, strlen($uuid->getBytes())); $this->assertSame('/2+MsMV9EeGbIQgAIAyaZg==', base64_encode($uuid->getBytes())); } public function testGetClockSeqHiAndReserved(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('155', $uuid->getClockSeqHiAndReserved()); } public function testGetClockSeqHiAndReservedHex(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('9b', $uuid->getClockSeqHiAndReservedHex()); } public function testGetClockSeqLow(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('33', $uuid->getClockSeqLow()); } public function testGetClockSeqLowHex(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('21', $uuid->getClockSeqLowHex()); } public function testGetClockSequence(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('6945', $uuid->getClockSequence()); } public function testGetClockSequenceHex(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('1b21', $uuid->getClockSequenceHex()); } public function testGetDateTime(): void { // Check a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u')); // Check an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); $this->assertSame('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('-12219146756.000000', $uuid->getDateTime()->format('U.u')); // Check a future date $uuid = Uuid::fromString('ff9785f6-ffff-1fff-9669-00007ffffffe'); $this->assertSame('5236-03-31T21:20:59+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('103072857659.999999', $uuid->getDateTime()->format('U.u')); // Check the last possible time supported by v1 UUIDs // See inline comments in // {@see \Ramsey\Uuid\Test\Converter\Time\GenericTimeConverterTest::provideCalculateTime()} $uuid = Uuid::fromString('fffffffa-ffff-1fff-8b1e-acde48001122'); $this->assertSame('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('103072857660.684697', $uuid->getDateTime()->format('U.u')); // Check the oldest date $uuid = Uuid::fromString('00000000-0000-1000-9669-00007ffffffe'); $this->assertSame('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('-12219292800.000000', $uuid->getDateTime()->format('U.u')); // The Unix epoch $uuid = Uuid::fromString('13814000-1dd2-11b2-9669-00007ffffffe'); $this->assertSame('1970-01-01T00:00:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('0.000000', $uuid->getDateTime()->format('U.u')); } public function testGetDateTimeForUuidV6(): void { // Check a recent date $uuid = Uuid::fromString('1e1c57df-f6f8-6cb0-9b21-0800200c9a66'); $this->assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u')); // Check an old date $uuid = Uuid::fromString('00001540-901e-6600-9b21-0800200c9a66'); $this->assertSame('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('-12219146756.000000', $uuid->getDateTime()->format('U.u')); // Check a future date $uuid = Uuid::fromString('ffffffff-f978-65f6-9669-00007ffffffe'); $this->assertSame('5236-03-31T21:20:59+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('103072857659.999999', $uuid->getDateTime()->format('U.u')); // Check the last possible time supported by UUIDs // See inline comments in // {@see \Ramsey\Uuid\Test\Converter\Time\GenericTimeConverterTest::provideCalculateTime()} $uuid = Uuid::fromString('ffffffff-ffff-6ffa-8b1e-acde48001122'); $this->assertSame('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('103072857660.684697', $uuid->getDateTime()->format('U.u')); // Check the oldest date $uuid = Uuid::fromString('00000000-0000-6000-9669-00007ffffffe'); $this->assertSame('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('-12219292800.000000', $uuid->getDateTime()->format('U.u')); // The Unix epoch $uuid = Uuid::fromString('1b21dd21-3814-6000-9669-00007ffffffe'); $this->assertSame('1970-01-01T00:00:00+00:00', $uuid->getDateTime()->format('c')); $this->assertSame('0.000000', $uuid->getDateTime()->format('U.u')); } public function testGetDateTimeFromNonVersion1Uuid(): void { // Using a version 4 UUID to test $uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de'); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('Not a time-based UUID'); $uuid->getDateTime(); } public function testGetFields(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertInstanceOf(FieldsInterface::class, $uuid->getFields()); } public function testGetFieldsHex(): void { $fields = [ 'time_low' => 'ff6f8cb0', 'time_mid' => 'c57d', 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', 'node' => '0800200c9a66', ]; $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame($fields, $uuid->getFieldsHex()); } public function testGetLeastSignificantBits(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('11178224546741000806', $uuid->getLeastSignificantBits()); } public function testGetLeastSignificantBitsHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('9b210800200c9a66', $uuid->getLeastSignificantBitsHex()); } public function testGetMostSignificantBits(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('18406084892941947361', $uuid->getMostSignificantBits()); } public function testGetMostSignificantBitsHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0c57d11e1', $uuid->getMostSignificantBitsHex()); } public function testGetNode(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('8796630719078', $uuid->getNode()); } public function testGetNodeHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('0800200c9a66', $uuid->getNodeHex()); } public function testGetTimeHiAndVersion(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('4577', $uuid->getTimeHiAndVersion()); } public function testGetTimeHiAndVersionHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('11e1', $uuid->getTimeHiAndVersionHex()); } public function testGetTimeLow(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('4285500592', $uuid->getTimeLow()); } public function testGetTimeLowHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0', $uuid->getTimeLowHex()); } public function testGetTimeMid(): void { /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('50557', $uuid->getTimeMid()); } public function testGetTimeMidHex(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('c57d', $uuid->getTimeMidHex()); } public function testGetTimestamp(): void { // Check for a recent date /** @var Uuid $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('135606608744910000', $uuid->getTimestamp()); // Check for an old date /** @var Uuid $uuid */ $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); $this->assertSame('1460440000000', $uuid->getTimestamp()); } public function testGetTimestampHex(): void { // Check for a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('1e1c57dff6f8cb0', $uuid->getTimestampHex()); // Check for an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); $this->assertSame('00001540901e600', $uuid->getTimestampHex()); } public function testGetTimestampFromNonVersion1Uuid(): void { // Using a version 4 UUID to test /** @var Uuid $uuid */ $uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de'); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('Not a time-based UUID'); $uuid->getTimestamp(); } public function testGetTimestampHexFromNonVersion1Uuid(): void { // Using a version 4 UUID to test $uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de'); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('Not a time-based UUID'); $uuid->getTimestampHex(); } public function testGetUrn(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('urn:uuid:ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->getUrn()); } /** * @param non-empty-string $uuid * * @dataProvider provideVariousVariantUuids */ public function testGetVariantForVariousVariantUuids(string $uuid, int $variant): void { $uuid = Uuid::fromString($uuid); $this->assertSame($variant, $uuid->getVariant()); } /** * @return array */ public function provideVariousVariantUuids(): array { return [ ['ff6f8cb0-c57d-11e1-0b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-1b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-2b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-3b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-4b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-5b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-6b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-7b21-0800200c9a66', Uuid::RESERVED_NCS], ['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', Uuid::RFC_4122], ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', Uuid::RFC_4122], ['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', Uuid::RFC_4122], ['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', Uuid::RFC_4122], ['ff6f8cb0-c57d-11e1-cb21-0800200c9a66', Uuid::RESERVED_MICROSOFT], ['ff6f8cb0-c57d-11e1-db21-0800200c9a66', Uuid::RESERVED_MICROSOFT], ['ff6f8cb0-c57d-11e1-eb21-0800200c9a66', Uuid::RESERVED_FUTURE], ['ff6f8cb0-c57d-11e1-fb21-0800200c9a66', Uuid::RESERVED_FUTURE], ]; } public function testGetVersionForVersion1(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame(1, $uuid->getVersion()); } public function testGetVersionForVersion2(): void { $uuid = Uuid::fromString('6fa459ea-ee8a-2ca4-894e-db77e160355e'); $this->assertSame(2, $uuid->getVersion()); } public function testGetVersionForVersion3(): void { $uuid = Uuid::fromString('6fa459ea-ee8a-3ca4-894e-db77e160355e'); $this->assertSame(3, $uuid->getVersion()); } public function testGetVersionForVersion4(): void { $uuid = Uuid::fromString('6fabf0bc-603a-42f2-925b-d9f779bd0032'); $this->assertSame(4, $uuid->getVersion()); } public function testGetVersionForVersion5(): void { $uuid = Uuid::fromString('886313e1-3b8a-5372-9b90-0c9aee199e5d'); $this->assertSame(5, $uuid->getVersion()); } public function testToString(): void { // Check with a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString()); $this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', (string) $uuid); $this->assertSame( 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66', (static fn (Stringable $uuid) => (string) $uuid)($uuid) ); // Check with an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); $this->assertSame('0901e600-0154-1000-9b21-0800200c9a66', $uuid->toString()); $this->assertSame('0901e600-0154-1000-9b21-0800200c9a66', (string) $uuid); $this->assertSame( '0901e600-0154-1000-9b21-0800200c9a66', (static fn (Stringable $uuid) => (string) $uuid)($uuid) ); } public function testUuid1(): void { $uuid = Uuid::uuid1(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); } public function testUuid1WithNodeAndClockSequence(): void { /** @var Uuid $uuid */ $uuid = Uuid::uuid1('0800200c9a66', 0x1669); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); $this->assertSame('5737', $uuid->getClockSequence()); $this->assertSame('8796630719078', $uuid->getNode()); $this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19)); } public function testUuid1WithHexadecimalObjectNodeAndClockSequence(): void { /** @var Uuid $uuid */ $uuid = Uuid::uuid1(new Hexadecimal('0800200c9a66'), 0x1669); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); $this->assertSame('5737', $uuid->getClockSequence()); $this->assertSame('8796630719078', $uuid->getNode()); $this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19)); } public function testUuid1WithHexadecimalNode(): void { /** @var Uuid $uuid */ $uuid = Uuid::uuid1('7160355e'); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); $this->assertSame('00007160355e', $uuid->getNodeHex()); $this->assertSame('1902130526', $uuid->getNode()); } public function testUuid1WithHexadecimalObjectNode(): void { /** @var Uuid $uuid */ $uuid = Uuid::uuid1(new Hexadecimal('7160355e')); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); $this->assertSame('00007160355e', $uuid->getNodeHex()); $this->assertSame('1902130526', $uuid->getNode()); } public function testUuid1WithMixedCaseHexadecimalNode(): void { /** @var Uuid $uuid */ $uuid = Uuid::uuid1('71B0aD5e'); $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); $this->assertSame('000071b0ad5e', $uuid->getNodeHex()); $this->assertSame('1907404126', $uuid->getNode()); } public function testUuid1WithOutOfBoundsNode(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid node value'); Uuid::uuid1('9223372036854775808'); } public function testUuid1WithNonHexadecimalNode(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid node value'); Uuid::uuid1('db77e160355g'); } public function testUuid1WithNon48bitNumber(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid node value'); Uuid::uuid1('db77e160355ef'); } public function testUuid1WithRandomNode(): void { Uuid::setFactory(new UuidFactory(new FeatureSet(false, false, false, true))); $uuid = Uuid::uuid1(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); } public function testUuid1WithUserGeneratedRandomNode(): void { $uuid = Uuid::uuid1(new Hexadecimal((string) (new RandomNodeProvider())->getNode())); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(1, $uuid->getVersion()); } public function testUuid6(): void { $uuid = Uuid::uuid6(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); } public function testUuid6WithNodeAndClockSequence(): void { $uuid = Uuid::uuid6(new Hexadecimal('0800200c9a66'), 0x1669); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); $this->assertSame('1669', $uuid->getClockSequenceHex()); $this->assertSame('0800200c9a66', $uuid->getNodeHex()); $this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19)); } public function testUuid6WithHexadecimalNode(): void { $uuid = Uuid::uuid6(new Hexadecimal('7160355e')); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); $this->assertSame('00007160355e', $uuid->getNodeHex()); } public function testUuid6WithMixedCaseHexadecimalNode(): void { $uuid = Uuid::uuid6(new Hexadecimal('71B0aD5e')); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); $this->assertSame('000071b0ad5e', $uuid->getNodeHex()); } public function testUuid6WithOutOfBoundsNode(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid node value'); Uuid::uuid6(new Hexadecimal('9223372036854775808')); } public function testUuid6WithNon48bitNumber(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid node value'); Uuid::uuid6(new Hexadecimal('db77e160355ef')); } public function testUuid6WithRandomNode(): void { Uuid::setFactory(new UuidFactory(new FeatureSet(false, false, false, true))); $uuid = Uuid::uuid6(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); } public function testUuid6WithUserGeneratedRandomNode(): void { $uuid = Uuid::uuid6(new Hexadecimal((string) (new RandomNodeProvider())->getNode())); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(6, $uuid->getVersion()); } public function testUuid7(): void { $uuid = Uuid::uuid7(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(7, $uuid->getVersion()); } public function testUuid7ThrowsExceptionForUnsupportedFactory(): void { /** @var UuidFactoryInterface&MockInterface $factory */ $factory = Mockery::mock(UuidFactoryInterface::class); Uuid::setFactory($factory); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('The provided factory does not support the uuid7() method'); Uuid::uuid7(); } public function testUuid7WithDateTime(): void { $dateTime = new DateTimeImmutable('@281474976710.655'); $uuid = Uuid::uuid7($dateTime); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(7, $uuid->getVersion()); $this->assertSame( '10889-08-02T05:31:50.655+00:00', $uuid->getDateTime()->format(DateTimeInterface::RFC3339_EXTENDED), ); } public function testUuid7SettingTheClockBackwards(): void { $dates = [ new DateTimeImmutable('now'), new DateTimeImmutable('last year'), new DateTimeImmutable('1979-01-01 00:00:00.000000'), ]; foreach ($dates as $dateTime) { $previous = Uuid::uuid7($dateTime); for ($i = 0; $i < 25; $i++) { $uuid = Uuid::uuid7($dateTime); $this->assertGreaterThan(0, $uuid->compareTo($previous)); $this->assertSame($dateTime->format('Y-m-d H:i'), $uuid->getDateTime()->format('Y-m-d H:i')); $previous = $uuid; } } } public function testUuid7WithMinimumDateTime(): void { $dateTime = new DateTimeImmutable('1979-01-01 00:00:00.000000'); $uuid = Uuid::uuid7($dateTime); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(7, $uuid->getVersion()); $this->assertSame( '1979-01-01T00:00:00.000+00:00', $uuid->getDateTime()->format(DateTimeInterface::RFC3339_EXTENDED), ); } public function testUuid7EachUuidIsMonotonicallyIncreasing(): void { $previous = Uuid::uuid7(); for ($i = 0; $i < 25; $i++) { $uuid = Uuid::uuid7(); $now = gmdate('Y-m-d H:i'); $this->assertGreaterThan(0, $uuid->compareTo($previous)); $this->assertSame($now, $uuid->getDateTime()->format('Y-m-d H:i')); $previous = $uuid; } } public function testUuid7EachUuidFromSameDateTimeIsMonotonicallyIncreasing(): void { $dateTime = new DateTimeImmutable(); $previous = Uuid::uuid7($dateTime); for ($i = 0; $i < 25; $i++) { $uuid = Uuid::uuid7($dateTime); $this->assertGreaterThan(0, $uuid->compareTo($previous)); $this->assertSame($dateTime->format('Y-m-d H:i'), $uuid->getDateTime()->format('Y-m-d H:i')); $previous = $uuid; } } public function testUuid8(): void { $uuid = Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(8, $uuid->getVersion()); } public function testUuid8ThrowsExceptionForUnsupportedFactory(): void { /** @var UuidFactoryInterface&MockInterface $factory */ $factory = Mockery::mock(UuidFactoryInterface::class); Uuid::setFactory($factory); $this->expectException(UnsupportedOperationException::class); $this->expectExceptionMessage('The provided factory does not support the uuid8() method'); /** @phpstan-ignore staticMethod.resultUnused */ Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"); } /** * Tests known version-3 UUIDs * * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py * * @param non-empty-string $uuid * @param non-empty-string $ns * @param non-empty-string $name * * @dataProvider provideUuid3WithKnownUuids */ public function testUuid3WithKnownUuids(string $uuid, string $ns, string $name): void { $uobj1 = Uuid::uuid3($ns, $name); $uobj2 = Uuid::uuid3(Uuid::fromString($ns), $name); $this->assertSame(2, $uobj1->getVariant()); $this->assertSame(3, $uobj1->getVersion()); $this->assertSame(Uuid::fromString($uuid)->toString(), $uobj1->toString()); $this->assertTrue($uobj1->equals($uobj2)); } /** * @return array */ public function provideUuid3WithKnownUuids(): array { return [ [ 'uuid' => '6fa459ea-ee8a-3ca4-894e-db77e160355e', 'ns' => Uuid::NAMESPACE_DNS, 'name' => 'python.org', ], [ 'uuid' => '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d', 'ns' => Uuid::NAMESPACE_URL, 'name' => 'http://python.org/', ], [ 'uuid' => 'dd1a1cef-13d5-368a-ad82-eca71acd4cd1', 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1', ], [ 'uuid' => '658d3002-db6b-3040-a1d1-8ddd7d189a4d', 'ns' => Uuid::NAMESPACE_X500, 'name' => 'c=ca', ], ]; } public function testUuid4(): void { $uuid = Uuid::uuid4(); $this->assertSame(2, $uuid->getVariant()); $this->assertSame(4, $uuid->getVersion()); } /** * Tests that generated UUID's using timestamp last COMB are sequential */ public function testUuid4TimestampLastComb(): void { $mock = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); $mock->expects($this->any()) ->method('generate') ->willReturnCallback(function (int $length) { // Makes first fields of UUIDs equal return hex2bin(str_pad('', $length * 2, '0')); }); $factory = new UuidFactory(); $generator = new CombGenerator($mock, $factory->getNumberConverter()); $codec = new TimestampLastCombCodec($factory->getUuidBuilder()); $factory->setRandomGenerator($generator); $factory->setCodec($codec); $previous = $factory->uuid4(); for ($i = 0; $i < 1000; $i++) { usleep(100); $uuid = $factory->uuid4(); $this->assertGreaterThan($previous->toString(), $uuid->toString()); $previous = $uuid; } } /** * Tests that generated UUID's using timestamp first COMB are sequential */ public function testUuid4TimestampFirstComb(): void { $mock = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); $mock->expects($this->any()) ->method('generate') ->willReturnCallback(function (int $length) { // Makes first fields of UUIDs equal return hex2bin(str_pad('', $length * 2, '0')); }); $factory = new UuidFactory(); $generator = new CombGenerator($mock, $factory->getNumberConverter()); $codec = new TimestampFirstCombCodec($factory->getUuidBuilder()); $factory->setRandomGenerator($generator); $factory->setCodec($codec); $previous = $factory->uuid4(); for ($i = 0; $i < 1000; $i++) { usleep(100); $uuid = $factory->uuid4(); $this->assertGreaterThan($previous->toString(), $uuid->toString()); $previous = $uuid; } } /** * Test that COMB UUID's have a version 4 flag */ public function testUuid4CombVersion(): void { $factory = new UuidFactory(); $generator = new CombGenerator( (new RandomGeneratorFactory())->getGenerator(), $factory->getNumberConverter() ); $factory->setRandomGenerator($generator); $uuid = $factory->uuid4(); $this->assertSame(4, $uuid->getVersion()); } /** * Tests known version-5 UUIDs * * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py * * @param non-empty-string $uuid * @param non-empty-string $ns * @param non-empty-string $name * * @dataProvider provideUuid5WithKnownUuids */ public function testUuid5WithKnownUuids(string $uuid, string $ns, string $name): void { $uobj1 = Uuid::uuid5($ns, $name); $uobj2 = Uuid::uuid5(Uuid::fromString($ns), $name); $this->assertSame(2, $uobj1->getVariant()); $this->assertSame(5, $uobj1->getVersion()); $this->assertSame(Uuid::fromString($uuid)->toString(), $uobj1->toString()); $this->assertTrue($uobj1->equals($uobj2)); } /** * @return array */ public function provideUuid5WithKnownUuids(): array { return [ [ 'uuid' => '886313e1-3b8a-5372-9b90-0c9aee199e5d', 'ns' => Uuid::NAMESPACE_DNS, 'name' => 'python.org', ], [ 'uuid' => '4c565f0d-3f5a-5890-b41b-20cf47701c5e', 'ns' => Uuid::NAMESPACE_URL, 'name' => 'http://python.org/', ], [ 'uuid' => '1447fa61-5277-5fef-a9b3-fbc6e44f4af3', 'ns' => Uuid::NAMESPACE_OID, 'name' => '1.3.6.1', ], [ 'uuid' => 'cc957dd1-a972-5349-98cd-874190002798', 'ns' => Uuid::NAMESPACE_X500, 'name' => 'c=ca', ], ]; } public function testCompareTo(): void { // $uuid1 and $uuid2 are identical $uuid1 = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $uuid2 = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); // The next three UUIDs are used for comparing msb and lsb in // the compareTo() method // msb are less than $uuid4, lsb are greater than $uuid5 $uuid3 = Uuid::fromString('44cca71e-d13d-11e1-a959-c8bcc8a476f4'); // msb are greater than $uuid3, lsb are equal to those in $uuid3 $uuid4 = Uuid::fromString('44cca71e-d13d-11e2-a959-c8bcc8a476f4'); // msb are equal to those in $uuid3, lsb are less than in $uuid3 $uuid5 = Uuid::fromString('44cca71e-d13d-11e1-a959-c8bcc8a476f3'); $this->assertSame(0, $uuid1->compareTo($uuid2)); $this->assertSame(0, $uuid2->compareTo($uuid1)); $this->assertSame(-1, $uuid3->compareTo($uuid4)); $this->assertSame(1, $uuid4->compareTo($uuid3)); $this->assertSame(-1, $uuid5->compareTo($uuid3)); $this->assertSame(1, $uuid3->compareTo($uuid5)); } public function testCompareToReturnsZeroWhenDifferentCases(): void { $uuidString = 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66'; // $uuid1 and $uuid2 are identical $uuid1 = Uuid::fromString($uuidString); $uuid2 = Uuid::fromString(strtoupper($uuidString)); $this->assertSame(0, $uuid1->compareTo($uuid2)); $this->assertSame(0, $uuid2->compareTo($uuid1)); } public function testEqualsReturnsTrueWhenDifferentCases(): void { $uuidString = 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66'; // $uuid1 and $uuid2 are identical $uuid1 = Uuid::fromString($uuidString); $uuid2 = Uuid::fromString(strtoupper($uuidString)); $this->assertTrue($uuid1->equals($uuid2)); $this->assertTrue($uuid2->equals($uuid1)); } public function testEquals(): void { $uuid1 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'python.org'); $uuid2 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'python.org'); $uuid3 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net'); $this->assertTrue($uuid1->equals($uuid2)); $this->assertFalse($uuid1->equals($uuid3)); $this->assertFalse($uuid1->equals(new stdClass())); } public function testCalculateUuidTime(): void { $timeOfDay = new FixedTimeProvider(new Time(1348845514, 277885)); $featureSet = new FeatureSet(); $featureSet->setTimeProvider($timeOfDay); // For usec = 277885 Uuid::setFactory(new UuidFactory($featureSet)); $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); $this->assertSame('c4dbe7e2-097f-11e2-9669-00007ffffffe', (string) $uuidA); $this->assertSame('c4dbe7e2', $uuidA->getTimeLowHex()); $this->assertSame('097f', $uuidA->getTimeMidHex()); $this->assertSame('11e2', $uuidA->getTimeHiAndVersionHex()); // For usec = 0 $timeOfDay->setUsec(0); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); $this->assertSame('c4b18100-097f-11e2-9669-00007ffffffe', (string) $uuidB); $this->assertSame('c4b18100', $uuidB->getTimeLowHex()); $this->assertSame('097f', $uuidB->getTimeMidHex()); $this->assertSame('11e2', $uuidB->getTimeHiAndVersionHex()); // For usec = 999999 $timeOfDay->setUsec(999999); $uuidC = Uuid::uuid1(0x00007ffffffe, 0x1669); $this->assertSame('c54a1776-097f-11e2-9669-00007ffffffe', (string) $uuidC); $this->assertSame('c54a1776', $uuidC->getTimeLowHex()); $this->assertSame('097f', $uuidC->getTimeMidHex()); $this->assertSame('11e2', $uuidC->getTimeHiAndVersionHex()); } public function testCalculateUuidTimeUpperLowerBounds(): void { // 5235-03-31T21:20:59+00:00 $timeOfDay = new FixedTimeProvider(new Time('103072857659', '999999')); $featureSet = new FeatureSet(); $featureSet->setTimeProvider($timeOfDay); Uuid::setFactory(new UuidFactory($featureSet)); $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); $this->assertSame('ff9785f6-ffff-1fff-9669-00007ffffffe', (string) $uuidA); $this->assertSame('ff9785f6', $uuidA->getTimeLowHex()); $this->assertSame('ffff', $uuidA->getTimeMidHex()); $this->assertSame('1fff', $uuidA->getTimeHiAndVersionHex()); // 1582-10-15T00:00:00+00:00 $timeOfDay = new FixedTimeProvider(new Time('-12219292800', '0')); $featureSet->setTimeProvider($timeOfDay); Uuid::setFactory(new UuidFactory($featureSet)); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); $this->assertSame('00000000-0000-1000-9669-00007ffffffe', (string) $uuidB); $this->assertSame('00000000', $uuidB->getTimeLowHex()); $this->assertSame('0000', $uuidB->getTimeMidHex()); $this->assertSame('1000', $uuidB->getTimeHiAndVersionHex()); } /** * Iterates over a 3600-second period and tests to ensure that, for each * second in the period, the 32-bit and 64-bit versions of the UUID match */ public function test32BitMatch64BitForOneHourPeriod(): void { $currentTime = strtotime('2012-12-11T00:00:00+00:00'); $endTime = $currentTime + 3600; $timeOfDay = new FixedTimeProvider(new Time($currentTime, 0)); $smallIntFeatureSet = new FeatureSet(false, true); $smallIntFeatureSet->setTimeProvider($timeOfDay); $smallIntFactory = new UuidFactory($smallIntFeatureSet); $featureSet = new FeatureSet(); $featureSet->setTimeProvider($timeOfDay); $factory = new UuidFactory($featureSet); while ($currentTime <= $endTime) { foreach ([0, 50000, 250000, 500000, 750000, 999999] as $usec) { $timeOfDay->setSec($currentTime); $timeOfDay->setUsec($usec); $uuid32 = $smallIntFactory->uuid1(0x00007ffffffe, 0x1669); $uuid64 = $factory->uuid1(0x00007ffffffe, 0x1669); $this->assertTrue( $uuid32->equals($uuid64), 'Breaks at ' . gmdate('r', $currentTime) . "; 32-bit: {$uuid32->toString()}, 64-bit: {$uuid64->toString()}" ); // Assert that the time matches $usecAdd = BigDecimal::of($usec)->dividedBy('1000000', 14, RoundingMode::HALF_UP); $testTime = BigDecimal::of($currentTime)->plus($usecAdd)->toScale(0, RoundingMode::DOWN); $this->assertSame((string) $testTime, (string) $uuid64->getDateTime()->getTimestamp()); $this->assertSame((string) $testTime, (string) $uuid32->getDateTime()->getTimestamp()); } $currentTime++; } } /** * This method should respond to the result of the factory */ public function testIsValid(): void { $argument = uniqid('passed argument '); /** @var MockObject & ValidatorInterface $validator */ $validator = $this->getMockBuilder(ValidatorInterface::class)->getMock(); $validator->expects($this->once())->method('validate')->with($argument)->willReturn(true); /** @var UuidFactory $factory */ $factory = Uuid::getFactory(); $factory->setValidator($validator); $this->assertTrue(Uuid::isValid($argument)); // reset the static validator $factory->setValidator(new GenericValidator()); } public function testUsingNilAsValidUuid(): void { self::assertSame( '0cb17687-6ec7-324b-833a-f1d101a7edb7', Uuid::uuid3(Uuid::NIL, 'randomtext') ->toString() ); self::assertSame( '3b24c15b-1273-5628-ade4-fc67c6ede500', Uuid::uuid5(Uuid::NIL, 'randomtext') ->toString() ); } public function testFromBytes(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $bytes = $uuid->getBytes(); $fromBytesUuid = Uuid::fromBytes($bytes); $this->assertTrue($uuid->equals($fromBytesUuid)); } public function testGuidBytesMatchesUuidWithSameString(): void { $uuidFactory = new UuidFactory(new FeatureSet(false)); $guidFactory = new UuidFactory(new FeatureSet(true)); $uuid = $uuidFactory->fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $bytes = $uuid->getBytes(); // Swap the order of the bytes for a GUID. $guidBytes = $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0]; $guidBytes .= $bytes[5] . $bytes[4]; $guidBytes .= $bytes[7] . $bytes[6]; $guidBytes .= substr($bytes, 8); $guid = $guidFactory->fromBytes($guidBytes); $this->assertSame($uuid->toString(), $guid->toString()); $this->assertTrue($uuid->equals($guid)); } public function testGuidBytesProducesSameGuidString(): void { $guidFactory = new UuidFactory(new FeatureSet(true)); $guid = $guidFactory->fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $bytes = $guid->getBytes(); $parsedGuid = $guidFactory->fromBytes($bytes); $this->assertSame($guid->toString(), $parsedGuid->toString()); $this->assertTrue($guid->equals($parsedGuid)); } public function testFromBytesArgumentTooShort(): void { $this->expectException(InvalidArgumentException::class); Uuid::fromBytes('thisisveryshort'); } public function testFromBytesArgumentTooLong(): void { $this->expectException(InvalidArgumentException::class); Uuid::fromBytes('thisisabittoolong'); } public function testFromInteger(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $integer = $uuid->getInteger()->toString(); $fromIntegerUuid = Uuid::fromInteger($integer); $this->assertTrue($uuid->equals($fromIntegerUuid)); } public function testFromDateTime(): void { /** @var UuidV1 $uuid */ $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-8b21-0800200c9a66'); $dateTime = $uuid->getDateTime(); $fromDateTimeUuid = Uuid::fromDateTime($dateTime, new Hexadecimal('0800200c9a66'), 2849); $this->assertTrue($uuid->equals($fromDateTimeUuid)); } /** * This test ensures that Ramsey\Uuid passes the same test cases * as the Python UUID library. * * @param non-empty-string $string * @param non-empty-string $curly * @param non-empty-string $hex * @param non-empty-string $bytes * @param non-empty-string $int * @param string[] $fields * @param non-empty-string $urn * @param non-empty-string $time * @param non-empty-string $clockSeq * * @dataProvider providePythonTests */ public function testUuidPassesPythonTests( string $string, string $curly, string $hex, string $bytes, string $int, array $fields, string $urn, string $time, string $clockSeq, int $variant, ?int $version ): void { $uuids = [ Uuid::fromString($string), Uuid::fromString($curly), Uuid::fromString($hex), Uuid::fromBytes(base64_decode($bytes)), Uuid::fromString($urn), Uuid::fromInteger($int), ]; /** @var UuidInterface $uuid */ foreach ($uuids as $uuid) { $this->assertSame($string, $uuid->toString()); $this->assertSame($hex, $uuid->getHex()->toString()); $this->assertSame(base64_decode($bytes), $uuid->getBytes()); $this->assertSame($int, $uuid->getInteger()->toString()); $this->assertSame($fields, $uuid->getFieldsHex()); $this->assertSame($fields['time_low'], $uuid->getTimeLowHex()); $this->assertSame($fields['time_mid'], $uuid->getTimeMidHex()); $this->assertSame($fields['time_hi_and_version'], $uuid->getTimeHiAndVersionHex()); $this->assertSame($fields['clock_seq_hi_and_reserved'], $uuid->getClockSeqHiAndReservedHex()); $this->assertSame($fields['clock_seq_low'], $uuid->getClockSeqLowHex()); $this->assertSame($fields['node'], $uuid->getNodeHex()); $this->assertSame($urn, $uuid->getUrn()); if ($uuid->getVersion() === 1) { $this->assertSame($time, $uuid->getTimestampHex()); } $this->assertSame($clockSeq, $uuid->getClockSequenceHex()); $this->assertSame($variant, $uuid->getVariant()); $this->assertSame($version, $uuid->getVersion()); } } /** * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py * * @return array, * urn: non-empty-string, * time: non-empty-string, * clock_seq: non-empty-string, * variant: int, * version: int | null, * }> */ public function providePythonTests(): array { // This array is taken directly from the Python tests, more or less. return [ [ 'string' => '00000000-0000-0000-0000-000000000000', 'curly' => '{00000000-0000-0000-0000-000000000000}', 'hex' => '00000000000000000000000000000000', 'bytes' => 'AAAAAAAAAAAAAAAAAAAAAA==', 'int' => '0', 'fields' => [ 'time_low' => '00000000', 'time_mid' => '0000', 'time_hi_and_version' => '0000', 'clock_seq_hi_and_reserved' => '00', 'clock_seq_low' => '00', 'node' => '000000000000', ], 'urn' => 'urn:uuid:00000000-0000-0000-0000-000000000000', 'time' => '0', 'clock_seq' => '0000', 'variant' => Uuid::RESERVED_NCS, 'version' => null, ], [ 'string' => '00010203-0405-0607-0809-0a0b0c0d0e0f', 'curly' => '{00010203-0405-0607-0809-0a0b0c0d0e0f}', 'hex' => '000102030405060708090a0b0c0d0e0f', 'bytes' => 'AAECAwQFBgcICQoLDA0ODw==', 'int' => '5233100606242806050955395731361295', 'fields' => [ 'time_low' => '00010203', 'time_mid' => '0405', 'time_hi_and_version' => '0607', 'clock_seq_hi_and_reserved' => '08', 'clock_seq_low' => '09', 'node' => '0a0b0c0d0e0f', ], 'urn' => 'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f', 'time' => '607040500010203', 'clock_seq' => '0809', 'variant' => Uuid::RESERVED_NCS, 'version' => null, ], [ 'string' => '02d9e6d5-9467-382e-8f9b-9300a64ac3cd', 'curly' => '{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}', 'hex' => '02d9e6d59467382e8f9b9300a64ac3cd', 'bytes' => 'Atnm1ZRnOC6Pm5MApkrDzQ==', 'int' => '3789866285607910888100818383505376205', 'fields' => [ 'time_low' => '02d9e6d5', 'time_mid' => '9467', 'time_hi_and_version' => '382e', 'clock_seq_hi_and_reserved' => '8f', 'clock_seq_low' => '9b', 'node' => '9300a64ac3cd', ], 'urn' => 'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd', 'time' => '82e946702d9e6d5', 'clock_seq' => '0f9b', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_HASH_MD5, ], [ 'string' => '12345678-1234-5678-1234-567812345678', 'curly' => '{12345678-1234-5678-1234-567812345678}', 'hex' => '12345678123456781234567812345678', 'bytes' => 'EjRWeBI0VngSNFZ4EjRWeA==', 'int' => '24197857161011715162171839636988778104', 'fields' => [ 'time_low' => '12345678', 'time_mid' => '1234', 'time_hi_and_version' => '5678', 'clock_seq_hi_and_reserved' => '12', 'clock_seq_low' => '34', 'node' => '567812345678', ], 'urn' => 'urn:uuid:12345678-1234-5678-1234-567812345678', 'time' => '678123412345678', 'clock_seq' => '1234', 'variant' => Uuid::RESERVED_NCS, 'version' => null, ], [ 'string' => '6ba7b810-9dad-11d1-80b4-00c04fd430c8', 'curly' => '{6ba7b810-9dad-11d1-80b4-00c04fd430c8}', 'hex' => '6ba7b8109dad11d180b400c04fd430c8', 'bytes' => 'a6e4EJ2tEdGAtADAT9QwyA==', 'int' => '143098242404177361603877621312831893704', 'fields' => [ 'time_low' => '6ba7b810', 'time_mid' => '9dad', 'time_hi_and_version' => '11d1', 'clock_seq_hi_and_reserved' => '80', 'clock_seq_low' => 'b4', 'node' => '00c04fd430c8', ], 'urn' => 'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8', 'time' => '1d19dad6ba7b810', 'clock_seq' => '00b4', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => '6ba7b811-9dad-11d1-80b4-00c04fd430c8', 'curly' => '{6ba7b811-9dad-11d1-80b4-00c04fd430c8}', 'hex' => '6ba7b8119dad11d180b400c04fd430c8', 'bytes' => 'a6e4EZ2tEdGAtADAT9QwyA==', 'int' => '143098242483405524118141958906375844040', 'fields' => [ 'time_low' => '6ba7b811', 'time_mid' => '9dad', 'time_hi_and_version' => '11d1', 'clock_seq_hi_and_reserved' => '80', 'clock_seq_low' => 'b4', 'node' => '00c04fd430c8', ], 'urn' => 'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8', 'time' => '1d19dad6ba7b811', 'clock_seq' => '00b4', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => '6ba7b812-9dad-11d1-80b4-00c04fd430c8', 'curly' => '{6ba7b812-9dad-11d1-80b4-00c04fd430c8}', 'hex' => '6ba7b8129dad11d180b400c04fd430c8', 'bytes' => 'a6e4Ep2tEdGAtADAT9QwyA==', 'int' => '143098242562633686632406296499919794376', 'fields' => [ 'time_low' => '6ba7b812', 'time_mid' => '9dad', 'time_hi_and_version' => '11d1', 'clock_seq_hi_and_reserved' => '80', 'clock_seq_low' => 'b4', 'node' => '00c04fd430c8', ], 'urn' => 'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8', 'time' => '1d19dad6ba7b812', 'clock_seq' => '00b4', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => '6ba7b814-9dad-11d1-80b4-00c04fd430c8', 'curly' => '{6ba7b814-9dad-11d1-80b4-00c04fd430c8}', 'hex' => '6ba7b8149dad11d180b400c04fd430c8', 'bytes' => 'a6e4FJ2tEdGAtADAT9QwyA==', 'int' => '143098242721090011660934971687007695048', 'fields' => [ 'time_low' => '6ba7b814', 'time_mid' => '9dad', 'time_hi_and_version' => '11d1', 'clock_seq_hi_and_reserved' => '80', 'clock_seq_low' => 'b4', 'node' => '00c04fd430c8', ], 'urn' => 'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8', 'time' => '1d19dad6ba7b814', 'clock_seq' => '00b4', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => '7d444840-9dc0-11d1-b245-5ffdce74fad2', 'curly' => '{7d444840-9dc0-11d1-b245-5ffdce74fad2}', 'hex' => '7d4448409dc011d1b2455ffdce74fad2', 'bytes' => 'fURIQJ3AEdGyRV/9znT60g==', 'int' => '166508041112410060672666770310773930706', 'fields' => [ 'time_low' => '7d444840', 'time_mid' => '9dc0', 'time_hi_and_version' => '11d1', 'clock_seq_hi_and_reserved' => 'b2', 'clock_seq_low' => '45', 'node' => '5ffdce74fad2', ], 'urn' => 'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2', 'time' => '1d19dc07d444840', 'clock_seq' => '3245', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => 'e902893a-9d22-3c7e-a7b8-d6e313b71d9f', 'curly' => '{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}', 'hex' => 'e902893a9d223c7ea7b8d6e313b71d9f', 'bytes' => '6QKJOp0iPH6nuNbjE7cdnw==', 'int' => '309723290945582129846206211755626405279', 'fields' => [ 'time_low' => 'e902893a', 'time_mid' => '9d22', 'time_hi_and_version' => '3c7e', 'clock_seq_hi_and_reserved' => 'a7', 'clock_seq_low' => 'b8', 'node' => 'd6e313b71d9f', ], 'urn' => 'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f', 'time' => 'c7e9d22e902893a', 'clock_seq' => '27b8', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_HASH_MD5, ], [ 'string' => 'eb424026-6f54-4ef8-a4d0-bb658a1fc6cf', 'curly' => '{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}', 'hex' => 'eb4240266f544ef8a4d0bb658a1fc6cf', 'bytes' => '60JAJm9UTvik0Ltlih/Gzw==', 'int' => '312712571721458096795100956955942831823', 'fields' => [ 'time_low' => 'eb424026', 'time_mid' => '6f54', 'time_hi_and_version' => '4ef8', 'clock_seq_hi_and_reserved' => 'a4', 'clock_seq_low' => 'd0', 'node' => 'bb658a1fc6cf', ], 'urn' => 'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf', 'time' => 'ef86f54eb424026', 'clock_seq' => '24d0', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_RANDOM, ], [ 'string' => 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6', 'curly' => '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}', 'hex' => 'f81d4fae7dec11d0a76500a0c91e6bf6', 'bytes' => '+B1Prn3sEdCnZQCgyR5r9g==', 'int' => '329800735698586629295641978511506172918', 'fields' => [ 'time_low' => 'f81d4fae', 'time_mid' => '7dec', 'time_hi_and_version' => '11d0', 'clock_seq_hi_and_reserved' => 'a7', 'clock_seq_low' => '65', 'node' => '00a0c91e6bf6', ], 'urn' => 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6', 'time' => '1d07decf81d4fae', 'clock_seq' => '2765', 'variant' => Uuid::RFC_4122, 'version' => Uuid::UUID_TYPE_TIME, ], [ 'string' => 'fffefdfc-fffe-fffe-fffe-fffefdfcfbfa', 'curly' => '{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}', 'hex' => 'fffefdfcfffefffefffefffefdfcfbfa', 'bytes' => '//79/P/+//7//v/+/fz7+g==', 'int' => '340277133821575024845345576078114880506', 'fields' => [ 'time_low' => 'fffefdfc', 'time_mid' => 'fffe', 'time_hi_and_version' => 'fffe', 'clock_seq_hi_and_reserved' => 'ff', 'clock_seq_low' => 'fe', 'node' => 'fffefdfcfbfa', ], 'urn' => 'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa', 'time' => 'ffefffefffefdfc', 'clock_seq' => '3ffe', 'variant' => Uuid::RESERVED_FUTURE, 'version' => null, ], [ 'string' => 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'curly' => '{ffffffff-ffff-ffff-ffff-ffffffffffff}', 'hex' => 'ffffffffffffffffffffffffffffffff', 'bytes' => '/////////////////////w==', 'int' => '340282366920938463463374607431768211455', 'fields' => [ 'time_low' => 'ffffffff', 'time_mid' => 'ffff', 'time_hi_and_version' => 'ffff', 'clock_seq_hi_and_reserved' => 'ff', 'clock_seq_low' => 'ff', 'node' => 'ffffffffffff', ], 'urn' => 'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff', 'time' => 'fffffffffffffff', // Python's tests think the clock sequence should be // 0x3fff because of the bit shifting performed on this field. // However, since all the bits in this UUID are defined as being // set to one, we will consider the clock sequence as 0xffff, // which all bits set to one. 'clock_seq' => 'ffff', 'variant' => Uuid::RESERVED_FUTURE, 'version' => null, ], ]; } /** * @covers Ramsey\Uuid\Uuid::jsonSerialize */ public function testJsonSerialize(): void { $uuid = Uuid::uuid1(); $this->assertSame('"' . $uuid->toString() . '"', json_encode($uuid)); } public function testSerialize(): void { $uuid = Uuid::uuid4(); $serialized = serialize($uuid); /** @var UuidInterface $unserializedUuid */ $unserializedUuid = unserialize($serialized); $this->assertTrue($uuid->equals($unserializedUuid)); } public function testSerializeWithOldStringFormat(): void { $serialized = 'C:26:"Ramsey\Uuid\Rfc4122\UuidV4":36:{b3cd586a-e3ca-44f3-988c-f4d666c1bf4d}'; /** @var UuidInterface $unserializedUuid */ $unserializedUuid = unserialize($serialized); $this->assertSame('b3cd586a-e3ca-44f3-988c-f4d666c1bf4d', $unserializedUuid->toString()); } public function testUuid3WithEmptyNamespace(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid UUID string:'); /** @phpstan-ignore staticMethod.resultUnused */ Uuid::uuid3('', ''); } public function testUuid3WithEmptyName(): void { $uuid = Uuid::uuid3(Uuid::NIL, ''); $this->assertSame('4ae71336-e44b-39bf-b9d2-752e234818a5', $uuid->toString()); } public function testUuid3WithZeroName(): void { $uuid = Uuid::uuid3(Uuid::NIL, '0'); $this->assertSame('19826852-5007-3022-a72a-212f66e9fac3', $uuid->toString()); } public function testUuid5WithEmptyNamespace(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid UUID string:'); /** @phpstan-ignore staticMethod.resultUnused */ Uuid::uuid5('', ''); } public function testUuid5WithEmptyName(): void { $uuid = Uuid::uuid5(Uuid::NIL, ''); $this->assertSame('e129f27c-5103-5c5c-844b-cdf0a15e160d', $uuid->toString()); } public function testUuid5WithZeroName(): void { $uuid = Uuid::uuid5(Uuid::NIL, '0'); $this->assertSame('b6c54489-38a0-5f50-a60a-fd8d76219cae', $uuid->toString()); } /** * @depends testGetVersionForVersion1 */ public function testUuidVersionConstantForVersion1(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_TIME); } /** * @depends testGetVersionForVersion2 */ public function testUuidVersionConstantForVersion2(): void { $uuid = Uuid::fromString('6fa459ea-ee8a-2ca4-894e-db77e160355e'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_DCE_SECURITY); } /** * @depends testGetVersionForVersion3 */ public function testUuidVersionConstantForVersion3(): void { $uuid = Uuid::fromString('6fa459ea-ee8a-3ca4-894e-db77e160355e'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_HASH_MD5); } /** * @depends testGetVersionForVersion4 */ public function testUuidVersionConstantForVersion4(): void { $uuid = Uuid::fromString('6fabf0bc-603a-42f2-925b-d9f779bd0032'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_RANDOM); } /** * @depends testGetVersionForVersion5 */ public function testUuidVersionConstantForVersion5(): void { $uuid = Uuid::fromString('886313e1-3b8a-5372-9b90-0c9aee199e5d'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_HASH_SHA1); } public function testUuidVersionConstantForVersion6(): void { $uuid = Uuid::fromString('886313e1-3b8a-6372-9b90-0c9aee199e5d'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_PEABODY); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_REORDERED_TIME); } public function testUuidVersionConstantForVersion7(): void { $uuid = Uuid::fromString('886313e1-3b8a-7372-9b90-0c9aee199e5d'); $this->assertSame($uuid->getVersion(), Uuid::UUID_TYPE_UNIX_TIME); } public function testGetDateTimeThrowsExceptionWhenDateTimeCannotParseDate(): void { $numberConverter = new BigNumberConverter(); $timeConverter = Mockery::mock(TimeConverterInterface::class); $timeConverter ->shouldReceive('convertTime') ->once() ->andReturn(new Time(1234567890, '1234567')); $builder = new DefaultUuidBuilder($numberConverter, $timeConverter); $codec = new StringCodec($builder); $factory = new UuidFactory(); $factory->setCodec($codec); $uuid = $factory->fromString('b1484596-25dc-11ea-978f-2e728ce88125'); $this->expectException(DateTimeException::class); $this->expectExceptionMessage( 'Failed to parse time string (@1234567890.1234567) at position 18 (7): Unexpected character' ); $uuid->getDateTime(); } /** * @param array $args * * @dataProvider provideStaticMethods */ public function testStaticCreationMethodsReturnSpecificUuidInstances( string $staticMethod, array $args = [] ): void { $this->assertInstanceOf(LazyUuidFromString::class, Uuid::$staticMethod(...$args)); } /** * @param array $args * * @dataProvider provideStaticMethods */ public function testUuidInstancesBuiltFromStringAreEquivalentToTheirGeneratedCounterparts( string $staticMethod, array $args = [] ): void { /** @var UuidInterface $generated */ $generated = Uuid::$staticMethod(...$args); self::assertSame( (string) $generated, (string) Uuid::fromString($generated->toString()) ); } /** * @param array $args * * @dataProvider provideStaticMethods */ public function testUuidInstancesBuiltFromBytesAreEquivalentToTheirGeneratedCounterparts( string $staticMethod, array $args = [] ): void { /** @var UuidInterface $generated */ $generated = Uuid::$staticMethod(...$args); self::assertSame( (string) $generated, (string) Uuid::fromBytes($generated->getBytes()) ); } /** * @return array}> */ public function provideStaticMethods(): array { return [ ['uuid1'], ['uuid2', [Uuid::DCE_DOMAIN_PERSON]], ['uuid3', [Uuid::NIL, 'foobar']], ['uuid4'], ['uuid5', [Uuid::NIL, 'foobar']], ]; } } ================================================ FILE: tests/Validator/GenericValidatorTest.php ================================================ assertSame($expected, $validator->validate($variation)); } } /** * @return array */ public function provideValuesForValidation(): array { $hexMutations = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']; $testValues = []; foreach ($hexMutations as $version) { foreach ($hexMutations as $variant) { $testValues[] = [ 'value' => "ff6f8cb0-c57d-{$version}1e1-{$variant}b21-0800200c9a66", 'expected' => true, ]; } } return array_merge($testValues, [ [ 'value' => 'zf6f8cb0-c57d-11e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => '3f6f8cb0-c57d-11e1-9b21-0800200c9a6', 'expected' => false, ], [ 'value' => 'af6f8cb-c57d-11e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => 'af6f8cb0c57d11e19b210800200c9a66', 'expected' => false, ], [ 'value' => 'ff6f8cb0-c57da-51e1-9b21-0800200c9a66', 'expected' => false, ], [ 'value' => "ff6f8cb0-c57d-11e1-1b21-0800200c9a66\n", 'expected' => false, ], [ 'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66", 'expected' => false, ], [ 'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66\n", 'expected' => false, ], ]); } public function testGetPattern(): void { $expectedPattern = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\z'; $validator = new GenericValidator(); $this->assertSame($expectedPattern, $validator->getPattern()); } } ================================================ FILE: tests/benchmark/GuidConversionBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use Ramsey\Uuid\FeatureSet; use Ramsey\Uuid\Guid\Guid; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidInterface; final class GuidConversionBench { private const UUID_BYTES = [ "\x1e\x94\x42\x33\x98\x10\x41\x38\x96\x22\x56\xe1\xf9\x0c\x56\xed", ]; private UuidInterface $uuid; public function __construct() { $factory = new UuidFactory(new FeatureSet(useGuids: true)); $this->uuid = $factory->fromBytes(self::UUID_BYTES[0]); assert($this->uuid instanceof Guid); } public function benchStringConversionOfGuid(): void { $this->uuid->toString(); } } ================================================ FILE: tests/benchmark/NonLazyUuidConversionBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidInterface; final class NonLazyUuidConversionBench { private const UUID_BYTES = [ "\x1e\x94\x42\x33\x98\x10\x41\x38\x96\x22\x56\xe1\xf9\x0c\x56\xed", ]; private UuidInterface $uuid; public function __construct() { $factory = new UuidFactory(); $this->uuid = $factory->fromBytes(self::UUID_BYTES[0]); } public function benchStringConversionOfUuid(): void { $this->uuid->toString(); } } ================================================ FILE: tests/benchmark/UuidFieldExtractionBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; final class UuidFieldExtractionBench { /** @var UuidInterface */ private $uuid; public function __construct() { $this->uuid = Uuid::fromString('0ae0cac5-2a40-465c-99ed-3d331b7cf72a'); } public function benchGetFields(): void { $this->uuid->getFields(); } public function benchGetFields10Times(): void { $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); $this->uuid->getFields(); } public function benchGetHex(): void { $this->uuid->getHex(); } public function benchGetHex10Times(): void { $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); $this->uuid->getHex(); } public function benchGetInteger(): void { $this->uuid->getInteger(); } public function benchGetInteger10Times(): void { $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); $this->uuid->getInteger(); } } ================================================ FILE: tests/benchmark/UuidGenerationBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use DateTimeImmutable; use Ramsey\Uuid\Provider\Node\StaticNodeProvider; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerIdentifier; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; final class UuidGenerationBench { /** @var Hexadecimal */ private $node; /** @var int */ private $clockSequence; /** @var IntegerIdentifier */ private $localIdentifier; /** @var UuidInterface */ private $namespace; public function __construct() { $this->node = (new StaticNodeProvider(new Hexadecimal('121212121212'))) ->getNode(); $this->clockSequence = 16383; $this->localIdentifier = new IntegerIdentifier(5); $this->namespace = Uuid::fromString('c485840e-9389-4548-a276-aeecd9730e50'); } public function benchUuid1GenerationWithoutParameters(): void { Uuid::uuid1(); } public function benchUuid1GenerationWithNode(): void { Uuid::uuid1($this->node); } public function benchUuid1GenerationWithNodeAndClockSequence(): void { Uuid::uuid1($this->node, $this->clockSequence); } public function benchUuid2GenerationWithDomainAndLocalIdentifier(): void { Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier); } public function benchUuid2GenerationWithDomainAndLocalIdentifierAndNode(): void { Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier, $this->node); } public function benchUuid2GenerationWithDomainAndLocalIdentifierAndNodeAndClockSequence(): void { Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier, $this->node, 63); } public function benchUuid3Generation(): void { Uuid::uuid3($this->namespace, 'name'); } public function benchUuid4Generation(): void { Uuid::uuid4(); } public function benchUuid5Generation(): void { Uuid::uuid5($this->namespace, 'name'); } public function benchUuid6GenerationWithoutParameters(): void { Uuid::uuid6(); } public function benchUuid6GenerationWithNode(): void { Uuid::uuid6($this->node); } public function benchUuid6GenerationWithNodeAndClockSequence(): void { Uuid::uuid6($this->node, $this->clockSequence); } public function benchUuid7Generation(): void { Uuid::uuid7(); } public function benchUuid7GenerationWithDateTime(): void { Uuid::uuid7(new DateTimeImmutable('@1663203901.667000')); } } ================================================ FILE: tests/benchmark/UuidSerializationBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use function array_map; use function serialize; final class UuidSerializationBench { private const TINY_UUID = '00000000-0000-0000-0000-000000000001'; private const HUGE_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; private const UUIDS_TO_BE_SHORTENED = [ '0ae0cac5-2a40-465c-99ed-3d331b7cf72a', '5759b9ce-07b5-4e89-b33a-f864317a2951', '20c8664e-81a8-498d-9e98-444973ef3122', '16fcbcf3-bb47-4227-90bd-3485d60510c3', 'fa83ae94-38e0-4903-bc6a-0a3eca6e9ef5', '51c9e011-0429-4d77-a753-702bd67dcd84', '1bd8857a-d6d7-4bd6-8734-b3dfedbcda7b', '7aa38b71-37c3-4561-9b2e-ca227f1c9c55', 'e6b8854c-435c-4bb1-b6ad-1800b5d3e6bb', '4e2b0031-8b09-46e2-8244-3814c46a2f53', 'bedd0850-da1a-4808-95c4-25fef0abbaa7', '516b9052-d6fb-4828-bfc1-dffdef2d56d2', '5d60a7e7-9139-4779-9f28-e6316b9fe3b7', '65aa3d74-c1fb-4bdd-9a00-ce88a5270c57', '27c2e339-74ed-49a7-a3c4-1a0172e9f945', 'e89b7727-4847-41ab-98d7-4148216eea8c', 'd79efaf3-b5dc-43a0-b3a5-c492155a7e0d', 'ee9ee6e7-5b7d-4e18-ab88-ce03d569305f', 'fe90c911-c13b-4103-bf33-16757aa87ff5', '4d7ff67a-0074-4195-95d7-cf8b84eba079', 'abe5d378-d021-4905-93f4-0e76a7848365', '19d21907-d121-4d85-8a34-a65d04ce8977', 'c421b8ad-33a4-42aa-b0cc-8f5f94b2cff7', 'f3dbbe55-3c80-453e-ab39-a6fe5001a7fc', 'f48d3eb2-6060-458f-809f-b5e887f9a17f', 'd189e406-de29-4889-8470-7bfa0d020c0c', '71627018-9f21-4034-aafe-4c8b17151217', '0c6a9278-0963-4460-9cae-6dc6f5420f4f', 'c833ac35-cce0-4315-8df3-3ed76656a548', '78e94126-1d0a-472a-9b99-37840784318f', '6e684707-ce4b-42df-8a77-71e57b54b581', '811df139-e7a3-4cd8-b778-c81494d239ee', 'c263c5d8-c166-4599-9219-3e975e506f45', 'b31e7c5d-95ba-41d4-bc29-e6357c96f005', '16ae2983-7f8f-4eee-9afb-6d4617836a01', 'ecbbfac7-f92a-4b41-996e-3e4724aa0e23', '2c6b3db9-a5ee-4425-a837-8880a86faaa0', '3d67a99a-b39a-4295-b7f8-0bf71ead5b2d', 'ca421bb7-ad73-41ea-9648-70073862ad5a', '5ba156fa-853d-460f-a884-ca8dd3a27314', '42a4359a-1df2-4086-b454-7477dbb726ff', '7db9517b-f6ba-4bcf-ae26-6a88a7dbb034', 'bc758bd6-eb50-425b-ada1-07e6bb312032', '254cf6d0-696d-4ff0-b579-ac3b633f03c0', 'f8f34b37-4c71-4177-bac5-6b99bb1929af', 'b0cc6179-f2b1-4ddf-8fe2-2251c3d935a3', '333ad834-fa3b-4cf4-b9ba-fdb1c481c497', '011fc3bc-a97d-4535-8cb0-81766e361e78', 'acf2262b-4ccf-4f1d-b5c1-5e44641884c6', '6bf661b1-2f85-4277-8dba-6552141e7e42', 'a76df66b-8c50-488f-b4e7-4f4d3c05afff', 'b5c5df47-f939-4536-a340-442bf00bd70d', 'd4914d41-0011-49fb-a1c2-fe69108e4983', 'efd5fa37-b0de-43b0-9fe7-1b7a7a6523f8', '6048f863-7faa-43f2-8202-4b349ae34810', '659a0024-fa05-4068-aed0-e61239554b6d', '6ec80af3-0415-429e-91e9-8491ab5745c0', '0e6f754c-0533-4336-b4f0-e2e35518efa1', '47469672-7e55-4316-b5d4-c458e43d2404', '0c5ad756-a823-4a3f-8449-840fac080f45', '8f8345da-1dd9-499b-bda5-57100bb305d5', '4a31d059-e375-4571-9d28-ea0de51740e7', 'ed7fb50c-1b3a-4594-920b-9a461abce57c', '3d8fe6f6-e603-44c0-b550-3568523c3224', '809259bc-7912-427a-a975-7298ee5626db', 'ec88d77e-5612-466c-b269-ad146abd70d0', 'bd308a10-8073-45ae-9bfb-9a663ad5dd10', '83a6a4cc-3079-46d8-9263-8f57af4fd4c7', '557f0041-7e7f-447c-988c-eafa6e396915', '6ad0fa1c-7425-41e9-9b74-19c4935750a2', 'a9193e21-e529-43cf-9421-6ed09b59d86e', '2a09f6e6-4fb2-4da0-97bf-6f32858ba977', 'd66e0940-087f-4e71-8292-fc38e306d9f7', '0dfc58b3-d591-40be-803d-e17a52e5d262', 'a46c6902-de10-45cc-8dac-600d68860532', '5200f9dc-b967-4d1e-ab01-51c726c152ba', 'acd8498b-ee8b-4d58-b0ef-c353fb1b5a45', '36adf355-cccc-406f-a814-6333ec4e31bf', 'd6d64c6f-8388-4de3-9db1-de07f02071b6', 'daf3fde9-41d0-422f-a0e3-8c7a93a77091', '160f4fac-a229-4169-893e-4e9e6864c098', '170c4be9-1fe6-4838-8a77-dee364ae9a95', '2864fed0-868c-4bd1-a3fa-ae3bb3de20f4', '8ea6639c-36dc-463c-8299-8f9a12b10898', '626bef95-2f24-47c2-a792-f06e8f13a11e', 'ede75c44-5a1d-484c-942d-87407f27db23', '966ec42b-0bf7-4923-9672-7a41fee377bc', '399d7ce6-b28f-4751-ac50-73e31b079f22', 'ab2b4086-e181-4f02-aee1-a94afed40b50', '3cfc33a6-73f7-49f7-9c01-fbcf84e604d0', '40cf06c6-74ca-4016-b388-17dc0334770d', '58f9ecd3-14ab-4100-b32a-cc2622f06c81', 'a5c35e34-5d05-4724-bb6c-613b5d306a18', '5133ae3e-e38b-47fa-a3dc-965c738be792', '594acd2f-7100-4b2b-8b8a-6097cb1cec3d', '08b3da92-6b32-43d8-9fdd-53eaa996d649', '93dcdc27-ab2c-4828-9074-4876ee7ab257', '8260a154-23cc-4510-a5df-cc5119f457fb', '732a6571-9729-4935-92be-1a74b3242636', 'c15f5581-e047-45b7-a36f-dfef4e7ba4bb', ]; /** @var UuidInterface */ private $tinyUuid; /** @var UuidInterface */ private $hugeUuid; /** @var UuidInterface */ private $uuid; /** * @var non-empty-list */ private $promiscuousUuids; /** @var string */ private $serializedTinyUuid; /** @var string */ private $serializedHugeUuid; /** @var string */ private $serializedUuid; /** * @var non-empty-list */ private $serializedPromiscuousUuids; public function __construct() { $this->tinyUuid = Uuid::fromString(self::TINY_UUID); $this->hugeUuid = Uuid::fromString(self::HUGE_UUID); $this->uuid = Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]); $this->promiscuousUuids = array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED); $this->serializedTinyUuid = serialize(Uuid::fromString(self::TINY_UUID)); $this->serializedHugeUuid = serialize(Uuid::fromString(self::HUGE_UUID)); $this->serializedUuid = serialize(Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0])); $this->serializedPromiscuousUuids = array_map( 'serialize', array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED) ); } public function benchSerializationOfTinyUuid(): void { serialize($this->tinyUuid); } public function benchSerializationOfHugeUuid(): void { serialize($this->hugeUuid); } public function benchSerializationOfUuid(): void { serialize($this->uuid); } public function benchSerializationOfPromiscuousUuids(): void { array_map('serialize', $this->promiscuousUuids); } public function benchDeSerializationOfTinyUuid(): void { unserialize($this->serializedTinyUuid); } public function benchDeSerializationOfHugeUuid(): void { unserialize($this->serializedHugeUuid); } public function benchDeSerializationOfUuid(): void { unserialize($this->serializedUuid); } public function benchDeSerializationOfPromiscuousUuids(): void { array_map('unserialize', $this->serializedPromiscuousUuids); } } ================================================ FILE: tests/benchmark/UuidStringConversionBench.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\Benchmark; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use function array_map; final class UuidStringConversionBench { private const TINY_UUID = '00000000-0000-0000-0000-000000000001'; private const HUGE_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; private const UUIDS_TO_BE_SHORTENED = [ '0ae0cac5-2a40-465c-99ed-3d331b7cf72a', '5759b9ce-07b5-4e89-b33a-f864317a2951', '20c8664e-81a8-498d-9e98-444973ef3122', '16fcbcf3-bb47-4227-90bd-3485d60510c3', 'fa83ae94-38e0-4903-bc6a-0a3eca6e9ef5', '51c9e011-0429-4d77-a753-702bd67dcd84', '1bd8857a-d6d7-4bd6-8734-b3dfedbcda7b', '7aa38b71-37c3-4561-9b2e-ca227f1c9c55', 'e6b8854c-435c-4bb1-b6ad-1800b5d3e6bb', '4e2b0031-8b09-46e2-8244-3814c46a2f53', 'bedd0850-da1a-4808-95c4-25fef0abbaa7', '516b9052-d6fb-4828-bfc1-dffdef2d56d2', '5d60a7e7-9139-4779-9f28-e6316b9fe3b7', '65aa3d74-c1fb-4bdd-9a00-ce88a5270c57', '27c2e339-74ed-49a7-a3c4-1a0172e9f945', 'e89b7727-4847-41ab-98d7-4148216eea8c', 'd79efaf3-b5dc-43a0-b3a5-c492155a7e0d', 'ee9ee6e7-5b7d-4e18-ab88-ce03d569305f', 'fe90c911-c13b-4103-bf33-16757aa87ff5', '4d7ff67a-0074-4195-95d7-cf8b84eba079', 'abe5d378-d021-4905-93f4-0e76a7848365', '19d21907-d121-4d85-8a34-a65d04ce8977', 'c421b8ad-33a4-42aa-b0cc-8f5f94b2cff7', 'f3dbbe55-3c80-453e-ab39-a6fe5001a7fc', 'f48d3eb2-6060-458f-809f-b5e887f9a17f', 'd189e406-de29-4889-8470-7bfa0d020c0c', '71627018-9f21-4034-aafe-4c8b17151217', '0c6a9278-0963-4460-9cae-6dc6f5420f4f', 'c833ac35-cce0-4315-8df3-3ed76656a548', '78e94126-1d0a-472a-9b99-37840784318f', '6e684707-ce4b-42df-8a77-71e57b54b581', '811df139-e7a3-4cd8-b778-c81494d239ee', 'c263c5d8-c166-4599-9219-3e975e506f45', 'b31e7c5d-95ba-41d4-bc29-e6357c96f005', '16ae2983-7f8f-4eee-9afb-6d4617836a01', 'ecbbfac7-f92a-4b41-996e-3e4724aa0e23', '2c6b3db9-a5ee-4425-a837-8880a86faaa0', '3d67a99a-b39a-4295-b7f8-0bf71ead5b2d', 'ca421bb7-ad73-41ea-9648-70073862ad5a', '5ba156fa-853d-460f-a884-ca8dd3a27314', '42a4359a-1df2-4086-b454-7477dbb726ff', '7db9517b-f6ba-4bcf-ae26-6a88a7dbb034', 'bc758bd6-eb50-425b-ada1-07e6bb312032', '254cf6d0-696d-4ff0-b579-ac3b633f03c0', 'f8f34b37-4c71-4177-bac5-6b99bb1929af', 'b0cc6179-f2b1-4ddf-8fe2-2251c3d935a3', '333ad834-fa3b-4cf4-b9ba-fdb1c481c497', '011fc3bc-a97d-4535-8cb0-81766e361e78', 'acf2262b-4ccf-4f1d-b5c1-5e44641884c6', '6bf661b1-2f85-4277-8dba-6552141e7e42', 'a76df66b-8c50-488f-b4e7-4f4d3c05afff', 'b5c5df47-f939-4536-a340-442bf00bd70d', 'd4914d41-0011-49fb-a1c2-fe69108e4983', 'efd5fa37-b0de-43b0-9fe7-1b7a7a6523f8', '6048f863-7faa-43f2-8202-4b349ae34810', '659a0024-fa05-4068-aed0-e61239554b6d', '6ec80af3-0415-429e-91e9-8491ab5745c0', '0e6f754c-0533-4336-b4f0-e2e35518efa1', '47469672-7e55-4316-b5d4-c458e43d2404', '0c5ad756-a823-4a3f-8449-840fac080f45', '8f8345da-1dd9-499b-bda5-57100bb305d5', '4a31d059-e375-4571-9d28-ea0de51740e7', 'ed7fb50c-1b3a-4594-920b-9a461abce57c', '3d8fe6f6-e603-44c0-b550-3568523c3224', '809259bc-7912-427a-a975-7298ee5626db', 'ec88d77e-5612-466c-b269-ad146abd70d0', 'bd308a10-8073-45ae-9bfb-9a663ad5dd10', '83a6a4cc-3079-46d8-9263-8f57af4fd4c7', '557f0041-7e7f-447c-988c-eafa6e396915', '6ad0fa1c-7425-41e9-9b74-19c4935750a2', 'a9193e21-e529-43cf-9421-6ed09b59d86e', '2a09f6e6-4fb2-4da0-97bf-6f32858ba977', 'd66e0940-087f-4e71-8292-fc38e306d9f7', '0dfc58b3-d591-40be-803d-e17a52e5d262', 'a46c6902-de10-45cc-8dac-600d68860532', '5200f9dc-b967-4d1e-ab01-51c726c152ba', 'acd8498b-ee8b-4d58-b0ef-c353fb1b5a45', '36adf355-cccc-406f-a814-6333ec4e31bf', 'd6d64c6f-8388-4de3-9db1-de07f02071b6', 'daf3fde9-41d0-422f-a0e3-8c7a93a77091', '160f4fac-a229-4169-893e-4e9e6864c098', '170c4be9-1fe6-4838-8a77-dee364ae9a95', '2864fed0-868c-4bd1-a3fa-ae3bb3de20f4', '8ea6639c-36dc-463c-8299-8f9a12b10898', '626bef95-2f24-47c2-a792-f06e8f13a11e', 'ede75c44-5a1d-484c-942d-87407f27db23', '966ec42b-0bf7-4923-9672-7a41fee377bc', '399d7ce6-b28f-4751-ac50-73e31b079f22', 'ab2b4086-e181-4f02-aee1-a94afed40b50', '3cfc33a6-73f7-49f7-9c01-fbcf84e604d0', '40cf06c6-74ca-4016-b388-17dc0334770d', '58f9ecd3-14ab-4100-b32a-cc2622f06c81', 'a5c35e34-5d05-4724-bb6c-613b5d306a18', '5133ae3e-e38b-47fa-a3dc-965c738be792', '594acd2f-7100-4b2b-8b8a-6097cb1cec3d', '08b3da92-6b32-43d8-9fdd-53eaa996d649', '93dcdc27-ab2c-4828-9074-4876ee7ab257', '8260a154-23cc-4510-a5df-cc5119f457fb', '732a6571-9729-4935-92be-1a74b3242636', 'c15f5581-e047-45b7-a36f-dfef4e7ba4bb', ]; /** @var UuidInterface */ private $tinyUuid; /** @var UuidInterface */ private $hugeUuid; /** @var UuidInterface */ private $uuid; /** * @var non-empty-list */ private $promiscuousUuids; /** * @var non-empty-string */ private $tinyUuidBytes; /** * @var non-empty-string */ private $hugeUuidBytes; /** * @var non-empty-string */ private $uuidBytes; /** * @var non-empty-list */ private $promiscuousUuidsBytes; public function __construct() { $this->tinyUuid = Uuid::fromString(self::TINY_UUID); $this->hugeUuid = Uuid::fromString(self::HUGE_UUID); $this->uuid = Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]); $this->promiscuousUuids = array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED); $this->tinyUuidBytes = $this->tinyUuid->getBytes(); $this->hugeUuidBytes = $this->hugeUuid->getBytes(); $this->uuidBytes = $this->uuid->getBytes(); $this->promiscuousUuidsBytes = array_map(static function (UuidInterface $uuid): string { return $uuid->getBytes(); }, $this->promiscuousUuids); } public function benchCreationOfTinyUuidFromString(): void { Uuid::fromString(self::TINY_UUID); } public function benchCreationOfHugeUuidFromString(): void { Uuid::fromString(self::HUGE_UUID); } public function benchCreationOfUuidFromString(): void { Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]); } public function benchCreationOfPromiscuousUuidsFromString(): void { array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED); } public function benchCreationOfTinyUuidFromBytes(): void { Uuid::fromBytes($this->tinyUuidBytes); } public function benchCreationOfHugeUuidFromBytes(): void { Uuid::fromBytes($this->hugeUuidBytes); } public function benchCreationOfUuidFromBytes(): void { Uuid::fromBytes($this->uuidBytes); } public function benchCreationOfPromiscuousUuidsFromBytes(): void { array_map([Uuid::class, 'fromBytes'], $this->promiscuousUuidsBytes); } public function benchStringConversionOfTinyUuid(): void { $this->tinyUuid->toString(); } public function benchStringConversionOfHugeUuid(): void { $this->hugeUuid->toString(); } public function benchStringConversionOfUuid(): void { $this->uuid->toString(); } public function benchStringConversionOfPromiscuousUuids(): void { array_map(static function (UuidInterface $uuid): string { return $uuid->toString(); }, $this->promiscuousUuids); } public function benchBytesConversionOfTinyUuid(): void { $this->tinyUuid->getBytes(); } public function benchBytesConversionOfHugeUuid(): void { $this->hugeUuid->getBytes(); } public function benchBytesConversionOfUuid(): void { $this->uuid->getBytes(); } public function benchBytesConversionOfPromiscuousUuids(): void { array_map(static function (UuidInterface $uuid): string { return $uuid->getBytes(); }, $this->promiscuousUuids); } } ================================================ FILE: tests/bootstrap.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\StaticAnalysis; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; /** * This is a static analysis fixture to verify that the API signature * of a UUID allows for pure operations. Almost all methods will seem to be * redundant or trivial: that's normal, we're just verifying the * transitivity of immutable type signatures. * * Please note that this does not guarantee that the internals of the UUID * library are pure/safe, but just that the declared API to the outside world * is seen as immutable. */ final class UuidIsImmutable { public static function pureCompareTo(UuidInterface $a, UuidInterface $b): int { return $a->compareTo($b); } public static function pureEquals(UuidInterface $a, ?object $b): bool { return $a->equals($b); } /** * @return mixed[] */ public static function pureGetters(UuidInterface $a): array { return [ $a->getBytes(), $a->getNumberConverter(), $a->getHex(), $a->getFieldsHex(), $a->getClockSeqHiAndReservedHex(), $a->getClockSeqLowHex(), $a->getClockSequenceHex(), $a->getDateTime(), $a->getInteger(), $a->getLeastSignificantBitsHex(), $a->getMostSignificantBitsHex(), $a->getNodeHex(), $a->getTimeHiAndVersionHex(), $a->getTimeLowHex(), $a->getTimeMidHex(), $a->getTimestampHex(), $a->getUrn(), $a->getVariant(), $a->getVersion(), $a->toString(), $a->__toString(), ]; } /** * @return UuidInterface[]|bool[] */ public static function pureStaticUuidApi(): array { $id = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); return [ Uuid::fromBytes($id->getBytes()), Uuid::fromInteger($id->getInteger()->toString()), Uuid::isValid('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'), ]; } public static function uuid3IsPure(): UuidInterface { return Uuid::uuid3( Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'), 'Look ma! I am a pure function!' ); } public static function uuid5IsPure(): UuidInterface { return Uuid::uuid5( Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'), 'Look ma! I am a pure function!' ); } } ================================================ FILE: tests/static-analysis/UuidIsNeverEmpty.php ================================================ * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); namespace Ramsey\Uuid\StaticAnalysis; use Ramsey\Uuid\UuidInterface; /** * This is a static analysis fixture to verify that the API signature * of a UUID does not return empty strings for methods that never will do so. */ final class UuidIsNeverEmpty { /** @return non-empty-string */ public function bytesAreNeverEmpty(UuidInterface $uuid): string { return $uuid->getBytes(); } /** @return non-empty-string */ public function stringIsNeverEmpty(UuidInterface $uuid): string { return $uuid->toString(); } } ================================================ FILE: tests/static-analysis/ValidUuidIsNonEmpty.php ================================================