ConnectionValidator::validateConnection()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 17
cp 0
rs 9.584
c 0
b 0
f 0
cc 4
nc 4
nop 3
crap 20
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/force/license
6
 * @link       https://www.flipboxfactory.com/software/force/
7
 */
8
9
namespace flipbox\craft\salesforce\validators;
10
11
use flipbox\craft\salesforce\connections\SavableConnectionInterface;
12
use flipbox\craft\salesforce\Force;
13
use flipbox\craft\salesforce\records\Connection;
14
use Flipbox\Salesforce\Connections\ConnectionInterface;
15
use yii\base\Model;
16
use yii\validators\Validator;
17
18
/**
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 1.0.0
21
 */
22
class ConnectionValidator extends Validator
23
{
24
    /**
25
     * @inheritdoc
26
     */
27
    public function validateAttribute($model, $attribute)
28
    {
29
        $class = $model->$attribute;
30
31
        // Handles are always required, so if it's blank, the required validator will catch this.
32
        if ($class) {
33
            if (!$this->isValid($class)) {
34
                $message = Force::t(
35
                    '“{class}” is a not a valid connection.',
36
                    ['class' => $class]
37
                );
38
                $this->addError($model, $attribute, $message);
39
            }
40
41
            $this->validateConnection($model, $class, $attribute);
42
        }
43
    }
44
45
    /**
46
     * @param string $class
47
     * @return bool
48
     */
49
    protected function isValid(string $class): bool
50
    {
51
        return $class instanceof ConnectionInterface ||
52
            is_subclass_of($class, ConnectionInterface::class);
53
    }
54
55
    /**
56
     * @param Model $model
57
     * @param string $class
58
     * @param $attribute
59
     */
60
    protected function validateConnection(Model $model, string $class, $attribute)
61
    {
62
        if (!$model instanceof Connection) {
63
            return;
64
        }
65
66
        /** @var ConnectionInterface $connection */
67
        $connection = $model->getConnection();
68
69
        if (!$connection instanceof SavableConnectionInterface) {
70
            return;
71
        }
72
73
        if (!$connection->validate()) {
74
            $message = Force::t(
75
                'Invalid settings.',
76
                ['class' => $class]
77
            );
78
            $this->addError($model, $attribute, $message);
79
        }
80
    }
81
}
82