Accounts::getAccountId()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 0
1
<?php
2
3
namespace Amelia\Monzo\Api;
4
5
use Amelia\Monzo\Models\Account;
6
use Amelia\Monzo\Exceptions\MonzoException;
7
8
trait Accounts
9
{
10
    /**
11
     * An account ID to use.
12
     *
13
     * @var string
14
     */
15
    protected $account;
16
17
    /**
18
     * Get a list of accounts for the current user.
19
     *
20
     * @return \Illuminate\Support\Collection|\Amelia\Monzo\Models\Account[]
21
     */
22
    public function accounts()
23
    {
24
        $results = $this->call('GET', 'accounts', [], [], 'accounts');
25
26
        return collect($results)->map(function ($item) {
27
            return new Account($item, $this);
28
        });
29
    }
30
31
    /**
32
     * Get an existing account ID.
33
     *
34
     * @return string
35
     */
36
    protected function getAccountId()
37
    {
38
        if ($this->account) {
39
            return $this->account;
40
        }
41
42
        $accounts = $this->accounts();
43
44
        $account = $accounts->first(function (Account $account) {
45
            return $account->type === 'uk_retail';
46
        });
47
48
        if ($account === null) {
49
            throw new MonzoException('The given user has no accounts. Did you use the correct email for auth?');
50
        }
51
52
        return $this->account = $account->id;
53
    }
54
}
55