1 | <?php |
||
2 | |||
3 | namespace Spinen\Halo\Concerns; |
||
4 | |||
5 | use Illuminate\Container\Container; |
||
6 | use Illuminate\Contracts\Container\BindingResolutionException; |
||
7 | use Illuminate\Database\Eloquent\Casts\Attribute; |
||
8 | use Illuminate\Support\Facades\Crypt; |
||
9 | use Spinen\Halo\Api\Client as Halo; |
||
10 | use Spinen\Halo\Api\Token; |
||
11 | use Spinen\Halo\Exceptions\NoClientException; |
||
12 | use Spinen\Halo\Support\Builder; |
||
13 | |||
14 | /** |
||
15 | * Trait HasHalo |
||
16 | * |
||
17 | * @property Halo $halo |
||
18 | * @property string $halo_token |
||
19 | */ |
||
20 | trait HasHalo |
||
21 | { |
||
22 | /** |
||
23 | * Halo Builder instance |
||
24 | */ |
||
25 | protected ?Builder $builder = null; |
||
26 | |||
27 | /** |
||
28 | * Return cached version of the Halo Builder for the user |
||
29 | * |
||
30 | * @throws BindingResolutionException |
||
31 | */ |
||
32 | 4 | public function halo(): Builder |
|
33 | { |
||
34 | // TODO: Need to deal with null halo_token |
||
35 | 4 | if (is_null($this->builder)) { |
|
36 | 4 | $this->builder = Container::getInstance() |
|
37 | 4 | ->make(Builder::class) |
|
38 | 4 | ->setClient( |
|
39 | 4 | Container::getInstance() |
|
40 | 4 | ->make(Halo::class) |
|
41 | 4 | ->setToken($this->halo_token) |
|
42 | 4 | ); |
|
43 | } |
||
44 | |||
45 | 4 | return $this->builder; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Accessor for Halo Client. |
||
50 | * |
||
51 | * @throws BindingResolutionException |
||
52 | * @throws NoClientException |
||
53 | */ |
||
54 | 1 | public function getHaloAttribute(): Halo |
|
55 | { |
||
56 | 1 | return $this->halo() |
|
57 | 1 | ->getClient(); |
|
58 | } |
||
59 | |||
60 | /** |
||
61 | * Accessor/Mutator for haloToken. |
||
62 | */ |
||
63 | 5 | public function haloToken(): Attribute |
|
64 | { |
||
65 | 5 | return Attribute::make( |
|
66 | 5 | get: fn ($value, array $attributes): ?Token => ! is_null($attributes['halo_token']) |
|
67 | 1 | ? unserialize(Crypt::decryptString($attributes['halo_token'])) |
|
68 | 5 | : null, |
|
69 | 5 | set: function ($value): ?string { |
|
70 | // If setting the password & already have a client, then |
||
71 | // empty the client to use new password in client |
||
72 | 3 | if (! is_null($this->builder)) { |
|
73 | 1 | $this->builder = null; |
|
74 | } |
||
75 | |||
76 | 3 | return is_null($value) |
|
77 | 1 | ? null |
|
78 | 3 | : Crypt::encryptString(serialize($value)); |
|
79 | 5 | }, |
|
80 | 5 | ); |
|
81 | } |
||
82 | |||
83 | /** |
||
84 | * Make sure that the halo_token is fillable & protected |
||
85 | */ |
||
86 | 1 | public function initializeHasHalo(): void |
|
87 | { |
||
88 | 1 | $this->fillable[] = 'halo_token'; |
|
0 ignored issues
–
show
|
|||
89 | 1 | $this->hidden[] = 'halo'; |
|
0 ignored issues
–
show
|
|||
90 | 1 | $this->hidden[] = 'halo_token'; |
|
91 | } |
||
92 | } |
||
93 |