Passed
Push — master ( 1ddf5f...c8f01d )
by Stephen
22:47 queued 22:12
created

AssertModelAttributes   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 8
c 1
b 1
f 0
dl 0
loc 54
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A assertModelAttributesEqual() 0 3 1
A assertModelAttributesSame() 0 3 1
A assertModelAttributes() 0 15 4
1
<?php
2
3
namespace Sfneal\Testing\Utils\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
trait AssertModelAttributes
8
{
9
    // todo: add tests
10
11
    /**
12
     * Assert model attributes are same.
13
     *
14
     * @param array $data
15
     * @param Model $model
16
     * @param array|null $ignoredAttributes
17
     * @return void
18
     */
19
    public static function assertModelAttributesSame(array $data, Model $model, array $ignoredAttributes = null): void
20
    {
21
        self::assertModelAttributes($data, $model, $ignoredAttributes, 'assertSame');
22
    }
23
24
    /**
25
     * Assert model attributes are equal.
26
     *
27
     * @param array $data
28
     * @param Model $model
29
     * @param array|null $ignoredAttributes
30
     * @return void
31
     */
32
    public static function assertModelAttributesEqual(array $data, Model $model, array $ignoredAttributes = null): void
33
    {
34
        self::assertModelAttributes($data, $model, $ignoredAttributes, 'assertEquals');
35
    }
36
37
    /**
38
     * Assert model attributes.
39
     *
40
     * @param array $data
41
     * @param Model $model
42
     * @param array|null $ignoredAttributes
43
     * @param string $method
44
     * @return void
45
     */
46
    private static function assertModelAttributes(array $data,
47
                                                  Model $model,
48
                                                  array $ignoredAttributes = null,
49
                                                  string $method = 'assertSame'): void
50
    {
51
        // Remove ignore attributes
52
        if (isset($ignoredAttributes)) {
53
            foreach ($ignoredAttributes as $attribute) {
54
                unset($data[$attribute]);
55
            }
56
        }
57
58
        // Execute assertions on each attribute
59
        foreach ($data as $attribute => $value) {
60
            self::{$method}($value, $model->{$attribute});
61
        }
62
    }
63
}
64