Test Failed
Pull Request — master (#684)
by Morten
05:28
created

Auditable::getAuditEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
namespace OwenIt\Auditing;
4
5
use Illuminate\Database\Eloquent\Relations\MorphMany;
6
use Illuminate\Database\Eloquent\SoftDeletes;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Facades\App;
9
use Illuminate\Support\Facades\Config;
10
use Illuminate\Support\Facades\Event;
11
use OwenIt\Auditing\Contracts\AttributeEncoder;
12
use OwenIt\Auditing\Contracts\AttributeRedactor;
13
use OwenIt\Auditing\Contracts\Resolver;
14
use OwenIt\Auditing\Events\AuditCustom;
15
use OwenIt\Auditing\Exceptions\AuditableTransitionException;
16
use OwenIt\Auditing\Exceptions\AuditingException;
17
18
trait Auditable
19
{
20
21
22
    /**
23
     * Auditable attributes excluded from the Audit.
24
     *
25
     * @var array
26
     */
27
    protected $excludedAttributes = [];
28
29
    /**
30
     * Audit event name.
31
     *
32
     * @var string
33
     */
34
    protected $auditEvent;
35
36
    /**
37
     * Is auditing disabled?
38
     *
39
     * @var bool
40
     */
41
    public static $auditingDisabled = false;
42
43
    /**
44
     * Property may set custom event data to register
45
     * @var null|array
46
     */
47
    public $auditCustomOld = null;
48
49
    /**
50
     * Property may set custom event data to register
51
     * @var null|array
52
     */
53
    public $auditCustomNew = null;
54
55
    /**
56
     * If this is a custom event (as opposed to an eloquent event
57
     * @var bool
58
     */
59
    public $isCustomEvent = false;
60
61
    /**
62
     * Auditable boot logic.
63
     *
64
     * @return void
65
     */
66
    public static function bootAuditable()
67
    {
68
        if (!self::$auditingDisabled && static::isAuditingEnabled()) {
69
            static::observe(new AuditableObserver());
70
        }
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function audits(): MorphMany
77
    {
78
        return $this->morphMany(
0 ignored issues
show
Bug introduced by
It seems like morphMany() 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

78
        return $this->/** @scrutinizer ignore-call */ morphMany(
Loading history...
79
            Config::get('audit.implementation', Models\Audit::class),
80
            'auditable'
81
        );
82
    }
83
84
    /**
85
     * Resolve the Auditable attributes to exclude from the Audit.
86
     *
87
     * @return void
88
     */
89
    protected function resolveAuditExclusions()
90
    {
91
        $this->excludedAttributes = $this->getAuditExclude();
92
93
        // When in strict mode, hidden and non visible attributes are excluded
94
        if ($this->getAuditStrict()) {
95
            // Hidden attributes
96
            $this->excludedAttributes = array_merge($this->excludedAttributes, $this->hidden);
97
98
            // Non visible attributes
99
            if ($this->visible) {
100
                $invisible = array_diff(array_keys($this->attributes), $this->visible);
101
102
                $this->excludedAttributes = array_merge($this->excludedAttributes, $invisible);
103
            }
104
        }
105
106
        // Exclude Timestamps
107
        if (!$this->getAuditTimestamps()) {
108
            array_push($this->excludedAttributes, $this->getCreatedAtColumn(), $this->getUpdatedAtColumn());
0 ignored issues
show
Bug introduced by
It seems like getCreatedAtColumn() 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

108
            array_push($this->excludedAttributes, $this->/** @scrutinizer ignore-call */ getCreatedAtColumn(), $this->getUpdatedAtColumn());
Loading history...
Bug introduced by
It seems like getUpdatedAtColumn() 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

108
            array_push($this->excludedAttributes, $this->getCreatedAtColumn(), $this->/** @scrutinizer ignore-call */ getUpdatedAtColumn());
Loading history...
109
110
            if (in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))) {
111
                $this->excludedAttributes[] = $this->getDeletedAtColumn();
0 ignored issues
show
Bug introduced by
It seems like getDeletedAtColumn() 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

111
                /** @scrutinizer ignore-call */ 
112
                $this->excludedAttributes[] = $this->getDeletedAtColumn();
Loading history...
112
            }
113
        }
114
115
        // Valid attributes are all those that made it out of the exclusion array
116
        $attributes = Arr::except($this->attributes, $this->excludedAttributes);
117
118
        foreach ($attributes as $attribute => $value) {
119
            // Apart from null, non scalar values will be excluded
120
            if (is_array($value) || (is_object($value) && !method_exists($value, '__toString'))) {
121
                $this->excludedAttributes[] = $attribute;
122
            }
123
        }
124
    }
125
126
    /**
127
     * @return array
128
     */
129
    public function getAuditExclude(): array
130
    {
131
        return $this->auditExclude ?? Config::get('audit.exclude', []);
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    public function getAuditInclude(): array
138
    {
139
        return $this->auditInclude ?? [];
140
    }
141
142
    /**
143
     * Get the old/new attributes of a retrieved event.
144
     *
145
     * @return array
146
     */
147
    protected function getRetrievedEventAttributes(): array
148
    {
149
        // This is a read event with no attribute changes,
150
        // only metadata will be stored in the Audit
151
152
        return [
153
            [],
154
            [],
155
        ];
156
    }
157
158
    /**
159
     * Get the old/new attributes of a created event.
160
     *
161
     * @return array
162
     */
163
    protected function getCreatedEventAttributes(): array
164
    {
165
        $new = [];
166
167
        foreach ($this->attributes as $attribute => $value) {
168
            if ($this->isAttributeAuditable($attribute)) {
169
                $new[$attribute] = $value;
170
            }
171
        }
172
173
        return [
174
            [],
175
            $new,
176
        ];
177
    }
178
179
    protected function getCustomEventAttributes(): array
180
    {
181
        return [
182
            $this->auditCustomOld,
183
            $this->auditCustomNew
184
        ];
185
    }
186
187
    /**
188
     * Get the old/new attributes of an updated event.
189
     *
190
     * @return array
191
     */
192
    protected function getUpdatedEventAttributes(): array
193
    {
194
        $old = [];
195
        $new = [];
196
197
        foreach ($this->getDirty() as $attribute => $value) {
0 ignored issues
show
Bug introduced by
It seems like getDirty() 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

197
        foreach ($this->/** @scrutinizer ignore-call */ getDirty() as $attribute => $value) {
Loading history...
198
            if ($this->isAttributeAuditable($attribute)) {
199
                $old[$attribute] = Arr::get($this->original, $attribute);
200
                $new[$attribute] = Arr::get($this->attributes, $attribute);
201
            }
202
        }
203
204
        return [
205
            $old,
206
            $new,
207
        ];
208
    }
209
210
    /**
211
     * Get the old/new attributes of a deleted event.
212
     *
213
     * @return array
214
     */
215
    protected function getDeletedEventAttributes(): array
216
    {
217
        $old = [];
218
219
        foreach ($this->attributes as $attribute => $value) {
220
            if ($this->isAttributeAuditable($attribute)) {
221
                $old[$attribute] = $value;
222
            }
223
        }
224
225
        return [
226
            $old,
227
            [],
228
        ];
229
    }
230
231
    /**
232
     * Get the old/new attributes of a restored event.
233
     *
234
     * @return array
235
     */
236
    protected function getRestoredEventAttributes(): array
237
    {
238
        // A restored event is just a deleted event in reverse
239
        return array_reverse($this->getDeletedEventAttributes());
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    public function readyForAuditing(): bool
246
    {
247
        if (static::$auditingDisabled) {
248
            return false;
249
        }
250
251
        if ($this->isCustomEvent) {
252
            return true;
253
        }
254
255
        return $this->isEventAuditable($this->auditEvent);
256
    }
257
258
    /**
259
     * Modify attribute value.
260
     *
261
     * @param string $attribute
262
     * @param mixed $value
263
     *
264
     * @return mixed
265
     * @throws AuditingException
266
     *
267
     */
268
    protected function modifyAttributeValue(string $attribute, $value)
269
    {
270
        $attributeModifiers = $this->getAttributeModifiers();
271
272
        if (!array_key_exists($attribute, $attributeModifiers)) {
273
            return $value;
274
        }
275
276
        $attributeModifier = $attributeModifiers[$attribute];
277
278
        if (is_subclass_of($attributeModifier, AttributeRedactor::class)) {
279
            return call_user_func([$attributeModifier, 'redact'], $value);
280
        }
281
282
        if (is_subclass_of($attributeModifier, AttributeEncoder::class)) {
283
            return call_user_func([$attributeModifier, 'encode'], $value);
284
        }
285
286
        throw new AuditingException(sprintf('Invalid AttributeModifier implementation: %s', $attributeModifier));
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292
    public function toAudit(): array
293
    {
294
        if (!$this->readyForAuditing()) {
295
            throw new AuditingException('A valid audit event has not been set');
296
        }
297
298
        $attributeGetter = $this->resolveAttributeGetter($this->auditEvent);
299
300
        if (!method_exists($this, $attributeGetter)) {
0 ignored issues
show
Bug introduced by
It seems like $attributeGetter can also be of type null; however, parameter $method of method_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

300
        if (!method_exists($this, /** @scrutinizer ignore-type */ $attributeGetter)) {
Loading history...
301
            throw new AuditingException(sprintf(
302
                'Unable to handle "%s" event, %s() method missing',
303
                $this->auditEvent,
304
                $attributeGetter
305
            ));
306
        }
307
308
        $this->resolveAuditExclusions();
309
310
        list($old, $new) = $this->$attributeGetter();
311
312
        if ($this->getAttributeModifiers() && !$this->isCustomEvent) {
313
            foreach ($old as $attribute => $value) {
314
                $old[$attribute] = $this->modifyAttributeValue($attribute, $value);
315
            }
316
317
            foreach ($new as $attribute => $value) {
318
                $new[$attribute] = $this->modifyAttributeValue($attribute, $value);
319
            }
320
        }
321
322
        $morphPrefix = Config::get('audit.user.morph_prefix', 'user');
323
324
        $tags = implode(',', $this->generateTags());
325
326
        $user = $this->resolveUser();
327
328
        return $this->transformAudit(array_merge([
329
            'old_values'           => $old,
330
            'new_values'           => $new,
331
            'event'                => $this->auditEvent,
332
            'auditable_id'         => $this->getKey(),
0 ignored issues
show
Bug introduced by
It seems like getKey() 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

332
            'auditable_id'         => $this->/** @scrutinizer ignore-call */ getKey(),
Loading history...
333
            'auditable_type'       => $this->getMorphClass(),
0 ignored issues
show
Bug introduced by
It seems like getMorphClass() 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

333
            'auditable_type'       => $this->/** @scrutinizer ignore-call */ getMorphClass(),
Loading history...
334
            $morphPrefix . '_id'   => $user ? $user->getAuthIdentifier() : null,
335
            $morphPrefix . '_type' => $user ? $user->getMorphClass() : null,
336
            'tags'                 => empty($tags) ? null : $tags,
337
        ], $this->runResolvers()));
338
    }
339
340
    /**
341
     * {@inheritdoc}
342
     */
343
    public function transformAudit(array $data): array
344
    {
345
        return $data;
346
    }
347
348
    /**
349
     * Resolve the User.
350
     *
351
     * @return mixed|null
352
     * @throws AuditingException
353
     *
354
     */
355
    protected function resolveUser()
356
    {
357
        $userResolver = Config::get('audit.user.resolver');
358
359
        if (is_subclass_of($userResolver, \OwenIt\Auditing\Contracts\UserResolver::class)) {
360
            return call_user_func([$userResolver, 'resolve']);
361
        }
362
363
        throw new AuditingException('Invalid UserResolver implementation');
364
    }
365
366
    protected function runResolvers(): array
367
    {
368
        $resolved = [];
369
        foreach (Config::get('audit.resolvers', []) as $name => $implementation) {
370
            if (empty($implementation)) {
371
                continue;
372
            }
373
374
            if (!is_subclass_of($implementation, Resolver::class)) {
375
                throw new AuditingException('Invalid Resolver implementation for: ' . $name);
376
            }
377
            $resolved[$name] = call_user_func([$implementation, 'resolve'], $this);
378
        }
379
        return $resolved;
380
    }
381
382
    /**
383
     * Determine if an attribute is eligible for auditing.
384
     *
385
     * @param string $attribute
386
     *
387
     * @return bool
388
     */
389
    protected function isAttributeAuditable(string $attribute): bool
390
    {
391
        // The attribute should not be audited
392
        if (in_array($attribute, $this->excludedAttributes, true)) {
393
            return false;
394
        }
395
396
        // The attribute is auditable when explicitly
397
        // listed or when the include array is empty
398
        $include = $this->getAuditInclude();
399
400
        return empty($include) || in_array($attribute, $include, true);
401
    }
402
403
    /**
404
     * Determine whether an event is auditable.
405
     *
406
     * @param string $event
407
     *
408
     * @return bool
409
     */
410
    protected function isEventAuditable($event): bool
411
    {
412
        return is_string($this->resolveAttributeGetter($event));
413
    }
414
415
    /**
416
     * Attribute getter method resolver.
417
     *
418
     * @param string $event
419
     *
420
     * @return string|null
421
     */
422
    protected function resolveAttributeGetter($event)
423
    {
424
        if (empty($event)) {
425
            return;
426
        }
427
428
        if ($this->isCustomEvent) {
429
            return 'getCustomEventAttributes';
430
        }
431
432
        foreach ($this->getAuditEvents() as $key => $value) {
433
            $auditableEvent = is_int($key) ? $value : $key;
434
435
            $auditableEventRegex = sprintf('/%s/', preg_replace('/\*+/', '.*', $auditableEvent));
436
437
            if (preg_match($auditableEventRegex, $event)) {
438
                return is_int($key) ? sprintf('get%sEventAttributes', ucfirst($event)) : $value;
439
            }
440
        }
441
    }
442
443
    /**
444
     * {@inheritdoc}
445
     */
446
    public function setAuditEvent(string $event): Contracts\Auditable
447
    {
448
        $this->auditEvent = $this->isEventAuditable($event) ? $event : null;
449
450
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type OwenIt\Auditing\Auditable which is incompatible with the type-hinted return OwenIt\Auditing\Contracts\Auditable.
Loading history...
451
    }
452
453
    /**
454
     * {@inheritdoc}
455
     */
456
    public function getAuditEvent()
457
    {
458
        return $this->auditEvent;
459
    }
460
461
    /**
462
     * {@inheritdoc}
463
     */
464
    public function getAuditEvents(): array
465
    {
466
        return $this->auditEvents ?? Config::get('audit.events', [
0 ignored issues
show
Bug introduced by
The property auditEvents does not exist on OwenIt\Auditing\Auditable. Did you mean auditEvent?
Loading history...
467
                'created',
468
                'updated',
469
                'deleted',
470
                'restored',
471
            ]);
472
    }
473
474
    /**
475
     * Disable Auditing.
476
     *
477
     * @return void
478
     */
479
    public static function disableAuditing()
480
    {
481
        static::$auditingDisabled = true;
482
    }
483
484
    /**
485
     * Enable Auditing.
486
     *
487
     * @return void
488
     */
489
    public static function enableAuditing()
490
    {
491
        static::$auditingDisabled = false;
492
    }
493
494
    /**
495
     * Determine whether auditing is enabled.
496
     *
497
     * @return bool
498
     */
499
    public static function isAuditingEnabled(): bool
500
    {
501
        if (App::runningInConsole()) {
502
            return Config::get('audit.enabled', true) && Config::get('audit.console', false);
503
        }
504
505
        return Config::get('audit.enabled', true);
506
    }
507
508
    /**
509
     * {@inheritdoc}
510
     */
511
    public function getAuditStrict(): bool
512
    {
513
        return $this->auditStrict ?? Config::get('audit.strict', false);
514
    }
515
516
    /**
517
     * {@inheritdoc}
518
     */
519
    public function getAuditTimestamps(): bool
520
    {
521
        return $this->auditTimestamps ?? Config::get('audit.timestamps', false);
522
    }
523
524
    /**
525
     * {@inheritdoc}
526
     */
527
    public function getAuditDriver()
528
    {
529
        return $this->auditDriver ?? Config::get('audit.driver', 'database');
530
    }
531
532
    /**
533
     * {@inheritdoc}
534
     */
535
    public function getAuditThreshold(): int
536
    {
537
        return $this->auditThreshold ?? Config::get('audit.threshold', 0);
538
    }
539
540
    /**
541
     * {@inheritdoc}
542
     */
543
    public function getAttributeModifiers(): array
544
    {
545
        return $this->attributeModifiers ?? [];
546
    }
547
548
    /**
549
     * {@inheritdoc}
550
     */
551
    public function generateTags(): array
552
    {
553
        return [];
554
    }
555
556
    /**
557
     * {@inheritdoc}
558
     */
559
    public function transitionTo(Contracts\Audit $audit, bool $old = false): Contracts\Auditable
560
    {
561
        // The Audit must be for an Auditable model of this type
562
        if ($this->getMorphClass() !== $audit->auditable_type) {
0 ignored issues
show
Bug introduced by
Accessing auditable_type on the interface OwenIt\Auditing\Contracts\Audit suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
563
            throw new AuditableTransitionException(sprintf(
564
                'Expected Auditable type %s, got %s instead',
565
                $this->getMorphClass(),
566
                $audit->auditable_type
567
            ));
568
        }
569
570
        // The Audit must be for this specific Auditable model
571
        if ($this->getKey() !== $audit->auditable_id) {
0 ignored issues
show
Bug introduced by
Accessing auditable_id on the interface OwenIt\Auditing\Contracts\Audit suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
572
            throw new AuditableTransitionException(sprintf(
573
                'Expected Auditable id %s, got %s instead',
574
                $this->getKey(),
575
                $audit->auditable_id
576
            ));
577
        }
578
579
        // Redacted data should not be used when transitioning states
580
        foreach ($this->getAttributeModifiers() as $attribute => $modifier) {
581
            if (is_subclass_of($modifier, AttributeRedactor::class)) {
582
                throw new AuditableTransitionException('Cannot transition states when an AttributeRedactor is set');
583
            }
584
        }
585
586
        // The attribute compatibility between the Audit and the Auditable model must be met
587
        $modified = $audit->getModified();
588
589
        if ($incompatibilities = array_diff_key($modified, $this->getAttributes())) {
0 ignored issues
show
Bug introduced by
The method getAttributes() does not exist on OwenIt\Auditing\Auditable. Did you maybe mean getAttributeModifiers()? ( Ignorable by Annotation )

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

589
        if ($incompatibilities = array_diff_key($modified, $this->/** @scrutinizer ignore-call */ getAttributes())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
It seems like $modified can also be of type string; however, parameter $array1 of array_diff_key() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

589
        if ($incompatibilities = array_diff_key(/** @scrutinizer ignore-type */ $modified, $this->getAttributes())) {
Loading history...
590
            throw new AuditableTransitionException(sprintf(
591
                'Incompatibility between [%s:%s] and [%s:%s]',
592
                $this->getMorphClass(),
593
                $this->getKey(),
594
                get_class($audit),
595
                $audit->getKey()
0 ignored issues
show
Bug introduced by
The method getKey() does not exist on OwenIt\Auditing\Contracts\Audit. Since it exists in all sub-types, consider adding an abstract or default implementation to OwenIt\Auditing\Contracts\Audit. ( Ignorable by Annotation )

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

595
                $audit->/** @scrutinizer ignore-call */ 
596
                        getKey()
Loading history...
596
            ), array_keys($incompatibilities));
597
        }
598
599
        $key = $old ? 'old' : 'new';
600
601
        foreach ($modified as $attribute => $value) {
602
            if (array_key_exists($key, $value)) {
603
                $this->setAttribute($attribute, $value[$key]);
0 ignored issues
show
Bug introduced by
It seems like setAttribute() 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

603
                $this->/** @scrutinizer ignore-call */ 
604
                       setAttribute($attribute, $value[$key]);
Loading history...
604
            }
605
        }
606
607
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type OwenIt\Auditing\Auditable which is incompatible with the type-hinted return OwenIt\Auditing\Contracts\Auditable.
Loading history...
608
    }
609
610
    /*
611
    |--------------------------------------------------------------------------
612
    | Pivot help methods
613
    |--------------------------------------------------------------------------
614
    |
615
    | Methods for auditing pivot actions
616
    |
617
    */
618
619
    /**
620
     * @param string $relationName
621
     * @param mixed $id
622
     * @param array $attributes
623
     * @param bool $touch
624
     * @return void
625
     * @throws AuditingException
626
     */
627
    public function auditAttach(string $relationName, $id, array $attributes = [], $touch = true, $columns = ['name'])
628
    {
629
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'attach')) {
630
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method attach');
631
        }
632
        $this->auditEvent = 'attach';
633
        $this->isCustomEvent = true;
634
        $this->auditCustomOld = [
635
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
636
        ];
637
        $this->{$relationName}()->attach($id, $attributes, $touch);
638
        $this->auditCustomNew = [
639
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
640
        ];
641
        Event::dispatch(AuditCustom::class, [$this]);
642
    }
643
644
    /**
645
     * @param string $relationName
646
     * @param mixed $ids
647
     * @param bool $touch
648
     * @return int
649
     * @throws AuditingException
650
     */
651
    public function auditDetach(string $relationName, $ids = null, $touch = true)
652
    {
653
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'detach')) {
654
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method detach');
655
        }
656
657
        $this->auditEvent = 'detach';
658
        $this->isCustomEvent = true;
659
        $this->auditCustomOld = [
660
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
661
        ];
662
        $results = $this->{$relationName}()->detach($ids, $touch);
663
        $this->auditCustomNew = [
664
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
665
        ];
666
        Event::dispatch(AuditCustom::class, [$this]);
667
        return empty($results) ? 0 : $results;
668
    }
669
670
    /**
671
     * @param $relationName
672
     * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids
673
     * @param bool $detaching
674
     * @return array
675
     * @throws AuditingException
676
     */
677
    public function auditSync($relationName, $ids, $detaching = true)
678
    {
679
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'sync')) {
680
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method sync');
681
        }
682
683
        $this->auditEvent = 'sync';
684
        $this->isCustomEvent = true;
685
        $this->auditCustomOld = [
686
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
687
        ];
688
        $changes = $this->{$relationName}()->sync($ids, $detaching);
689
        $this->auditCustomNew = [
690
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
691
        ];
692
        Event::dispatch(AuditCustom::class, [$this]);
693
        return $changes;
694
    }
695
696
    /**
697
     * @param string $relationName
698
     * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids
699
     * @return array
700
     * @throws AuditingException
701
     */
702
    public function auditSyncWithoutDetaching(string $relationName, $ids)
703
    {
704
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'syncWithoutDetaching')) {
705
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method syncWithoutDetaching');
706
        }
707
        return $this->auditSync($relationName, $ids, false);
708
    }
709
}
710