Completed
Push — develop ( 5e4791...90850c )
by Nate
04:00
created

BeforeInsertToken::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 9
cp 0
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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\models\Settings;
12
use flipbox\flux\Flux;
13
use flipbox\patron\records\Token;
14
use yii\base\ModelEvent;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 1.0.0
19
 */
20
class BeforeInsertToken
21
{
22
    /**
23
     * Assign default environments to a provider
24
     * @param ModelEvent $event
25
     */
26
    public static function handle(ModelEvent $event)
27
    {
28
        /** @var Token $token */
29
        $token = $event->sender;
30
31
        // Ignore if already set
32
        if ($token->isRelationPopulated('environments') === true) {
33
            return;
34
        }
35
        
36
        $token->setEnvironments((array_unique(self::getEnvironments($token))));
37
        $token->autoSaveEnvironments = true;
38
    }
39
40
    /**
41
     * @param Token $token
42
     * @return array
43
     */
44
    protected static function getEnvironments(Token $token): array
45
    {
46
        /** @var Settings $settings */
47
        $settings = Flux::getInstance()->getSettings();
48
49
        if ($settings->getApplyProviderEnvironmentsToToken() === true) {
50
            return self::getEnvironmentsFromTokenProvider($token);
51
        }
52
53
        return [$settings->getEnvironment()];
54
    }
55
56
    /**
57
     * @param Token $token
58
     * @return array
59
     */
60
    protected static function getEnvironmentsFromTokenProvider(Token $token): array
61
    {
62
        $environments = [];
63
64
        foreach ($token->instances as $instance) {
65
            $environments = array_merge(
66
                $environments,
67
                $instance->getEnvironments()
68
                    ->select('environment')
69
                    ->indexBy(null)
70
                    ->column()
71
            );
72
        }
73
74
        return $environments;
75
    }
76
}
77