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