NovaAdDirector   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 12
eloc 29
c 2
b 0
f 0
dl 0
loc 61
ccs 0
cts 33
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareAds() 0 7 2
A possibleKeys() 0 9 2
A setFallbackKeyConnector() 0 3 1
A fallbackKey() 0 11 3
A prepareAd() 0 19 4
1
<?php
2
3
namespace NovaAdDirector;
4
5
use Illuminate\Support\Str;
6
use NovaAdDirector\Contracts\ConfigurationLayout;
7
use NovaAdDirector\Models\AdConfiguration;
8
9
class NovaAdDirector
10
{
11
    public static string $fallbackKeyConnector = ':';
12
13
    public static function setFallbackKeyConnector(string $fallbackKeyConnector): void
14
    {
15
        self::$fallbackKeyConnector = $fallbackKeyConnector;
16
    }
17
18
    public function prepareAds(array $preparationMap): static
19
    {
20
        foreach ($preparationMap as $locationName => $keyName) {
21
            $this->prepareAd($locationName, $keyName);
22
        }
23
24
        return $this;
25
    }
26
27
    public function prepareAd(string $locationName, string $keyName): static
28
    {
29
        /** @var AdConfiguration $adConfiguration */
30
        $adConfiguration = AdConfiguration::query()
31
                                          ->active()
32
                                          ->locatedPossibleKeys(
33
                                              $locationName,
34
                                              $this->possibleKeys($keyName)
35
                                          )
36
                                          ->first();
37
        if ($adConfiguration
38
            && !$adConfiguration->flexibleConfiguration->isEmpty()) {
39
            $configuration = $adConfiguration->flexibleConfiguration->first();
40
            if ($configuration instanceof ConfigurationLayout) {
41
                $configuration->applyConfiguration($locationName);
42
            }
43
        }
44
45
        return $this;
46
    }
47
48
    public function fallbackKey(string|array ...$keys): string
49
    {
50
        $stack = [];
51
        foreach ($keys as $key) {
52
            if (is_string($key)) {
53
                $key = (array) $key;
54
            }
55
            $stack = array_merge($stack, $key);
56
        }
57
58
        return implode(static::$fallbackKeyConnector, $stack);
59
    }
60
61
    public function possibleKeys(string $key): array
62
    {
63
        $keys = [$key];
64
        while (str_contains($key, static::$fallbackKeyConnector)) {
65
            $key    = Str::beforeLast($key, static::$fallbackKeyConnector);
66
            $keys[] = $key;
67
        }
68
69
        return $keys;
70
    }
71
}
72