NewsletterListCollection   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 47
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createFromConfig() 0 16 3
A getDefault() 0 9 3
A findByName() 0 13 4
1
<?php
2
3
namespace DansMaCulotte\Newsletter;
4
5
use Illuminate\Support\Collection;
6
use DansMaCulotte\Newsletter\Exceptions\InvalidNewsletterList;
7
8
class NewsletterListCollection extends Collection
9
{
10
    /** @var string */
11
    public $defaultList = '';
12
13
    public static function createFromConfig(array $config): self
14
    {
15
        $collection = new static();
16
17
        if (!count($config['lists']))
18
        {
19
            throw InvalidNewsletterList::noListsDefined();
20
        }
21
22
        foreach ($config['lists'] as $name => $listProperties) {
23
            $collection->push(new NewsletterList($name, $listProperties));
24
        }
25
26
        $collection->defaultList = $config['defaultList'];
27
28
        return $collection;
29
    }
30
31
    public function findByName(string $name): NewsletterList
32
    {
33
        if ($name === '') {
34
            return $this->getDefault();
35
        }
36
37
        foreach ($this->items as $newsletterList) {
38
            if ($newsletterList->getName() === $name) {
39
                return $newsletterList;
40
            }
41
        }
42
43
        throw InvalidNewsletterList::noListWithName($name);
44
    }
45
46
    public function getDefault(): NewsletterList
47
    {
48
        foreach ($this->items as $newsletterList) {
49
            if ($newsletterList->getName() === $this->defaultList) {
50
                return $newsletterList;
51
            }
52
        }
53
54
        throw InvalidNewsletterList::defaultListDoesNotExist($this->defaultList);
55
    }
56
}
57