|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the Laudis Neo4j package. |
| 7 | + * |
| 8 | + * (c) Laudis technologies <http://laudis.tech> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Laudis\Neo4j\Databags; |
| 15 | + |
| 16 | +use function bin2hex; |
| 17 | +use Exception; |
| 18 | +use function random_bytes; |
| 19 | +use function substr; |
| 20 | + |
| 21 | +final class Bookmark |
| 22 | +{ |
| 23 | + /** @var list<string> */ |
| 24 | + private array $bookmarks; |
| 25 | + |
| 26 | + /** |
| 27 | + * @param list<string> $bookmarks |
| 28 | + */ |
| 29 | + public function __construct(?array $bookmarks = null) |
| 30 | + { |
| 31 | + $this->bookmarks = $bookmarks ?? []; |
| 32 | + } |
| 33 | + |
| 34 | + public function isEmpty(): bool |
| 35 | + { |
| 36 | + return count($this->bookmarks) === 0; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @return list<string> |
| 41 | + */ |
| 42 | + public function values(): array |
| 43 | + { |
| 44 | + return $this->bookmarks; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * @throws Exception |
| 49 | + */ |
| 50 | + public function withIncrement(?string $bookmark = null): self |
| 51 | + { |
| 52 | + $copy = $this->bookmarks; |
| 53 | + if ($bookmark === null) { |
| 54 | + $bookmark = $this->generateUuidV4(); |
| 55 | + } |
| 56 | + $copy[] = $bookmark; |
| 57 | + |
| 58 | + return new self($copy); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @throws Exception |
| 63 | + */ |
| 64 | + private function generateUuidV4(): string |
| 65 | + { |
| 66 | + $uuid = random_bytes(16); |
| 67 | + $uuid[6] = ((int) $uuid[6]) & 0x0F | 0x40; |
| 68 | + $uuid[8] = ((int) $uuid[8]) & 0x3F | 0x80; |
| 69 | + $uuid = bin2hex($uuid); |
| 70 | + |
| 71 | + return substr($uuid, 0, 8).'-' |
| 72 | + .substr($uuid, 8, 4).'-' |
| 73 | + .substr($uuid, 12, 4).'-' |
| 74 | + .substr($uuid, 16, 4).'-' |
| 75 | + .substr($uuid, 20, 12); |
| 76 | + } |
| 77 | +} |
0 commit comments