|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Jenssegers\Mongodb\Eloquent\Casts; |
| 4 | + |
| 5 | +use function bin2hex; |
| 6 | +use function hex2bin; |
| 7 | +use Illuminate\Contracts\Database\Eloquent\CastsAttributes; |
| 8 | +use Jenssegers\Mongodb\Eloquent\Model; |
| 9 | +use MongoDB\BSON\Binary; |
| 10 | +use function str_replace; |
| 11 | +use function substr; |
| 12 | + |
| 13 | +class BinaryUuid implements CastsAttributes |
| 14 | +{ |
| 15 | + /** |
| 16 | + * Cast the given value. |
| 17 | + * |
| 18 | + * @param Model $model |
| 19 | + * @param string $key |
| 20 | + * @param mixed $value |
| 21 | + * @param array $attributes |
| 22 | + * @return mixed |
| 23 | + */ |
| 24 | + public function get($model, string $key, $value, array $attributes) |
| 25 | + { |
| 26 | + if (! $value instanceof Binary || $value->getType() !== Binary::TYPE_UUID) { |
| 27 | + return $value; |
| 28 | + } |
| 29 | + |
| 30 | + $base16Uuid = bin2hex($value->getData()); |
| 31 | + |
| 32 | + return sprintf( |
| 33 | + '%s-%s-%s-%s-%s', |
| 34 | + substr($base16Uuid, 0, 8), |
| 35 | + substr($base16Uuid, 8, 4), |
| 36 | + substr($base16Uuid, 12, 4), |
| 37 | + substr($base16Uuid, 16, 4), |
| 38 | + substr($base16Uuid, 20, 12), |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Prepare the given value for storage. |
| 44 | + * |
| 45 | + * @param Model $model |
| 46 | + * @param string $key |
| 47 | + * @param mixed $value |
| 48 | + * @param array $attributes |
| 49 | + * @return mixed |
| 50 | + */ |
| 51 | + public function set($model, string $key, $value, array $attributes) |
| 52 | + { |
| 53 | + if ($value instanceof Binary) { |
| 54 | + return $value; |
| 55 | + } |
| 56 | + |
| 57 | + if (is_string($value) && strlen($value) === 16) { |
| 58 | + return new Binary($value, Binary::TYPE_UUID); |
| 59 | + } |
| 60 | + |
| 61 | + return new Binary(hex2bin(str_replace('-', '', $value)), Binary::TYPE_UUID); |
| 62 | + } |
| 63 | +} |
0 commit comments