Passed
Push — master ( f7ba70...7b802f )
by Morten
09:16 queued 12s
created

Auditable::getCustomEventAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
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
     * Auditable attributes excluded from the Audit.
22
     *
23
     * @var array
24
     */
25
    protected $excludedAttributes = [];
26
27
    /**
28
     * Audit event name.
29
     *
30
     * @var string
31
     */
32
    public $auditEvent;
33
34
    /**
35
     * Is auditing disabled?
36
     *
37
     * @var bool
38
     */
39
    public static $auditingDisabled = false;
40
41
    /**
42
     * Property may set custom event data to register
43
     * @var null|array
44
     */
45
    public $auditCustomOld = null;
46
47
    /**
48
     * Property may set custom event data to register
49
     * @var null|array
50
     */
51
    public $auditCustomNew = null;
52
53
    /**
54
     * If this is a custom event (as opposed to an eloquent event
55
     * @var bool
56
     */
57
    public $isCustomEvent = false;
58
59
    /**
60
     * Auditable boot logic.
61
     *
62
     * @return void
63
     */
64 214
    public static function bootAuditable()
65
    {
66 214
        if (!self::$auditingDisabled && static::isAuditingEnabled()) {
67 210
            static::observe(new AuditableObserver());
68
        }
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 38
    public function audits(): MorphMany
75
    {
76 38
        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

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

106
            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

106
            array_push($this->excludedAttributes, $this->getCreatedAtColumn(), $this->/** @scrutinizer ignore-call */ getUpdatedAtColumn());
Loading history...
107
108 142
            if (in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))) {
109 134
                $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

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

200
        foreach ($this->/** @scrutinizer ignore-call */ getDirty() as $attribute => $value) {
Loading history...
201 16
            if ($this->isAttributeAuditable($attribute)) {
202 14
                $old[$attribute] = Arr::get($this->original, $attribute);
203 14
                $new[$attribute] = Arr::get($this->attributes, $attribute);
204
            }
205
        }
206
207
        return [
208 18
            $old,
209
            $new,
210
        ];
211
    }
212
213
    /**
214
     * Get the old/new attributes of a deleted event.
215
     *
216
     * @return array
217
     */
218 8
    protected function getDeletedEventAttributes(): array
219
    {
220 8
        $old = [];
221
222 8
        foreach ($this->attributes as $attribute => $value) {
223 8
            if ($this->isAttributeAuditable($attribute)) {
224 8
                $old[$attribute] = $value;
225
            }
226
        }
227
228
        return [
229 8
            $old,
230
            [],
231
        ];
232
    }
233
234
    /**
235
     * Get the old/new attributes of a restored event.
236
     *
237
     * @return array
238
     */
239 4
    protected function getRestoredEventAttributes(): array
240
    {
241
        // A restored event is just a deleted event in reverse
242 4
        return array_reverse($this->getDeletedEventAttributes());
243
    }
244
245
    /**
246
     * {@inheritdoc}
247
     */
248 164
    public function readyForAuditing(): bool
249
    {
250 164
        if (static::$auditingDisabled) {
251 2
            return false;
252
        }
253
254 164
        if ($this->isCustomEvent) {
255 12
            return true;
256
        }
257
258 164
        return $this->isEventAuditable($this->auditEvent);
259
    }
260
261
    /**
262
     * Modify attribute value.
263
     *
264
     * @param string $attribute
265
     * @param mixed $value
266
     *
267
     * @return mixed
268
     * @throws AuditingException
269
     *
270
     */
271 4
    protected function modifyAttributeValue(string $attribute, $value)
272
    {
273 4
        $attributeModifiers = $this->getAttributeModifiers();
274
275 4
        if (!array_key_exists($attribute, $attributeModifiers)) {
276 2
            return $value;
277
        }
278
279 4
        $attributeModifier = $attributeModifiers[$attribute];
280
281 4
        if (is_subclass_of($attributeModifier, AttributeRedactor::class)) {
282 2
            return call_user_func([$attributeModifier, 'redact'], $value);
283
        }
284
285 4
        if (is_subclass_of($attributeModifier, AttributeEncoder::class)) {
286 2
            return call_user_func([$attributeModifier, 'encode'], $value);
287
        }
288
289 2
        throw new AuditingException(sprintf('Invalid AttributeModifier implementation: %s', $attributeModifier));
290
    }
291
292
    /**
293
     * {@inheritdoc}
294
     */
295 152
    public function toAudit(): array
296
    {
297 152
        if (!$this->readyForAuditing()) {
298 2
            throw new AuditingException('A valid audit event has not been set');
299
        }
300
301 150
        $attributeGetter = $this->resolveAttributeGetter($this->auditEvent);
302
303 150
        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

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

335
            'auditable_id'         => $this->/** @scrutinizer ignore-call */ getKey(),
Loading history...
336 138
            '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

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

604
        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

604
        if ($incompatibilities = array_diff_key(/** @scrutinizer ignore-type */ $modified, $this->getAttributes())) {
Loading history...
605 2
            throw new AuditableTransitionException(sprintf(
606
                'Incompatibility between [%s:%s] and [%s:%s]',
607 2
                $this->getMorphClass(),
608 2
                $this->getKey(),
609 2
                get_class($audit),
610 2
                $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

610
                $audit->/** @scrutinizer ignore-call */ 
611
                        getKey()
Loading history...
611 2
            ), array_keys($incompatibilities));
612
        }
613
614 10
        $key = $old ? 'old' : 'new';
615
616 10
        foreach ($modified as $attribute => $value) {
617 6
            if (array_key_exists($key, $value)) {
618 6
                $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

618
                $this->/** @scrutinizer ignore-call */ 
619
                       setAttribute($attribute, $value[$key]);
Loading history...
619
            }
620
        }
621
622 10
        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...
623
    }
624
625
    /*
626
    |--------------------------------------------------------------------------
627
    | Pivot help methods
628
    |--------------------------------------------------------------------------
629
    |
630
    | Methods for auditing pivot actions
631
    |
632
    */
633
634
    /**
635
     * @param string $relationName
636
     * @param mixed $id
637
     * @param array $attributes
638
     * @param bool $touch
639
     * @return void
640
     * @throws AuditingException
641
     */
642 2
    public function auditAttach(string $relationName, $id, array $attributes = [], $touch = true, $columns = ['name'])
643
    {
644 2
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'attach')) {
645
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method attach');
646
        }
647 2
        $this->auditEvent = 'attach';
648 2
        $this->isCustomEvent = true;
649 2
        $this->auditCustomOld = [
650 2
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
651
        ];
652 2
        $this->{$relationName}()->attach($id, $attributes, $touch);
653 2
        $this->auditCustomNew = [
654 2
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
655
        ];
656 2
        Event::dispatch(AuditCustom::class, [$this]);
657 2
        $this->isCustomEvent = false;
658
    }
659
660
    /**
661
     * @param string $relationName
662
     * @param mixed $ids
663
     * @param bool $touch
664
     * @return int
665
     * @throws AuditingException
666
     */
667
    public function auditDetach(string $relationName, $ids = null, $touch = true)
668
    {
669
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'detach')) {
670
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method detach');
671
        }
672
673
        $this->auditEvent = 'detach';
674
        $this->isCustomEvent = true;
675
        $this->auditCustomOld = [
676
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
677
        ];
678
        $results = $this->{$relationName}()->detach($ids, $touch);
679
        $this->auditCustomNew = [
680
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
681
        ];
682
        Event::dispatch(AuditCustom::class, [$this]);
683
        $this->isCustomEvent = false;
684
        return empty($results) ? 0 : $results;
685
    }
686
687
    /**
688
     * @param $relationName
689
     * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids
690
     * @param bool $detaching
691
     * @param bool $skipUnchanged
692
     * @return array
693
     * @throws AuditingException
694
     */
695 8
    public function auditSync($relationName, $ids, $detaching = true)
696
    {
697 8
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'sync')) {
698
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method sync');
699
        }
700
701 8
        $this->auditEvent = 'sync';
702
703 8
        $this->auditCustomOld = [
704 8
            $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
705
        ];
706
707 8
        $changes = $this->{$relationName}()->sync($ids, $detaching);
708
709 8
        if (collect($changes)->flatten()->isEmpty()) {
710 4
            $this->auditCustomOld = [];
711 4
            $this->auditCustomNew = [];
712
        } else {
713 4
            $this->auditCustomNew = [
714 4
                $relationName => $this->{$relationName}()->get()->isEmpty() ? [] : $this->{$relationName}()->get()->toArray()
715
            ];
716
        }
717
718 8
        $this->isCustomEvent = true;
719 8
        Event::dispatch(AuditCustom::class, [$this]);
720 8
        $this->isCustomEvent = false;
721
722 8
        return $changes;
723
    }
724
725
    /**
726
     * @param string $relationName
727
     * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids
728
     * @param bool $skipUnchanged
729
     * @return array
730
     * @throws AuditingException
731
     */
732
    public function auditSyncWithoutDetaching(string $relationName, $ids)
733
    {
734
        if (!method_exists($this, $relationName) || !method_exists($this->{$relationName}(), 'syncWithoutDetaching')) {
735
            throw new AuditingException('Relationship ' . $relationName . ' was not found or does not support method syncWithoutDetaching');
736
        }
737
        return $this->auditSync($relationName, $ids, false);
738
    }
739
}
740