1<?php 2 3/** 4 * This file is part of the ramsey/uuid library 5 * 6 * For the full copyright and license information, please view the LICENSE 7 * file that was distributed with this source code. 8 * 9 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> 10 * @license http://opensource.org/licenses/MIT MIT 11 */ 12 13declare(strict_types=1); 14 15namespace Ramsey\Uuid\Guid; 16 17use Ramsey\Uuid\Builder\UuidBuilderInterface; 18use Ramsey\Uuid\Codec\CodecInterface; 19use Ramsey\Uuid\Converter\NumberConverterInterface; 20use Ramsey\Uuid\Converter\TimeConverterInterface; 21use Ramsey\Uuid\Exception\UnableToBuildUuidException; 22use Ramsey\Uuid\UuidInterface; 23use Throwable; 24 25/** 26 * GuidBuilder builds instances of Guid 27 * 28 * @see Guid 29 * 30 * @psalm-immutable 31 */ 32class GuidBuilder implements UuidBuilderInterface 33{ 34 /** 35 * @var NumberConverterInterface 36 */ 37 private $numberConverter; 38 39 /** 40 * @var TimeConverterInterface 41 */ 42 private $timeConverter; 43 44 /** 45 * @param NumberConverterInterface $numberConverter The number converter to 46 * use when constructing the Guid 47 * @param TimeConverterInterface $timeConverter The time converter to use 48 * for converting timestamps extracted from a UUID to Unix timestamps 49 */ 50 public function __construct( 51 NumberConverterInterface $numberConverter, 52 TimeConverterInterface $timeConverter 53 ) { 54 $this->numberConverter = $numberConverter; 55 $this->timeConverter = $timeConverter; 56 } 57 58 /** 59 * Builds and returns a Guid 60 * 61 * @param CodecInterface $codec The codec to use for building this Guid instance 62 * @param string $bytes The byte string from which to construct a UUID 63 * 64 * @return Guid The GuidBuilder returns an instance of Ramsey\Uuid\Guid\Guid 65 * 66 * @psalm-pure 67 */ 68 public function build(CodecInterface $codec, string $bytes): UuidInterface 69 { 70 try { 71 return new Guid( 72 $this->buildFields($bytes), 73 $this->numberConverter, 74 $codec, 75 $this->timeConverter 76 ); 77 } catch (Throwable $e) { 78 throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e); 79 } 80 } 81 82 /** 83 * Proxy method to allow injecting a mock, for testing 84 */ 85 protected function buildFields(string $bytes): Fields 86 { 87 return new Fields($bytes); 88 } 89} 90