1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Services; |
4
|
|
|
|
5
|
|
|
use App\Interfaces\ContactServiceInterface; |
6
|
|
|
use App\Models\Contact; |
7
|
|
|
use App\Models\User; |
8
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator; |
9
|
|
|
use Illuminate\Support\Collection; |
10
|
|
|
|
11
|
|
|
class ContactService implements ContactServiceInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* All contacts. |
15
|
|
|
* |
16
|
|
|
* @param User $user |
17
|
|
|
* @return LengthAwarePaginator |
18
|
|
|
*/ |
19
|
3 |
|
public function contacts(User $user): LengthAwarePaginator |
20
|
|
|
{ |
21
|
3 |
|
return Contact::forUser($user->id)->with('source')->paginate(); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Retrieve a contact. |
26
|
|
|
* |
27
|
|
|
* @param string $contact_id |
28
|
|
|
* @return Contact |
29
|
|
|
*/ |
30
|
1 |
|
public function contact(string $contact_id): Contact |
31
|
|
|
{ |
32
|
1 |
|
return Contact::find($contact_id); |
|
|
|
|
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Creates contact. |
37
|
|
|
* @param User $user |
38
|
|
|
* @param User $contact |
39
|
|
|
* @return Contact |
40
|
|
|
*/ |
41
|
11 |
|
public function addContact(User $user, User $contact): Contact |
42
|
|
|
{ |
43
|
11 |
|
return Contact::updateOrCreate([ |
44
|
11 |
|
'user_id' => $user->id, |
45
|
11 |
|
'source_type' => get_class($contact), |
46
|
11 |
|
'source_id' => $contact->id, |
47
|
|
|
], [ |
48
|
11 |
|
'name' => $contact->name, |
|
|
|
|
49
|
|
|
]); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Creates contact by user collection and returns contact. |
54
|
|
|
* |
55
|
|
|
* @param Collection $users |
56
|
|
|
* @return Collection |
57
|
|
|
*/ |
58
|
10 |
|
public function setContacts(Collection $users): Collection |
59
|
|
|
{ |
60
|
10 |
|
return $users->map(function ($user) use ($users){ |
61
|
|
|
return $users |
62
|
10 |
|
->filter(function ($item) use ($user) { |
63
|
10 |
|
return !$item->is($user); |
64
|
10 |
|
}) |
65
|
10 |
|
->map(function ($contact) use ($user) { |
66
|
7 |
|
return $this->addContact($user, $contact); |
67
|
10 |
|
}); |
68
|
10 |
|
}) |
69
|
10 |
|
->flatten(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Remove a contact. |
74
|
|
|
* |
75
|
|
|
* @param string $contact_id |
76
|
|
|
* @return Contact |
77
|
|
|
*/ |
78
|
1 |
|
public function removeContact(string $contact_id): Contact |
79
|
|
|
{ |
80
|
1 |
|
$contact = Contact::find($contact_id); |
81
|
1 |
|
$contact->delete(); |
82
|
|
|
|
83
|
1 |
|
return $contact; |
|
|
|
|
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|