Passed
Push — master ( 0099ad...e2777a )
by Stephen
09:13 queued 06:59
created

SaveAddressTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A updateAddress() 0 3 1
A createOrUpdateAddress() 0 16 4
A createAddress() 0 3 1
1
<?php
2
3
namespace Sfneal\Address\Models\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Sfneal\Address\Models\Address;
7
8
trait SaveAddressTrait
9
{
10
    // todo: add use in actions
11
12
    /**
13
     * Create a new Address related to the Model.
14
     *
15
     * @param string $key Request key
16
     *
17
     * @return Model|false
18
     */
19
    private function createAddress(string $key = 'address')
20
    {
21
        return $this->model->address()->save(new Address($this->request->input($key)));
22
    }
23
24
    /**
25
     * Update an existing Address relationship.
26
     *
27
     * @param string $key
28
     *
29
     * @return mixed
30
     */
31
    private function updateAddress(string $key = 'address')
32
    {
33
        return $this->model->address->update($this->request->input($key));
34
    }
35
36
    /**
37
     * Create or update an Address model depending on if the relationship already exists.
38
     *
39
     * @param string $key
40
     *
41
     * @return bool|false|Model|mixed
42
     */
43
    private function createOrUpdateAddress(string $key = 'address')
44
    {
45
        // Confirm address data has passed to the request
46
        if ($this->request->has("{$key}.city") && $this->request->input("{$key}.city")) {
47
            // Update Address if it exists
48
            if ($this->model->address) {
49
                return $this->updateAddress($key);
50
            }
51
52
            // Create the Address if it doesn't exist
53
            else {
54
                return $this->createAddress($key);
55
            }
56
        }
57
58
        return false;
59
    }
60
}
61