HasContacts::forceDeleteContact()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Chuckcms\Contacts\Traits;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Validation\Validator;
0 ignored issues
show
Bug introduced by
The type Illuminate\Validation\Validator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Chuckcms\Contacts\Contracts\Contact;
8
use Chuckcms\Contacts\Exceptions\FailedValidation;
9
use Chuckcms\Contacts\Models\Contact as ContactModel;
10
use Illuminate\Database\Eloquent\Relations\MorphToMany;
11
12
trait HasContacts
13
{
14
    private $contactClass;
15
16
    /**
17
     * Boot the contactable trait for the model.
18
     *
19
     * @return void
20
     */
21
    public static function bootHasContacts()
22
    {
23
        static::deleting(function (self $model) {
24
            if (method_exists($model, 'isForceDeleting') && $model->isForceDeleting()) {
25
                $model->contacts()->forceDelete();
26
27
                return;
28
            }
29
30
            $model->contacts()->detach();
31
        });
32
    }
33
34
    public function getContactClass()
35
    {
36
        if (!isset($this->contactClass)) {
37
            $this->contactClass = config('contacts.models.contact');
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
            $this->contactClass = /** @scrutinizer ignore-call */ config('contacts.models.contact');
Loading history...
38
        }
39
40
        return $this->contactClass;
41
    }
42
43
    /**
44
     * A model may have multiple contacts.
45
     *
46
     * @return MorphToMany
47
     */
48
    public function contacts(): MorphToMany
49
    {
50
        return $this->morphToMany(
0 ignored issues
show
Bug introduced by
It seems like morphToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

50
        return $this->/** @scrutinizer ignore-call */ morphToMany(
Loading history...
51
            config('contacts.models.contact'),
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
            /** @scrutinizer ignore-call */ 
52
            config('contacts.models.contact'),
Loading history...
52
            'model',
53
            config('contacts.table_names.model_has_contacts'),
54
            config('contacts.column_names.model_morph_key'),
55
            'contact_id'
56
        );
57
    }
58
59
    /**
60
     * Assign the given contacts to the model. (credit to Spatie)
61
     *
62
     * @param array|int|\Chuckcms\Contacts\Contracts\Contact ...$contacts
63
     *
64
     * @return $this
65
     */
66
    public function assignContact(...$contacts)
67
    {
68
        $contacts = collect($contacts)
0 ignored issues
show
Bug introduced by
$contacts of type array<integer,Chuckcms\C...\Contact|array|integer> is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

68
        $contacts = collect(/** @scrutinizer ignore-type */ $contacts)
Loading history...
69
            ->flatten()
70
            ->map(function ($contact) {
71
                if (empty($contact)) {
72
                    return false;
73
                }
74
75
                return $this->getStoredContact($contact);
76
            })
77
            ->filter(function ($contact) {
78
                return $contact instanceof Contact;
79
            })
80
            ->map->id
81
            ->all();
82
83
        $model = $this->getModel();
0 ignored issues
show
Bug introduced by
It seems like getModel() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

83
        /** @scrutinizer ignore-call */ 
84
        $model = $this->getModel();
Loading history...
84
85
        if ($model->exists) {
86
            $this->contacts()->sync($contacts, false);
87
            $model->load('contacts');
88
        } else {
89
            $class = \get_class($model);
90
91
            $class::saved(
92
                function ($object) use ($contacts, $model) {
93
                    static $modelLastFiredOn;
94
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
95
                        return;
96
                    }
97
                    $object->contacts()->sync($contacts, false);
98
                    $object->load('contacts');
99
                    $modelLastFiredOn = $object;
100
                });
101
        }
102
103
        return $this;
104
    }
105
106
    /**
107
     * Revoke the given contact from the model.
108
     *
109
     * @param int|\Chuckcms\Contacts\Contracts\Contact $contact
110
     */
111
    public function removeContact($contact)
112
    {
113
        $this->contacts()->detach($this->getStoredContact($contact));
114
115
        $this->load('contacts');
0 ignored issues
show
Bug introduced by
It seems like load() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

115
        $this->/** @scrutinizer ignore-call */ 
116
               load('contacts');
Loading history...
116
117
        return $this;
118
    }
119
120
    /**
121
     * Remove all current contacts and set the given ones.
122
     *
123
     * @param array|int|\Chuckcms\Contacts\Contracts\Contact ...$contacts
124
     *
125
     * @return $this
126
     */
127
    public function syncContacts(...$contacts)
128
    {
129
        $this->contacts()->detach();
130
131
        return $this->assignContact($contacts);
132
    }
133
134
    /**
135
     * Check if model has contacts.
136
     *
137
     * @return bool
138
     */
139
    public function hasContacts(): bool
140
    {
141
        return (bool) count($this->contacts);
0 ignored issues
show
Bug introduced by
The property contacts does not exist on Chuckcms\Contacts\Traits\HasContacts. Did you mean contactClass?
Loading history...
142
    }
143
144
    /**
145
     * Add a contact to this model.
146
     *
147
     * @param array $attributes
148
     *
149
     * @throws Exception
150
     *
151
     * @return mixed
152
     */
153
    public function addContact(array $attributes)
154
    {
155
        $attributes = $this->loadContactAttributes($attributes);
156
        
157
        $contact = $this->getContactClass();
158
        $contact = $contact::create($attributes);
159
160
        return $this->assignContact($contact);
161
    }
162
163
    /**
164
     * Updates the given contact.
165
     *
166
     * @param Contact $contact
167
     * @param array   $attributes
168
     *
169
     * @throws Exception
170
     *
171
     * @return bool
172
     */
173
    public function updateContact(Contact $contact, array $attributes): bool
174
    {
175
        $attributes = $this->loadContactAttributes($attributes);
176
177
        return $contact->fill($attributes)->save();
0 ignored issues
show
Bug introduced by
The method fill() does not exist on Chuckcms\Contacts\Contracts\Contact. Since it exists in all sub-types, consider adding an abstract or default implementation to Chuckcms\Contacts\Contracts\Contact. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

177
        return $contact->/** @scrutinizer ignore-call */ fill($attributes)->save();
Loading history...
178
    }
179
180
    /**
181
     * Deletes given contact(s).
182
     *
183
     * @param int|array|\Chuckcms\Contacts\Contracts\Contact $contacts
184
     * @param bool                                           $force
185
     *
186
     * @throws Exception
187
     *
188
     * @return mixed
189
     */
190
    public function deleteContact($contacts, $force = false): bool
191
    {
192
        if (is_int($contacts) && $this->hasContact($contacts)) {
193
            return $force ?
194
                    $this->contacts()->where('id', $contacts)->forceDelete() :
195
                    $this->contacts()->where('id', $contacts)->delete();
196
        }
197
198
        if ($contacts instanceof Contact && $this->hasContact($contacts)) {
199
            return $force ?
200
                    $this->contacts()->where('id', $contacts->id)->forceDelete() :
0 ignored issues
show
Bug introduced by
Accessing id on the interface Chuckcms\Contacts\Contracts\Contact suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
201
                    $this->contacts()->where('id', $contacts->id)->delete();
202
        }
203
204
        if (is_array($contacts)) {
205
            foreach ($contacts as $contact) {
206
                if ($this->deleteContact($contact, $force)) {
207
                    continue;
208
                }
209
            }
210
211
            return true;
212
        }
213
214
        return false;
215
    }
216
217
    /**
218
     * Forcefully deletes given contact(s).
219
     *
220
     * @param int|array|\Chuck\Contact\Contracts\Contact $contacts
0 ignored issues
show
Bug introduced by
The type Chuck\Contact\Contracts\Contact was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
221
     * @param bool                                       $force
222
     *
223
     * @throws Exception
224
     *
225
     * @return mixed
226
     */
227
    public function forceDeleteContact($contacts): bool
228
    {
229
        return $this->deleteContact($contacts, true);
230
    }
231
232
    /**
233
     * Determine if the model has (one of) the given contact(s).
234
     *
235
     * @param int|array|\Chuck\Contact\Contracts\Contact|\Illuminate\Support\Collection $contacts
236
     *
237
     * @return bool
238
     */
239
    public function hasContact($contacts): bool
240
    {
241
        if (is_int($contacts)) {
242
            return $this->contacts->contains('id', $contacts);
0 ignored issues
show
Bug introduced by
The property contacts does not exist on Chuckcms\Contacts\Traits\HasContacts. Did you mean contactClass?
Loading history...
243
        }
244
245
        if ($contacts instanceof Contact) {
246
            return $this->contacts->contains('id', $contacts->id);
247
        }
248
249
        if (is_array($contacts)) {
250
            foreach ($contacts as $contact) {
251
                if ($this->hasContact($contact)) {
252
                    return true;
253
                }
254
            }
255
256
            return false;
257
        }
258
259
        return $contacts->intersect($this->contacts)->isNotEmpty();
260
    }
261
262
    public function getContactFirstNames(): Collection
263
    {
264
        return $this->contacts->pluck('first_name');
0 ignored issues
show
Bug introduced by
The property contacts does not exist on Chuckcms\Contacts\Traits\HasContacts. Did you mean contactClass?
Loading history...
265
    }
266
267
    /**
268
     * Get the public contact.
269
     *
270
     * @param string $direction
271
     *
272
     * @return Contact|null
273
     */
274
    public function getPublicContact(string $direction = 'desc'): ?Contact
275
    {
276
        return $this->contacts()
277
                    ->isPublic()
278
                    ->orderBy('is_public', $direction)
279
                    ->first();
280
    }
281
282
    /**
283
     * Get the primary contact.
284
     *
285
     * @param string $direction
286
     *
287
     * @return Contact|null
288
     */
289
    public function getPrimaryContact(string $direction = 'desc'): ?Contact
290
    {
291
        return $this->contacts()
292
                    ->isPrimary()
293
                    ->orderBy('is_primary', $direction)
294
                    ->first();
295
    }
296
297
    /**
298
     * Load and validate the contact attributes array.
299
     *
300
     * @param array $attributes
301
     *
302
     * @throws FailedValidation
303
     *
304
     * @return array
305
     */
306
    public function loadContactAttributes(array $attributes): array
307
    {
308
        if (!isset($attributes['first_name'])) {
309
            throw new FailedValidation('[Contacts] No first name given.');
310
        }
311
312
        $validator = $this->validateContact($attributes);
313
314
        if ($validator->fails()) {
315
            $errors = $validator->errors()->all();
316
            $error = '[Contacts] '.implode(' ', $errors);
317
318
            throw new FailedValidation($error);
319
        }
320
321
        return $attributes;
322
    }
323
324
    /**
325
     * Validate the contact.
326
     *
327
     * @param array $attributes
328
     *
329
     * @return Validator
330
     */
331
    public function validateContact(array $attributes): Validator
332
    {
333
        $rules = (new ContactModel())->getValidationRules();
334
335
        return validator($attributes, $rules);
0 ignored issues
show
Bug introduced by
The function validator was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

335
        return /** @scrutinizer ignore-call */ validator($attributes, $rules);
Loading history...
336
    }
337
338
    protected function getStoredContact($contact): Contact
339
    {
340
        $contactClass = $this->getContactClass();
341
342
        if (is_numeric($contact)) {
343
            return $contactClass::findById($contact);
344
        }
345
346
        return $contact;
347
    }
348
}
349