SaveAddressTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

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

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 as EloquentModel;
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
     * @return EloquentModel|false
17
     */
18
    private function createAddress(string $key = 'address')
19
    {
20
        return $this->model->address()->save(new Address($this->request->input($key)));
21
    }
22
23
    /**
24
     * Update an existing Address relationship.
25
     *
26
     * @param  string  $key
27
     * @return mixed
28
     */
29
    private function updateAddress(string $key = 'address')
30
    {
31
        return $this->model->address->update($this->request->input($key));
32
    }
33
34
    /**
35
     * Create or update an Address model depending on if the relationship already exists.
36
     *
37
     * @param  string  $key
38
     * @return bool|false|EloquentModel|mixed
39
     */
40
    private function createOrUpdateAddress(string $key = 'address')
41
    {
42
        // Confirm address data has passed to the request
43
        if ($this->request->has("{$key}.city") && $this->request->input("{$key}.city")) {
44
            // Update Address if it exists
45
            if ($this->model->address) {
46
                return $this->updateAddress($key);
47
            }
48
49
            // Create the Address if it doesn't exist
50
            else {
51
                return $this->createAddress($key);
52
            }
53
        }
54
55
        return false;
56
    }
57
}
58