1 | <?php declare(strict_types=1); |
||
10 | class AccountCollection implements \Countable, \IteratorAggregate |
||
11 | { |
||
12 | |||
13 | /** @var FioAccount[] */ |
||
14 | private $accounts = []; |
||
15 | |||
16 | |||
17 | public function account(string $alias = ''): FioAccount |
||
18 | { |
||
19 | if ($alias === '') { |
||
20 | return $this->getDefault(); |
||
21 | } |
||
22 | return $this->get($alias); |
||
23 | } |
||
24 | |||
25 | |||
26 | private function get(string $alias): FioAccount |
||
27 | { |
||
28 | if (isset($this->accounts[$alias])) { |
||
29 | return $this->accounts[$alias]; |
||
30 | } |
||
31 | throw new Exceptions\InvalidArgument('This account alias does not exists: ' . $alias); |
||
32 | } |
||
33 | |||
34 | |||
35 | private function getDefault(): FioAccount |
||
36 | { |
||
37 | if ($this->accounts === []) { |
||
38 | throw new Exceptions\InvalidState('Missing account, let\'s fill in configuration.'); |
||
39 | } |
||
40 | return reset($this->accounts); |
||
41 | } |
||
42 | |||
43 | |||
44 | public function addAccount(string $alias, FioAccount $account): AccountCollection |
||
45 | { |
||
46 | if (isset($this->accounts[$alias])) { |
||
47 | throw new Exceptions\InvalidArgument('This alias already exists: ' . $alias); |
||
48 | } |
||
49 | |||
50 | $this->accounts[$alias] = $account; |
||
51 | return $this; |
||
52 | } |
||
53 | |||
54 | |||
55 | public function count(): int |
||
59 | |||
60 | |||
61 | public function getIterator(): \ArrayIterator |
||
62 | { |
||
63 | return new \ArrayIterator($this->accounts); |
||
65 | |||
66 | } |
||
67 |