Issues (85)

app/Services/ContactService.php (2 issues)

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
    public function contacts(User $user): LengthAwarePaginator
20
    {
21
        return Contact::forUser($user->id)->with('source')->paginate();
22
    }
23
24
    /**
25
     * Retrieve a contact.
26
     *
27
     * @param  string  $contact_id
28
     * @param  User  $user
29
     * @return Contact|null
30
     */
31
    public function contact(string $contact_id, User $user): ?Contact
32
    {
33
        return Contact::with('user')->where('id', $contact_id)->forUser($user->id)->first();
34
    }
35
36
    /**
37
     * Creates contact.
38
     *
39
     * @param  User  $user
40
     * @param  User  $contact
41
     * @return Contact
42
     */
43
    public function addContact(User $user, User $contact): Contact
44
    {
45
        return Contact::updateOrCreate([
46
            'user_id' => $user->id,
47
            'source_type' => get_class($contact),
48
            'source_id' => $contact->id,
49
        ], [
50
            'name' => $contact->name,
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on App\Models\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
51
        ]);
52
    }
53
54
    /**
55
     * Creates contact by user collection and returns contact.
56
     *
57
     * @param  Collection  $users
58
     * @return Collection
59
     */
60
    public function setContacts(Collection $users): Collection
61
    {
62
        return $users->map(function ($user) use ($users) {
63
            return $users
64
                    ->filter(function ($item) use ($user) {
65
                        return ! $item->is($user);
66
                    })
67
                    ->map(function ($contact) use ($user) {
68
                        return $this->addContact($user, $contact);
69
                    });
70
        })
71
                ->flatten();
72
    }
73
74
    /**
75
     * Remove a contact.
76
     *
77
     * @param  string  $contact_id
78
     * @return Contact
79
     */
80
    public function removeContact(string $contact_id): Contact
81
    {
82
        $contact = Contact::find($contact_id);
83
        $contact->delete();
84
85
        return $contact;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $contact could return the type null which is incompatible with the type-hinted return App\Models\Contact. Consider adding an additional type-check to rule them out.
Loading history...
86
    }
87
}
88