-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSuperModel.php
76 lines (63 loc) · 1.86 KB
/
SuperModel.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
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Grummfy\EloquentExtendedCast\Eloquent\JsonReadOnlyCollectionCastable;
use Grummfy\EloquentExtendedCast\Eloquent\CastableModel;
use Grummfy\EloquentExtendedCast\ValueObject\ReadOnlyCollection;
class SuperModel extends Model
{
use CastableModel;
use JsonReadOnlyCollectionCastable;
protected $casts = [
'phones' => 'jsonCollection',
'descriptions' => 'jsonCollection',
'period' => 'period',
];
protected $fillable = [
'phones',
'period',
'descriptions',
];
protected $castParameters = [
'descriptions' => TranslatableLabel::class,
'phones' => Phone::class,
];
public function __construct(array $attributes = [])
{
$this->descriptions = new ReadOnlyCollection();
$this->phones = new ReadOnlyCollection();
parent::__construct($attributes);
}
public function addDescription(string $language, string $description)
{
$this->descriptions = $this->descriptions
->push(new TranslatableLabel($language, $description));
return $this;
}
public function getDescription(string $language): string
{
$description = $this->descriptions->toCollection()->first(function(TranslatableLabel $value) use ($language)
{
return $value->getLanguage() == $language;
});
return $description ? $description->getLabel() : ($this->descriptions->toCollection()->isNotEmpty() ? $this->descriptions->toCollection()->first()->getLabel() : '-');
}
public function addPhone(string $prefix, string $number): self
{
if (is_null($this->phones))
{
$this->phones = new ReadOnlyCollection();
}
$this->phones = $this->phones->push(new Phone($prefix, $number));
return $this;
}
public function toPeriod(Period $period): string
{
return $period->format();
}
public function fromPeriod(string $period): Period
{
return Period::fromString($period);
}
}