Completed
Push — master ( 04ac75...81967b )
by Nate
17:06
created

BeforeInsertToken   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 56
ccs 0
cts 31
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 13 2
A getEnvironments() 0 10 2
A getEnvironmentsFromTokenProvider() 0 16 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/patron/license
6
 * @link       https://www.flipboxfactory.com/software/patron/
7
 */
8
9
namespace flipbox\patron\events\handlers;
10
11
use flipbox\patron\Patron;
12
use flipbox\patron\records\Token;
13
use yii\base\ModelEvent;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 1.0.0
18
 */
19
class BeforeInsertToken
20
{
21
    /**
22
     * Assign default environments to a provider
23
     * @param ModelEvent $event
24
     */
25
    public static function handle(ModelEvent $event)
26
    {
27
        /** @var Token $token */
28
        $token = $event->sender;
29
30
        // Ignore if already set
31
        if ($token->isRelationPopulated('environments') === true) {
32
            return;
33
        }
34
35
        $token->setEnvironments((array_unique(self::getEnvironments($token))));
36
        $token->autoSaveEnvironments = true;
37
    }
38
39
    /**
40
     * @param Token $token
41
     * @return array
42
     */
43
    protected static function getEnvironments(Token $token): array
44
    {
45
        $settings = Patron::getInstance()->getSettings();
46
47
        if ($settings->getApplyProviderEnvironmentsToToken() === true) {
48
            return self::getEnvironmentsFromTokenProvider($token);
49
        }
50
51
        return [$settings->getEnvironment()];
52
    }
53
54
    /**
55
     * @param Token $token
56
     * @return array
57
     */
58
    protected static function getEnvironmentsFromTokenProvider(Token $token): array
59
    {
60
        $environments = [];
61
62
        foreach ($token->instances as $instance) {
63
            $environments = array_merge(
64
                $environments,
65
                $instance->getEnvironments()
66
                    ->select('environment')
67
                    ->indexBy(null)
68
                    ->column()
69
            );
70
        }
71
72
        return $environments;
73
    }
74
}
75