Completed
Push — develop ( 2d4f17...d5975b )
by Nate
05:25
created

ConnectionValidator::isValid()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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