-
Notifications
You must be signed in to change notification settings - Fork 1
/
MathCast.php
57 lines (49 loc) · 1.5 KB
/
MathCast.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
<?php
/*
* This file is part of fab2s/Math.
* (c) Fabrice de Stefanis / https://github.com/fab2s/Math
* This source file is licensed under the MIT license which you will
* find in the LICENSE file or at https://opensource.org/licenses/MIT
*/
namespace fab2s\Math\Laravel;
use fab2s\Math\Laravel\Exception\NotNullableException;
use fab2s\Math\Math;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class MathCast implements CastsAttributes
{
protected bool $isNullable = false;
public function __construct(...$options)
{
$this->isNullable = in_array('nullable', $options);
}
/**
* Cast the given value.
*
* @param Model $model
*
* @throws NotNullableException
*/
public function get($model, string $key, $value, array $attributes): ?Math
{
return Math::isNumber($value) ? Math::number($value) : $this->handleNullable($model, $key);
}
/**
* Prepare the given value for storage.
*
* @param Model $model
*
* @throws NotNullableException
*/
public function set($model, string $key, $value, array $attributes): ?string
{
return Math::isNumber($value) ? (string) Math::number($value) : $this->handleNullable($model, $key);
}
/**
* @throws NotNullableException
*/
protected function handleNullable(Model $model, string $key)
{
return $this->isNullable ? null : throw NotNullableException::make($key, $model);
}
}