Upgrade framework

This commit is contained in:
2023-11-14 16:54:35 +01:00
parent 1648a5cd42
commit 4fcf6fffcc
10548 changed files with 693138 additions and 466698 deletions

19
vendor/ramsey/collection/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2015-2022 Ben Ramsey <ben@benramsey.com>
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.

70
vendor/ramsey/collection/README.md vendored Normal file
View File

@@ -0,0 +1,70 @@
<h1 align="center">ramsey/collection</h1>
<p align="center">
<strong>A PHP library for representing and manipulating collections.</strong>
</p>
<p align="center">
<a href="https://github.com/ramsey/collection"><img src="http://img.shields.io/badge/source-ramsey/collection-blue.svg?style=flat-square" alt="Source Code"></a>
<a href="https://packagist.org/packages/ramsey/collection"><img src="https://img.shields.io/packagist/v/ramsey/collection.svg?style=flat-square&label=release" alt="Download Package"></a>
<a href="https://php.net"><img src="https://img.shields.io/packagist/php-v/ramsey/collection.svg?style=flat-square&colorB=%238892BF" alt="PHP Programming Language"></a>
<a href="https://github.com/ramsey/collection/blob/master/LICENSE"><img src="https://img.shields.io/packagist/l/ramsey/collection.svg?style=flat-square&colorB=darkcyan" alt="Read License"></a>
<a href="https://github.com/ramsey/collection/actions/workflows/continuous-integration.yml"><img src="https://img.shields.io/github/actions/workflow/status/ramsey/collection/continuous-integration.yml?branch=main&logo=github&style=flat-square" alt="Build Status"></a>
<a href="https://codecov.io/gh/ramsey/collection"><img src="https://img.shields.io/codecov/c/gh/ramsey/collection?label=codecov&logo=codecov&style=flat-square" alt="Codecov Code Coverage"></a>
<a href="https://shepherd.dev/github/ramsey/collection"><img src="https://img.shields.io/endpoint?style=flat-square&url=https%3A%2F%2Fshepherd.dev%2Fgithub%2Framsey%2Fcollection%2Fcoverage" alt="Psalm Type Coverage"></a>
</p>
## About
ramsey/collection is a PHP library for representing and manipulating collections.
Much inspiration for this library came from the [Java Collections Framework][java].
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.
## Installation
Install this package as a dependency using [Composer](https://getcomposer.org).
``` bash
composer require ramsey/collection
```
## Usage
Examples of how to use this library may be found in the
[Wiki pages](https://github.com/ramsey/collection/wiki/Examples).
## 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/collection for Enterprise
Available as part of the Tidelift Subscription.
The maintainers of ramsey/collection 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-collection?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Copyright and License
The ramsey/collection library is copyright © [Ben Ramsey](https://benramsey.com)
and licensed for use under the terms of the
MIT License (MIT). Please see [LICENSE](LICENSE) for more information.
[java]: http://docs.oracle.com/javase/8/docs/technotes/guides/collections/index.html
[security.md]: https://github.com/ramsey/collection/blob/main/SECURITY.md

169
vendor/ramsey/collection/SECURITY.md vendored Normal file
View File

@@ -0,0 +1,169 @@
<!--
This policy template was created using the HackerOne Policy Builder [1],
with guidance from the National Telecommunications and Information
Administration Coordinated Vulnerability Disclosure Template [2].
-->
# Vulnerability Disclosure Policy (VDP)
## Brand Promise
<!--
This is your brand promise. Its objective is to "demonstrate a clear, good
faith commitment to customers and other stakeholders potentially impacted by
security vulnerabilities" [2].
-->
Keeping user information safe and secure is a top priority, and we welcome the
contribution of external security researchers.
## Scope
<!--
This is your initial scope. It tells vulnerability finders and reporters
"which systems and capabilities are 'fair game' versus 'off limits'" [2].
For software packages, this is often a list of currently maintained versions
of the package.
-->
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 | ✅ | https://github.com/ramsey/collection |
## How to Submit a Report
<!--
This is your communication process. It tells security researchers how to
contact you to report a vulnerability. It may be a link to a web form that
uses HTTPS for secure communication, or it may be an email address.
Optionally, you may choose to include a PGP public key, so that researchers
may send you encrypted messages.
-->
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
<!--
This section assures vulnerability finders and reporters that they will
receive good faith responses to their good faith acts. In other words,
"we will not take legal action if..." [2].
-->
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
<!--
The preferences section sets expectations based on priority and submission
volume, rather than legal objection or restriction [2].
According to the NTIA [2]:
This section is a living document that sets expectations for preferences
and priorities, typically maintained by the support and engineering
team. This can outline classes of vulnerabilities, reporting style
(crash dumps, CVSS scoring, proof-of-concept, etc.), tools, etc. Too
many preferences can set the wrong tone or make reporting findings
difficult to navigate. This section also sets expectations to the
researcher community for what types of issues are considered important
or not.
-->
* 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.
<!--
References
[1] HackerOne. Policy builder. Retrieved from https://hackerone.com/policy-builder/
[2] NTIA Safety Working Group. 2016. "Early stage" coordinated vulnerability
disclosure template: Version 1.1. (15 December 2016). Retrieved from
https://www.ntia.doc.gov/files/ntia/publications/ntia_vuln_disclosure_early_stage_template.pdf
-->
## 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-----
```

120
vendor/ramsey/collection/composer.json vendored Normal file
View File

@@ -0,0 +1,120 @@
{
"name": "ramsey/collection",
"description": "A PHP library for representing and manipulating collections.",
"license": "MIT",
"type": "library",
"keywords": [
"array",
"collection",
"hash",
"map",
"queue",
"set"
],
"authors": [
{
"name": "Ben Ramsey",
"email": "ben@benramsey.com",
"homepage": "https://benramsey.com"
}
],
"require": {
"php": "^7.4 || ^8.0",
"symfony/polyfill-php81": "^1.23"
},
"require-dev": {
"captainhook/plugin-composer": "^5.3",
"ergebnis/composer-normalize": "^2.28.3",
"fakerphp/faker": "^1.21",
"hamcrest/hamcrest-php": "^2.0",
"jangregor/phpstan-prophecy": "^1.0",
"mockery/mockery": "^1.5",
"php-parallel-lint/php-console-highlighter": "^1.0",
"php-parallel-lint/php-parallel-lint": "^1.3",
"phpcsstandards/phpcsutils": "^1.0.0-rc1",
"phpspec/prophecy-phpunit": "^2.0",
"phpstan/extension-installer": "^1.2",
"phpstan/phpstan": "^1.9",
"phpstan/phpstan-mockery": "^1.1",
"phpstan/phpstan-phpunit": "^1.3",
"phpunit/phpunit": "^9.5",
"psalm/plugin-mockery": "^1.1",
"psalm/plugin-phpunit": "^0.18.4",
"ramsey/coding-standard": "^2.0.3",
"ramsey/conventional-commits": "^1.3",
"vimeo/psalm": "^5.4"
},
"minimum-stability": "RC",
"prefer-stable": true,
"autoload": {
"psr-4": {
"Ramsey\\Collection\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Ramsey\\Collection\\Test\\": "tests/",
"Ramsey\\Test\\Generics\\": "tests/generics/"
},
"files": [
"vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest.php"
]
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true,
"ergebnis/composer-normalize": true,
"phpstan/extension-installer": true,
"captainhook/plugin-composer": true
},
"sort-packages": true
},
"extra": {
"captainhook": {
"force-install": true
},
"ramsey/conventional-commits": {
"configFile": "conventional-commits.json"
}
},
"scripts": {
"dev:analyze": [
"@dev:analyze:phpstan",
"@dev:analyze:psalm"
],
"dev:analyze:phpstan": "phpstan analyse --ansi --memory-limit=1G",
"dev:analyze:psalm": "psalm",
"dev:build:clean": "git clean -fX build/",
"dev:lint": [
"@dev:lint:syntax",
"@dev:lint:style"
],
"dev:lint:fix": "phpcbf",
"dev:lint:style": "phpcs --colors",
"dev:lint:syntax": "parallel-lint --colors src/ tests/",
"dev:test": [
"@dev:lint",
"@dev:analyze",
"@dev:test:unit"
],
"dev:test:coverage:ci": "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": "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:analyze:psalm": "Runs the Psalm static analyzer.",
"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."
}
}

View File

@@ -0,0 +1,22 @@
{
"typeCase": "kebab",
"types": [
"chore",
"ci",
"docs",
"feat",
"fix",
"refactor",
"security",
"style",
"test"
],
"scopeCase": "kebab",
"scopeRequired": false,
"scopes": [],
"descriptionCase": null,
"descriptionEndMark": "",
"bodyRequired": false,
"bodyWrapWidth": 72,
"requiredFooters": []
}

View File

@@ -0,0 +1,208 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use ArrayIterator;
use Traversable;
use function count;
use function serialize;
use function unserialize;
/**
* This class provides a basic implementation of `ArrayInterface`, to minimize
* the effort required to implement this interface.
*
* @template T
* @implements ArrayInterface<T>
*/
abstract class AbstractArray implements ArrayInterface
{
/**
* The items of this array.
*
* @var array<array-key, T>
*/
protected array $data = [];
/**
* Constructs a new array object.
*
* @param array<array-key, T> $data The initial items to add to this array.
*/
public function __construct(array $data = [])
{
// Invoke offsetSet() for each value added; in this way, sub-classes
// may provide additional logic about values added to the array object.
foreach ($data as $key => $value) {
$this[$key] = $value;
}
}
/**
* Returns an iterator for this array.
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php IteratorAggregate::getIterator()
*
* @return Traversable<array-key, T>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->data);
}
/**
* Returns `true` if the given offset exists in this array.
*
* @link http://php.net/manual/en/arrayaccess.offsetexists.php ArrayAccess::offsetExists()
*
* @param array-key $offset The offset to check.
*/
public function offsetExists($offset): bool
{
return isset($this->data[$offset]);
}
/**
* Returns the value at the specified offset.
*
* @link http://php.net/manual/en/arrayaccess.offsetget.php ArrayAccess::offsetGet()
*
* @param array-key $offset The offset for which a value should be returned.
*
* @return T|null the value stored at the offset, or null if the offset
* does not exist.
*/
#[\ReturnTypeWillChange] // phpcs:ignore
public function offsetGet($offset)
{
return $this->data[$offset] ?? null;
}
/**
* Sets the given value to the given offset in the array.
*
* @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet()
*
* @param array-key|null $offset The offset to set. If `null`, the value may be
* set at a numerically-indexed offset.
* @param T $value The value to set at the given offset.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function offsetSet($offset, $value): void
{
if ($offset === null) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
/**
* Removes the given offset and its value from the array.
*
* @link http://php.net/manual/en/arrayaccess.offsetunset.php ArrayAccess::offsetUnset()
*
* @param array-key $offset The offset to remove from the array.
*/
public function offsetUnset($offset): void
{
unset($this->data[$offset]);
}
/**
* Returns a serialized string representation of this array object.
*
* @deprecated The Serializable interface will go away in PHP 9.
*
* @link http://php.net/manual/en/serializable.serialize.php Serializable::serialize()
*
* @return string a PHP serialized string.
*/
public function serialize(): string
{
return serialize($this->data);
}
/**
* Returns data suitable for PHP serialization.
*
* @link https://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.serialize
* @link https://www.php.net/serialize
*
* @return array<array-key, T>
*/
public function __serialize(): array
{
return $this->data;
}
/**
* Converts a serialized string representation into an instance object.
*
* @deprecated The Serializable interface will go away in PHP 9.
*
* @link http://php.net/manual/en/serializable.unserialize.php Serializable::unserialize()
*
* @param string $serialized A PHP serialized string to unserialize.
*
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
*/
public function unserialize($serialized): void
{
/** @var array<array-key, T> $data */
$data = unserialize($serialized, ['allowed_classes' => false]);
$this->data = $data;
}
/**
* Adds unserialized data to the object.
*
* @param array<array-key, T> $data
*/
public function __unserialize(array $data): void
{
$this->data = $data;
}
/**
* Returns the number of items in this array.
*
* @link http://php.net/manual/en/countable.count.php Countable::count()
*/
public function count(): int
{
return count($this->data);
}
public function clear(): void
{
$this->data = [];
}
/**
* @inheritDoc
*/
public function toArray(): array
{
return $this->data;
}
public function isEmpty(): bool
{
return count($this->data) === 0;
}
}

View File

@@ -0,0 +1,341 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use Closure;
use Ramsey\Collection\Exception\CollectionMismatchException;
use Ramsey\Collection\Exception\InvalidArgumentException;
use Ramsey\Collection\Exception\InvalidSortOrderException;
use Ramsey\Collection\Exception\OutOfBoundsException;
use Ramsey\Collection\Tool\TypeTrait;
use Ramsey\Collection\Tool\ValueExtractorTrait;
use Ramsey\Collection\Tool\ValueToStringTrait;
use function array_filter;
use function array_map;
use function array_merge;
use function array_search;
use function array_udiff;
use function array_uintersect;
use function current;
use function end;
use function in_array;
use function is_int;
use function is_object;
use function reset;
use function spl_object_id;
use function sprintf;
use function unserialize;
use function usort;
/**
* This class provides a basic implementation of `CollectionInterface`, to
* minimize the effort required to implement this interface
*
* @template T
* @extends AbstractArray<T>
* @implements CollectionInterface<T>
*/
abstract class AbstractCollection extends AbstractArray implements CollectionInterface
{
use TypeTrait;
use ValueToStringTrait;
use ValueExtractorTrait;
/**
* @inheritDoc
*/
public function add($element): bool
{
$this[] = $element;
return true;
}
/**
* @inheritDoc
*/
public function contains($element, bool $strict = true): bool
{
return in_array($element, $this->data, $strict);
}
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($this->checkType($this->getType(), $value) === false) {
throw new InvalidArgumentException(
'Value must be of type ' . $this->getType() . '; value is '
. $this->toolValueToString($value),
);
}
if ($offset === null) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
/**
* @inheritDoc
*/
public function remove($element): bool
{
if (($position = array_search($element, $this->data, true)) !== false) {
unset($this[$position]);
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function column(string $propertyOrMethod): array
{
$temp = [];
foreach ($this->data as $item) {
/** @var mixed $value */
$value = $this->extractValue($item, $propertyOrMethod);
/** @psalm-suppress MixedAssignment */
$temp[] = $value;
}
return $temp;
}
/**
* @inheritDoc
*/
public function first()
{
if ($this->isEmpty()) {
throw new OutOfBoundsException('Can\'t determine first item. Collection is empty');
}
reset($this->data);
/** @var T $first */
$first = current($this->data);
return $first;
}
/**
* @inheritDoc
*/
public function last()
{
if ($this->isEmpty()) {
throw new OutOfBoundsException('Can\'t determine last item. Collection is empty');
}
/** @var T $item */
$item = end($this->data);
reset($this->data);
return $item;
}
public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): CollectionInterface
{
if (!in_array($order, [self::SORT_ASC, self::SORT_DESC], true)) {
throw new InvalidSortOrderException('Invalid sort order given: ' . $order);
}
$collection = clone $this;
usort(
$collection->data,
/**
* @param T $a
* @param T $b
*/
function ($a, $b) use ($propertyOrMethod, $order): int {
/** @var mixed $aValue */
$aValue = $this->extractValue($a, $propertyOrMethod);
/** @var mixed $bValue */
$bValue = $this->extractValue($b, $propertyOrMethod);
return ($aValue <=> $bValue) * ($order === self::SORT_DESC ? -1 : 1);
},
);
return $collection;
}
public function filter(callable $callback): CollectionInterface
{
$collection = clone $this;
$collection->data = array_merge([], array_filter($collection->data, $callback));
return $collection;
}
/**
* {@inheritdoc}
*/
public function where(string $propertyOrMethod, $value): CollectionInterface
{
return $this->filter(function ($item) use ($propertyOrMethod, $value) {
/** @var mixed $accessorValue */
$accessorValue = $this->extractValue($item, $propertyOrMethod);
return $accessorValue === $value;
});
}
public function map(callable $callback): CollectionInterface
{
return new Collection('mixed', array_map($callback, $this->data));
}
public function diff(CollectionInterface $other): CollectionInterface
{
$this->compareCollectionTypes($other);
$diffAtoB = array_udiff($this->data, $other->toArray(), $this->getComparator());
$diffBtoA = array_udiff($other->toArray(), $this->data, $this->getComparator());
/** @var array<array-key, T> $diff */
$diff = array_merge($diffAtoB, $diffBtoA);
$collection = clone $this;
$collection->data = $diff;
return $collection;
}
public function intersect(CollectionInterface $other): CollectionInterface
{
$this->compareCollectionTypes($other);
/** @var array<array-key, T> $intersect */
$intersect = array_uintersect($this->data, $other->toArray(), $this->getComparator());
$collection = clone $this;
$collection->data = $intersect;
return $collection;
}
public function merge(CollectionInterface ...$collections): CollectionInterface
{
$mergedCollection = clone $this;
foreach ($collections as $index => $collection) {
if (!$collection instanceof static) {
throw new CollectionMismatchException(
sprintf('Collection with index %d must be of type %s', $index, static::class),
);
}
// When using generics (Collection.php, Set.php, etc),
// we also need to make sure that the internal types match each other
if ($this->getUniformType($collection) !== $this->getUniformType($this)) {
throw new CollectionMismatchException(
sprintf(
'Collection items in collection with index %d must be of type %s',
$index,
$this->getType(),
),
);
}
foreach ($collection as $key => $value) {
if (is_int($key)) {
$mergedCollection[] = $value;
} else {
$mergedCollection[$key] = $value;
}
}
}
return $mergedCollection;
}
/**
* @inheritDoc
*/
public function unserialize($serialized): void
{
/** @var array<array-key, T> $data */
$data = unserialize($serialized, ['allowed_classes' => [$this->getType()]]);
$this->data = $data;
}
/**
* @param CollectionInterface<T> $other
*/
private function compareCollectionTypes(CollectionInterface $other): void
{
if (!$other instanceof static) {
throw new CollectionMismatchException('Collection must be of type ' . static::class);
}
// When using generics (Collection.php, Set.php, etc),
// we also need to make sure that the internal types match each other
if ($this->getUniformType($other) !== $this->getUniformType($this)) {
throw new CollectionMismatchException('Collection items must be of type ' . $this->getType());
}
}
private function getComparator(): Closure
{
return /**
* @param T $a
* @param T $b
*/
function ($a, $b): int {
// If the two values are object, we convert them to unique scalars.
// If the collection contains mixed values (unlikely) where some are objects
// and some are not, we leave them as they are.
// The comparator should still work and the result of $a < $b should
// be consistent but unpredictable since not documented.
if (is_object($a) && is_object($b)) {
$a = spl_object_id($a);
$b = spl_object_id($b);
}
return $a === $b ? 0 : ($a < $b ? 1 : -1);
};
}
/**
* @param CollectionInterface<mixed> $collection
*/
private function getUniformType(CollectionInterface $collection): string
{
switch ($collection->getType()) {
case 'integer':
return 'int';
case 'boolean':
return 'bool';
case 'double':
return 'float';
default:
return $collection->getType();
}
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
/**
* This class contains the basic implementation of a collection that does not
* allow duplicated values (a set), to minimize the effort required to implement
* this specific type of collection.
*
* @template T
* @extends AbstractCollection<T>
*/
abstract class AbstractSet extends AbstractCollection
{
/**
* @inheritDoc
*/
public function add($element): bool
{
if ($this->contains($element)) {
return false;
}
return parent::add($element);
}
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($this->contains($value)) {
return;
}
parent::offsetSet($offset, $value);
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use ArrayAccess;
use Countable;
use IteratorAggregate;
use Serializable;
/**
* `ArrayInterface` provides traversable array functionality to data types.
*
* @template T
* @extends ArrayAccess<array-key, T>
* @extends IteratorAggregate<array-key, T>
*/
interface ArrayInterface extends
ArrayAccess,
Countable,
IteratorAggregate,
Serializable
{
/**
* Removes all items from this array.
*/
public function clear(): void;
/**
* Returns a native PHP array representation of this array object.
*
* @return array<array-key, T>
*/
public function toArray(): array;
/**
* Returns `true` if this array is empty.
*/
public function isEmpty(): bool;
}

View File

@@ -0,0 +1,104 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
/**
* A collection represents a group of objects.
*
* Each object in the collection is of a specific, defined type.
*
* This is a direct implementation of `CollectionInterface`, provided for
* the sake of convenience.
*
* Example usage:
*
* ``` php
* $collection = new \Ramsey\Collection\Collection('My\\Foo');
* $collection->add(new \My\Foo());
* $collection->add(new \My\Foo());
*
* foreach ($collection as $foo) {
* // Do something with $foo
* }
* ```
*
* It is preferable to subclass `AbstractCollection` to create your own typed
* collections. For example:
*
* ``` php
* namespace My\Foo;
*
* class FooCollection extends \Ramsey\Collection\AbstractCollection
* {
* public function getType()
* {
* return 'My\\Foo';
* }
* }
* ```
*
* And then use it similarly to the earlier example:
*
* ``` php
* $fooCollection = new \My\Foo\FooCollection();
* $fooCollection->add(new \My\Foo());
* $fooCollection->add(new \My\Foo());
*
* foreach ($fooCollection as $foo) {
* // Do something with $foo
* }
* ```
*
* The benefit with this approach is that you may do type-checking on the
* collection object:
*
* ``` php
* if ($collection instanceof \My\Foo\FooCollection) {
* // the collection is a collection of My\Foo objects
* }
* ```
*
* @template T
* @extends AbstractCollection<T>
*/
class Collection extends AbstractCollection
{
/**
* The type of elements stored in this collection.
*
* A collection's type is immutable once it is set. For this reason, this
* property is set private.
*/
private string $collectionType;
/**
* Constructs a collection object of the specified type, optionally with the
* specified data.
*
* @param string $collectionType The type (FQCN) associated with this
* collection.
* @param array<array-key, T> $data The initial items to store in the collection.
*/
public function __construct(string $collectionType, array $data = [])
{
$this->collectionType = $collectionType;
parent::__construct($data);
}
public function getType(): string
{
return $this->collectionType;
}
}

View File

@@ -0,0 +1,206 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
/**
* A collection represents a group of objects, known as its elements.
*
* Some collections allow duplicate elements and others do not. Some are ordered
* and others unordered.
*
* @template T
* @extends ArrayInterface<T>
*/
interface CollectionInterface extends ArrayInterface
{
/**
* Ascending sort type.
*/
public const SORT_ASC = 'asc';
/**
* Descending sort type.
*/
public const SORT_DESC = 'desc';
/**
* Ensures that this collection contains the specified element (optional
* operation).
*
* Returns `true` if this collection changed as a result of the call.
* (Returns `false` if this collection does not permit duplicates and
* already contains the specified element.)
*
* Collections that support this operation may place limitations on what
* elements may be added to this collection. In particular, some
* collections will refuse to add `null` elements, and others will impose
* restrictions on the type of elements that may be added. Collection
* classes should clearly specify in their documentation any restrictions
* on what elements may be added.
*
* If a collection refuses to add a particular element for any reason other
* than that it already contains the element, it must throw an exception
* (rather than returning `false`). This preserves the invariant that a
* collection always contains the specified element after this call returns.
*
* @param T $element The element to add to the collection.
*
* @return bool `true` if this collection changed as a result of the call.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function add($element): bool;
/**
* Returns `true` if this collection contains the specified element.
*
* @param T $element The element to check whether the collection contains.
* @param bool $strict Whether to perform a strict type check on the value.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function contains($element, bool $strict = true): bool;
/**
* Returns the type associated with this collection.
*/
public function getType(): string;
/**
* Removes a single instance of the specified element from this collection,
* if it is present.
*
* @param T $element The element to remove from the collection.
*
* @return bool `true` if an element was removed as a result of this call.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function remove($element): bool;
/**
* Returns the values from the given property or method.
*
* @param string $propertyOrMethod The property or method name to filter by.
*
* @return list<mixed>
*/
public function column(string $propertyOrMethod): array;
/**
* Returns the first item of the collection.
*
* @return T
*/
public function first();
/**
* Returns the last item of the collection.
*
* @return T
*/
public function last();
/**
* Sort the collection by a property or method with the given sort order.
*
* This will always leave the original collection untouched and will return
* a new one.
*
* @param string $propertyOrMethod The property or method to sort by.
* @param string $order The sort order for the resulting collection (one of
* this interface's `SORT_*` constants).
*
* @return CollectionInterface<T>
*/
public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): self;
/**
* Filter out items of the collection which don't match the criteria of
* given callback.
*
* This will always leave the original collection untouched and will return
* a new one.
*
* See the {@link http://php.net/manual/en/function.array-filter.php PHP array_filter() documentation}
* for examples of how the `$callback` parameter works.
*
* @param callable(T):bool $callback A callable to use for filtering elements.
*
* @return CollectionInterface<T>
*/
public function filter(callable $callback): self;
/**
* Create a new collection where items match the criteria of given callback.
*
* This will always leave the original collection untouched and will return
* a new one.
*
* @param string $propertyOrMethod The property or method to evaluate.
* @param mixed $value The value to match.
*
* @return CollectionInterface<T>
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function where(string $propertyOrMethod, $value): self;
/**
* Apply a given callback method on each item of the collection.
*
* This will always leave the original collection untouched. The new
* collection is created by mapping the callback to each item of the
* original collection.
*
* See the {@link http://php.net/manual/en/function.array-map.php PHP array_map() documentation}
* for examples of how the `$callback` parameter works.
*
* @param callable(T):TCallbackReturn $callback A callable to apply to each
* item of the collection.
*
* @return CollectionInterface<TCallbackReturn>
*
* @template TCallbackReturn
*/
public function map(callable $callback): self;
/**
* Create a new collection with divergent items between current and given
* collection.
*
* @param CollectionInterface<T> $other The collection to check for divergent
* items.
*
* @return CollectionInterface<T>
*/
public function diff(CollectionInterface $other): self;
/**
* Create a new collection with intersecting item between current and given
* collection.
*
* @param CollectionInterface<T> $other The collection to check for
* intersecting items.
*
* @return CollectionInterface<T>
*/
public function intersect(CollectionInterface $other): self;
/**
* Merge current items and items of given collections into a new one.
*
* @param CollectionInterface<T> ...$collections The collections to merge.
*
* @return CollectionInterface<T>
*/
public function merge(CollectionInterface ...$collections): self;
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use Ramsey\Collection\Exception\InvalidArgumentException;
use Ramsey\Collection\Exception\NoSuchElementException;
/**
* This class provides a basic implementation of `DoubleEndedQueueInterface`, to
* minimize the effort required to implement this interface.
*
* @template T
* @extends Queue<T>
* @implements DoubleEndedQueueInterface<T>
*/
class DoubleEndedQueue extends Queue implements DoubleEndedQueueInterface
{
/**
* Index of the last element in the queue.
*/
private int $tail = -1;
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($this->checkType($this->getType(), $value) === false) {
throw new InvalidArgumentException(
'Value must be of type ' . $this->getType() . '; value is '
. $this->toolValueToString($value),
);
}
$this->tail++;
$this->data[$this->tail] = $value;
}
/**
* @throws InvalidArgumentException if $element is of the wrong type
*
* @inheritDoc
*/
public function addFirst($element): bool
{
if ($this->checkType($this->getType(), $element) === false) {
throw new InvalidArgumentException(
'Value must be of type ' . $this->getType() . '; value is '
. $this->toolValueToString($element),
);
}
$this->index--;
$this->data[$this->index] = $element;
return true;
}
/**
* @inheritDoc
*/
public function addLast($element): bool
{
return $this->add($element);
}
/**
* @inheritDoc
*/
public function offerFirst($element): bool
{
try {
return $this->addFirst($element);
} catch (InvalidArgumentException $e) {
return false;
}
}
/**
* @inheritDoc
*/
public function offerLast($element): bool
{
return $this->offer($element);
}
/**
* @inheritDoc
*/
public function removeFirst()
{
return $this->remove();
}
/**
* @inheritDoc
*/
public function removeLast()
{
$tail = $this->pollLast();
if ($tail === null) {
throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.');
}
return $tail;
}
/**
* @inheritDoc
*/
public function pollFirst()
{
return $this->poll();
}
/**
* @inheritDoc
*/
public function pollLast()
{
if ($this->count() === 0) {
return null;
}
$tail = $this[$this->tail];
unset($this[$this->tail]);
$this->tail--;
return $tail;
}
/**
* @inheritDoc
*/
public function firstElement()
{
return $this->element();
}
/**
* @inheritDoc
*/
public function lastElement()
{
if ($this->count() === 0) {
throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.');
}
return $this->data[$this->tail];
}
/**
* @inheritDoc
*/
public function peekFirst()
{
return $this->peek();
}
/**
* @inheritDoc
*/
public function peekLast()
{
if ($this->count() === 0) {
return null;
}
return $this->data[$this->tail];
}
}

View File

@@ -0,0 +1,317 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use Ramsey\Collection\Exception\NoSuchElementException;
use RuntimeException;
/**
* A linear collection that supports element insertion and removal at both ends.
*
* Most `DoubleEndedQueueInterface` implementations place no fixed limits on the
* number of elements they may contain, but this interface supports
* capacity-restricted double-ended queues as well as those with no fixed size
* limit.
*
* This interface defines methods to access the elements at both ends of the
* double-ended queue. Methods are provided to insert, remove, and examine the
* element. Each of these methods exists in two forms: one throws an exception
* if the operation fails, the other returns a special value (either `null` or
* `false`, depending on the operation). The latter form of the insert operation
* is designed specifically for use with capacity-restricted implementations; in
* most implementations, insert operations cannot fail.
*
* The twelve methods described above are summarized in the following table:
*
* <table>
* <caption>Summary of DoubleEndedQueueInterface methods</caption>
* <thead>
* <tr>
* <th></th>
* <th colspan=2>First Element (Head)</th>
* <th colspan=2>Last Element (Tail)</th>
* </tr>
* <tr>
* <td></td>
* <td><em>Throws exception</em></td>
* <td><em>Special value</em></td>
* <td><em>Throws exception</em></td>
* <td><em>Special value</em></td>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Insert</th>
* <td><code>addFirst()</code></td>
* <td><code>offerFirst()</code></td>
* <td><code>addLast()</code></td>
* <td><code>offerLast()</code></td>
* </tr>
* <tr>
* <th>Remove</th>
* <td><code>removeFirst()</code></td>
* <td><code>pollFirst()</code></td>
* <td><code>removeLast()</code></td>
* <td><code>pollLast()</code></td>
* </tr>
* <tr>
* <th>Examine</th>
* <td><code>firstElement()</code></td>
* <td><code>peekFirst()</code></td>
* <td><code>lastElement()</code></td>
* <td><code>peekLast()</code></td>
* </tr>
* </tbody>
* </table>
*
* This interface extends the `QueueInterface`. When a double-ended queue is
* used as a queue, FIFO (first-in-first-out) behavior results. Elements are
* added at the end of the double-ended queue and removed from the beginning.
* The methods inherited from the `QueueInterface` are precisely equivalent to
* `DoubleEndedQueueInterface` methods as indicated in the following table:
*
* <table>
* <caption>Comparison of QueueInterface and DoubleEndedQueueInterface methods</caption>
* <thead>
* <tr>
* <th>QueueInterface Method</th>
* <th>DoubleEndedQueueInterface Method</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><code>add()</code></td>
* <td><code>addLast()</code></td>
* </tr>
* <tr>
* <td><code>offer()</code></td>
* <td><code>offerLast()</code></td>
* </tr>
* <tr>
* <td><code>remove()</code></td>
* <td><code>removeFirst()</code></td>
* </tr>
* <tr>
* <td><code>poll()</code></td>
* <td><code>pollFirst()</code></td>
* </tr>
* <tr>
* <td><code>element()</code></td>
* <td><code>firstElement()</code></td>
* </tr>
* <tr>
* <td><code>peek()</code></td>
* <td><code>peekFirst()</code></td>
* </tr>
* </tbody>
* </table>
*
* Double-ended queues can also be used as LIFO (last-in-first-out) stacks. When
* a double-ended queue is used as a stack, elements are pushed and popped from
* the beginning of the double-ended queue. Stack concepts are precisely
* equivalent to `DoubleEndedQueueInterface` methods as indicated in the table
* below:
*
* <table>
* <caption>Comparison of stack concepts and DoubleEndedQueueInterface methods</caption>
* <thead>
* <tr>
* <th>Stack concept</th>
* <th>DoubleEndedQueueInterface Method</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><em>push</em></td>
* <td><code>addFirst()</code></td>
* </tr>
* <tr>
* <td><em>pop</em></td>
* <td><code>removeFirst()</code></td>
* </tr>
* <tr>
* <td><em>peek</em></td>
* <td><code>peekFirst()</code></td>
* </tr>
* </tbody>
* </table>
*
* Note that the `peek()` method works equally well when a double-ended queue is
* used as a queue or a stack; in either case, elements are drawn from the
* beginning of the double-ended queue.
*
* While `DoubleEndedQueueInterface` implementations are not strictly required
* to prohibit the insertion of `null` elements, they are strongly encouraged to
* do so. Users of any `DoubleEndedQueueInterface` implementations that do allow
* `null` elements are strongly encouraged *not* to take advantage of the
* ability to insert nulls. This is so because `null` is used as a special
* return value by various methods to indicated that the double-ended queue is
* empty.
*
* @template T
* @extends QueueInterface<T>
*/
interface DoubleEndedQueueInterface extends QueueInterface
{
/**
* Inserts the specified element at the front of this queue if it is
* possible to do so immediately without violating capacity restrictions.
*
* When using a capacity-restricted double-ended queue, it is generally
* preferable to use the `offerFirst()` method.
*
* @param T $element The element to add to the front of this queue.
*
* @return bool `true` if this queue changed as a result of the call.
*
* @throws RuntimeException if a queue refuses to add a particular element
* for any reason other than that it already contains the element.
* Implementations should use a more-specific exception that extends
* `\RuntimeException`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function addFirst($element): bool;
/**
* Inserts the specified element at the end of this queue if it is possible
* to do so immediately without violating capacity restrictions.
*
* When using a capacity-restricted double-ended queue, it is generally
* preferable to use the `offerLast()` method.
*
* This method is equivalent to `add()`.
*
* @param T $element The element to add to the end of this queue.
*
* @return bool `true` if this queue changed as a result of the call.
*
* @throws RuntimeException if a queue refuses to add a particular element
* for any reason other than that it already contains the element.
* Implementations should use a more-specific exception that extends
* `\RuntimeException`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function addLast($element): bool;
/**
* Inserts the specified element at the front of this queue if it is
* possible to do so immediately without violating capacity restrictions.
*
* When using a capacity-restricted queue, this method is generally
* preferable to `addFirst()`, which can fail to insert an element only by
* throwing an exception.
*
* @param T $element The element to add to the front of this queue.
*
* @return bool `true` if the element was added to this queue, else `false`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function offerFirst($element): bool;
/**
* Inserts the specified element at the end of this queue if it is possible
* to do so immediately without violating capacity restrictions.
*
* When using a capacity-restricted queue, this method is generally
* preferable to `addLast()` which can fail to insert an element only by
* throwing an exception.
*
* @param T $element The element to add to the end of this queue.
*
* @return bool `true` if the element was added to this queue, else `false`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function offerLast($element): bool;
/**
* Retrieves and removes the head of this queue.
*
* This method differs from `pollFirst()` only in that it throws an
* exception if this queue is empty.
*
* @return T the first element in this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function removeFirst();
/**
* Retrieves and removes the tail of this queue.
*
* This method differs from `pollLast()` only in that it throws an exception
* if this queue is empty.
*
* @return T the last element in this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function removeLast();
/**
* Retrieves and removes the head of this queue, or returns `null` if this
* queue is empty.
*
* @return T|null the head of this queue, or `null` if this queue is empty.
*/
public function pollFirst();
/**
* Retrieves and removes the tail of this queue, or returns `null` if this
* queue is empty.
*
* @return T|null the tail of this queue, or `null` if this queue is empty.
*/
public function pollLast();
/**
* Retrieves, but does not remove, the head of this queue.
*
* This method differs from `peekFirst()` only in that it throws an
* exception if this queue is empty.
*
* @return T the head of this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function firstElement();
/**
* Retrieves, but does not remove, the tail of this queue.
*
* This method differs from `peekLast()` only in that it throws an exception
* if this queue is empty.
*
* @return T the tail of this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function lastElement();
/**
* Retrieves, but does not remove, the head of this queue, or returns `null`
* if this queue is empty.
*
* @return T|null the head of this queue, or `null` if this queue is empty.
*/
public function peekFirst();
/**
* Retrieves, but does not remove, the tail of this queue, or returns `null`
* if this queue is empty.
*
* @return T|null the tail of this queue, or `null` if this queue is empty.
*/
public function peekLast();
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
use RuntimeException;
/**
* Thrown when attempting to operate on collections of differing types.
*/
class CollectionMismatchException extends RuntimeException
{
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
/**
* Thrown to indicate an argument is not of the expected type.
*/
class InvalidArgumentException extends \InvalidArgumentException
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
use RuntimeException;
/**
* Thrown when attempting to use a sort order that is not recognized.
*/
class InvalidSortOrderException extends RuntimeException
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
use RuntimeException;
/**
* Thrown when attempting to access an element that does not exist.
*/
class NoSuchElementException extends RuntimeException
{
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
/**
* Thrown when attempting to access an element out of the range of the collection.
*/
class OutOfBoundsException extends \OutOfBoundsException
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
use RuntimeException;
/**
* Thrown to indicate that the requested operation is not supported.
*/
class UnsupportedOperationException extends RuntimeException
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Exception;
use RuntimeException;
/**
* Thrown when attempting to extract a value for a method or property that does not exist.
*/
class ValueExtractionException extends RuntimeException
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
/**
* `GenericArray` represents a standard array object.
*
* @extends AbstractArray<mixed>
*/
class GenericArray extends AbstractArray
{
}

View File

@@ -0,0 +1,163 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
use Ramsey\Collection\AbstractArray;
use Ramsey\Collection\Exception\InvalidArgumentException;
use function array_key_exists;
use function array_keys;
use function in_array;
use function var_export;
/**
* This class provides a basic implementation of `MapInterface`, to minimize the
* effort required to implement this interface.
*
* @template T
* @extends AbstractArray<T>
* @implements MapInterface<T>
*/
abstract class AbstractMap extends AbstractArray implements MapInterface
{
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($offset === null) {
throw new InvalidArgumentException(
'Map elements are key/value pairs; a key must be provided for '
. 'value ' . var_export($value, true),
);
}
$this->data[$offset] = $value;
}
/**
* @inheritDoc
*/
public function containsKey($key): bool
{
return array_key_exists($key, $this->data);
}
/**
* @inheritDoc
*/
public function containsValue($value): bool
{
return in_array($value, $this->data, true);
}
/**
* @inheritDoc
*/
public function keys(): array
{
return array_keys($this->data);
}
/**
* @inheritDoc
*/
public function get($key, $defaultValue = null)
{
if (!$this->containsKey($key)) {
return $defaultValue;
}
return $this[$key];
}
/**
* @inheritDoc
*/
public function put($key, $value)
{
$previousValue = $this->get($key);
$this[$key] = $value;
return $previousValue;
}
/**
* @inheritDoc
*/
public function putIfAbsent($key, $value)
{
$currentValue = $this->get($key);
if ($currentValue === null) {
$this[$key] = $value;
}
return $currentValue;
}
/**
* @inheritDoc
*/
public function remove($key)
{
$previousValue = $this->get($key);
unset($this[$key]);
return $previousValue;
}
/**
* @inheritDoc
*/
public function removeIf($key, $value): bool
{
if ($this->get($key) === $value) {
unset($this[$key]);
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function replace($key, $value)
{
$currentValue = $this->get($key);
if ($this->containsKey($key)) {
$this[$key] = $value;
}
return $currentValue;
}
/**
* @inheritDoc
*/
public function replaceIf($key, $oldValue, $newValue): bool
{
if ($this->get($key) === $oldValue) {
$this[$key] = $newValue;
return true;
}
return false;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
use Ramsey\Collection\Exception\InvalidArgumentException;
use Ramsey\Collection\Tool\TypeTrait;
use Ramsey\Collection\Tool\ValueToStringTrait;
use function var_export;
/**
* This class provides a basic implementation of `TypedMapInterface`, to
* minimize the effort required to implement this interface.
*
* @template K of array-key
* @template T
* @extends AbstractMap<T>
* @implements TypedMapInterface<T>
*/
abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface
{
use TypeTrait;
use ValueToStringTrait;
/**
* @param K|null $offset
* @param T $value
*
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($offset === null) {
throw new InvalidArgumentException(
'Map elements are key/value pairs; a key must be provided for '
. 'value ' . var_export($value, true),
);
}
if ($this->checkType($this->getKeyType(), $offset) === false) {
throw new InvalidArgumentException(
'Key must be of type ' . $this->getKeyType() . '; key is '
. $this->toolValueToString($offset),
);
}
if ($this->checkType($this->getValueType(), $value) === false) {
throw new InvalidArgumentException(
'Value must be of type ' . $this->getValueType() . '; value is '
. $this->toolValueToString($value),
);
}
parent::offsetSet($offset, $value);
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
/**
* `AssociativeArrayMap` represents a standard associative array object.
*
* @template T
* @extends AbstractMap<T>
*/
class AssociativeArrayMap extends AbstractMap
{
}

View File

@@ -0,0 +1,149 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
use Ramsey\Collection\ArrayInterface;
/**
* An object that maps keys to values.
*
* A map cannot contain duplicate keys; each key can map to at most one value.
*
* @template T
* @extends ArrayInterface<T>
*/
interface MapInterface extends ArrayInterface
{
/**
* Returns `true` if this map contains a mapping for the specified key.
*
* @param array-key $key The key to check in the map.
*/
public function containsKey($key): bool;
/**
* Returns `true` if this map maps one or more keys to the specified value.
*
* This performs a strict type check on the value.
*
* @param T $value The value to check in the map.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function containsValue($value): bool;
/**
* Return an array of the keys contained in this map.
*
* @return list<array-key>
*/
public function keys(): array;
/**
* Returns the value to which the specified key is mapped, `null` if this
* map contains no mapping for the key, or (optionally) `$defaultValue` if
* this map contains no mapping for the key.
*
* @param array-key $key The key to return from the map.
* @param T|null $defaultValue The default value to use if `$key` is not found.
*
* @return T|null the value or `null` if the key could not be found.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function get($key, $defaultValue = null);
/**
* Associates the specified value with the specified key in this map.
*
* If the map previously contained a mapping for the key, the old value is
* replaced by the specified value.
*
* @param array-key $key The key to put or replace in the map.
* @param T $value The value to store at `$key`.
*
* @return T|null the previous value associated with key, or `null` if
* there was no mapping for `$key`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function put($key, $value);
/**
* Associates the specified value with the specified key in this map only if
* it is not already set.
*
* If there is already a value associated with `$key`, this returns that
* value without replacing it.
*
* @param array-key $key The key to put in the map.
* @param T $value The value to store at `$key`.
*
* @return T|null the previous value associated with key, or `null` if
* there was no mapping for `$key`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function putIfAbsent($key, $value);
/**
* Removes the mapping for a key from this map if it is present.
*
* @param array-key $key The key to remove from the map.
*
* @return T|null the previous value associated with key, or `null` if
* there was no mapping for `$key`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function remove($key);
/**
* Removes the entry for the specified key only if it is currently mapped to
* the specified value.
*
* This performs a strict type check on the value.
*
* @param array-key $key The key to remove from the map.
* @param T $value The value to match.
*
* @return bool true if the value was removed.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function removeIf($key, $value): bool;
/**
* Replaces the entry for the specified key only if it is currently mapped
* to some value.
*
* @param array-key $key The key to replace.
* @param T $value The value to set at `$key`.
*
* @return T|null the previous value associated with key, or `null` if
* there was no mapping for `$key`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function replace($key, $value);
/**
* Replaces the entry for the specified key only if currently mapped to the
* specified value.
*
* This performs a strict type check on the value.
*
* @param array-key $key The key to remove from the map.
* @param T $oldValue The value to match.
* @param T $newValue The value to use as a replacement.
*
* @return bool true if the value was replaced.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function replaceIf($key, $oldValue, $newValue): bool;
}

View File

@@ -0,0 +1,121 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
use Ramsey\Collection\Exception\InvalidArgumentException;
use Ramsey\Collection\Tool\TypeTrait;
use Ramsey\Collection\Tool\ValueToStringTrait;
use function array_combine;
use function array_key_exists;
use function is_int;
use function var_export;
/**
* `NamedParameterMap` represents a mapping of values to a set of named keys
* that may optionally be typed
*
* @extends AbstractMap<mixed>
*/
class NamedParameterMap extends AbstractMap
{
use TypeTrait;
use ValueToStringTrait;
/**
* Named parameters defined for this map.
*
* @var array<string, string>
*/
protected array $namedParameters;
/**
* Constructs a new `NamedParameterMap`.
*
* @param array<array-key, string> $namedParameters The named parameters defined for this map.
* @param array<array-key, mixed> $data An initial set of data to set on this map.
*/
public function __construct(array $namedParameters, array $data = [])
{
$this->namedParameters = $this->filterNamedParameters($namedParameters);
parent::__construct($data);
}
/**
* Returns named parameters set for this `NamedParameterMap`.
*
* @return array<string, string>
*/
public function getNamedParameters(): array
{
return $this->namedParameters;
}
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void
{
if ($offset === null) {
throw new InvalidArgumentException(
'Map elements are key/value pairs; a key must be provided for '
. 'value ' . var_export($value, true),
);
}
if (!array_key_exists($offset, $this->namedParameters)) {
throw new InvalidArgumentException(
'Attempting to set value for unconfigured parameter \''
. $offset . '\'',
);
}
if ($this->checkType($this->namedParameters[$offset], $value) === false) {
throw new InvalidArgumentException(
'Value for \'' . $offset . '\' must be of type '
. $this->namedParameters[$offset] . '; value is '
. $this->toolValueToString($value),
);
}
$this->data[$offset] = $value;
}
/**
* Given an array of named parameters, constructs a proper mapping of
* named parameters to types.
*
* @param array<array-key, string> $namedParameters The named parameters to filter.
*
* @return array<string, string>
*/
protected function filterNamedParameters(array $namedParameters): array
{
$names = [];
$types = [];
foreach ($namedParameters as $key => $value) {
if (is_int($key)) {
$names[] = $value;
$types[] = 'mixed';
} else {
$names[] = $key;
$types[] = $value;
}
}
return array_combine($names, $types) ?: [];
}
}

View File

@@ -0,0 +1,132 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
use Ramsey\Collection\Tool\TypeTrait;
/**
* A `TypedMap` represents a map of elements where key and value are typed.
*
* Each element is identified by a key with defined type and a value of defined
* type. The keys of the map must be unique. The values on the map can be
* repeated but each with its own different key.
*
* The most common case is to use a string type key, but it's not limited to
* this type of keys.
*
* This is a direct implementation of `TypedMapInterface`, provided for the sake
* of convenience.
*
* Example usage:
*
* ```php
* $map = new TypedMap('string', Foo::class);
* $map['x'] = new Foo();
* foreach ($map as $key => $value) {
* // do something with $key, it will be a Foo::class
* }
*
* // this will throw an exception since key must be string
* $map[10] = new Foo();
*
* // this will throw an exception since value must be a Foo
* $map['bar'] = 'bar';
*
* // initialize map with contents
* $map = new TypedMap('string', Foo::class, [
* new Foo(), new Foo(), new Foo()
* ]);
* ```
*
* It is preferable to subclass `AbstractTypedMap` to create your own typed map
* implementation:
*
* ```php
* class FooTypedMap extends AbstractTypedMap
* {
* public function getKeyType()
* {
* return 'int';
* }
*
* public function getValueType()
* {
* return Foo::class;
* }
* }
* ```
*
* … but you also may use the `TypedMap` class:
*
* ```php
* class FooTypedMap extends TypedMap
* {
* public function __constructor(array $data = [])
* {
* parent::__construct('int', Foo::class, $data);
* }
* }
* ```
*
* @template K of array-key
* @template T
* @extends AbstractTypedMap<K, T>
*/
class TypedMap extends AbstractTypedMap
{
use TypeTrait;
/**
* The data type of keys stored in this collection.
*
* A map key's type is immutable once it is set. For this reason, this
* property is set private.
*/
private string $keyType;
/**
* The data type of values stored in this collection.
*
* A map value's type is immutable once it is set. For this reason, this
* property is set private.
*/
private string $valueType;
/**
* Constructs a map object of the specified key and value types,
* optionally with the specified data.
*
* @param string $keyType The data type of the map's keys.
* @param string $valueType The data type of the map's values.
* @param array<K, T> $data The initial data to set for this map.
*/
public function __construct(string $keyType, string $valueType, array $data = [])
{
$this->keyType = $keyType;
$this->valueType = $valueType;
parent::__construct($data);
}
public function getKeyType(): string
{
return $this->keyType;
}
public function getValueType(): string
{
return $this->valueType;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Map;
/**
* A `TypedMapInterface` represents a map of elements where key and value are
* typed.
*
* @template T
* @extends MapInterface<T>
*/
interface TypedMapInterface extends MapInterface
{
/**
* Return the type used on the key.
*/
public function getKeyType(): string;
/**
* Return the type forced on the values.
*/
public function getValueType(): string;
}

169
vendor/ramsey/collection/src/Queue.php vendored Normal file
View File

@@ -0,0 +1,169 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use Ramsey\Collection\Exception\InvalidArgumentException;
use Ramsey\Collection\Exception\NoSuchElementException;
use Ramsey\Collection\Tool\TypeTrait;
use Ramsey\Collection\Tool\ValueToStringTrait;
/**
* This class provides a basic implementation of `QueueInterface`, to minimize
* the effort required to implement this interface.
*
* @template T
* @extends AbstractArray<T>
* @implements QueueInterface<T>
*/
class Queue extends AbstractArray implements QueueInterface
{
use TypeTrait;
use ValueToStringTrait;
/**
* The type of elements stored in this queue.
*
* A queue's type is immutable once it is set. For this reason, this
* property is set private.
*/
private string $queueType;
/**
* The index of the head of the queue.
*/
protected int $index = 0;
/**
* Constructs a queue object of the specified type, optionally with the
* specified data.
*
* @param string $queueType The type (FQCN) associated with this queue.
* @param array<array-key, T> $data The initial items to store in the collection.
*/
public function __construct(string $queueType, array $data = [])
{
$this->queueType = $queueType;
parent::__construct($data);
}
/**
* {@inheritDoc}
*
* Since arbitrary offsets may not be manipulated in a queue, this method
* serves only to fulfill the `ArrayAccess` interface requirements. It is
* invoked by other operations when adding values to the queue.
*
* @throws InvalidArgumentException if $value is of the wrong type
*/
public function offsetSet($offset, $value): void
{
if ($this->checkType($this->getType(), $value) === false) {
throw new InvalidArgumentException(
'Value must be of type ' . $this->getType() . '; value is '
. $this->toolValueToString($value),
);
}
$this->data[] = $value;
}
/**
* @throws InvalidArgumentException if $value is of the wrong type
*
* @inheritDoc
*/
public function add($element): bool
{
$this[] = $element;
return true;
}
/**
* @inheritDoc
*/
public function element()
{
$element = $this->peek();
if ($element === null) {
throw new NoSuchElementException(
'Can\'t return element from Queue. Queue is empty.',
);
}
return $element;
}
/**
* @inheritDoc
*/
public function offer($element): bool
{
try {
return $this->add($element);
} catch (InvalidArgumentException $e) {
return false;
}
}
/**
* @inheritDoc
*/
public function peek()
{
if ($this->count() === 0) {
return null;
}
return $this[$this->index];
}
/**
* @inheritDoc
*/
public function poll()
{
if ($this->count() === 0) {
return null;
}
$head = $this[$this->index];
unset($this[$this->index]);
$this->index++;
return $head;
}
/**
* @inheritDoc
*/
public function remove()
{
$head = $this->poll();
if ($head === null) {
throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.');
}
return $head;
}
public function getType(): string
{
return $this->queueType;
}
}

View File

@@ -0,0 +1,204 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
use Ramsey\Collection\Exception\NoSuchElementException;
use RuntimeException;
/**
* A queue is a collection in which the entities in the collection are kept in
* order.
*
* The principal operations on the queue are the addition of entities to the end
* (tail), also known as *enqueue*, and removal of entities from the front
* (head), also known as *dequeue*. This makes the queue a first-in-first-out
* (FIFO) data structure.
*
* Besides basic array operations, queues provide additional insertion,
* extraction, and inspection operations. Each of these methods exists in two
* forms: one throws an exception if the operation fails, the other returns a
* special value (either `null` or `false`, depending on the operation). The
* latter form of the insert operation is designed specifically for use with
* capacity-restricted `QueueInterface` implementations; in most
* implementations, insert operations cannot fail.
*
* <table>
* <caption>Summary of QueueInterface methods</caption>
* <thead>
* <tr>
* <td></td>
* <td><em>Throws exception</em></td>
* <td><em>Returns special value</em></td>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Insert</th>
* <td><code>add()</code></td>
* <td><code>offer()</code></td>
* </tr>
* <tr>
* <th>Remove</th>
* <td><code>remove()</code></td>
* <td><code>poll()</code></td>
* </tr>
* <tr>
* <th>Examine</th>
* <td><code>element()</code></td>
* <td><code>peek()</code></td>
* </tr>
* </tbody>
* </table>
*
* Queues typically, but do not necessarily, order elements in a FIFO
* (first-in-first-out) manner. Among the exceptions are priority queues, which
* order elements according to a supplied comparator, or the elements' natural
* ordering, and LIFO queues (or stacks) which order the elements LIFO
* (last-in-first-out). Whatever the ordering used, the head of the queue is
* that element which would be removed by a call to remove() or poll(). In a
* FIFO queue, all new elements are inserted at the tail of the queue. Other
* kinds of queues may use different placement rules. Every `QueueInterface`
* implementation must specify its ordering properties.
*
* The `offer()` method inserts an element if possible, otherwise returning
* `false`. This differs from the `add()` method, which can fail to add an
* element only by throwing an unchecked exception. The `offer()` method is
* designed for use when failure is a normal, rather than exceptional
* occurrence, for example, in fixed-capacity (or "bounded") queues.
*
* The `remove()` and `poll()` methods remove and return the head of the queue.
* Exactly which element is removed from the queue is a function of the queue's
* ordering policy, which differs from implementation to implementation. The
* `remove()` and `poll()` methods differ only in their behavior when the queue
* is empty: the `remove()` method throws an exception, while the `poll()`
* method returns `null`.
*
* The `element()` and `peek()` methods return, but do not remove, the head of
* the queue.
*
* `QueueInterface` implementations generally do not allow insertion of `null`
* elements, although some implementations do not prohibit insertion of `null`.
* Even in the implementations that permit it, `null` should not be inserted
* into a queue, as `null` is also used as a special return value by the
* `poll()` method to indicate that the queue contains no elements.
*
* @template T
* @extends ArrayInterface<T>
*/
interface QueueInterface extends ArrayInterface
{
/**
* Ensures that this queue contains the specified element (optional
* operation).
*
* Returns `true` if this queue changed as a result of the call. (Returns
* `false` if this queue does not permit duplicates and already contains the
* specified element.)
*
* Queues that support this operation may place limitations on what elements
* may be added to this queue. In particular, some queues will refuse to add
* `null` elements, and others will impose restrictions on the type of
* elements that may be added. Queue classes should clearly specify in their
* documentation any restrictions on what elements may be added.
*
* If a queue refuses to add a particular element for any reason other than
* that it already contains the element, it must throw an exception (rather
* than returning `false`). This preserves the invariant that a queue always
* contains the specified element after this call returns.
*
* @see self::offer()
*
* @param T $element The element to add to this queue.
*
* @return bool `true` if this queue changed as a result of the call.
*
* @throws RuntimeException if a queue refuses to add a particular element
* for any reason other than that it already contains the element.
* Implementations should use a more-specific exception that extends
* `\RuntimeException`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function add($element): bool;
/**
* Retrieves, but does not remove, the head of this queue.
*
* This method differs from `peek()` only in that it throws an exception if
* this queue is empty.
*
* @see self::peek()
*
* @return T the head of this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function element();
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions.
*
* When using a capacity-restricted queue, this method is generally
* preferable to `add()`, which can fail to insert an element only by
* throwing an exception.
*
* @see self::add()
*
* @param T $element The element to add to this queue.
*
* @return bool `true` if the element was added to this queue, else `false`.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
public function offer($element): bool;
/**
* Retrieves, but does not remove, the head of this queue, or returns `null`
* if this queue is empty.
*
* @see self::element()
*
* @return T|null the head of this queue, or `null` if this queue is empty.
*/
public function peek();
/**
* Retrieves and removes the head of this queue, or returns `null`
* if this queue is empty.
*
* @see self::remove()
*
* @return T|null the head of this queue, or `null` if this queue is empty.
*/
public function poll();
/**
* Retrieves and removes the head of this queue.
*
* This method differs from `poll()` only in that it throws an exception if
* this queue is empty.
*
* @see self::poll()
*
* @return T the head of this queue.
*
* @throws NoSuchElementException if this queue is empty.
*/
public function remove();
/**
* Returns the type associated with this queue.
*/
public function getType(): string;
}

67
vendor/ramsey/collection/src/Set.php vendored Normal file
View File

@@ -0,0 +1,67 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection;
/**
* A set is a collection that contains no duplicate elements.
*
* Great care must be exercised if mutable objects are used as set elements.
* The behavior of a set is not specified if the value of an object is changed
* in a manner that affects equals comparisons while the object is an element in
* the set.
*
* Example usage:
*
* ``` php
* $foo = new \My\Foo();
* $set = new Set(\My\Foo::class);
*
* $set->add($foo); // returns TRUE, the element don't exists
* $set->add($foo); // returns FALSE, the element already exists
*
* $bar = new \My\Foo();
* $set->add($bar); // returns TRUE, $bar !== $foo
* ```
*
* @template T
* @extends AbstractSet<T>
*/
class Set extends AbstractSet
{
/**
* The type of elements stored in this set
*
* A set's type is immutable. For this reason, this property is private.
*/
private string $setType;
/**
* Constructs a set object of the specified type, optionally with the
* specified data.
*
* @param string $setType The type (FQCN) associated with this set.
* @param array<array-key, T> $data The initial items to store in the set.
*/
public function __construct(string $setType, array $data = [])
{
$this->setType = $setType;
parent::__construct($data);
}
public function getType(): string
{
return $this->setType;
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Tool;
use function is_array;
use function is_bool;
use function is_callable;
use function is_float;
use function is_int;
use function is_numeric;
use function is_object;
use function is_resource;
use function is_scalar;
use function is_string;
/**
* Provides functionality to check values for specific types.
*/
trait TypeTrait
{
/**
* Returns `true` if value is of the specified type.
*
* @param string $type The type to check the value against.
* @param mixed $value The value to check.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
protected function checkType(string $type, $value): bool
{
switch ($type) {
case 'array':
return is_array($value);
case 'bool':
case 'boolean':
return is_bool($value);
case 'callable':
return is_callable($value);
case 'float':
case 'double':
return is_float($value);
case 'int':
case 'integer':
return is_int($value);
case 'null':
return $value === null;
case 'numeric':
return is_numeric($value);
case 'object':
return is_object($value);
case 'resource':
return is_resource($value);
case 'scalar':
return is_scalar($value);
case 'string':
return is_string($value);
case 'mixed':
return true;
default:
return $value instanceof $type;
}
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Tool;
use Ramsey\Collection\Exception\ValueExtractionException;
use function get_class;
use function is_object;
use function method_exists;
use function property_exists;
use function sprintf;
/**
* Provides functionality to extract the value of a property or method from an object.
*/
trait ValueExtractorTrait
{
/**
* Extracts the value of the given property or method from the object.
*
* @param mixed $object The object to extract the value from.
* @param string $propertyOrMethod The property or method for which the
* value should be extracted.
*
* @return mixed the value extracted from the specified property or method.
*
* @throws ValueExtractionException if the method or property is not defined.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
protected function extractValue($object, string $propertyOrMethod)
{
if (!is_object($object)) {
throw new ValueExtractionException('Unable to extract a value from a non-object');
}
if (property_exists($object, $propertyOrMethod)) {
return $object->$propertyOrMethod;
}
if (method_exists($object, $propertyOrMethod)) {
return $object->{$propertyOrMethod}();
}
throw new ValueExtractionException(
// phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall
sprintf('Method or property "%s" not defined in %s', $propertyOrMethod, get_class($object)),
);
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* This file is part of the ramsey/collection library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Collection\Tool;
use DateTimeInterface;
use function get_class;
use function get_resource_type;
use function is_array;
use function is_bool;
use function is_callable;
use function is_object;
use function is_resource;
use function is_scalar;
use function var_export;
/**
* Provides functionality to express a value as string
*/
trait ValueToStringTrait
{
/**
* Returns a string representation of the value.
*
* - null value: `'NULL'`
* - boolean: `'TRUE'`, `'FALSE'`
* - array: `'Array'`
* - scalar: converted-value
* - resource: `'(type resource #number)'`
* - object with `__toString()`: result of `__toString()`
* - object DateTime: ISO 8601 date
* - object: `'(className Object)'`
* - anonymous function: same as object
*
* @param mixed $value the value to return as a string.
*/
// phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
protected function toolValueToString($value): string
{
// null
if ($value === null) {
return 'NULL';
}
// boolean constants
if (is_bool($value)) {
return $value ? 'TRUE' : 'FALSE';
}
// array
if (is_array($value)) {
return 'Array';
}
// scalar types (integer, float, string)
if (is_scalar($value)) {
return (string) $value;
}
// resource
if (is_resource($value)) {
return '(' . get_resource_type($value) . ' resource #' . (int) $value . ')';
}
// If we don't know what it is, use var_export().
if (!is_object($value)) {
return '(' . var_export($value, true) . ')';
}
// From here, $value should be an object.
// __toString() is implemented
if (is_callable([$value, '__toString'])) {
return (string) $value->__toString();
}
// object of type \DateTime
if ($value instanceof DateTimeInterface) {
return $value->format('c');
}
// unknown type
// phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall
return '(' . get_class($value) . ' Object)';
}
}

View File

@@ -1,335 +0,0 @@
# ramsey/uuid Changelog
## 3.6.1
_Released: 2017-03-26_
* Optimize UUID string decoding [#164](https://github.com/ramsey/uuid/pull/164)
## 3.6.0
_Released: 2017-03-18_
* Add `InvalidUuidStringException`, 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` [#162](https://github.com/ramsey/uuid/pull/162)
* Improve memory usage when generating large quantities of UUIDs (use `str_pad()` and `dechex()` instead of `sprintf()`) [#160](https://github.com/ramsey/uuid/pull/160)
* Minor test and documentation updates
## 3.5.2
_Released: 2016-11-22_
* Improved test coverage.
## 3.5.1
_Released: 2016-10-02_
* Fixed issue where same UUIDs were not treated as equal with mixed case ([#131](https://github.com/ramsey/uuid/issues/131), [#137](https://github.com/ramsey/uuid/pull/137)).
* Test cleanup.
## 3.5.0
_Released: 2016-08-02_
* Add `OrderedTimeCodec` to store UUID in an optimized way for InnoDB ([#117](https://github.com/ramsey/uuid/issues/117), [#118](https://github.com/ramsey/uuid/pull/118)).
* Fixed `RandomNodeProvider` to prevent invalid node generation ([#129](https://github.com/ramsey/uuid/pull/129)).
* Cache failed attempt to retrieve system node to avoid multiple system calls ([#107](https://github.com/ramsey/uuid/issues/107), [#121](https://github.com/ramsey/uuid/pull/121)).
* Various test improvements.
## 3.4.1
_Released: 2016-04-23_
* Fixed test that violated a PHP CodeSniffer rule, breaking the build.
## 3.4.0
_Released: 2016-04-23_
* Add `TimestampFirstCombCodec` and `TimestampLastCombCodec` codecs.
* Improve logic of `CombGenerator` for COMB sequential UUIDs.
* Significantly improved test coverage.
## 3.3.0
_Released: 2016-03-22_
* 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][].
* Improved test coverage.
* Update code to conduct to version 1.4 of the Contributor Covenant.
## 3.2.0
_Released: 2016-02-17_
* Add random generator option for use for the PECL libsodium extension.
* Updates to test infrastructure.
## 3.1.0
_Released: 2015-12-17_
* Uuid objects now may be properly serialized/unserialized.
* Update build environments for testing on Travis CI.
## 3.0.1
_Released: 2015-10-21_
* Add project [Contributor Code of Conduct](https://github.com/ramsey/uuid/blob/master/CONDUCT.md)
* Modify Travis CI builds to run tests on multiple CPU architectures
* Clean up code, tests, and documentation
## 3.0.0
_Released: 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.
* BREAK: The root namespace for this package has changed 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.
* BREAK: The UUID [Doctrine field type](http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html) has been moved to [ramsey/uuid-doctrine](https://github.com/ramsey/uuid-doctrine).
* BREAK: The `uuid` console application has been moved to [ramsey/uuid-console](https://github.com/ramsey/uuid-console).
* BREAK: The `Uuid::VERSION` package version constant has been removed.
* See also the release notes for [3.0.0-alpha1][300-alpha1], [3.0.0-alpha2][300-alpha2], [3.0.0-alpha3][300-alpha3], and [3.0.0-beta1][300-beta1].
[300-alpha1]: https://github.com/ramsey/uuid/blob/master/CHANGELOG.md#300-alpha1
[300-alpha2]: https://github.com/ramsey/uuid/blob/master/CHANGELOG.md#300-alpha2
[300-alpha3]: https://github.com/ramsey/uuid/blob/master/CHANGELOG.md#300-alpha3
[300-beta1]: https://github.com/ramsey/uuid/blob/master/CHANGELOG.md#300-beta1
## 3.0.0-beta1
_Released: 2015-08-31_
* 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()`.
* Add Scrutinizer configuration to run code-quality builds through Scrutinizer.
* Auto-fix Scrutinizer issues.
* Fix support URLs in composer.json to point to the correct GitHub repository.
## 3.0.0-alpha3
_Released: 2015-07-28_
* Time generator improvements:
* Enabled use of custom TimeGenerator implementations.
* BREAK: Removed now unnecessary `timeConverter` and `timeProvider` properties, setters, and getters in both `FeatureSet` and `UuidFactory` as those are now exclusively used by the default `TimeGenerator`.
* Added a `setTimeGenerator` method on `UuidFactory` to override the default time generator.
* Add option to enable `PeclUuidTimeGenerator` via `FeatureSet`.
## 3.0.0-alpha2
_Released: 2015-07-28_
* BREAK: Removed `PeclUuidFactory` in favor of using pecl-uuid with generators.
* NEW: Refactored time-based (version 1) UUIDs into a `TimeGeneratorInterface` to allow for other sources to generate version 1 UUIDs in this library.
* NEW: Added `PeclUuidTimeGenerator` and `PeclUuidRandomGenerator` for creating version 1 or version 4 UUIDs using the pecl-uuid extension.
* NEW: Add `RandomBytesGenerator` for use with PHP 7. ramsey/uuid will default to use this generator when running on PHP 7.
* `RandomLibAdapter` now defaults to a medium-strength generator with [ircmaxell/random-lib](https://github.com/ircmaxell/RandomLib). This is configurable, so other generator strengths may be used.
* Migrated to the Travis CI container-based infrastructure for builds.
* Documentation updates and corrections.
## 3.0.0-alpha1
_Released: 2015-07-16_
* BREAK: The root namespace for this package has changed 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.
* BREAK: The UUID [Doctrine field type](http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html) has been moved to [ramsey/uuid-doctrine](https://github.com/ramsey/uuid-doctrine).
* BREAK: The `uuid` console application has been moved to [ramsey/uuid-console](https://github.com/ramsey/uuid-console).
* BREAK: The `Uuid::VERSION` package version constant has been removed.
* NEW: The `Uuid` class is no longer marked 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.
* NEW: Through setting dependencies on `UuidFactory` and/or extending `FeatureSet`, you may override any package defaults, injecting your own dependencies.
* NEW: For random number generation, in addition to `OpenSslGenerator` (used if `openssl_random_pseudo_bytes()` is present) and the fallback `MtRandGenerator`, you may use the bundled `CombGenerator` for sequential UUIDs or the `RandomLibAdapter` if using [ircmaxell/random-lib](https://github.com/ircmaxell/RandomLib).
* NEW: In addition to the default UUID generation, this library also supports GUID generation by configuring a `FeatureSet` to use GUIDs.
* NEW: While the interface to create UUIDs hasn't changed, if using this package on a 32-bit system, you will now receive an object of type `DegradedUuid` (which extends `Uuid`, which implements `UuidInterface`).
* NEW: All UUIDs are now [JsonSerializable](http://php.net/JsonSerializable).
## 2.9.0
_Released: 2016-03-22_
* Drop support for OpenSSL in favor of [paragonie/random_compat][]. This addresses and fixes the [collision issue][].
## 2.8.4
_Released: 2015-12-17_
* Add support for symfony/console v3.
* Update build matrix to run Travis CI tests on PHP 7 & with lowest package versions.
## 2.8.3
_Released: 2015-08-31_
* Fix exception message in `Uuid::calculateUuidTime()`.
* Update composer.json to reflect new repository and package name.
## 2.8.2
_Released: 2015-07-23_
* Ensure the release tag makes it into the rhumsaa/uuid package.
* Minor documentation changes.
## 2.8.1
_Released: 2015-06-16_
* Use `passthru()` and output buffering in `getIfconfig()`.
* Cache the system node in a static variable so that we process it only once per runtime.
* Set ramsey/uuid as a replacement for rhumsaa/uuid in composer.json.
* Documentation updates and corrections.
## 2.8.0
_Released: 2014-11-09_
* Added static `fromInteger()` method to create UUIDs from string integer or `\Moontoast\Math\BigNumber`.
* Friendlier Doctrine conversion to Uuid or string.
* Documentation fixes.
## 2.7.4
_Released: 2014-10-29_
* Changed loop in `generateBytes()` from `foreach` to `for`; see #33
* Use `toString()` in README examples to avoid confusion
* Exclude build/development tools from releases using .gitattributes
* Set timezone properly for tests
## 2.7.3
_Released: 2014-08-27_
* Fixed upper range for `mt_rand` used in version 4 UUIDs
## 2.7.2
_Released: 2014-07-28_
* Upgraded to PSR-4 autoloading
* Testing upgrades:
* Testing against PHP 5.6
* Testing with PHPUnit 4
* Using Coveralls.io to generate code coverage reports
* Documentation fixes
## 2.7.1
_Released: 2014-02-19_
* Moved moontoast/math and symfony/console to require-dev; fixes #20
* Now supporting symfony/console for 2.3 (LTS version); fixes #21
* Updated tests to run even when dev packages are not installed (skips tests if requirements are not met)
## 2.7.0
_Released: 2014-01-31_
* Moved UUID validation regex pattern into constant for external use (`Uuid::VALID_PATTERN`)
## 2.6.1
_Released: 2014-01-27_
* Fixed bug where `uuid` console application could not find the Composer autoloader when installed in another project
## 2.6.0
_Released: 2014-01-17_
* Introduced `uuid` console application for generating and decoding UUIDs from CLI (run `./bin/uuid` for details)
* Added `Uuid::getInteger()` to retrieve a Moontoast\Math\BigNumber representation of the 128-bit integer representing the UUID
* Added `Uuid::getHex()` to retrieve the hexadecimal representation of the UUID
* Now using netstat on Linux to capture the node for a version 1 UUID
* Now requiring Moontoast\Math as part of the regular package requirements, not just the dev requirements
## 2.5.0
_Released: 2013-10-30_
* Using `openssl_random_pseudo_bytes()`, if available, to generate random bytes, by merging in PR #15 from @dfreudenberger
* Fixed test for Rhumsaa\Uuid\Doctrine\UuidType, by merging in PR #17 from @dfreudenberger
* Documentation fixes
## 2.4.0
_Released: 2013-07-29_
* `Uuid::getVersion()` now returns null if the UUID isn't an RFC 4122 variant
* `Uuid::fromString()` now supports a 128-bit integer formatted as a hexadecimal string (UUID without dashes)
* Tests have been greatly enhanced, borrowing from the Python UUID library
## 2.3.0
_Released: 2013-07-16_
* Added `Uuid::fromBytes()` by merging in PR #14 from @asm89
## 2.2.0
_Released: 2013-07-04_
* Added `Doctrine\UuidType::requiresSQLCommentHint()` method by merging in PR #13 from @zerrvox
* Removed `"minimum-stability": "dev"` from composer.json
## 2.1.2
_Released: 2013-07-03_
* @ericthelin found 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
_Released: 2013-04-29_
* Fixed NIL bug in `Uuid::isValid()` method, reported by @ocubom in PR #11
## 2.1.0
_Released: 2013-04-15_
* Added static `Uuid::isValid()` method for checking whether a string is a valid UUID
## 2.0.0
_Released: 2013-02-11_
* Break: `Uuid` class is now marked as "final"
* Break: `Uuid::getLeastSignificantBits()` no longer returns an integer on 64-bit platforms; it requires `moontoast/math`
* Break: `Uuid::getMostSignificantBits()` no longer returns an integer on 64-bit platforms; it requires `moontoast/math`
* Break: Moved `UnsupportedOperationException` to the `Exception` subnamespace
* Added support for 32-bit platforms
* Added generated API documentation to the repository
## 1.1.2
_Released: 2012-11-29_
* Relaxed Doctrine type conversion rules
## 1.1.1
_Released: 2012-08-27_
* Removed `final` keyword from `Uuid` class
## 1.1.0
_Released: 2012-08-06_
* Added `Doctrine\UuidType` as a field mapping type for the Doctrine Database Abstraction Layer (DBAL)
* Improved tests and code coverage
## 1.0.0
_Released: 2012-07-19_
* Initial release
[paragonie/random_compat]: https://github.com/paragonie/random_compat
[collision issue]: https://github.com/ramsey/uuid/issues/80

View File

@@ -1,74 +0,0 @@
# 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 at <ben@benramsey.com>. 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 [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,75 +0,0 @@
# Contributing
Contributions are welcome. We accept pull requests on [GitHub](https://github.com/ramsey/uuid).
This project adheres to a [Contributor Code of Conduct](https://github.com/ramsey/uuid/blob/master/CODE_OF_CONDUCT.md). By participating in this project and its community, you are expected to uphold this code.
## Team members
* [Ben Ramsey](https://github.com/ramsey) - original author and maintainer
* [Marijn Huizendveld](https://github.com/marijn) - contributor, author of UUID type definition for Doctrine DBAL
* [Thibaud Fabre](https://github.com/aztech-dev) - contributor, lead developer for version 3.0.0 re-architecture
## Communication Channels
You can find help and discussion in the following places:
* GitHub Issues: <https://github.com/ramsey/uuid/issues>
* Wiki: <https://github.com/ramsey/uuid/wiki>
## Reporting Bugs
Bugs are tracked in our project's [issue tracker](https://github.com/ramsey/uuid/issues).
When submitting a bug report, please include enough information for us to reproduce the bug. A good bug report includes the following sections:
* Expected outcome
* Actual outcome
* Steps to reproduce, including sample code
* Any other information that will help us debug and reproduce the issue, including stack traces, system/environment information, and screenshots
**Please do not include passwords or any personally identifiable information in your bug report and sample code.**
## Fixing Bugs
We welcome 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 us pull requests.
## Adding New Features
If you have an idea for a new feature, it's a good idea to check out our [issues](https://github.com/ramsey/uuid/issues) or active [pull requests](https://github.com/ramsey/uuid/pulls) first to see if the feature is already being worked on. 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 just 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 add to our CHANGELOG. If there is no description or it does not adequately describe your feature, we will ask you to update the description.
* We following the **[PSR-2 coding standard](http://www.php-fig.org/psr/psr-2/)**. Please ensure your code does, too.
* Please **write tests** for any new features you add.
* Please **ensure that tests pass** before submitting your pull request. We have Travis CI automatically running tests for pull requests. However, running the tests locally will help save time.
* **Use topic/feature branches.** Please do not ask us to pull from your master branch.
* **Submit one feature per pull request.** If you have multiple features you wish to submit, please break them up into separate pull requests.
* **Send coherent history**. Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
## Running Tests
The following tests must pass before we will accept a pull request. If any of these do not pass, it will result in a complete build failure. Before you can run these, be sure to `composer install`.
```
composer test
```
### Locally Test With Emulated MIPS Architecture
The following commands use [Vagrant](https://www.vagrantup.com/) to start an Ubuntu VM, install necessary dependencies, and then run the `util/run-tests.sh` script that will download a Docker image emulating the MIPS architecture. This is especially helpful for testing UUID generation in a big-endian environment.
```
vagrant init ubuntu/trusty64
vagrant up
vagrant ssh
sudo apt-get install docker.io qemu-user-static php5-cli php5-curl
cd /vagrant
curl -sS https://getcomposer.org/installer | php
php composer.phar install --no-interaction --prefer-dist
mkdir -p build/logs
ARCH=mips PHP_VERSION=5.6.14 TRAVIS_BUILD_DIR=/vagrant ./util/run-tests.sh
```

View File

@@ -1,4 +1,4 @@
Copyright (c) 2012-2017 Ben Ramsey <ben@benramsey.com>
Copyright (c) 2012-2022 Ben Ramsey <ben@benramsey.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -7,13 +7,13 @@ 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 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.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,159 +1,83 @@
# ramsey/uuid
<h1 align="center">ramsey/uuid</h1>
_NOTICE: Formerly known as `rhumsaa/uuid`, The package and namespace names have changed to `ramsey/uuid` and `Ramsey\Uuid`, respectively._
<p align="center">
<strong>A PHP library for generating and working with UUIDs.</strong>
</p>
[![Source Code][badge-source]][source]
[![Latest Version][badge-release]][release]
[![Software License][badge-license]][license]
[![Build Status][badge-build]][build]
[![Coverage Status][badge-coverage]][coverage]
[![Total Downloads][badge-downloads]][downloads]
<p align="center">
<a href="https://github.com/ramsey/uuid"><img src="http://img.shields.io/badge/source-ramsey/uuid-blue.svg?style=flat-square" alt="Source Code"></a>
<a href="https://packagist.org/packages/ramsey/uuid"><img src="https://img.shields.io/packagist/v/ramsey/uuid.svg?style=flat-square&label=release" alt="Download Package"></a>
<a href="https://php.net"><img src="https://img.shields.io/packagist/php-v/ramsey/uuid.svg?style=flat-square&colorB=%238892BF" alt="PHP Programming Language"></a>
<a href="https://github.com/ramsey/uuid/blob/4.x/LICENSE"><img src="https://img.shields.io/packagist/l/ramsey/uuid.svg?style=flat-square&colorB=darkcyan" alt="Read License"></a>
<a href="https://github.com/ramsey/uuid/actions/workflows/continuous-integration.yml"><img src="https://img.shields.io/github/actions/workflow/status/ramsey/uuid/continuous-integration.yml?branch=4.x&logo=github&style=flat-square" alt="Build Status"></a>
<a href="https://app.codecov.io/gh/ramsey/uuid/branch/4.x"><img src="https://img.shields.io/codecov/c/github/ramsey/uuid/4.x?label=codecov&logo=codecov&style=flat-square" alt="Codecov Code Coverage"></a>
<a href="https://shepherd.dev/github/ramsey/uuid"><img src="https://img.shields.io/endpoint?style=flat-square&url=https%3A%2F%2Fshepherd.dev%2Fgithub%2Framsey%2Fuuid%2Fcoverage" alt="Psalm Type Coverage"></a>
</p>
ramsey/uuid is a PHP 5.4+ library for generating and working with [RFC 4122][rfc4122] version 1, 3, 4, and 5 universally unique identifiers (UUID).
ramsey/uuid is a PHP library for generating and working with universally unique
identifiers (UUIDs).
This project adheres to a [Contributor Code of Conduct][conduct]. By participating in this project and its community, you are expected to uphold this code.
## About
From [Wikipedia](http://en.wikipedia.org/wiki/Universally_unique_identifier):
> The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean "practically unique" rather than "guaranteed unique". Since the identifiers have a finite size, it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.
Much inspiration for this library came from the [Java][javauuid] and [Python][pyuuid] UUID libraries.
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 [Packagist][] and [Composer][]. Run the following command to install the package and add it as a requirement to your project's `composer.json`:
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
## Upgrading from 2.x to 3.x
See the documentation for a thorough upgrade guide:
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.
* [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/stable/upgrading/3-to-4.html)
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."
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](https://packagist.org/packages/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](https://packagist.org/packages/ramsey/uuid-doctrine). If using the Doctrine functionality, use Composer to require `ramsey/uuid-doctrine`.
## What to do if you see a "rhumsaa/uuid is abandoned" message
When installing your project's dependencies using Composer, you might see the following message:
```
Package rhumsaa/uuid is abandoned, you should avoid using it. Use ramsey/uuid instead.
```
Don't panic. Simply execute the following commands with Composer:
``` 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`.
## Requirements
Some methods in this library have requirements due to integer size restrictions on 32-bit and 64-bit builds of PHP. A 64-bit build of PHP and the [Moontoast\Math][] library are recommended. However, this library is designed to work on 32-bit builds of PHP without Moontoast\Math, with some degraded functionality. Please check the API documentation for more information.
If a particular requirement is not present, then an `UnsatisfiedDependencyException` is thrown, allowing one to catch a bad call in an environment where the call is not supported and gracefully degrade.
## API documentation
The [latest class API documentation][apidocs] is available online.
This project uses [ApiGen](http://apigen.org/) to generate this documentation. To generate the documentation on your own, install dev dependencies and run the following command from the root of the project:
```
composer build-docs
```
This will generate documentation in the `build/apidocs/` folder.
## Examples
See the [cookbook on the wiki][wiki-cookbook] for more examples and approaches to specific use-cases.
```php
<?php
require 'vendor/autoload.php';
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
try {
// Generate a version 1 (time-based) UUID object
$uuid1 = Uuid::uuid1();
echo $uuid1->toString() . "\n"; // i.e. e4eaaaf2-d142-11e1-b3e4-080027620cdd
// Generate a version 3 (name-based and hashed with MD5) UUID object
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid3->toString() . "\n"; // i.e. 11a38b9a-b3da-360f-9353-a5a725514269
// Generate a version 4 (random) UUID object
$uuid4 = Uuid::uuid4();
echo $uuid4->toString() . "\n"; // i.e. 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a
// Generate a version 5 (name-based and hashed with SHA1) UUID object
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid5->toString() . "\n"; // i.e. c4a760a8-dbcf-5254-a0d9-6a4474bd1b62
} catch (UnsatisfiedDependencyException $e) {
// Some dependency was not met. Either the method cannot be called on a
// 32-bit system, or it can, but it relies on Moontoast\Math to be present.
echo 'Caught exception: ' . $e->getMessage() . "\n";
}
```
## Documentation
Please see <https://uuid.ramsey.dev> for documentation, tips, examples, and
frequently asked questions.
## Contributing
Contributions are welcome! Please read [CONTRIBUTING][] for details.
Contributions are welcome! To contribute, please familiarize yourself with
[CONTRIBUTING.md](CONTRIBUTING.md).
## Coordinated Disclosure
## Copyright and license
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.
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.
## 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/master/CODE_OF_CONDUCT.md
[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
[packagist]: https://packagist.org/packages/ramsey/uuid
[composer]: http://getcomposer.org/
[moontoast\math]: https://packagist.org/packages/moontoast/math
[apidocs]: http://docs.benramsey.com/ramsey-uuid/latest/
[wiki-cookbook]: https://github.com/ramsey/uuid/wiki/Ramsey%5CUuid-Cookbook
[contributing]: https://github.com/ramsey/uuid/blob/master/CONTRIBUTING.md
[badge-source]: https://img.shields.io/badge/source-ramsey/uuid-blue.svg?style=flat-square
[badge-release]: https://img.shields.io/packagist/v/ramsey/uuid.svg?style=flat-square
[badge-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[badge-build]: https://img.shields.io/travis/ramsey/uuid/master.svg?style=flat-square
[badge-coverage]: https://img.shields.io/coveralls/ramsey/uuid/master.svg?style=flat-square
[badge-downloads]: https://img.shields.io/packagist/dt/ramsey/uuid.svg?style=flat-square
[source]: https://github.com/ramsey/uuid
[release]: https://packagist.org/packages/ramsey/uuid
[license]: https://github.com/ramsey/uuid/blob/master/LICENSE
[build]: https://travis-ci.org/ramsey/uuid
[coverage]: https://coveralls.io/r/ramsey/uuid?branch=master
[downloads]: https://packagist.org/packages/ramsey/uuid
[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

View File

@@ -1,78 +1,108 @@
{
"name": "ramsey/uuid",
"description": "Formerly rhumsaa/uuid. A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID).",
"type": "library",
"keywords": ["uuid", "identifier", "guid"],
"homepage": "https://github.com/ramsey/uuid",
"description": "A PHP library for generating and working with universally unique identifiers (UUIDs).",
"license": "MIT",
"authors": [
{
"name": "Ben Ramsey",
"email": "ben@benramsey.com",
"homepage": "https://benramsey.com"
},
{
"name": "Marijn Huizendveld",
"email": "marijn.huizendveld@gmail.com"
},
{
"name": "Thibaud Fabre",
"email": "thibaud@aztech.io"
}
"type": "library",
"keywords": [
"uuid",
"identifier",
"guid"
],
"support": {
"issues": "https://github.com/ramsey/uuid/issues",
"source": "https://github.com/ramsey/uuid"
},
"require": {
"php": "^5.4 || ^7.0",
"paragonie/random_compat": "^1.0|^2.0"
"php": "^8.0",
"ext-json": "*",
"brick/math": "^0.8.8 || ^0.9 || ^0.10",
"ramsey/collection": "^1.2"
},
"require-dev": {
"moontoast/math": "^1.1",
"ircmaxell/random-lib": "^1.1",
"phpunit/phpunit": "^4.7|>=5.0 <5.4",
"squizlabs/php_codesniffer": "^2.3",
"jakub-onderka/php-parallel-lint": "^0.9.0",
"satooshi/php-coveralls": "^0.6.1",
"apigen/apigen": "^4.1",
"mockery/mockery": "^0.9.4",
"goaop/framework": "1.0.0-alpha.2 | ^1.0 | ^2.1",
"doctrine/annotations": "~1.2.0",
"codeception/aspect-mock": "^1.0 | ^2.0",
"php-mock/php-mock-phpunit": "^0.3|^1.1"
},
"suggest": {
"ircmaxell/random-lib": "Provides RandomLib for use with the RandomLibAdapter",
"ext-libsodium": "Provides the PECL libsodium extension for use with the SodiumRandomGenerator",
"ext-uuid": "Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator",
"moontoast/math": "Provides support for converting UUID to 128-bit integer (in string form).",
"ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type.",
"ramsey/uuid-console": "A console application for generating UUIDs with ramsey/uuid"
},
"autoload": {
"psr-4": {"Ramsey\\Uuid\\": "src/"}
},
"autoload-dev": {
"psr-4": {"Ramsey\\Uuid\\Test\\": "tests/"}
"captainhook/captainhook": "^5.10",
"captainhook/plugin-composer": "^5.3",
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
"doctrine/annotations": "^1.8",
"ergebnis/composer-normalize": "^2.15",
"mockery/mockery": "^1.3",
"paragonie/random-lib": "^2",
"php-mock/php-mock": "^2.2",
"php-mock/php-mock-mockery": "^1.3",
"php-parallel-lint/php-parallel-lint": "^1.1",
"phpbench/phpbench": "^1.0",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan": "^1.8",
"phpstan/phpstan-mockery": "^1.1",
"phpstan/phpstan-phpunit": "^1.1",
"phpunit/phpunit": "^8.5 || ^9",
"ramsey/composer-repl": "^1.4",
"slevomat/coding-standard": "^8.4",
"squizlabs/php_codesniffer": "^3.5",
"vimeo/psalm": "^4.9"
},
"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,
"ergebnis/composer-normalize": true,
"phpstan/extension-installer": true,
"dealerdirect/phpcodesniffer-composer-installer": true,
"ramsey/composer-repl": true
},
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
"captainhook": {
"force-install": true
}
},
"scripts": {
"analyze": [
"@phpstan",
"@psalm"
],
"build:clean": "git clean -fX build/",
"lint": "parallel-lint src tests",
"lint:paths": "parallel-lint",
"phpbench": "phpbench run",
"phpcbf": "phpcbf -vpw --cache=build/cache/phpcs.cache",
"phpcs": "phpcs --cache=build/cache/phpcs.cache",
"phpstan": [
"phpstan analyse --no-progress --memory-limit=1G",
"phpstan analyse -c phpstan-tests.neon --no-progress --memory-limit=1G"
],
"phpunit": "phpunit --verbose --colors=always",
"phpcs": "phpcs src tests --standard=psr2 -sp --colors",
"phpunit-coverage": "phpunit --verbose --colors=always --coverage-html build/coverage",
"psalm": "psalm --show-info=false --config=psalm.xml",
"test": [
"@lint",
"@phpunit",
"@phpcs"
],
"build-docs": "apigen generate --source='src' --destination='build/apidocs' --template-theme='bootstrap' --deprecated --todo"
"@phpbench",
"@phpcs",
"@phpstan",
"@psalm",
"@phpunit"
]
}
}

View File

@@ -1,5 +1,17 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid;
/**
@@ -8,34 +20,42 @@ namespace Ramsey\Uuid;
class BinaryUtils
{
/**
* Applies the RFC 4122 variant field to the `clock_seq_hi_and_reserved` field
* Applies the RFC 4122 variant field to the 16-bit clock sequence
*
* @param $clockSeqHi
* @return int The high field of the clock sequence multiplexed with the variant
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant
*
* @param int $clockSeq The 16-bit clock sequence value before the RFC 4122
* variant is applied
*
* @return int The 16-bit clock sequence multiplexed with the UUID variant
*
* @psalm-pure
*/
public static function applyVariant($clockSeqHi)
public static function applyVariant(int $clockSeq): int
{
// Set the variant to RFC 4122
$clockSeqHi = $clockSeqHi & 0x3f;
$clockSeqHi &= ~(0xc0);
$clockSeqHi |= 0x80;
$clockSeq = $clockSeq & 0x3fff;
$clockSeq |= 0x8000;
return $clockSeqHi;
return $clockSeq;
}
/**
* Applies the RFC 4122 version number to the `time_hi_and_version` field
* Applies the RFC 4122 version number to the 16-bit `time_hi_and_version` field
*
* @param string $timeHi
* @param integer $version
* @return int The high field of the timestamp multiplexed with the version number
* @link http://tools.ietf.org/html/rfc4122#section-4.1.3
* @link http://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version
*
* @param int $timeHi The value of the 16-bit `time_hi_and_version` field
* before the RFC 4122 version is applied
* @param int $version The RFC 4122 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
*
* @psalm-pure
*/
public static function applyVersion($timeHi, $version)
public static function applyVersion(int $timeHi, int $version): int
{
$timeHi = hexdec($timeHi) & 0x0fff;
$timeHi &= ~(0xf000);
$timeHi = $timeHi & 0x0fff;
$timeHi |= $version << 12;
return $timeHi;

View File

@@ -0,0 +1,85 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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<T>` instead.
*
* @extends AbstractCollection<UuidBuilderInterface>
*/
class BuilderCollection extends AbstractCollection
{
public function getType(): string
{
return UuidBuilderInterface::class;
}
/**
* @psalm-mutation-free
* @psalm-suppress ImpureMethodCall
* @psalm-suppress InvalidTemplateParam
*/
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
*
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @psalm-suppress RedundantConditionGivenDocblockType
*/
public function unserialize($serialized): void
{
/** @var array<array-key, UuidBuilderInterface> $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 {
return $unserialized instanceof UuidBuilderInterface;
}
);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,48 +8,19 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder;
/**
* DefaultUuidBuilder is the default UUID builder for ramsey/uuid; it builds
* instances of Uuid objects
* @deprecated Transition to {@see Rfc4122UuidBuilder}.
*
* @psalm-immutable
*/
class DefaultUuidBuilder implements UuidBuilderInterface
class DefaultUuidBuilder extends Rfc4122UuidBuilder
{
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs the DefaultUuidBuilder
*
* @param NumberConverterInterface $converter The number converter to use when constructing the Uuid
*/
public function __construct(NumberConverterInterface $converter)
{
$this->converter = $converter;
}
/**
* Builds a Uuid
*
* @param CodecInterface $codec The codec to use for building this Uuid
* @param array $fields An array of fields from which to construct the Uuid;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return Uuid
*/
public function build(CodecInterface $codec, array $fields)
{
return new Uuid($fields, $this->converter, $codec);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,47 +8,60 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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;
/**
* DegradedUuidBuilder builds instances of DegradedUuid
* @deprecated DegradedUuid instances are no longer necessary to support 32-bit
* systems. Transition to {@see DefaultUuidBuilder}.
*
* @psalm-immutable
*/
class DegradedUuidBuilder implements UuidBuilderInterface
{
/**
* @var NumberConverterInterface
*/
private $converter;
private TimeConverterInterface $timeConverter;
/**
* Constructs the DegradedUuidBuilder
*
* @param NumberConverterInterface $converter The number converter to use when constructing the DegradedUuid
* @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(NumberConverterInterface $converter)
{
$this->converter = $converter;
public function __construct(
private NumberConverterInterface $numberConverter,
?TimeConverterInterface $timeConverter = null
) {
$this->timeConverter = $timeConverter ?: new DegradedTimeConverter();
}
/**
* Builds a DegradedUuid
* Builds and returns a DegradedUuid
*
* @param CodecInterface $codec The codec to use for building this DegradedUuid
* @param array $fields An array of fields from which to construct the DegradedUuid;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return 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
*
* @psalm-pure
*/
public function build(CodecInterface $codec, array $fields)
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
return new DegradedUuid($fields, $this->converter, $codec);
return new DegradedUuid(
new Rfc4122Fields($bytes),
$this->numberConverter,
$codec,
$this->timeConverter
);
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-immutable
*/
class FallbackBuilder implements UuidBuilderInterface
{
/**
* @param iterable<UuidBuilderInterface> $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
*
* @psalm-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
);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,28 +8,32 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\UuidInterface;
/**
* UuidBuilderInterface builds instances UuidInterface
* A UUID builder builds instances of UuidInterface
*
* @psalm-immutable
*/
interface UuidBuilderInterface
{
/**
* Builds an instance of a UuidInterface
* Builds and returns a UuidInterface
*
* @param CodecInterface $codec The codec to use for building this UuidInterface instance
* @param array $fields An array of fields from which to construct a UuidInterface instance;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return UuidInterface
* @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
*
* @psalm-pure
*/
public function build(CodecInterface $codec, array $fields);
public function build(CodecInterface $codec, string $bytes): UuidInterface;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,49 +8,64 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Codec;
use Ramsey\Uuid\UuidInterface;
/**
* CodecInterface represents a UUID coder-decoder
* A codec encodes and decodes a UUID according to defined rules
*
* @psalm-immutable
*/
interface CodecInterface
{
/**
* Encodes a UuidInterface as a string representation of a UUID
* Returns a hexadecimal string representation of a UuidInterface
*
* @param UuidInterface $uuid The UUID for which to create a hexadecimal
* string representation
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a UUID
*
* @psalm-return non-empty-string
*/
public function encode(UuidInterface $uuid);
public function encode(UuidInterface $uuid): string;
/**
* Encodes a UuidInterface as a binary representation of a UUID
* Returns a binary string representation of a UuidInterface
*
* @param UuidInterface $uuid The UUID for which to create a binary string
* representation
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
*
* @psalm-return non-empty-string
*/
public function encodeBinary(UuidInterface $uuid);
public function encodeBinary(UuidInterface $uuid): string;
/**
* Decodes a string representation of a UUID into a UuidInterface object instance
* Returns a UuidInterface derived from a hexadecimal string representation
*
* @param string $encodedUuid
* @return UuidInterface
* @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
*/
public function decode($encodedUuid);
public function decode(string $encodedUuid): UuidInterface;
/**
* Decodes a binary representation of a UUID into a UuidInterface object instance
* Returns a UuidInterface derived from a binary string representation
*
* @param string $bytes
* @return UuidInterface
* @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
*/
public function decodeBytes($bytes);
public function decodeBytes(string $bytes): UuidInterface;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,94 +8,69 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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)
*
* @link https://en.wikipedia.org/wiki/Globally_unique_identifier
* @see Guid
*
* @psalm-immutable
*/
class GuidStringCodec extends StringCodec
{
/**
* Encodes a UuidInterface as a string representation of a GUID
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a GUID
*/
public function encode(UuidInterface $uuid)
public function encode(UuidInterface $uuid): string
{
$components = array_values($uuid->getFieldsHex());
$hex = bin2hex($uuid->getFields()->getBytes());
// Swap byte-order on the first three fields
$this->swapFields($components);
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$components
/** @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),
);
}
/**
* Encodes a UuidInterface as a binary representation of a GUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a GUID
*/
public function encodeBinary(UuidInterface $uuid)
public function decode(string $encodedUuid): UuidInterface
{
$components = array_values($uuid->getFieldsHex());
$bytes = $this->getBytes($encodedUuid);
return hex2bin(implode('', $components));
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
/**
* Decodes a string representation of a GUID into a UuidInterface object instance
*
* @param string $encodedUuid
* @return UuidInterface
*/
public function decode($encodedUuid)
{
$components = $this->extractComponents($encodedUuid);
$this->swapFields($components);
return $this->getBuilder()->build($this, $this->getFields($components));
}
/**
* Decodes a binary representation of a GUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
public function decodeBytes(string $bytes): UuidInterface
{
// Specifically call parent::decode to preserve correct byte order
return parent::decode(bin2hex($bytes));
}
/**
* Swaps fields to support GUID byte order
*
* @param array $components An array of UUID components (the UUID exploded on its dashes)
* @return void
* Swaps bytes according to the GUID rules
*/
protected function swapFields(array &$components)
private function swapBytes(string $bytes): string
{
$hex = unpack('H*', pack('L', hexdec($components[0])));
$components[0] = $hex[1];
$hex = unpack('H*', pack('S', hexdec($components[1])));
$components[1] = $hex[1];
$hex = unpack('H*', pack('S', hexdec($components[2])));
$components[2] = $hex[1];
return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0]
. $bytes[5] . $bytes[4]
. $bytes[7] . $bytes[6]
. substr($bytes, 8);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,61 +8,106 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Codec;
use InvalidArgumentException;
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 optimizes the bytes to increment UUIDs when time goes by, to improve database INSERTs.
* The string value will be unchanged from StringCodec. Only works for UUID type 1.
* 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
* INSERTs and SELECTs 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.
*
* @link https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ Storing UUID Values in MySQL
*
* @psalm-immutable
*/
class OrderedTimeCodec extends StringCodec
{
/**
* Encodes a UuidInterface as an optimized binary representation of a UUID
* Returns a binary string representation of a UUID, with the timestamp
* fields rearranged for optimized storage
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
* @inheritDoc
* @psalm-return non-empty-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function encodeBinary(UuidInterface $uuid)
public function encodeBinary(UuidInterface $uuid): string
{
$fields = $uuid->getFieldsHex();
$optimized = [
$fields['time_hi_and_version'],
$fields['time_mid'],
$fields['time_low'],
$fields['clock_seq_hi_and_reserved'],
$fields['clock_seq_low'],
$fields['node'],
];
return hex2bin(implode('', $optimized));
}
/**
* Decodes an optimized binary representation of a UUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
if (
!($uuid->getFields() instanceof Rfc4122FieldsInterface)
|| $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME
) {
throw new InvalidArgumentException(
'Expected RFC 4122 version 1 (time-based) UUID'
);
}
$hex = unpack('H*', $bytes)[1];
$bytes = $uuid->getFields()->getBytes();
// Rearrange the fields to their original order
$hex = substr($hex, 8, 4) . substr($hex, 12, 4) . substr($hex, 4, 4) . substr($hex, 0, 4) . substr($hex, 16);
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $bytes[6] . $bytes[7]
. $bytes[4] . $bytes[5]
. $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3]
. substr($bytes, 8);
}
return $this->decode($hex);
/**
* 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);
if (
!($uuid->getFields() instanceof Rfc4122FieldsInterface)
|| $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME
) {
throw new UnsupportedOperationException(
'Attempting to decode a non-time-based UUID using '
. 'OrderedTimeCodec'
);
}
return $uuid;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,161 +8,124 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Codec;
use InvalidArgumentException;
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 4122 UUIDs
*
* @link http://tools.ietf.org/html/rfc4122
*
* @psalm-immutable
*/
class StringCodec implements CodecInterface
{
/**
* @var UuidBuilderInterface
*/
private $builder;
/**
* Constructs a StringCodec for use encoding and decoding UUIDs
* Constructs a StringCodec
*
* @param UuidBuilderInterface $builder The UUID builder to use when encoding UUIDs
* @param UuidBuilderInterface $builder The builder to use when encoding UUIDs
*/
public function __construct(UuidBuilderInterface $builder)
public function __construct(private UuidBuilderInterface $builder)
{
$this->builder = $builder;
}
/**
* Encodes a UuidInterface as a string representation of a UUID
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a UUID
*/
public function encode(UuidInterface $uuid)
public function encode(UuidInterface $uuid): string
{
$fields = array_values($uuid->getFieldsHex());
$hex = bin2hex($uuid->getFields()->getBytes());
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$fields
/** @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),
);
}
/**
* Encodes a UuidInterface as a binary representation of a UUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
* @psalm-return non-empty-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function encodeBinary(UuidInterface $uuid)
public function encodeBinary(UuidInterface $uuid): string
{
return hex2bin($uuid->getHex());
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $uuid->getFields()->getBytes();
}
/**
* Decodes a string representation of a UUID into a UuidInterface object instance
* @throws InvalidUuidStringException
*
* @param string $encodedUuid
* @return UuidInterface
* @inheritDoc
*/
public function decode($encodedUuid)
public function decode(string $encodedUuid): UuidInterface
{
$components = $this->extractComponents($encodedUuid);
$fields = $this->getFields($components);
return $this->builder->build($this, $fields);
return $this->builder->build($this, $this->getBytes($encodedUuid));
}
/**
* Decodes a binary representation of a UUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
public function decodeBytes(string $bytes): UuidInterface
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
throw new InvalidArgumentException(
'$bytes string should contain 16 characters.'
);
}
$hexUuid = unpack('H*', $bytes);
return $this->decode($hexUuid[1]);
return $this->builder->build($this, $bytes);
}
/**
* Returns the UUID builder
*
* @return UuidBuilderInterface
*/
protected function getBuilder()
protected function getBuilder(): UuidBuilderInterface
{
return $this->builder;
}
/**
* Returns an array of UUID components (the UUID exploded on its dashes)
*
* @param string $encodedUuid
* @return array
* Returns a byte string of the UUID
*/
protected function extractComponents($encodedUuid)
protected function getBytes(string $encodedUuid): string
{
$nameParsed = str_replace(array(
'urn:',
'uuid:',
'{',
'}',
'-'
), '', $encodedUuid);
// We have stripped out the dashes and are breaking up the string using
// substr(). In this way, we can accept a full hex value that doesn't
// contain dashes.
$components = array(
substr($nameParsed, 0, 8),
substr($nameParsed, 8, 4),
substr($nameParsed, 12, 4),
substr($nameParsed, 16, 4),
substr($nameParsed, 20)
$parsedUuid = str_replace(
['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}', '-'],
'',
$encodedUuid
);
$nameParsed = implode('-', $components);
$components = [
substr($parsedUuid, 0, 8),
substr($parsedUuid, 8, 4),
substr($parsedUuid, 12, 4),
substr($parsedUuid, 16, 4),
substr($parsedUuid, 20),
];
if (!Uuid::isValid($nameParsed)) {
throw new InvalidUuidStringException('Invalid UUID string: ' . $encodedUuid);
if (!Uuid::isValid(implode('-', $components))) {
throw new InvalidUuidStringException(
'Invalid UUID string: ' . $encodedUuid
);
}
return $components;
}
/**
* Returns the fields that make up this UUID
*
* @see \Ramsey\Uuid\UuidInterface::getFieldsHex()
* @param array $components
* @return array
*/
protected function getFields(array $components)
{
return array(
'time_low' => str_pad($components[0], 8, '0', STR_PAD_LEFT),
'time_mid' => str_pad($components[1], 4, '0', STR_PAD_LEFT),
'time_hi_and_version' => str_pad($components[2], 4, '0', STR_PAD_LEFT),
'clock_seq_hi_and_reserved' => str_pad(substr($components[3], 0, 2), 2, '0', STR_PAD_LEFT),
'clock_seq_low' => str_pad(substr($components[3], 2), 2, '0', STR_PAD_LEFT),
'node' => str_pad($components[4], 12, '0', STR_PAD_LEFT)
);
return (string) hex2bin($parsedUuid);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,99 +8,106 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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;
/**
* TimestampLastCombCodec encodes and decodes COMB UUIDs which have the timestamp as the first 48 bits.
* To be used with MySQL, PostgreSQL, Oracle.
* 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.
*
* ``` php
* $factory = new UuidFactory();
*
* $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder()));
*
* $factory->setRandomGenerator(new CombGenerator(
* $factory->getRandomGenerator(),
* $factory->getNumberConverter()
* ));
*
* $timestampFirstComb = $factory->uuid4();
* ```
*
* @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
*
* @psalm-immutable
*/
class TimestampFirstCombCodec extends StringCodec
{
/**
* Encodes a UuidInterface as a string representation of a timestamp first COMB UUID
*
* @param UuidInterface $uuid
*
* @return string Hexadecimal string representation of a GUID
* @psalm-return non-empty-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function encode(UuidInterface $uuid)
public function encode(UuidInterface $uuid): string
{
$sixPieceComponents = array_values($uuid->getFieldsHex());
$bytes = $this->swapBytes($uuid->getFields()->getBytes());
$this->swapTimestampAndRandomBits($sixPieceComponents);
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$sixPieceComponents
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))
);
}
/**
* Encodes a UuidInterface as a binary representation of timestamp first COMB UUID
*
* @param UuidInterface $uuid
*
* @return string Binary string representation of timestamp first COMB UUID
* @psalm-return non-empty-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function encodeBinary(UuidInterface $uuid)
public function encodeBinary(UuidInterface $uuid): string
{
$stringEncoding = $this->encode($uuid);
return hex2bin(str_replace('-', '', $stringEncoding));
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $this->swapBytes($uuid->getFields()->getBytes());
}
/**
* Decodes a string representation of timestamp first COMB UUID into a UuidInterface object instance
* @throws InvalidUuidStringException
*
* @param string $encodedUuid
*
* @return UuidInterface
* @inheritDoc
*/
public function decode($encodedUuid)
public function decode(string $encodedUuid): UuidInterface
{
$fivePieceComponents = $this->extractComponents($encodedUuid);
$bytes = $this->getBytes($encodedUuid);
$this->swapTimestampAndRandomBits($fivePieceComponents);
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
return $this->getBuilder()->build($this, $this->getFields($fivePieceComponents));
public function decodeBytes(string $bytes): UuidInterface
{
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
/**
* Decodes a binary representation of timestamp first COMB UUID into a UuidInterface object instance
*
* @param string $bytes
*
* @return UuidInterface
* Swaps bytes according to the timestamp-first COMB rules
*/
public function decodeBytes($bytes)
private function swapBytes(string $bytes): string
{
return $this->decode(bin2hex($bytes));
}
$first48Bits = substr($bytes, 0, 6);
$last48Bits = substr($bytes, -6);
/**
* Swaps the first 48 bits with the last 48 bits
*
* @param array $components An array of UUID components (the UUID exploded on its dashes)
*
* @return void
*/
protected function swapTimestampAndRandomBits(array &$components)
{
$last48Bits = $components[4];
if (count($components) == 6) {
$last48Bits = $components[5];
$components[5] = $components[0] . $components[1];
} else {
$components[4] = $components[0] . $components[1];
}
$bytes = substr_replace($bytes, $last48Bits, 0, 6);
$bytes = substr_replace($bytes, $first48Bits, -6);
$components[0] = substr($last48Bits, 0, 8);
$components[1] = substr($last48Bits, 8, 4);
return $bytes;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,17 +8,44 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Codec;
/**
* TimestampLastCombCodec encodes and decodes COMB UUIDs which have the timestamp as the last 48 bits.
* To be used with MSSQL.
* 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.
*
* ``` php
* $factory = new UuidFactory();
*
* $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder()));
*
* $factory->setRandomGenerator(new CombGenerator(
* $factory->getRandomGenerator(),
* $factory->getNumberConverter()
* ));
*
* $timestampLastComb = $factory->uuid4();
* ```
*
* @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
*
* @psalm-immutable
*/
class TimestampLastCombCodec extends StringCodec
{
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,48 +8,47 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter\Number;
use Moontoast\Math\BigNumber;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
/**
* BigNumberConverter converts UUIDs from hexadecimal characters into
* moontoast/math `BigNumber` representations of integers and vice versa
* Previously used to integrate moontoast/math as a bignum arithmetic library,
* BigNumberConverter is deprecated in favor of GenericNumberConverter
*
* @deprecated Transition to {@see GenericNumberConverter}.
*
* @psalm-immutable
*/
class BigNumberConverter implements NumberConverterInterface
{
/**
* Converts a hexadecimal number into a `Moontoast\Math\BigNumber` representation
*
* @param string $hex The hexadecimal string representation to convert
* @return BigNumber
*/
public function fromHex($hex)
{
$number = BigNumber::convertToBase10($hex, 16);
private NumberConverterInterface $converter;
return new BigNumber($number);
public function __construct()
{
$this->converter = new GenericNumberConverter(new BrickMathCalculator());
}
/**
* Converts an integer or `Moontoast\Math\BigNumber` integer representation
* into a hexadecimal string representation
*
* @param int|string|BigNumber $integer An integer or `Moontoast\Math\BigNumber`
* @return string Hexadecimal string
* @inheritDoc
* @psalm-pure
*/
public function toHex($integer)
public function fromHex(string $hex): string
{
if (!$integer instanceof BigNumber) {
$integer = new BigNumber($integer);
}
return $this->converter->fromHex($hex);
}
return BigNumber::convertFromBase10($integer, 16);
/**
* @inheritDoc
* @psalm-pure
*/
public function toHex(string $number): string
{
return $this->converter->toHex($number);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,52 +8,18 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter\Number;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Ramsey\Uuid\Converter\NumberConverterInterface;
/**
* DegradedNumberConverter throws `UnsatisfiedDependencyException` exceptions
* if attempting to use number conversion functionality in an environment that
* does not support large integers (i.e. when moontoast/math is not available)
* @deprecated DegradedNumberConverter is no longer necessary for converting
* numbers on 32-bit systems. Transition to {@see GenericNumberConverter}.
*
* @psalm-immutable
*/
class DegradedNumberConverter implements NumberConverterInterface
class DegradedNumberConverter extends BigNumberConverter
{
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param string $hex The hexadecimal string representation to convert
* @return void
* @throws UnsatisfiedDependencyException
*/
public function fromHex($hex)
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' without support for large '
. 'integers, since integer is an unsigned '
. '128-bit integer; Moontoast\Math\BigNumber is required.'
);
}
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param mixed $integer An integer representation to convert
* @return void
* @throws UnsatisfiedDependencyException
*/
public function toHex($integer)
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' without support for large '
. 'integers, since integer is an unsigned '
. '128-bit integer; Moontoast\Math\BigNumber is required. '
);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-immutable
*/
class GenericNumberConverter implements NumberConverterInterface
{
public function __construct(private CalculatorInterface $calculator)
{
}
/**
* @inheritDoc
* @psalm-pure
* @psalm-return numeric-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function fromHex(string $hex): string
{
return $this->calculator->fromBase($hex, 16)->toString();
}
/**
* @inheritDoc
* @psalm-pure
* @psalm-return non-empty-string
* @psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
* @psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
*/
public function toHex(string $number): string
{
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $this->calculator->toBase(new IntegerObject($number), 16);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,38 +8,50 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter;
/**
* NumberConverterInterface converts UUIDs from hexadecimal characters into
* A number converter converts UUIDs from hexadecimal characters into
* representations of integers and vice versa
*
* @psalm-immutable
*/
interface NumberConverterInterface
{
/**
* Converts a hexadecimal number into an integer representation of the number
* Converts a hexadecimal number into an string integer representation of
* the number
*
* The integer representation returned may be an object or a string
* representation of the integer, depending on the implementation.
* The integer representation returned is a string representation of the
* integer, to accommodate unsigned integers greater than PHP_INT_MAX.
*
* @param string $hex The hexadecimal string representation to convert
* @return mixed
*
* @return string String representation of an integer
*
* @psalm-return numeric-string
*
* @psalm-pure
*/
public function fromHex($hex);
public function fromHex(string $hex): string;
/**
* Converts an integer representation into a hexadecimal string representation
* of the number
* 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 greater
* than PHP_INT_MAX.
*
* @param mixed $integer An integer representation to convert; this may be
* a true integer, a string integer, or a object representation that
* this converter can understand
* @return string Hexadecimal string
*
* @psalm-return non-empty-string
*
* @psalm-pure
*/
public function toHex($integer);
public function toHex(string $number): string;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,52 +8,41 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter\Time;
use Moontoast\Math\BigNumber;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
/**
* BigNumberTimeConverter uses the moontoast/math library's `BigNumber` to
* provide facilities for converting parts of time into representations that may
* be used in UUIDs
* Previously used to integrate moontoast/math as a bignum arithmetic library,
* BigNumberTimeConverter is deprecated in favor of GenericTimeConverter
*
* @deprecated Transition to {@see GenericTimeConverter}.
*
* @psalm-immutable
*/
class BigNumberTimeConverter implements TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array containing `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
*/
public function calculateTime($seconds, $microSeconds)
private TimeConverterInterface $converter;
public function __construct()
{
$uuidTime = new BigNumber('0');
$this->converter = new GenericTimeConverter(new BrickMathCalculator());
}
$sec = new BigNumber($seconds);
$sec->multiply('10000000');
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
return $this->converter->calculateTime($seconds, $microseconds);
}
$usec = new BigNumber($microSeconds);
$usec->multiply('10');
$uuidTime->add($sec)
->add($usec)
->add('122192928000000000');
$uuidTimeHex = sprintf('%016s', $uuidTime->convertToBase(16));
return array(
'low' => substr($uuidTimeHex, 8),
'mid' => substr($uuidTimeHex, 4, 4),
'hi' => substr($uuidTimeHex, 0, 4),
);
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
return $this->converter->convertTime($uuidTimestamp);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,36 +8,18 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
/**
* DegradedTimeConverter throws `UnsatisfiedDependencyException` exceptions
* if attempting to use time conversion functionality in an environment that
* does not support large integers (i.e. when moontoast/math is not available)
* @deprecated DegradedTimeConverter is no longer necessary for converting
* time on 32-bit systems. Transition to {@see GenericTimeConverter}.
*
* @psalm-immutable
*/
class DegradedTimeConverter implements TimeConverterInterface
class DegradedTimeConverter extends BigNumberTimeConverter
{
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param string $seconds
* @param string $microSeconds
* @return void
* @throws UnsatisfiedDependencyException
*/
public function calculateTime($seconds, $microSeconds)
{
throw new UnsatisfiedDependencyException(
'When calling ' . __METHOD__ . ' on a 32-bit system, '
. 'Moontoast\Math\BigNumber must be present.'
);
}
}

View File

@@ -0,0 +1,118 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-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
{
$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)
);
// Convert the microseconds into a count of 100-nanosecond intervals.
$usec = $this->calculator->multiply(
$timestamp->getMicroseconds(),
new IntegerObject(self::MICROSECOND_INTERVALS)
);
// Combine the seconds and microseconds intervals 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 */
$uuidTime = $this->calculator->add(
$sec,
$usec,
new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS)
);
$uuidTimeHex = str_pad(
$this->calculator->toHexadecimal($uuidTime)->toString(),
16,
'0',
STR_PAD_LEFT
);
return new Hexadecimal($uuidTimeHex);
}
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)
);
// Convert the 100-nanosecond intervals into seconds and microseconds.
$unixTimestamp = $this->calculator->divide(
RoundingMode::HALF_UP,
6,
$epochNanoseconds,
new IntegerObject(self::SECOND_INTERVALS)
);
$split = explode('.', (string) $unixTimestamp, 2);
return new Time($split[0], $split[1] ?? 0);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,41 +8,165 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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
*
* @psalm-immutable
*/
class PhpTimeConverter implements TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array containing `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
* The number of 100-nanosecond intervals from the Gregorian calendar epoch
* to the Unix epoch.
*/
public function calculateTime($seconds, $microSeconds)
{
// 0x01b21dd213814000 is the number of 100-ns intervals between the
// UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
$uuidTime = ($seconds * 10000000) + ($microSeconds * 10) + 0x01b21dd213814000;
private const GREGORIAN_TO_UNIX_INTERVALS = 0x01b21dd213814000;
return array(
'low' => sprintf('%08x', $uuidTime & 0xffffffff),
'mid' => sprintf('%04x', ($uuidTime >> 32) & 0xffff),
'hi' => sprintf('%04x', ($uuidTime >> 48) & 0x0fff),
/**
* 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;
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);
$microseconds = new IntegerObject($microseconds);
// 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.
/** @psalm-suppress RedundantCondition */
if (!is_int($uuidTime)) {
return $this->fallbackConverter->calculateTime(
$seconds->toString(),
$microseconds->toString()
);
}
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(
((int) $timestamp->toString() - self::GREGORIAN_TO_UNIX_INTERVALS)
/ self::SECOND_INTERVALS
);
if (count($splitTime) === 0) {
return $this->fallbackConverter->convertTime($uuidTimestamp);
}
return new Time($splitTime['sec'], $splitTime['usec']);
}
/**
* @param float|int $time The time to split into seconds and microseconds
*
* @return string[]
*/
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),
];
}
}

View File

@@ -0,0 +1,90 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-immutable
*/
class UnixTimeConverter implements TimeConverterInterface
{
private const MILLISECONDS = 1000;
public function __construct(private CalculatorInterface $calculator)
{
}
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
$timestamp = new Time($seconds, $microseconds);
// Convert the seconds into milliseconds.
$sec = $this->calculator->multiply(
$timestamp->getSeconds(),
new IntegerObject(self::MILLISECONDS),
);
// 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),
);
/** @var IntegerObject $unixTime */
$unixTime = $this->calculator->add($sec, $usec);
$unixTimeHex = str_pad(
$this->calculator->toHexadecimal($unixTime)->toString(),
12,
'0',
STR_PAD_LEFT
);
return new Hexadecimal($unixTimeHex);
}
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
$milliseconds = $this->calculator->toInteger($uuidTimestamp);
$unixTimestamp = $this->calculator->divide(
RoundingMode::HALF_UP,
6,
$milliseconds,
new IntegerObject(self::MILLISECONDS)
);
$split = explode('.', (string) $unixTimestamp, 2);
return new Time($split[0], $split[1] ?? '0');
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,27 +8,51 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Converter;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
/**
* TimeConverterInterface provides facilities for converting parts of time into
* representations that may be used in UUIDs
* A time converter converts timestamps into representations that may be used
* in UUIDs
*
* @psalm-immutable
*/
interface TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
* 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 4122 variant UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array guaranteed to contain `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2 RFC 4122, § 4.2.2: Generation Details
*
* @param string $seconds A string representation of the number 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
*
* @psalm-pure
*/
public function calculateTime($seconds, $microSeconds);
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}
*
* @psalm-pure
*/
public function convertTime(Hexadecimal $uuidTimestamp): Time;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,105 +8,18 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
/**
* DegradedUuid represents an RFC 4122 UUID on 32-bit systems
* @deprecated DegradedUuid is no longer necessary to represent UUIDs on 32-bit
* systems. Transition typehints to {@see UuidInterface}.
*
* @see Uuid
* @psalm-immutable
*/
class DegradedUuid extends Uuid
{
public function getDateTime()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
$time = $this->converter->fromHex($this->getTimestampHex());
$ts = new \Moontoast\Math\BigNumber($time, 20);
$ts->subtract('122192928000000000');
$ts->divide('10000000.0');
$ts->round();
$unixTime = $ts->getValue();
return new \DateTime("@{$unixTime}");
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getFields()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since some '
. 'values overflow the system max integer value'
. '; consider calling getFieldsHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getNode()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since node '
. 'is an unsigned 48-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getNodeHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getTimeLow()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since time_low '
. 'is an unsigned 32-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getTimeLowHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public function getTimestamp()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since timestamp '
. 'is an unsigned 60-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getTimestampHex instead'
);
}
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-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;
}

View File

@@ -0,0 +1,360 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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.
*
* @psalm-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();
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,17 +8,17 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that the requested operation has dependencies that have not
* been satisfied.
* Thrown to indicate that no suitable builder could be found
*/
class UnsatisfiedDependencyException extends \RuntimeException
class BuilderNotFoundException extends PhpRuntimeException implements UuidExceptionInterface
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,16 +8,18 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Exception;
/**
* Thrown to indicate that the parsed UUID string is invalid.
* 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
class InvalidUuidStringException extends InvalidArgumentException implements UuidExceptionInterface
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,27 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,16 +8,17 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Exception;
use LogicException as PhpLogicException;
/**
* Thrown to indicate that the requested operation is not supported.
* Thrown to indicate that the requested operation is not supported
*/
class UnsupportedOperationException extends \RuntimeException
class UnsupportedOperationException extends PhpLogicException implements UuidExceptionInterface
{
}

View File

@@ -0,0 +1,21 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Exception;
use Throwable;
interface UuidExceptionInterface extends Throwable
{
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,206 +8,259 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Generator\PeclUuidTimeGenerator;
use Ramsey\Uuid\Provider\Node\FallbackNodeProvider;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Provider\Node\SystemNodeProvider;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Number\BigNumberConverter;
use Ramsey\Uuid\Converter\Number\DegradedNumberConverter;
use Ramsey\Uuid\Converter\Time\BigNumberTimeConverter;
use Ramsey\Uuid\Converter\Time\DegradedTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
use Ramsey\Uuid\Provider\Time\SystemTimeProvider;
use Ramsey\Uuid\Builder\FallbackBuilder;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Builder\DefaultUuidBuilder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Codec\GuidStringCodec;
use Ramsey\Uuid\Builder\DegradedUuidBuilder;
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\Provider\TimeProviderInterface;
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
* (32- or 64-bit, available dependencies, etc.)
*
* A feature set is used by UuidFactory to determine the available features and
* capabilities of the environment.
*/
class FeatureSet
{
/**
* @var bool
*/
private $disableBigNumber = false;
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;
/**
* @var bool
*/
private $disable64Bit = false;
/**
* @var bool
*/
private $ignoreSystemNode = false;
/**
* @var bool
*/
private $enablePecl = false;
/**
* @var UuidBuilderInterface
*/
private $builder;
/**
* @var CodecInterface
*/
private $codec;
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var NumberConverterInterface
*/
private $numberConverter;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator;
/**
* @var TimeGeneratorInterface
*/
private $timeGenerator;
/**
* Constructs a `FeatureSet` for use by a `UuidFactory` to determine or set
* features available to the environment
*
* @param bool $useGuids Whether to build UUIDs using the `GuidStringCodec`
* @param bool $force32Bit Whether to force the use of 32-bit functionality
* @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 Whether to disable the use of moontoast/math
* `BigNumber` (primarily for testing purposes)
* @param bool $ignoreSystemNode Whether to disable attempts to check for
* the system host ID (primarily for testing purposes)
* @param bool $enablePecl Whether to enable the use of the `PeclUuidTimeGenerator`
* @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
*/
public function __construct(
$useGuids = false,
$force32Bit = false,
$forceNoBigNumber = false,
$ignoreSystemNode = false,
$enablePecl = false
bool $useGuids = false,
private bool $force32Bit = false,
bool $forceNoBigNumber = false,
private bool $ignoreSystemNode = false,
private bool $enablePecl = false
) {
$this->disableBigNumber = $forceNoBigNumber;
$this->disable64Bit = $force32Bit;
$this->ignoreSystemNode = $ignoreSystemNode;
$this->enablePecl = $enablePecl;
$this->numberConverter = $this->buildNumberConverter();
$this->builder = $this->buildUuidBuilder();
$this->randomGenerator = $this->buildRandomGenerator();
$this->setCalculator(new BrickMathCalculator());
$this->builder = $this->buildUuidBuilder($useGuids);
$this->codec = $this->buildCodec($useGuids);
$this->nodeProvider = $this->buildNodeProvider();
$this->randomGenerator = $this->buildRandomGenerator();
$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
*
* @return UuidBuilderInterface
*/
public function getBuilder()
public function getBuilder(): UuidBuilderInterface
{
return $this->builder;
}
/**
* Returns the UUID UUID coder-decoder configured for this environment
*
* @return CodecInterface
* Returns the calculator configured for this environment
*/
public function getCodec()
public function getCalculator(): CalculatorInterface
{
return $this->calculator;
}
/**
* Returns the codec configured for this environment
*/
public function getCodec(): CodecInterface
{
return $this->codec;
}
/**
* Returns the system node ID provider configured for this environment
*
* @return NodeProviderInterface
* Returns the DCE Security generator configured for this environment
*/
public function getNodeProvider()
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
*
* @return NumberConverterInterface
*/
public function getNumberConverter()
public function getNumberConverter(): NumberConverterInterface
{
return $this->numberConverter;
}
/**
* Returns the random UUID generator configured for this environment
*
* @return RandomGeneratorInterface
* Returns the random generator configured for this environment
*/
public function getRandomGenerator()
public function getRandomGenerator(): RandomGeneratorInterface
{
return $this->randomGenerator;
}
/**
* Returns the time-based UUID generator configured for this environment
*
* @return TimeGeneratorInterface
* Returns the time converter configured for this environment
*/
public function getTimeGenerator()
public function getTimeConverter(): TimeConverterInterface
{
return $this->timeConverter;
}
/**
* Returns the time generator configured for this environment
*/
public function getTimeGenerator(): TimeGeneratorInterface
{
return $this->timeGenerator;
}
/**
* Sets the time provider for use in this environment
*
* @param TimeProviderInterface $timeProvider
* Returns the Unix Epoch time generator configured for this environment
*/
public function setTimeProvider(TimeProviderInterface $timeProvider)
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);
/** @psalm-suppress RedundantPropertyInitializationCheck */
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);
}
/**
* Determines which UUID coder-decoder to use and returns the configured
* codec for this environment
*
* @param bool $useGuids Whether to build UUIDs using the `GuidStringCodec`
* @return CodecInterface
* Set the validator to use in this environment
*/
protected function buildCodec($useGuids = false)
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);
@@ -216,12 +270,22 @@ class FeatureSet
}
/**
* Determines which system node ID provider to use and returns the configured
* system node ID provider for this environment
*
* @return NodeProviderInterface
* Returns a DCE Security generator configured for this environment
*/
protected function buildNodeProvider()
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();
@@ -229,44 +293,37 @@ class FeatureSet
return new FallbackNodeProvider([
new SystemNodeProvider(),
new RandomNodeProvider()
new RandomNodeProvider(),
]);
}
/**
* Determines which number converter to use and returns the configured
* number converter for this environment
*
* @return NumberConverterInterface
* Returns a number converter configured for this environment
*/
protected function buildNumberConverter()
private function buildNumberConverter(CalculatorInterface $calculator): NumberConverterInterface
{
if ($this->hasBigNumber()) {
return new BigNumberConverter();
}
return new DegradedNumberConverter();
return new GenericNumberConverter($calculator);
}
/**
* Determines which random UUID generator to use and returns the configured
* random UUID generator for this environment
*
* @return RandomGeneratorInterface
* Returns a random generator configured for this environment
*/
protected function buildRandomGenerator()
private function buildRandomGenerator(): RandomGeneratorInterface
{
if ($this->enablePecl) {
return new PeclUuidRandomGenerator();
}
return (new RandomGeneratorFactory())->getGenerator();
}
/**
* Determines which time-based UUID generator to use and returns the configured
* time-based UUID generator for this environment
* Returns a time generator configured for this environment
*
* @param TimeProviderInterface $timeProvider
* @return TimeGeneratorInterface
* @param TimeProviderInterface $timeProvider The time provider to use with
* the time generator
*/
protected function buildTimeGenerator(TimeProviderInterface $timeProvider)
private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface
{
if ($this->enablePecl) {
return new PeclUuidTimeGenerator();
@@ -274,60 +331,67 @@ class FeatureSet
return (new TimeGeneratorFactory(
$this->nodeProvider,
$this->buildTimeConverter(),
$this->timeConverter,
$timeProvider
))->getGenerator();
}
/**
* Determines which time converter to use and returns the configured
* time converter for this environment
*
* @return TimeConverterInterface
* Returns a Unix Epoch time generator configured for this environment
*/
protected function buildTimeConverter()
private function buildUnixTimeGenerator(): TimeGeneratorInterface
{
if ($this->is64BitSystem()) {
return new PhpTimeConverter();
} elseif ($this->hasBigNumber()) {
return new BigNumberTimeConverter();
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 DegradedTimeConverter();
return (new NameGeneratorFactory())->getGenerator();
}
/**
* Determines which UUID builder to use and returns the configured UUID
* builder for this environment
*
* @return UuidBuilderInterface
* Returns a time converter configured for this environment
*/
protected function buildUuidBuilder()
private function buildTimeConverter(CalculatorInterface $calculator): TimeConverterInterface
{
$genericConverter = new GenericTimeConverter($calculator);
if ($this->is64BitSystem()) {
return new DefaultUuidBuilder($this->numberConverter);
return new PhpTimeConverter($calculator, $genericConverter);
}
return new DegradedUuidBuilder($this->numberConverter);
return $genericConverter;
}
/**
* Returns true if the system has `Moontoast\Math\BigNumber`
* Returns a UUID builder configured for this environment
*
* @return bool
* @param bool $useGuids Whether to build UUIDs using the GuidStringCodec
*/
protected function hasBigNumber()
private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface
{
return class_exists('Moontoast\Math\BigNumber') && !$this->disableBigNumber;
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 system is 64-bit, false otherwise
*
* @return bool
* Returns true if the PHP build is 64-bit
*/
protected function is64BitSystem()
private function is64BitSystem(): bool
{
return PHP_INT_SIZE == 8 && !$this->disable64Bit;
return PHP_INT_SIZE === 8 && !$this->force32Bit;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Fields;
use Serializable;
/**
* UUIDs are comprised of unsigned integers, the bytes of which are separated
* into fields and arranged in a particular layout defined by the specification
* for the variant
*
* @psalm-immutable
*/
interface FieldsInterface extends Serializable
{
/**
* Returns the bytes that comprise the fields
*/
public function getBytes(): string;
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-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 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
*
* @psalm-suppress UnusedMethodCall
*/
public function unserialize(string $data): void
{
if (strlen($data) === 16) {
$this->__construct($data);
} else {
$this->__construct(base64_decode($data));
}
}
/**
* @param array{bytes?: string} $data
*
* @psalm-suppress UnusedMethodCall
*/
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']);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,76 +8,105 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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 provides functionality to generate COMB (combined GUID/timestamp)
* sequential UUIDs
* CombGenerator generates COMBs (combined UUID/timestamp)
*
* @link https://en.wikipedia.org/wiki/Globally_unique_identifier#Sequential_algorithms
* 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.
*
* ``` php
* $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.
*
* ``` php
* $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder()));
* ```
*
* @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
*/
class CombGenerator implements RandomGeneratorInterface
{
const TIMESTAMP_BYTES = 6;
public const TIMESTAMP_BYTES = 6;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator;
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs a `CombGenerator` using a random-number generator and a number converter
*
* @param RandomGeneratorInterface $generator Random-number generator for the non-time part.
* @param NumberConverterInterface $numberConverter Instance of number converter.
*/
public function __construct(RandomGeneratorInterface $generator, NumberConverterInterface $numberConverter)
{
$this->converter = $numberConverter;
$this->randomGenerator = $generator;
public function __construct(
private RandomGeneratorInterface $generator,
private NumberConverterInterface $numberConverter
) {
}
/**
* Generates a string of binary data of the specified length
* @throws InvalidArgumentException if $length is not a positive integer
* greater than or equal to CombGenerator::TIMESTAMP_BYTES
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
* @inheritDoc
*/
public function generate($length)
public function generate(int $length): string
{
if ($length < self::TIMESTAMP_BYTES || $length < 0) {
throw new \InvalidArgumentException('Length must be a positive integer.');
if ($length < self::TIMESTAMP_BYTES) {
throw new InvalidArgumentException(
'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES
);
}
$hash = '';
if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) {
$hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES);
$hash = $this->generator->generate($length - self::TIMESTAMP_BYTES);
}
$lsbTime = str_pad($this->converter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT);
$lsbTime = str_pad(
$this->numberConverter->toHex($this->timestamp()),
self::TIMESTAMP_BYTES * 2,
'0',
STR_PAD_LEFT
);
return hex2bin(str_pad(bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime);
return (string) hex2bin(
str_pad(
bin2hex($hash),
$length - self::TIMESTAMP_BYTES,
'0'
)
. $lsbTime
);
}
/**
* Returns current timestamp as integer, precise to 0.00001 seconds
*
* @return string
* Returns current timestamp a string integer, precise to 0.00001 seconds
*/
private function timestamp()
private function timestamp(): string
{
$time = explode(' ', microtime(false));

View File

@@ -0,0 +1,141 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
// 4294967295. 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);
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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;
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
/** @psalm-pure */
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
try {
/** @var string|bool $bytes */
$bytes = @hash($hashAlgorithm, $ns->getBytes() . $name, true);
} catch (ValueError $e) {
$bytes = false; // keep same behavior than PHP 7
}
if ($bytes === false) {
throw new NameException(sprintf(
'Unable to hash namespace and name with algorithm \'%s\'',
$hashAlgorithm
));
}
return (string) $bytes;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,126 +8,122 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\BinaryUtils;
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 provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
* DefaultTimeGenerator generates strings of binary data based on a node ID,
* clock sequence, and the current time
*/
class DefaultTimeGenerator implements TimeGeneratorInterface
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `DefaultTimeGenerator` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
* @throws InvalidArgumentException if the parameters contain invalid values
* @throws RandomSourceException if random_int() throws an exception/error
*
* If $node is not given, we will attempt to obtain the local hardware
* address. If $clockSeq is given, it is used as the sequence number;
* otherwise a random 14-bit sequence number is chosen.
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $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
* @inheritDoc
*/
public function generate($node = null, $clockSeq = null)
public function generate($node = null, ?int $clockSeq = null): string
{
if ($node instanceof Hexadecimal) {
$node = $node->toString();
}
$node = $this->getValidNode($node);
if ($clockSeq === null) {
// Not using "stable storage"; see RFC 4122, Section 4.2.1.1
$clockSeq = mt_rand(0, 1 << 14);
try {
// This does not use "stable storage"; see RFC 4122, Section 4.2.1.1.
$clockSeq = random_int(0, 0x3fff);
} catch (Throwable $exception) {
throw new RandomSourceException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
// Create a 60-bit time value as a count of 100-nanosecond intervals
// since 00:00:00.00, 15 October 1582
$timeOfDay = $this->timeProvider->currentTime();
$uuidTime = $this->timeConverter->calculateTime($timeOfDay['sec'], $timeOfDay['usec']);
$time = $this->timeProvider->getTime();
$timeHi = BinaryUtils::applyVersion($uuidTime['hi'], 1);
$clockSeqHi = BinaryUtils::applyVariant($clockSeq >> 8);
$hex = vsprintf(
'%08s%04s%04s%02s%02s%012s',
array(
$uuidTime['low'],
$uuidTime['mid'],
sprintf('%04x', $timeHi),
sprintf('%02x', $clockSeqHi),
sprintf('%02x', $clockSeq & 0xff),
$node,
)
$uuidTime = $this->timeConverter->calculateTime(
$time->getSeconds()->toString(),
$time->getMicroseconds()->toString()
);
return hex2bin($hex);
$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 string|int $node A node value that may be used to override the node provider
* @return string Hexadecimal representation of the node ID
* @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
*/
protected function getValidNode($node)
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
// Convert the node to hex, if it is still an integer.
if (is_int($node)) {
$node = sprintf('%012x', $node);
$node = dechex($node);
}
if (!ctype_xdigit($node) || strlen($node) > 12) {
throw new \InvalidArgumentException('Invalid node value');
if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) {
throw new InvalidArgumentException('Invalid node value');
}
return strtolower(sprintf('%012s', $node));
return (string) hex2bin(str_pad((string) $node, 12, '0', STR_PAD_LEFT));
}
}

View File

@@ -1,41 +0,0 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* MtRandRandomGenerator provides functionality to generate strings of random
* binary data using the `mt_rand()` PHP function
*
* @link http://php.net/mt_rand
*/
class MtRandGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
$bytes = '';
for ($i = 1; $i <= $length; $i++) {
$bytes = chr(mt_rand(0, 255)) . $bytes;
}
return $bytes;
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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();
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
*
* @psalm-pure
*/
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string;
}

View File

@@ -1,38 +0,0 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* OpenSslRandomGenerator provides functionality to generate strings of random
* binary data using the `openssl_random_pseudo_bytes()` PHP function
*
* The use of this generator requires PHP to be compiled using the
* `--with-openssl` option.
*
* @link http://php.net/openssl_random_pseudo_bytes
*/
class OpenSslGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return openssl_random_pseudo_bytes($length);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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
{
/** @psalm-pure */
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
$uuid = match ($hashAlgorithm) {
'md5' => uuid_generate_md5($ns->toString(), $name),
'sha1' => uuid_generate_sha1($ns->toString(), $name),
default => throw new NameException(
sprintf(
'Unable to hash namespace and name with algorithm \'%s\'',
$hashAlgorithm
)
),
};
return uuid_parse($uuid);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,28 +8,25 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use function uuid_create;
use function uuid_parse;
use const UUID_TYPE_RANDOM;
/**
* PeclUuidRandomGenerator provides functionality to generate strings of random
* binary data using the PECL UUID PHP extension
* PeclUuidRandomGenerator generates strings of random binary data using ext-uuid
*
* @link https://pecl.php.net/package/uuid
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
public function generate(int $length): string
{
$uuid = uuid_create(UUID_TYPE_RANDOM);

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,29 +8,29 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use function uuid_create;
use function uuid_parse;
use const UUID_TYPE_TIME;
/**
* PeclUuidTimeGenerator provides functionality to generate strings of binary
* data for version 1 UUIDs using the PECL UUID PHP extension
* PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs,
* using ext-uuid
*
* @link https://pecl.php.net/package/uuid
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidTimeGenerator implements TimeGeneratorInterface
{
/**
* Generate a version 1 UUID using the PECL UUID extension
*
* @param int|string $node Not used in this context
* @param int $clockSeq Not used in this context
* @return string A binary string
* @inheritDoc
*/
public function generate($node = null, $clockSeq = null)
public function generate($node = null, ?int $clockSeq = null): string
{
$uuid = uuid_create(UUID_TYPE_TIME);

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,30 +8,38 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Exception\RandomSourceException;
use Throwable;
/**
* RandomBytesGenerator provides functionality to generate strings of random
* binary data using `random_bytes()` function in PHP 7+ or paragonie/random_compat
* RandomBytesGenerator generates strings of random binary data using the
* built-in `random_bytes()` PHP function
*
* @link http://php.net/random_bytes
* @link https://github.com/paragonie/random_compat
* @link http://php.net/random_bytes random_bytes()
*/
class RandomBytesGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
* @throws RandomSourceException if random_bytes() throws an exception/error
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
* @inheritDoc
*/
public function generate($length)
public function generate(int $length): string
{
return random_bytes($length);
try {
return random_bytes($length);
} catch (Throwable $exception) {
throw new RandomSourceException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,24 +8,22 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* A factory for retrieving a random generator, based on the environment
* RandomGeneratorFactory retrieves a default random generator, based on the
* environment
*/
class RandomGeneratorFactory
{
/**
* Returns a default random generator, based on the current environment
*
* @return RandomGeneratorInterface
*/
public static function getGenerator()
public function getGenerator(): RandomGeneratorInterface
{
return new RandomBytesGenerator();
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,24 +8,23 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* RandomGeneratorInterface provides functionality to generate strings of random
* binary data
* A random generator generates strings of random binary data
*/
interface RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
* Generates a string of randomized binary data
*
* @param int<1, max> $length The number of bytes of random binary data to generate
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length);
public function generate(int $length): string;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,55 +8,48 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use RandomLib\Generator;
use RandomLib\Factory;
use RandomLib\Generator;
/**
* RandomLibAdapter provides functionality to generate strings of random
* binary data using the ircmaxell/random-lib library
* RandomLibAdapter generates strings of random binary data using the
* paragonie/random-lib library
*
* @link https://packagist.org/packages/ircmaxell/random-lib
* @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
{
/**
* @var Generator
*/
private $generator;
private Generator $generator;
/**
* Constructs a `RandomLibAdapter` using a `RandomLib\Generator`
* Constructs a RandomLibAdapter
*
* By default, if no `Generator` is passed in, this creates a medium-strength
* By default, if no Generator is passed in, this creates a high-strength
* generator to use when generating random binary data.
*
* @param Generator $generator An ircmaxell/random-lib `Generator`
* @param Generator|null $generator The generator to use when generating binary data
*/
public function __construct(Generator $generator = null)
public function __construct(?Generator $generator = null)
{
$this->generator = $generator;
if ($this->generator === null) {
if ($generator === null) {
$factory = new Factory();
$this->generator = $factory->getMediumStrengthGenerator();
$generator = $factory->getHighStrengthGenerator();
}
$this->generator = $generator;
}
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
public function generate(int $length): string
{
return $this->generator->generate($length);
}

View File

@@ -1,36 +0,0 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* SodiumRandomGenerator provides functionality to generate strings of random
* binary data using the PECL libsodium extension
*
* @link http://pecl.php.net/package/libsodium
* @link https://paragonie.com/book/pecl-libsodium
*/
class SodiumRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return \Sodium\randombytes_buf($length);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,11 +8,10 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\TimeConverterInterface;
@@ -19,49 +19,22 @@ use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* A factory for retrieving a time generator, based on the environment
* TimeGeneratorFactory retrieves a default time generator, based on the
* environment
*/
class TimeGeneratorFactory
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `TimeGeneratorFactory` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Returns a default time generator, based on the current environment
*
* @return TimeGeneratorInterface
*/
public function getGenerator()
public function getGenerator(): TimeGeneratorInterface
{
return new DefaultTimeGenerator(
$this->nodeProvider,

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,29 +8,31 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* TimeGeneratorInterface provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
* A time generator generates strings of binary data based on a node ID,
* clock sequence, and the current time
*/
interface TimeGeneratorInterface
{
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
* 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
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $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, $clockSeq = null);
public function generate($node = null, ?int $clockSeq = null): string;
}

Some files were not shown because too many files have changed in this diff Show More